hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 2,
"code_window": [
" this.exclude = (excludeExtensions || []).length ? buildRegexp(excludeExtensions) : null;\n",
"\n",
" function combine(prev, curr) {\n",
" if (curr.charAt(0) !== \".\") throw new TypeError(\"Extension must begin with '.'\");\n",
" curr = '(' + curr + ')';\n",
" return prev ? (prev + '|' + curr) : curr;\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let kSpecialRegexpChars = /[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g;\n",
" curr = '(' + curr.replace(kSpecialRegexpChars, '\\\\$&') + ')';\n"
],
"file_path": "tools/broccoli/tree-differ.ts",
"type": "replace",
"edit_start_line_idx": 24
} | import {
InjectAnnotation,
InjectPromiseAnnotation,
InjectLazyAnnotation,
OptionalAnnotation,
InjectableAnnotation
} from './annotations';
import {makeDecorator, makeParamDecorator} from '../util/decorators';
export var Inject = makeParamDecorator(InjectAnnotation);
export var InjectPromise = makeParamDecorator(InjectPromiseAnnotation);
export var InjectLazy = makeParamDecorator(InjectLazyAnnotation);
export var Optional = makeParamDecorator(OptionalAnnotation);
export var Injectable = makeDecorator(InjectableAnnotation);
| modules/angular2/src/di/decorators.ts | 0 | https://github.com/angular/angular/commit/a58c9f83bd1a5be110a7982bab7023b209634c37 | [
0.0001731028751237318,
0.00017298312741331756,
0.00017286337970290333,
0.00017298312741331756,
1.1974771041423082e-7
] |
{
"id": 2,
"code_window": [
" this.exclude = (excludeExtensions || []).length ? buildRegexp(excludeExtensions) : null;\n",
"\n",
" function combine(prev, curr) {\n",
" if (curr.charAt(0) !== \".\") throw new TypeError(\"Extension must begin with '.'\");\n",
" curr = '(' + curr + ')';\n",
" return prev ? (prev + '|' + curr) : curr;\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let kSpecialRegexpChars = /[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g;\n",
" curr = '(' + curr.replace(kSpecialRegexpChars, '\\\\$&') + ')';\n"
],
"file_path": "tools/broccoli/tree-differ.ts",
"type": "replace",
"edit_start_line_idx": 24
} | <div class="md-grid-list">
<div class="md-grid-tile">
<figure></figure>
</div>
</div>
| modules/angular2_material/src/components/grid_list/grid_list.html | 0 | https://github.com/angular/angular/commit/a58c9f83bd1a5be110a7982bab7023b209634c37 | [
0.00016803876496851444,
0.00016803876496851444,
0.00016803876496851444,
0.00016803876496851444,
0
] |
{
"id": 0,
"code_window": [
" \"prepare\": \"node ../../scripts/prepare.js\"\n",
" },\n",
" \"dependencies\": {\n",
" \"@storybook/addons\": \"5.1.0-alpha.9\",\n",
" \"@storybook/core-events\": \"5.1.0-alpha.9\",\n",
" \"common-tags\": \"^1.8.0\",\n",
" \"core-js\": \"^2.6.5\",\n",
" \"global\": \"^4.3.2\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"@storybook/router\": \"5.1.0-alpha.9\",\n"
],
"file_path": "addons/links/package.json",
"type": "add",
"edit_start_line_idx": 26
} | import { document } from 'global';
import qs from 'qs';
import addons from '@storybook/addons';
import { SELECT_STORY, STORY_CHANGED } from '@storybook/core-events';
import EVENTS from './constants';
export const navigate = params => addons.getChannel().emit(SELECT_STORY, params);
const generateUrl = id => {
const { location } = document;
const query = qs.parse(location.search, { ignoreQueryPrefix: true });
return `${location.origin + location.pathname}?${qs.stringify(
{ ...query, id },
{ encode: false }
)}`;
};
const valueOrCall = args => value => (typeof value === 'function' ? value(...args) : value);
export const linkTo = (kind, story) => (...args) => {
const resolver = valueOrCall(args);
navigate({
kind: resolver(kind),
story: resolver(story),
});
};
export const hrefTo = (kind, name) =>
new Promise(resolve => {
const channel = addons.getChannel();
channel.once(EVENTS.RECEIVE, id => resolve(generateUrl(id)));
channel.emit(EVENTS.REQUEST, { kind, name });
});
const linksListener = e => {
const { sbKind: kind, sbStory: story } = e.target.dataset;
if (kind || story) {
e.preventDefault();
navigate({ kind, story });
}
};
let hasListener = false;
const on = () => {
if (!hasListener) {
hasListener = true;
document.addEventListener('click', linksListener);
}
};
const off = () => {
if (hasListener) {
hasListener = false;
document.removeEventListener('click', linksListener);
}
};
export const withLinks = storyFn => {
on();
addons.getChannel().once(STORY_CHANGED, off);
return storyFn();
};
| addons/links/src/preview.js | 1 | https://github.com/storybookjs/storybook/commit/b7bc65c723d11473988bc34582a138c4aced0186 | [
0.00017191575898323208,
0.00016801246965769678,
0.00016521078941877931,
0.0001671379868639633,
0.000002315244501005509
] |
{
"id": 0,
"code_window": [
" \"prepare\": \"node ../../scripts/prepare.js\"\n",
" },\n",
" \"dependencies\": {\n",
" \"@storybook/addons\": \"5.1.0-alpha.9\",\n",
" \"@storybook/core-events\": \"5.1.0-alpha.9\",\n",
" \"common-tags\": \"^1.8.0\",\n",
" \"core-js\": \"^2.6.5\",\n",
" \"global\": \"^4.3.2\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"@storybook/router\": \"5.1.0-alpha.9\",\n"
],
"file_path": "addons/links/package.json",
"type": "add",
"edit_start_line_idx": 26
} | import { logger } from '@storybook/client-logger';
import { mockChannel } from '@storybook/addons';
import ClientApi from './client_api';
import ConfigApi from './config_api';
import StoryStore from './story_store';
export const getContext = (() => decorateStory => {
const channel = mockChannel();
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,
};
})();
jest.mock('@storybook/client-logger', () => ({
logger: { warn: jest.fn(), log: jest.fn() },
}));
describe('preview.client_api', () => {
describe('setAddon', () => {
it('should register addons', () => {
const { clientApi } = getContext();
let data;
clientApi.setAddon({
aa() {
data = 'foo';
},
});
clientApi.storiesOf('none', module).aa();
expect(data).toBe('foo');
});
it('should not remove previous addons', () => {
const { clientApi } = getContext();
const data = [];
clientApi.setAddon({
aa() {
data.push('foo');
},
});
clientApi.setAddon({
bb() {
data.push('bar');
},
});
clientApi
.storiesOf('none', module)
.aa()
.bb();
expect(data).toEqual(['foo', 'bar']);
});
it('should call with the clientApi context', () => {
const { clientApi } = getContext();
let data;
clientApi.setAddon({
aa() {
data = typeof this.add;
},
});
clientApi.storiesOf('none', module).aa();
expect(data).toBe('function');
});
it('should be able to access addons added previously', () => {
const { clientApi } = getContext();
let data;
clientApi.setAddon({
aa() {
data = 'foo';
},
});
clientApi.setAddon({
bb() {
this.aa();
},
});
clientApi.storiesOf('none', module).bb();
expect(data).toBe('foo');
});
it('should be able to access the current kind', () => {
const { clientApi } = getContext();
const kind = 'dfdwf3e3';
let data;
clientApi.setAddon({
aa() {
data = this.kind;
},
});
clientApi.storiesOf(kind, module).aa();
expect(data).toBe(kind);
});
});
describe('addDecorator', () => {
it('should add local decorators', () => {
const {
clientApi: { storiesOf },
storyStore,
} = getContext();
storiesOf('kind', module)
.addDecorator(fn => `aa-${fn()}`)
.add('name', () => 'Hello');
expect(storyStore.fromId('kind--name').storyFn()).toBe('aa-Hello');
});
it('should add global decorators', () => {
const {
clientApi: { addDecorator, storiesOf },
storyStore,
} = getContext();
addDecorator(fn => `bb-${fn()}`);
storiesOf('kind', module).add('name', () => 'Hello');
expect(storyStore.fromId('kind--name').storyFn()).toBe('bb-Hello');
});
it('should utilize both decorators at once', () => {
const {
clientApi: { addDecorator, storiesOf },
storyStore,
} = getContext();
addDecorator(fn => `aa-${fn()}`);
storiesOf('kind', module)
.addDecorator(fn => `bb-${fn()}`)
.add('name', () => 'Hello');
expect(storyStore.fromId('kind--name').storyFn()).toBe('aa-bb-Hello');
});
it('should pass the context', () => {
const {
clientApi: { storiesOf },
storyStore,
} = getContext();
storiesOf('kind', module)
.addDecorator(fn => `aa-${fn()}`)
.add('name', c => `${c.kind}-${c.name}`);
const result = storyStore.fromId('kind--name').storyFn();
expect(result).toBe(`aa-kind-name`);
});
it('should have access to the context', () => {
const {
clientApi: { storiesOf },
storyStore,
} = getContext();
storiesOf('kind', module)
.addDecorator((fn, { kind, name }) => `${kind}-${name}-${fn()}`)
.add('name', () => 'Hello');
const result = storyStore.fromId('kind--name').storyFn();
expect(result).toBe(`kind-name-Hello`);
});
});
describe('clearDecorators', () => {
it('should remove all global decorators', () => {
const { clientApi } = getContext();
// eslint-disable-next-line no-underscore-dangle
clientApi._globalDecorators = 1234;
clientApi.clearDecorators();
// eslint-disable-next-line no-underscore-dangle
expect(clientApi._globalDecorators).toEqual([]);
});
});
describe('getStorybook', () => {
it('should transform the storybook to an array with filenames', () => {
const {
clientApi: { getStorybook, storiesOf },
} = getContext();
let book;
book = getStorybook();
expect(book).toEqual([]);
storiesOf('kind 1', module)
.add('name 1', () => '1')
.add('name 2', () => '2');
storiesOf('kind 2', module)
.add('name 1', () => '1')
.add('name 2', () => '2');
book = getStorybook();
expect(book).toEqual([
expect.objectContaining({
fileName: expect.any(String),
kind: 'kind 1',
stories: [
{
name: 'name 1',
render: expect.any(Function),
},
{
name: 'name 2',
render: expect.any(Function),
},
],
}),
expect.objectContaining({
fileName: expect.any(String),
kind: 'kind 2',
stories: [
{
name: 'name 1',
render: expect.any(Function),
},
{
name: 'name 2',
render: expect.any(Function),
},
],
}),
]);
});
it('reads filename from module', () => {
const {
clientApi: { getStorybook, storiesOf },
} = getContext();
const fn = jest.fn();
storiesOf('kind', { id: 'foo.js' }).add('name', fn);
const storybook = getStorybook();
expect(storybook).toEqual([
{
kind: 'kind',
fileName: 'foo.js',
stories: [
{
name: 'name',
render: expect.any(Function),
},
],
},
]);
});
it('should stringify ids from module', () => {
const {
clientApi: { getStorybook, storiesOf },
} = getContext();
const fn = jest.fn();
storiesOf('kind', { id: 1211 }).add('name', fn);
const storybook = getStorybook();
expect(storybook).toEqual([
{
kind: 'kind',
fileName: '1211',
stories: [
{
name: 'name',
render: expect.any(Function),
},
],
},
]);
});
});
describe('hot module loading', () => {
class MockModule {
id = 'mock-module-id';
hot = {
callbacks: [],
dispose(fn) {
this.callbacks.push(fn);
},
reload() {
this.callbacks.forEach(fn => fn());
},
};
}
it('should increment store revision when the module reloads', () => {
const {
storyStore,
clientApi: { storiesOf },
} = getContext();
const module = new MockModule();
expect(storyStore.getRevision()).toEqual(0);
storiesOf('kind', module);
module.hot.reload();
expect(storyStore.getRevision()).toEqual(1);
});
it('should replace a kind when the module reloads', () => {
const {
clientApi: { storiesOf, getStorybook },
} = getContext();
const module = new MockModule();
const stories = [jest.fn(), jest.fn()];
expect(getStorybook()).toEqual([]);
storiesOf('kind', module).add('story', stories[0]);
const firstStorybook = getStorybook();
expect(firstStorybook).toEqual([
{
fileName: expect.any(String),
kind: 'kind',
stories: [{ name: 'story', render: expect.anything() }],
},
]);
firstStorybook[0].stories[0].render();
expect(stories[0]).toHaveBeenCalled();
module.hot.reload();
expect(getStorybook()).toEqual([]);
storiesOf('kind', module).add('story', stories[1]);
const secondStorybook = getStorybook();
expect(secondStorybook).toEqual([
{
fileName: expect.any(String),
kind: 'kind',
stories: [{ name: 'story', render: expect.anything() }],
},
]);
secondStorybook[0].stories[0].render();
expect(stories[1]).toHaveBeenCalled();
expect(logger.warn).not.toHaveBeenCalled();
});
});
describe('parameters', () => {
it('collects parameters across different modalities', () => {
const {
storyStore,
clientApi: { storiesOf, addParameters },
} = getContext();
addParameters({ a: 'global', b: 'global', c: 'global' });
const kind = storiesOf('kind', module);
kind.addParameters({ b: 'kind', c: 'kind' });
kind.add('name', jest.fn(), { c: 'story' });
expect(storyStore.fromId('kind--name').parameters).toEqual({
a: 'global',
b: 'kind',
c: 'story',
fileName: expect.any(String),
options: expect.any(Object),
});
});
it('combines object parameters per-key', () => {
const {
storyStore,
clientApi: { storiesOf, addParameters },
} = getContext();
addParameters({
addon1: 'global string value',
addon2: ['global array value'],
addon3: {
global: true,
sub: { global: true },
},
options: expect.any(Object),
});
storiesOf('kind', module)
.addParameters({
addon1: 'local string value',
addon2: ['local array value'],
addon3: {
local: true,
sub: {
local: true,
},
},
})
.add('name', jest.fn(), {
addon1: 'local string value',
addon2: ['local array value'],
addon3: {
local: true,
sub: {
local: true,
},
},
});
expect(storyStore.fromId('kind--name').parameters).toEqual({
addon1: 'local string value',
addon2: ['local array value'],
addon3: {
global: true,
local: true,
sub: {
global: true,
local: true,
},
},
fileName: expect.any(String),
options: expect.any(Object),
});
});
});
describe('storiesOf', () => {
describe('add', () => {
it('should replace stories when adding the same story', () => {
const stories = [jest.fn().mockReturnValue('story1'), jest.fn().mockReturnValue('story2')];
const {
clientApi: { storiesOf, getStorybook },
} = getContext();
expect(getStorybook()).toEqual([]);
storiesOf('kind', module).add('story', stories[0]);
{
const book = getStorybook();
expect(book).toHaveLength(1);
const entry = book[0];
expect(entry.kind).toMatch('kind');
expect(entry.stories).toHaveLength(1);
expect(entry.stories[0].name).toBe('story');
// v3 returns the same function we passed in
if (jest.isMockFunction(entry.stories[0].render)) {
expect(entry.stories[0].render).toBe(stories[0]);
} else {
expect(entry.stories[0].render()).toBe('story1');
}
}
storiesOf('kind', module).add('story', stories[1]);
expect(logger.warn.mock.calls[0][0]).toMatch(
/Story with id kind--story already exists in the store/
);
{
const book = getStorybook();
expect(book).toHaveLength(1);
const entry = book[0];
expect(entry.kind).toMatch('kind');
expect(entry.stories).toHaveLength(1);
expect(entry.stories[0].name).toBe('story');
// v3 returns the same function we passed in
if (jest.isMockFunction(entry.stories[0].render)) {
expect(entry.stories[0].render).toBe(stories[0]);
} else {
expect(entry.stories[0].render()).toBe('story2');
}
}
});
});
});
});
| lib/client-api/src/client_api.test.js | 0 | https://github.com/storybookjs/storybook/commit/b7bc65c723d11473988bc34582a138c4aced0186 | [
0.000174910863279365,
0.00016918196342885494,
0.00016448333917651325,
0.0001694912207312882,
0.0000028484867016231874
] |
{
"id": 0,
"code_window": [
" \"prepare\": \"node ../../scripts/prepare.js\"\n",
" },\n",
" \"dependencies\": {\n",
" \"@storybook/addons\": \"5.1.0-alpha.9\",\n",
" \"@storybook/core-events\": \"5.1.0-alpha.9\",\n",
" \"common-tags\": \"^1.8.0\",\n",
" \"core-js\": \"^2.6.5\",\n",
" \"global\": \"^4.3.2\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"@storybook/router\": \"5.1.0-alpha.9\",\n"
],
"file_path": "addons/links/package.json",
"type": "add",
"edit_start_line_idx": 26
} | import packageJson from '../../package.json';
export default {
packageJson,
frameworkPresets: [require.resolve('./framework-preset-mithril.js')],
};
| app/mithril/src/server/options.js | 0 | https://github.com/storybookjs/storybook/commit/b7bc65c723d11473988bc34582a138c4aced0186 | [
0.00017051292525138706,
0.00017051292525138706,
0.00017051292525138706,
0.00017051292525138706,
0
] |
{
"id": 0,
"code_window": [
" \"prepare\": \"node ../../scripts/prepare.js\"\n",
" },\n",
" \"dependencies\": {\n",
" \"@storybook/addons\": \"5.1.0-alpha.9\",\n",
" \"@storybook/core-events\": \"5.1.0-alpha.9\",\n",
" \"common-tags\": \"^1.8.0\",\n",
" \"core-js\": \"^2.6.5\",\n",
" \"global\": \"^4.3.2\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"@storybook/router\": \"5.1.0-alpha.9\",\n"
],
"file_path": "addons/links/package.json",
"type": "add",
"edit_start_line_idx": 26
} | import React from 'react';
import { storiesOf, forceReRender } from '@storybook/react';
let count = 0;
const increment = () => {
count += 1;
forceReRender();
};
storiesOf('Force ReRender', module).add('button', () => (
<button type="button" onClick={increment}>
Click me to increment: {count}
</button>
));
| examples/cra-kitchen-sink/src/stories/force-rerender.stories.js | 0 | https://github.com/storybookjs/storybook/commit/b7bc65c723d11473988bc34582a138c4aced0186 | [
0.00017139870033133775,
0.0001680935238255188,
0.00016478834731969982,
0.0001680935238255188,
0.000003305176505818963
] |
{
"id": 1,
"code_window": [
"import qs from 'qs';\n",
"import addons from '@storybook/addons';\n",
"import { SELECT_STORY, STORY_CHANGED } from '@storybook/core-events';\n",
"\n",
"import EVENTS from './constants';\n",
"\n",
"export const navigate = params => addons.getChannel().emit(SELECT_STORY, params);\n",
"const generateUrl = id => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { toId } from '@storybook/router/utils';\n"
],
"file_path": "addons/links/src/preview.js",
"type": "replace",
"edit_start_line_idx": 4
} | import { document } from 'global';
import qs from 'qs';
import addons from '@storybook/addons';
import { SELECT_STORY, STORY_CHANGED } from '@storybook/core-events';
import EVENTS from './constants';
export const navigate = params => addons.getChannel().emit(SELECT_STORY, params);
const generateUrl = id => {
const { location } = document;
const query = qs.parse(location.search, { ignoreQueryPrefix: true });
return `${location.origin + location.pathname}?${qs.stringify(
{ ...query, id },
{ encode: false }
)}`;
};
const valueOrCall = args => value => (typeof value === 'function' ? value(...args) : value);
export const linkTo = (kind, story) => (...args) => {
const resolver = valueOrCall(args);
navigate({
kind: resolver(kind),
story: resolver(story),
});
};
export const hrefTo = (kind, name) =>
new Promise(resolve => {
const channel = addons.getChannel();
channel.once(EVENTS.RECEIVE, id => resolve(generateUrl(id)));
channel.emit(EVENTS.REQUEST, { kind, name });
});
const linksListener = e => {
const { sbKind: kind, sbStory: story } = e.target.dataset;
if (kind || story) {
e.preventDefault();
navigate({ kind, story });
}
};
let hasListener = false;
const on = () => {
if (!hasListener) {
hasListener = true;
document.addEventListener('click', linksListener);
}
};
const off = () => {
if (hasListener) {
hasListener = false;
document.removeEventListener('click', linksListener);
}
};
export const withLinks = storyFn => {
on();
addons.getChannel().once(STORY_CHANGED, off);
return storyFn();
};
| addons/links/src/preview.js | 1 | https://github.com/storybookjs/storybook/commit/b7bc65c723d11473988bc34582a138c4aced0186 | [
0.9982088804244995,
0.4279412627220154,
0.00016546806728001684,
0.0011239011073485017,
0.49367401003837585
] |
{
"id": 1,
"code_window": [
"import qs from 'qs';\n",
"import addons from '@storybook/addons';\n",
"import { SELECT_STORY, STORY_CHANGED } from '@storybook/core-events';\n",
"\n",
"import EVENTS from './constants';\n",
"\n",
"export const navigate = params => addons.getChannel().emit(SELECT_STORY, params);\n",
"const generateUrl = id => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { toId } from '@storybook/router/utils';\n"
],
"file_path": "addons/links/src/preview.js",
"type": "replace",
"edit_start_line_idx": 4
} | import { configure } from '@storybook/react';
// automatically import all files ending in *.stories.js
const req = require.context('../stories', true, /.stories.js$/);
function loadStories() {
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);
| lib/cli/test/fixtures/react_babel_pkg_json/.storybook/config.js | 0 | https://github.com/storybookjs/storybook/commit/b7bc65c723d11473988bc34582a138c4aced0186 | [
0.0001671720965532586,
0.0001671720965532586,
0.0001671720965532586,
0.0001671720965532586,
0
] |
{
"id": 1,
"code_window": [
"import qs from 'qs';\n",
"import addons from '@storybook/addons';\n",
"import { SELECT_STORY, STORY_CHANGED } from '@storybook/core-events';\n",
"\n",
"import EVENTS from './constants';\n",
"\n",
"export const navigate = params => addons.getChannel().emit(SELECT_STORY, params);\n",
"const generateUrl = id => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { toId } from '@storybook/router/utils';\n"
],
"file_path": "addons/links/src/preview.js",
"type": "replace",
"edit_start_line_idx": 4
} | # Website for [storybook.js.org](https://storybook.js.org)
This is the source for [storybook.js.org](https://storybook.js.org). It documents [Storybook](https://github.com/storybooks/storybook), an amazing UI component development environment for React and React Native. The site is built with [Gatsby](https://github.com/gatsbyjs/gatsby).
### Usage
```sh
yarn
yarn dev
yarn storybook
```
### Edit Documentation
Documentation is written in Markdown and located inside the [`docs/src/pages`](https://github.com/storybooks/storybook/tree/master/docs/src/pages) directory.
### Guidelines for Writing Good Documentation
0. Explain **why** in addition to **how**. If something is designed a certain way for a reason, provide that reason.
1. Provide examples of code snippets whenever possible - showing is always better than telling.
2. Avoid simplifying problems - this frustrates users even more when they don't understand something "simple".
* Bad examples:
- `All you need to do is apply...`
- `Simply add...`
- `The object is just...`
3. Use concise language - The less time users spend on reading and understanding docs, the better.
* Avoid using passive voice.
- Passive (bad): `It is believed by Storybook that empowering component builders is important.`
- Active (good): `Storybook believes in empowering component builders.`
* Place action in the verb.
- Indirect action (bad): `A refactor of this code is necessary`.
- Direct action (good): `This code needs to be refactored`.
4. Avoid the use of pronouns - documentation should not address the reader because not everything applies to the person reading our docs.
* Don't use `you` to refer to the user or a third party.
- Pronoun (bad): `You can also...`
- Without pronoun (good): `Users can also...`
* Don't use `we` to refer to Storybook, contributors, or Storybook users.
- Pronoun (bad): `We can create this component...`
- Without pronoun (good): `The component can be created...`
* Don't use `he`, `she`, `him`, `her`, etc. to refer to a third party unless referring to a specific person.
* Refer to contributors and the product as `Storybook`.
* Refer to users as `users`.
| docs/README.md | 0 | https://github.com/storybookjs/storybook/commit/b7bc65c723d11473988bc34582a138c4aced0186 | [
0.0001707022893242538,
0.00016696816601324826,
0.0001604920980753377,
0.00016791303642094135,
0.0000034907247936644126
] |
{
"id": 1,
"code_window": [
"import qs from 'qs';\n",
"import addons from '@storybook/addons';\n",
"import { SELECT_STORY, STORY_CHANGED } from '@storybook/core-events';\n",
"\n",
"import EVENTS from './constants';\n",
"\n",
"export const navigate = params => addons.getChannel().emit(SELECT_STORY, params);\n",
"const generateUrl = id => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { toId } from '@storybook/router/utils';\n"
],
"file_path": "addons/links/src/preview.js",
"type": "replace",
"edit_start_line_idx": 4
} | # Official storybook
This storybook includes stories for:
- `@storybook/components` - reusable UI components for addon authors
- `@storybook/ui` - the UI of storybook itself
- `@storybook/addon-*` - various addons.
- `@storybook/other-*` - various examples.
| examples/official-storybook/README.md | 0 | https://github.com/storybookjs/storybook/commit/b7bc65c723d11473988bc34582a138c4aced0186 | [
0.00020385354582685977,
0.00020385354582685977,
0.00020385354582685977,
0.00020385354582685977,
0
] |
{
"id": 2,
"code_window": [
" });\n",
"};\n",
"\n",
"export const hrefTo = (kind, name) =>\n",
" new Promise(resolve => {\n",
" const channel = addons.getChannel();\n",
" channel.once(EVENTS.RECEIVE, id => resolve(generateUrl(id)));\n",
" channel.emit(EVENTS.REQUEST, { kind, name });\n",
" });\n",
"\n",
"const linksListener = e => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" resolve(generateUrl(toId({ kind, name })));\n"
],
"file_path": "addons/links/src/preview.js",
"type": "replace",
"edit_start_line_idx": 29
} | {
"name": "@storybook/addon-links",
"version": "5.1.0-alpha.9",
"description": "Story Links addon for storybook",
"keywords": [
"addon",
"storybook"
],
"homepage": "https://github.com/storybooks/storybook/tree/master/addons/links",
"bugs": {
"url": "https://github.com/storybooks/storybook/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/storybooks/storybook.git",
"directory": "addons/links"
},
"license": "MIT",
"main": "dist/index.js",
"jsnext:main": "src/index.js",
"scripts": {
"prepare": "node ../../scripts/prepare.js"
},
"dependencies": {
"@storybook/addons": "5.1.0-alpha.9",
"@storybook/core-events": "5.1.0-alpha.9",
"common-tags": "^1.8.0",
"core-js": "^2.6.5",
"global": "^4.3.2",
"prop-types": "^15.7.2",
"qs": "^6.6.0"
},
"peerDependencies": {
"react": "*"
},
"publishConfig": {
"access": "public"
}
}
| addons/links/package.json | 1 | https://github.com/storybookjs/storybook/commit/b7bc65c723d11473988bc34582a138c4aced0186 | [
0.000174381144461222,
0.00017296781879849732,
0.00017110348562709987,
0.00017319330072496086,
0.0000012067575880791992
] |
{
"id": 2,
"code_window": [
" });\n",
"};\n",
"\n",
"export const hrefTo = (kind, name) =>\n",
" new Promise(resolve => {\n",
" const channel = addons.getChannel();\n",
" channel.once(EVENTS.RECEIVE, id => resolve(generateUrl(id)));\n",
" channel.emit(EVENTS.REQUEST, { kind, name });\n",
" });\n",
"\n",
"const linksListener = e => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" resolve(generateUrl(toId({ kind, name })));\n"
],
"file_path": "addons/links/src/preview.js",
"type": "replace",
"edit_start_line_idx": 29
} | require('./dist/manager').register();
| addons/links/register.js | 0 | https://github.com/storybookjs/storybook/commit/b7bc65c723d11473988bc34582a138c4aced0186 | [
0.00017342866340186447,
0.00017342866340186447,
0.00017342866340186447,
0.00017342866340186447,
0
] |
{
"id": 2,
"code_window": [
" });\n",
"};\n",
"\n",
"export const hrefTo = (kind, name) =>\n",
" new Promise(resolve => {\n",
" const channel = addons.getChannel();\n",
" channel.once(EVENTS.RECEIVE, id => resolve(generateUrl(id)));\n",
" channel.emit(EVENTS.REQUEST, { kind, name });\n",
" });\n",
"\n",
"const linksListener = e => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" resolve(generateUrl(toId({ kind, name })));\n"
],
"file_path": "addons/links/src/preview.js",
"type": "replace",
"edit_start_line_idx": 29
} | import fs from 'fs';
import path from 'path';
import semver from 'semver';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import { normalizeCondition } from 'webpack/lib/RuleSet';
const cssExtensions = ['.css', '.scss', '.sass'];
const cssModuleExtensions = ['.module.css', '.module.scss', '.module.sass'];
const typeScriptExtensions = ['.ts', '.tsx'];
let reactScriptsPath;
export function getReactScriptsPath({ noCache } = {}) {
if (reactScriptsPath && !noCache) return reactScriptsPath;
const appDirectory = fs.realpathSync(process.cwd());
const reactScriptsScriptPath = fs.realpathSync(
path.join(appDirectory, '/node_modules/.bin/react-scripts')
);
reactScriptsPath = path.join(reactScriptsScriptPath, '../..');
const scriptsPkgJson = path.join(reactScriptsPath, 'package.json');
if (!fs.existsSync(scriptsPkgJson)) {
reactScriptsPath = 'react-scripts';
}
return reactScriptsPath;
}
export function isReactScriptsInstalled(requiredVersion = '2.0.0') {
try {
// eslint-disable-next-line import/no-dynamic-require,global-require
const reactScriptsJson = require(path.join(getReactScriptsPath(), 'package.json'));
return !semver.lt(reactScriptsJson.version, requiredVersion);
} catch (e) {
return false;
}
}
export const getRules = extensions => rules =>
rules.reduce((craRules, rule) => {
// If at least one extension satisfies the rule test, the rule is one
// we want to extract
if (rule.test && extensions.some(normalizeCondition(rule.test))) {
// If the base test is for extensions, return early
return craRules.concat(rule);
}
// Get any rules contained in rule.oneOf
if (!rule.test && rule.oneOf) {
craRules.push(...getRules(extensions)(rule.oneOf));
}
// Get any rules contained in rule.rules
if (!rule.test && rule.rules) {
craRules.push(...getRules(extensions)(rule.rules));
}
return craRules;
}, []);
const getStyleRules = getRules(cssExtensions.concat(cssModuleExtensions));
export const getTypeScriptRules = (webpackConfigRules, configDir) => {
const rules = getRules(typeScriptExtensions)(webpackConfigRules);
// We know CRA only has one rule targetting TS for now, which is the first rule.
const babelRule = rules[0];
// Resolves an issue where this config is parsed twice (#4903).
if (typeof babelRule.include !== 'string') return rules;
// Adds support for using TypeScript in the `.storybook` (or config) folder.
return [
{
...babelRule,
include: [babelRule.include, path.resolve(configDir)],
},
...rules.slice(1),
];
};
function mergePlugins(basePlugins, additionalPlugins) {
return [...basePlugins, ...additionalPlugins].reduce((plugins, plugin) => {
if (
plugins.some(includedPlugin => includedPlugin.constructor.name === plugin.constructor.name)
) {
return plugins;
}
return [...plugins, plugin];
}, []);
}
export function getCraWebpackConfig(mode) {
const pathToReactScripts = getReactScriptsPath();
const craWebpackConfig =
mode === 'production' ? 'config/webpack.config.prod.js' : 'config/webpack.config.dev.js';
let pathToWebpackConfig = path.join(pathToReactScripts, craWebpackConfig);
if (!fs.existsSync(pathToWebpackConfig)) {
pathToWebpackConfig = path.join(pathToReactScripts, 'config/webpack.config.js');
}
// eslint-disable-next-line import/no-dynamic-require,global-require
const webpackConfig = require(pathToWebpackConfig);
if (typeof webpackConfig === 'function') {
return webpackConfig(mode);
}
return webpackConfig;
}
export function applyCRAWebpackConfig(baseConfig, configDir) {
// Check if the user can use TypeScript (react-scripts version 2.1+).
const hasTsSupport = isReactScriptsInstalled('2.1.0');
const tsExtensions = hasTsSupport ? typeScriptExtensions : [];
const extensions = [...cssExtensions, ...tsExtensions];
// Remove any rules from baseConfig that test true for any one of the extensions
const filteredBaseRules = baseConfig.module.rules.filter(
rule => !rule.test || !extensions.some(normalizeCondition(rule.test))
);
// Load create-react-app config
const craWebpackConfig = getCraWebpackConfig(baseConfig.mode);
const craStyleRules = getStyleRules(craWebpackConfig.module.rules);
const craTypeScriptRules = hasTsSupport
? getTypeScriptRules(craWebpackConfig.module.rules, configDir)
: [];
// Add css minification for production
const plugins = [...baseConfig.plugins];
if (baseConfig.mode === 'production') {
plugins.push(new MiniCssExtractPlugin());
}
return {
...baseConfig,
module: {
...baseConfig.module,
rules: [...filteredBaseRules, ...craStyleRules, ...craTypeScriptRules],
},
plugins: mergePlugins(plugins, hasTsSupport ? craWebpackConfig.plugins : []),
resolve: {
...baseConfig.resolve,
extensions: [...baseConfig.resolve.extensions, ...tsExtensions],
},
};
}
| app/react/src/server/cra-config.js | 0 | https://github.com/storybookjs/storybook/commit/b7bc65c723d11473988bc34582a138c4aced0186 | [
0.00017748922982718796,
0.00017292742268182337,
0.00016617878281977028,
0.00017308472888544202,
0.0000027641733595373807
] |
{
"id": 2,
"code_window": [
" });\n",
"};\n",
"\n",
"export const hrefTo = (kind, name) =>\n",
" new Promise(resolve => {\n",
" const channel = addons.getChannel();\n",
" channel.once(EVENTS.RECEIVE, id => resolve(generateUrl(id)));\n",
" channel.emit(EVENTS.REQUEST, { kind, name });\n",
" });\n",
"\n",
"const linksListener = e => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" resolve(generateUrl(toId({ kind, name })));\n"
],
"file_path": "addons/links/src/preview.js",
"type": "replace",
"edit_start_line_idx": 29
} | import React from 'react';
import PropTypes from 'prop-types';
import { TouchableNativeFeedback } from 'react-native';
export default function Button({ onPress, children }) {
return <TouchableNativeFeedback onPress={onPress}>{children}</TouchableNativeFeedback>;
}
Button.defaultProps = {
children: null,
onPress: () => {},
};
Button.propTypes = {
children: PropTypes.node,
onPress: PropTypes.func,
};
| lib/cli/generators/REACT_NATIVE/template/storybook/stories/Button/index.android.js | 0 | https://github.com/storybookjs/storybook/commit/b7bc65c723d11473988bc34582a138c4aced0186 | [
0.00017484900308772922,
0.00017455157649237663,
0.00017425414989702404,
0.00017455157649237663,
2.974265953525901e-7
] |
{
"id": 0,
"code_window": [
" bulkSelectEnabled: boolean;\n",
" lastFetched?: string;\n",
"}\n",
"\n",
"const parsedErrorMessage = (\n",
" errorMessage: Record<string, string[]> | string,\n",
") => {\n",
" if (typeof errorMessage === 'string') {\n",
" return errorMessage;\n",
" }\n",
" return Object.entries(errorMessage)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" errorMessage: Record<string, string[] | string> | string,\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 rison from 'rison';
import { useState, useEffect, useCallback } from 'react';
import { makeApi, SupersetClient, t } from '@superset-ui/core';
import { createErrorHandler } from 'src/views/CRUD/utils';
import { FetchDataConfig } from 'src/components/ListView';
import { FilterValue } from 'src/components/ListView/types';
import Chart, { Slice } from 'src/types/Chart';
import copyTextToClipboard from 'src/utils/copy';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import { FavoriteStatus, ImportResourceName, DatabaseObject } from './types';
interface ListViewResourceState<D extends object = any> {
loading: boolean;
collection: D[];
count: number;
permissions: string[];
lastFetchDataConfig: FetchDataConfig | null;
bulkSelectEnabled: boolean;
lastFetched?: string;
}
const parsedErrorMessage = (
errorMessage: Record<string, string[]> | string,
) => {
if (typeof errorMessage === 'string') {
return errorMessage;
}
return Object.entries(errorMessage)
.map(([key, value]) => `(${key}) ${value.join(', ')}`)
.join('\n');
};
export function useListViewResource<D extends object = any>(
resource: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
infoEnable = true,
defaultCollectionValue: D[] = [],
baseFilters?: FilterValue[], // must be memoized
initialLoadingState = true,
) {
const [state, setState] = useState<ListViewResourceState<D>>({
count: 0,
collection: defaultCollectionValue,
loading: initialLoadingState,
lastFetchDataConfig: null,
permissions: [],
bulkSelectEnabled: false,
});
function updateState(update: Partial<ListViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
function toggleBulkSelect() {
updateState({ bulkSelectEnabled: !state.bulkSelectEnabled });
}
useEffect(() => {
if (!infoEnable) return;
SupersetClient.get({
endpoint: `/api/v1/${resource}/_info?q=${rison.encode({
keys: ['permissions'],
})}`,
}).then(
({ json: infoJson = {} }) => {
updateState({
permissions: infoJson.permissions,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %s info: %s',
resourceLabel,
errMsg,
),
),
),
);
}, []);
function hasPerm(perm: string) {
if (!state.permissions.length) {
return false;
}
return Boolean(state.permissions.find(p => p === perm));
}
const fetchData = useCallback(
({
pageIndex,
pageSize,
sortBy,
filters: filterValues,
}: FetchDataConfig) => {
// set loading state, cache the last config for refreshing data.
updateState({
lastFetchDataConfig: {
filters: filterValues,
pageIndex,
pageSize,
sortBy,
},
loading: true,
});
const filterExps = (baseFilters || [])
.concat(filterValues)
.map(({ id, operator: opr, value }) => ({
col: id,
opr,
value,
}));
const queryParams = rison.encode({
order_column: sortBy[0].id,
order_direction: sortBy[0].desc ? 'desc' : 'asc',
page: pageIndex,
page_size: pageSize,
...(filterExps.length ? { filters: filterExps } : {}),
});
return SupersetClient.get({
endpoint: `/api/v1/${resource}/?q=${queryParams}`,
})
.then(
({ json = {} }) => {
updateState({
collection: json.result,
count: json.count,
lastFetched: new Date().toISOString(),
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
errMsg,
),
),
),
)
.finally(() => {
updateState({ loading: false });
});
},
[baseFilters],
);
return {
state: {
loading: state.loading,
resourceCount: state.count,
resourceCollection: state.collection,
bulkSelectEnabled: state.bulkSelectEnabled,
lastFetched: state.lastFetched,
},
setResourceCollection: (update: D[]) =>
updateState({
collection: update,
}),
hasPerm,
fetchData,
toggleBulkSelect,
refreshData: (provideConfig?: FetchDataConfig) => {
if (state.lastFetchDataConfig) {
return fetchData(state.lastFetchDataConfig);
}
if (provideConfig) {
return fetchData(provideConfig);
}
return null;
},
};
}
// In the same vein as above, a hook for viewing a single instance of a resource (given id)
interface SingleViewResourceState<D extends object = any> {
loading: boolean;
resource: D | null;
error: string | Record<string, string[]> | null;
}
export function useSingleViewResource<D extends object = any>(
resourceName: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<SingleViewResourceState<D>>({
loading: false,
resource: null,
error: null,
});
function updateState(update: Partial<SingleViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
const fetchResource = useCallback(
(resourceID: number) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.get({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const createResource = useCallback(
(resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.id;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while creating %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const updateResource = useCallback(
(resourceID: number, resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.put({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler(errMsg => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
JSON.stringify(errMsg),
),
);
updateState({
error: errMsg,
});
return errMsg;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const clearError = () =>
updateState({
error: null,
});
return {
state,
setResource: (update: D) =>
updateState({
resource: update,
}),
fetchResource,
createResource,
updateResource,
clearError,
};
}
interface ImportResourceState {
loading: boolean;
passwordsNeeded: string[];
alreadyExists: string[];
}
export function useImportResource(
resourceName: ImportResourceName,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<ImportResourceState>({
loading: false,
passwordsNeeded: [],
alreadyExists: [],
});
function updateState(update: Partial<ImportResourceState>) {
setState(currentState => ({ ...currentState, ...update }));
}
/* eslint-disable no-underscore-dangle */
const isNeedsPassword = (payload: any) =>
typeof payload === 'object' &&
Array.isArray(payload._schema) &&
payload._schema.length === 1 &&
payload._schema[0] === 'Must provide a password for the database';
const isAlreadyExists = (payload: any) =>
typeof payload === 'string' &&
payload.includes('already exists and `overwrite=true` was not passed');
const getPasswordsNeeded = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isNeedsPassword(validationErrors))
.map(([fileName]) => fileName);
const getAlreadyExists = (errMsg: Record<string, Record<string, string[]>>) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isAlreadyExists(validationErrors))
.map(([fileName]) => fileName);
const hasTerminalValidation = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.values(errMsg).some(
validationErrors =>
!isNeedsPassword(validationErrors) &&
!isAlreadyExists(validationErrors),
);
const importResource = useCallback(
(
bundle: File,
databasePasswords: Record<string, string> = {},
overwrite = false,
) => {
// Set loading state
updateState({
loading: true,
});
const formData = new FormData();
formData.append('formData', bundle);
/* The import bundle never contains database passwords; if required
* they should be provided by the user during import.
*/
if (databasePasswords) {
formData.append('passwords', JSON.stringify(databasePasswords));
}
/* If the imported model already exists the user needs to confirm
* that they want to overwrite it.
*/
if (overwrite) {
formData.append('overwrite', 'true');
}
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/import/`,
body: formData,
})
.then(() => true)
.catch(response =>
getClientErrorObject(response).then(error => {
const errMsg = error.message || error.error;
if (typeof errMsg === 'string') {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
return false;
}
if (hasTerminalValidation(errMsg)) {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
} else {
updateState({
passwordsNeeded: getPasswordsNeeded(errMsg),
alreadyExists: getAlreadyExists(errMsg),
});
}
return false;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[],
);
return { state, importResource };
}
enum FavStarClassName {
CHART = 'slice',
DASHBOARD = 'Dashboard',
}
type FavoriteStatusResponse = {
result: Array<{
id: string;
value: boolean;
}>;
};
const favoriteApis = {
chart: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/chart/favorite_status/',
}),
dashboard: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/dashboard/favorite_status/',
}),
};
export function useFavoriteStatus(
type: 'chart' | 'dashboard',
ids: Array<string | number>,
handleErrorMsg: (message: string) => void,
) {
const [favoriteStatus, setFavoriteStatus] = useState<FavoriteStatus>({});
const updateFavoriteStatus = (update: FavoriteStatus) =>
setFavoriteStatus(currentState => ({ ...currentState, ...update }));
useEffect(() => {
if (!ids.length) {
return;
}
favoriteApis[type](ids).then(
({ result }) => {
const update = result.reduce((acc, element) => {
acc[element.id] = element.value;
return acc;
}, {});
updateFavoriteStatus(update);
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error fetching the favorite status: %s', errMsg),
),
),
);
}, [ids, type, handleErrorMsg]);
const saveFaveStar = useCallback(
(id: number, isStarred: boolean) => {
const urlSuffix = isStarred ? 'unselect' : 'select';
SupersetClient.get({
endpoint: `/superset/favstar/${
type === 'chart' ? FavStarClassName.CHART : FavStarClassName.DASHBOARD
}/${id}/${urlSuffix}/`,
}).then(
({ json }) => {
updateFavoriteStatus({
[id]: (json as { count: number })?.count > 0,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error saving the favorite status: %s', errMsg),
),
),
);
},
[type],
);
return [saveFaveStar, favoriteStatus] as const;
}
export const useChartEditModal = (
setCharts: (charts: Array<Chart>) => void,
charts: Array<Chart>,
) => {
const [
sliceCurrentlyEditing,
setSliceCurrentlyEditing,
] = useState<Slice | null>(null);
function openChartEditModal(chart: Chart) {
setSliceCurrentlyEditing({
slice_id: chart.id,
slice_name: chart.slice_name,
description: chart.description,
cache_timeout: chart.cache_timeout,
});
}
function closeChartEditModal() {
setSliceCurrentlyEditing(null);
}
function handleChartUpdated(edits: Chart) {
// update the chart in our state with the edited info
const newCharts = charts.map((chart: Chart) =>
chart.id === edits.id ? { ...chart, ...edits } : chart,
);
setCharts(newCharts);
}
return {
sliceCurrentlyEditing,
handleChartUpdated,
openChartEditModal,
closeChartEditModal,
};
};
export const copyQueryLink = (
id: number,
addDangerToast: (arg0: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
copyTextToClipboard(
`${window.location.origin}/superset/sqllab?savedQueryId=${id}`,
)
.then(() => {
addSuccessToast(t('Link Copied!'));
})
.catch(() => {
addDangerToast(t('Sorry, your browser does not support copying.'));
});
};
export const testDatabaseConnection = (
connection: DatabaseObject,
handleErrorMsg: (errorMsg: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
SupersetClient.post({
endpoint: 'api/v1/database/test_connection',
body: JSON.stringify(connection),
headers: { 'Content-Type': 'application/json' },
}).then(
() => {
addSuccessToast(t('Connection looks good!'));
},
createErrorHandler((errMsg: Record<string, string[]> | string) => {
handleErrorMsg(t(`${t('ERROR: ')}${parsedErrorMessage(errMsg)}`));
}),
);
};
| superset-frontend/src/views/CRUD/hooks.ts | 1 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.9990026354789734,
0.09943942725658417,
0.00016559385403525084,
0.0001998936932068318,
0.290982723236084
] |
{
"id": 0,
"code_window": [
" bulkSelectEnabled: boolean;\n",
" lastFetched?: string;\n",
"}\n",
"\n",
"const parsedErrorMessage = (\n",
" errorMessage: Record<string, string[]> | string,\n",
") => {\n",
" if (typeof errorMessage === 'string') {\n",
" return errorMessage;\n",
" }\n",
" return Object.entries(errorMessage)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" errorMessage: Record<string, string[] | string> | string,\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 React from 'react';
import PropTypes from 'prop-types';
import { Dropdown } from 'src/components/Dropdown';
import { EditableTabs } from 'src/components/Tabs';
import { Menu } from 'src/common/components';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import URI from 'urijs';
import { styled, t } from '@superset-ui/core';
import { isFeatureEnabled, FeatureFlag } from 'src/featureFlags';
import { areArraysShallowEqual } from 'src/reduxUtils';
import { Tooltip } from 'src/components/Tooltip';
import { detectOS } from 'src/utils/common';
import * as Actions from '../actions/sqlLab';
import SqlEditor from './SqlEditor';
import TabStatusIcon from './TabStatusIcon';
const propTypes = {
actions: PropTypes.object.isRequired,
defaultDbId: PropTypes.number,
displayLimit: PropTypes.number,
defaultQueryLimit: PropTypes.number.isRequired,
maxRow: PropTypes.number.isRequired,
databases: PropTypes.object.isRequired,
queries: PropTypes.object.isRequired,
queryEditors: PropTypes.array,
requestedQuery: PropTypes.object,
tabHistory: PropTypes.array.isRequired,
tables: PropTypes.array.isRequired,
offline: PropTypes.bool,
saveQueryWarning: PropTypes.string,
scheduleQueryWarning: PropTypes.string,
};
const defaultProps = {
queryEditors: [],
offline: false,
requestedQuery: null,
saveQueryWarning: null,
scheduleQueryWarning: null,
};
let queryCount = 1;
const TabTitleWrapper = styled.div`
display: flex;
align-items: center;
`;
const TabTitle = styled.span`
margin-right: ${({ theme }) => theme.gridUnit * 2}px;
text-transform: none;
`;
// Get the user's OS
const userOS = detectOS();
class TabbedSqlEditors extends React.PureComponent {
constructor(props) {
super(props);
const sqlLabUrl = '/superset/sqllab';
this.state = {
sqlLabUrl,
queriesArray: [],
dataPreviewQueries: [],
};
this.removeQueryEditor = this.removeQueryEditor.bind(this);
this.renameTab = this.renameTab.bind(this);
this.toggleLeftBar = this.toggleLeftBar.bind(this);
this.removeAllOtherQueryEditors = this.removeAllOtherQueryEditors.bind(
this,
);
this.duplicateQueryEditor = this.duplicateQueryEditor.bind(this);
this.handleSelect = this.handleSelect.bind(this);
this.handleEdit = this.handleEdit.bind(this);
}
componentDidMount() {
// migrate query editor and associated tables state to server
if (isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)) {
const localStorageTables = this.props.tables.filter(
table => table.inLocalStorage,
);
const localStorageQueries = Object.values(this.props.queries).filter(
query => query.inLocalStorage,
);
this.props.queryEditors
.filter(qe => qe.inLocalStorage)
.forEach(qe => {
// get all queries associated with the query editor
const queries = localStorageQueries.filter(
query => query.sqlEditorId === qe.id,
);
const tables = localStorageTables.filter(
table => table.queryEditorId === qe.id,
);
this.props.actions.migrateQueryEditorFromLocalStorage(
qe,
tables,
queries,
);
});
}
// merge post form data with GET search params
// Hack: this data should be comming from getInitialState
// but for some reason this data isn't being passed properly through
// the reducer.
const appContainer = document.getElementById('app');
const bootstrapData = JSON.parse(
appContainer?.getAttribute('data-bootstrap') || '{}',
);
const query = {
...bootstrapData.requested_query,
...URI(window.location).search(true),
};
// Popping a new tab based on the querystring
if (
query.id ||
query.sql ||
query.savedQueryId ||
query.datasourceKey ||
query.queryId
) {
if (query.id) {
this.props.actions.popStoredQuery(query.id);
} else if (query.savedQueryId) {
this.props.actions.popSavedQuery(query.savedQueryId);
} else if (query.queryId) {
this.props.actions.popQuery(query.queryId);
} else if (query.datasourceKey) {
this.props.actions.popDatasourceQuery(query.datasourceKey, query.sql);
} else if (query.sql) {
let dbId = query.dbid;
if (dbId) {
dbId = parseInt(dbId, 10);
} else {
const { databases } = this.props;
const dbName = query.dbname;
if (dbName) {
Object.keys(databases).forEach(db => {
if (databases[db].database_name === dbName) {
dbId = databases[db].id;
}
});
}
}
const newQueryEditor = {
title: query.title,
dbId,
schema: query.schema,
autorun: query.autorun,
sql: query.sql,
};
this.props.actions.addQueryEditor(newQueryEditor);
}
this.popNewTab();
} else if (query.new || this.props.queryEditors.length === 0) {
this.newQueryEditor();
if (query.new) {
window.history.replaceState({}, document.title, this.state.sqlLabUrl);
}
} else {
const qe = this.activeQueryEditor();
const latestQuery = this.props.queries[qe.latestQueryId];
if (
isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE) &&
latestQuery &&
latestQuery.resultsKey
) {
// when results are not stored in localStorage they need to be
// fetched from the results backend (if configured)
this.props.actions.fetchQueryResults(
latestQuery,
this.props.displayLimit,
);
}
}
}
UNSAFE_componentWillReceiveProps(nextProps) {
const nextActiveQeId =
nextProps.tabHistory[nextProps.tabHistory.length - 1];
const queriesArray = Object.values(nextProps.queries).filter(
query => query.sqlEditorId === nextActiveQeId,
);
if (!areArraysShallowEqual(queriesArray, this.state.queriesArray)) {
this.setState({ queriesArray });
}
const dataPreviewQueries = [];
nextProps.tables.forEach(table => {
const queryId = table.dataPreviewQueryId;
if (
queryId &&
nextProps.queries[queryId] &&
table.queryEditorId === nextActiveQeId
) {
dataPreviewQueries.push({
...nextProps.queries[queryId],
tableName: table.name,
});
}
});
if (
!areArraysShallowEqual(dataPreviewQueries, this.state.dataPreviewQueries)
) {
this.setState({ dataPreviewQueries });
}
}
popNewTab() {
queryCount += 1;
// Clean the url in browser history
window.history.replaceState({}, document.title, this.state.sqlLabUrl);
}
renameTab(qe) {
/* eslint no-alert: 0 */
const newTitle = prompt(t('Enter a new title for the tab'));
if (newTitle) {
this.props.actions.queryEditorSetTitle(qe, newTitle);
}
}
activeQueryEditor() {
if (this.props.tabHistory.length === 0) {
return this.props.queryEditors[0];
}
const qeid = this.props.tabHistory[this.props.tabHistory.length - 1];
return this.props.queryEditors.find(qe => qe.id === qeid) || null;
}
newQueryEditor() {
queryCount += 1;
const activeQueryEditor = this.activeQueryEditor();
const firstDbId = Math.min(
...Object.values(this.props.databases).map(database => database.id),
);
const warning = isFeatureEnabled(FeatureFlag.SQLLAB_BACKEND_PERSISTENCE)
? ''
: `${t(
'-- Note: Unless you save your query, these tabs will NOT persist if you clear your cookies or change browsers.',
)}\n\n`;
const qe = {
title: t('Untitled Query %s', queryCount),
dbId:
activeQueryEditor && activeQueryEditor.dbId
? activeQueryEditor.dbId
: this.props.defaultDbId || firstDbId,
schema: activeQueryEditor ? activeQueryEditor.schema : null,
autorun: false,
sql: `${warning}SELECT ...`,
queryLimit: this.props.defaultQueryLimit,
};
this.props.actions.addQueryEditor(qe);
}
handleSelect(key) {
const qeid = this.props.tabHistory[this.props.tabHistory.length - 1];
if (key !== qeid) {
const queryEditor = this.props.queryEditors.find(qe => qe.id === key);
this.props.actions.switchQueryEditor(
queryEditor,
this.props.displayLimit,
);
}
}
handleEdit(key, action) {
if (action === 'remove') {
const qe = this.props.queryEditors.find(qe => qe.id === key);
this.removeQueryEditor(qe);
}
if (action === 'add') {
this.newQueryEditor();
}
}
removeQueryEditor(qe) {
this.props.actions.removeQueryEditor(qe);
}
removeAllOtherQueryEditors(cqe) {
this.props.queryEditors.forEach(
qe => qe !== cqe && this.removeQueryEditor(qe),
);
}
duplicateQueryEditor(qe) {
this.props.actions.cloneQueryToNewTab(qe, false);
}
toggleLeftBar(qe) {
this.props.actions.toggleLeftBar(qe);
}
render() {
const editors = this.props.queryEditors.map(qe => {
let latestQuery;
if (qe.latestQueryId) {
latestQuery = this.props.queries[qe.latestQueryId];
}
let database;
if (qe.dbId) {
database = this.props.databases[qe.dbId];
}
const state = latestQuery ? latestQuery.state : '';
const menu = (
<Menu style={{ width: 176 }}>
<Menu.Item
className="close-btn"
key="1"
onClick={() => this.removeQueryEditor(qe)}
data-test="close-tab-menu-option"
>
<div className="icon-container">
<i className="fa fa-close" />
</div>
{t('Close tab')}
</Menu.Item>
<Menu.Item key="2" onClick={() => this.renameTab(qe)}>
<div className="icon-container">
<i className="fa fa-i-cursor" />
</div>
{t('Rename tab')}
</Menu.Item>
<Menu.Item key="3" onClick={() => this.toggleLeftBar(qe)}>
<div className="icon-container">
<i className="fa fa-cogs" />
</div>
{qe.hideLeftBar ? t('Expand tool bar') : t('Hide tool bar')}
</Menu.Item>
<Menu.Item
key="4"
onClick={() => this.removeAllOtherQueryEditors(qe)}
>
<div className="icon-container">
<i className="fa fa-times-circle-o" />
</div>
{t('Close all other tabs')}
</Menu.Item>
<Menu.Item key="5" onClick={() => this.duplicateQueryEditor(qe)}>
<div className="icon-container">
<i className="fa fa-files-o" />
</div>
{t('Duplicate tab')}
</Menu.Item>
</Menu>
);
const tabHeader = (
<TabTitleWrapper>
<div data-test="dropdown-toggle-button">
<Dropdown overlay={menu} trigger={['click']} />
</div>
<TabTitle>{qe.title}</TabTitle> <TabStatusIcon tabState={state} />{' '}
</TabTitleWrapper>
);
return (
<EditableTabs.TabPane
key={qe.id}
tab={tabHeader}
// for tests - key prop isn't handled by enzyme well bcs it's a react keyword
data-key={qe.id}
>
<SqlEditor
tables={this.props.tables.filter(xt => xt.queryEditorId === qe.id)}
queryEditorId={qe.id}
editorQueries={this.state.queriesArray}
dataPreviewQueries={this.state.dataPreviewQueries}
latestQuery={latestQuery}
database={database}
actions={this.props.actions}
hideLeftBar={qe.hideLeftBar}
defaultQueryLimit={this.props.defaultQueryLimit}
maxRow={this.props.maxRow}
displayLimit={this.props.displayLimit}
saveQueryWarning={this.props.saveQueryWarning}
scheduleQueryWarning={this.props.scheduleQueryWarning}
/>
</EditableTabs.TabPane>
);
});
return (
<EditableTabs
activeKey={this.props.tabHistory[this.props.tabHistory.length - 1]}
id="a11y-query-editor-tabs"
className="SqlEditorTabs"
data-test="sql-editor-tabs"
onChange={this.handleSelect}
fullWidth={false}
hideAdd={this.props.offline}
onEdit={this.handleEdit}
addIcon={
<Tooltip
id="add-tab"
placement="bottom"
title={
userOS === 'Windows'
? t('New tab (Ctrl + q)')
: t('New tab (Ctrl + t)')
}
>
<i data-test="add-tab-icon" className="fa fa-plus-circle" />
</Tooltip>
}
>
{editors}
</EditableTabs>
);
}
}
TabbedSqlEditors.propTypes = propTypes;
TabbedSqlEditors.defaultProps = defaultProps;
function mapStateToProps({ sqlLab, common, requestedQuery }) {
return {
databases: sqlLab.databases,
queryEditors: sqlLab.queryEditors,
queries: sqlLab.queries,
tabHistory: sqlLab.tabHistory,
tables: sqlLab.tables,
defaultDbId: sqlLab.defaultDbId,
displayLimit: common.conf.DISPLAY_MAX_ROW,
offline: sqlLab.offline,
defaultQueryLimit: common.conf.DEFAULT_SQLLAB_LIMIT,
maxRow: common.conf.SQL_MAX_ROW,
saveQueryWarning: common.conf.SQLLAB_SAVE_WARNING_MESSAGE,
scheduleQueryWarning: common.conf.SQLLAB_SCHEDULE_WARNING_MESSAGE,
requestedQuery,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(Actions, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(TabbedSqlEditors);
| superset-frontend/src/SqlLab/components/TabbedSqlEditors.jsx | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00020464950648602098,
0.00017199479043483734,
0.0001660413108766079,
0.00017006800044327974,
0.000006872718131489819
] |
{
"id": 0,
"code_window": [
" bulkSelectEnabled: boolean;\n",
" lastFetched?: string;\n",
"}\n",
"\n",
"const parsedErrorMessage = (\n",
" errorMessage: Record<string, string[]> | string,\n",
") => {\n",
" if (typeof errorMessage === 'string') {\n",
" return errorMessage;\n",
" }\n",
" return Object.entries(errorMessage)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" errorMessage: Record<string, string[] | string> | string,\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 41
} | ---
name: Amazon Redshift
menu: Connecting to Databases
route: /docs/databases/redshift
index: 3
version: 1
---
## AWS Redshift
The [sqlalchemy-redshift](https://pypi.org/project/sqlalchemy-redshift/) library is the recommended
way to connect to Redshift through SQLAlchemy.
You'll need to the following setting values to form the connection string:
- **User Name**: userName
- **Password**: DBPassword
- **Database Host**: AWS Endpoint
- **Database Name**: Database Name
- **Port**: default 5439
Here's what the connection string looks like:
```
redshift+psycopg2://<userName>:<DBPassword>@<AWS End Point>:5439/<Database Name>
```
| docs/src/pages/docs/Connecting to Databases/redshift.mdx | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00016749376663938165,
0.00016582735406700522,
0.00016466395754832774,
0.00016532438166905195,
0.0000012087739378330298
] |
{
"id": 0,
"code_window": [
" bulkSelectEnabled: boolean;\n",
" lastFetched?: string;\n",
"}\n",
"\n",
"const parsedErrorMessage = (\n",
" errorMessage: Record<string, string[]> | string,\n",
") => {\n",
" if (typeof errorMessage === 'string') {\n",
" return errorMessage;\n",
" }\n",
" return Object.entries(errorMessage)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" errorMessage: Record<string, string[] | string> | string,\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 React from 'react';
import { useStaticQuery, graphql } from 'gatsby';
import Img from 'gatsby-image';
interface Props {
imageName?: string;
width?: string;
height?: string;
otherProps?: any;
}
const Image = ({
imageName, width, height, ...otherProps
}: Props) => {
const data = useStaticQuery(graphql`
query {
logoSm: file(relativePath: { eq: "src/images/s.png" }) {
childImageSharp {
fixed(height: 30) {
...GatsbyImageSharpFixed
}
}
}
logoLg: file(relativePath: { eq: "src/images/s.png" }) {
childImageSharp {
fixed(width: 150) {
...GatsbyImageSharpFixed
}
}
}
stackoverflow: file(
relativePath: { eq: "src/images/stack_overflow.png" }
) {
childImageSharp {
fixed(width: 60) {
...GatsbyImageSharpFixed
}
}
}
docker: file(relativePath: { eq: "src/images/docker.png" }) {
childImageSharp {
fixed(width: 100) {
...GatsbyImageSharpFixed
}
}
}
preset: file(relativePath: { eq: "src/images/preset.png" }) {
childImageSharp {
fixed(width: 100) {
...GatsbyImageSharpFixed
}
}
}
}
`);
return <Img fixed={data[imageName]?.childImageSharp?.fixed} {...otherProps} />;
};
export default Image;
| docs/src/components/image.tsx | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.0001777188736014068,
0.00017461084644310176,
0.00017156270041596144,
0.00017480399401392788,
0.0000015984458059392637
] |
{
"id": 1,
"code_window": [
" return errorMessage;\n",
" }\n",
" return Object.entries(errorMessage)\n",
" .map(([key, value]) => `(${key}) ${value.join(', ')}`)\n",
" .join('\\n');\n",
"};\n",
"\n",
"export function useListViewResource<D extends object = any>(\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .map(([key, value]) => {\n",
" if (Array.isArray(value)) {\n",
" return `(${key}) ${value.join(', ')}`;\n",
" }\n",
" return `(${key}) ${value}`;\n",
" })\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 47
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 rison from 'rison';
import { useState, useEffect, useCallback } from 'react';
import { makeApi, SupersetClient, t } from '@superset-ui/core';
import { createErrorHandler } from 'src/views/CRUD/utils';
import { FetchDataConfig } from 'src/components/ListView';
import { FilterValue } from 'src/components/ListView/types';
import Chart, { Slice } from 'src/types/Chart';
import copyTextToClipboard from 'src/utils/copy';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import { FavoriteStatus, ImportResourceName, DatabaseObject } from './types';
interface ListViewResourceState<D extends object = any> {
loading: boolean;
collection: D[];
count: number;
permissions: string[];
lastFetchDataConfig: FetchDataConfig | null;
bulkSelectEnabled: boolean;
lastFetched?: string;
}
const parsedErrorMessage = (
errorMessage: Record<string, string[]> | string,
) => {
if (typeof errorMessage === 'string') {
return errorMessage;
}
return Object.entries(errorMessage)
.map(([key, value]) => `(${key}) ${value.join(', ')}`)
.join('\n');
};
export function useListViewResource<D extends object = any>(
resource: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
infoEnable = true,
defaultCollectionValue: D[] = [],
baseFilters?: FilterValue[], // must be memoized
initialLoadingState = true,
) {
const [state, setState] = useState<ListViewResourceState<D>>({
count: 0,
collection: defaultCollectionValue,
loading: initialLoadingState,
lastFetchDataConfig: null,
permissions: [],
bulkSelectEnabled: false,
});
function updateState(update: Partial<ListViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
function toggleBulkSelect() {
updateState({ bulkSelectEnabled: !state.bulkSelectEnabled });
}
useEffect(() => {
if (!infoEnable) return;
SupersetClient.get({
endpoint: `/api/v1/${resource}/_info?q=${rison.encode({
keys: ['permissions'],
})}`,
}).then(
({ json: infoJson = {} }) => {
updateState({
permissions: infoJson.permissions,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %s info: %s',
resourceLabel,
errMsg,
),
),
),
);
}, []);
function hasPerm(perm: string) {
if (!state.permissions.length) {
return false;
}
return Boolean(state.permissions.find(p => p === perm));
}
const fetchData = useCallback(
({
pageIndex,
pageSize,
sortBy,
filters: filterValues,
}: FetchDataConfig) => {
// set loading state, cache the last config for refreshing data.
updateState({
lastFetchDataConfig: {
filters: filterValues,
pageIndex,
pageSize,
sortBy,
},
loading: true,
});
const filterExps = (baseFilters || [])
.concat(filterValues)
.map(({ id, operator: opr, value }) => ({
col: id,
opr,
value,
}));
const queryParams = rison.encode({
order_column: sortBy[0].id,
order_direction: sortBy[0].desc ? 'desc' : 'asc',
page: pageIndex,
page_size: pageSize,
...(filterExps.length ? { filters: filterExps } : {}),
});
return SupersetClient.get({
endpoint: `/api/v1/${resource}/?q=${queryParams}`,
})
.then(
({ json = {} }) => {
updateState({
collection: json.result,
count: json.count,
lastFetched: new Date().toISOString(),
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
errMsg,
),
),
),
)
.finally(() => {
updateState({ loading: false });
});
},
[baseFilters],
);
return {
state: {
loading: state.loading,
resourceCount: state.count,
resourceCollection: state.collection,
bulkSelectEnabled: state.bulkSelectEnabled,
lastFetched: state.lastFetched,
},
setResourceCollection: (update: D[]) =>
updateState({
collection: update,
}),
hasPerm,
fetchData,
toggleBulkSelect,
refreshData: (provideConfig?: FetchDataConfig) => {
if (state.lastFetchDataConfig) {
return fetchData(state.lastFetchDataConfig);
}
if (provideConfig) {
return fetchData(provideConfig);
}
return null;
},
};
}
// In the same vein as above, a hook for viewing a single instance of a resource (given id)
interface SingleViewResourceState<D extends object = any> {
loading: boolean;
resource: D | null;
error: string | Record<string, string[]> | null;
}
export function useSingleViewResource<D extends object = any>(
resourceName: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<SingleViewResourceState<D>>({
loading: false,
resource: null,
error: null,
});
function updateState(update: Partial<SingleViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
const fetchResource = useCallback(
(resourceID: number) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.get({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const createResource = useCallback(
(resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.id;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while creating %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const updateResource = useCallback(
(resourceID: number, resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.put({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler(errMsg => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
JSON.stringify(errMsg),
),
);
updateState({
error: errMsg,
});
return errMsg;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const clearError = () =>
updateState({
error: null,
});
return {
state,
setResource: (update: D) =>
updateState({
resource: update,
}),
fetchResource,
createResource,
updateResource,
clearError,
};
}
interface ImportResourceState {
loading: boolean;
passwordsNeeded: string[];
alreadyExists: string[];
}
export function useImportResource(
resourceName: ImportResourceName,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<ImportResourceState>({
loading: false,
passwordsNeeded: [],
alreadyExists: [],
});
function updateState(update: Partial<ImportResourceState>) {
setState(currentState => ({ ...currentState, ...update }));
}
/* eslint-disable no-underscore-dangle */
const isNeedsPassword = (payload: any) =>
typeof payload === 'object' &&
Array.isArray(payload._schema) &&
payload._schema.length === 1 &&
payload._schema[0] === 'Must provide a password for the database';
const isAlreadyExists = (payload: any) =>
typeof payload === 'string' &&
payload.includes('already exists and `overwrite=true` was not passed');
const getPasswordsNeeded = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isNeedsPassword(validationErrors))
.map(([fileName]) => fileName);
const getAlreadyExists = (errMsg: Record<string, Record<string, string[]>>) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isAlreadyExists(validationErrors))
.map(([fileName]) => fileName);
const hasTerminalValidation = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.values(errMsg).some(
validationErrors =>
!isNeedsPassword(validationErrors) &&
!isAlreadyExists(validationErrors),
);
const importResource = useCallback(
(
bundle: File,
databasePasswords: Record<string, string> = {},
overwrite = false,
) => {
// Set loading state
updateState({
loading: true,
});
const formData = new FormData();
formData.append('formData', bundle);
/* The import bundle never contains database passwords; if required
* they should be provided by the user during import.
*/
if (databasePasswords) {
formData.append('passwords', JSON.stringify(databasePasswords));
}
/* If the imported model already exists the user needs to confirm
* that they want to overwrite it.
*/
if (overwrite) {
formData.append('overwrite', 'true');
}
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/import/`,
body: formData,
})
.then(() => true)
.catch(response =>
getClientErrorObject(response).then(error => {
const errMsg = error.message || error.error;
if (typeof errMsg === 'string') {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
return false;
}
if (hasTerminalValidation(errMsg)) {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
} else {
updateState({
passwordsNeeded: getPasswordsNeeded(errMsg),
alreadyExists: getAlreadyExists(errMsg),
});
}
return false;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[],
);
return { state, importResource };
}
enum FavStarClassName {
CHART = 'slice',
DASHBOARD = 'Dashboard',
}
type FavoriteStatusResponse = {
result: Array<{
id: string;
value: boolean;
}>;
};
const favoriteApis = {
chart: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/chart/favorite_status/',
}),
dashboard: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/dashboard/favorite_status/',
}),
};
export function useFavoriteStatus(
type: 'chart' | 'dashboard',
ids: Array<string | number>,
handleErrorMsg: (message: string) => void,
) {
const [favoriteStatus, setFavoriteStatus] = useState<FavoriteStatus>({});
const updateFavoriteStatus = (update: FavoriteStatus) =>
setFavoriteStatus(currentState => ({ ...currentState, ...update }));
useEffect(() => {
if (!ids.length) {
return;
}
favoriteApis[type](ids).then(
({ result }) => {
const update = result.reduce((acc, element) => {
acc[element.id] = element.value;
return acc;
}, {});
updateFavoriteStatus(update);
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error fetching the favorite status: %s', errMsg),
),
),
);
}, [ids, type, handleErrorMsg]);
const saveFaveStar = useCallback(
(id: number, isStarred: boolean) => {
const urlSuffix = isStarred ? 'unselect' : 'select';
SupersetClient.get({
endpoint: `/superset/favstar/${
type === 'chart' ? FavStarClassName.CHART : FavStarClassName.DASHBOARD
}/${id}/${urlSuffix}/`,
}).then(
({ json }) => {
updateFavoriteStatus({
[id]: (json as { count: number })?.count > 0,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error saving the favorite status: %s', errMsg),
),
),
);
},
[type],
);
return [saveFaveStar, favoriteStatus] as const;
}
export const useChartEditModal = (
setCharts: (charts: Array<Chart>) => void,
charts: Array<Chart>,
) => {
const [
sliceCurrentlyEditing,
setSliceCurrentlyEditing,
] = useState<Slice | null>(null);
function openChartEditModal(chart: Chart) {
setSliceCurrentlyEditing({
slice_id: chart.id,
slice_name: chart.slice_name,
description: chart.description,
cache_timeout: chart.cache_timeout,
});
}
function closeChartEditModal() {
setSliceCurrentlyEditing(null);
}
function handleChartUpdated(edits: Chart) {
// update the chart in our state with the edited info
const newCharts = charts.map((chart: Chart) =>
chart.id === edits.id ? { ...chart, ...edits } : chart,
);
setCharts(newCharts);
}
return {
sliceCurrentlyEditing,
handleChartUpdated,
openChartEditModal,
closeChartEditModal,
};
};
export const copyQueryLink = (
id: number,
addDangerToast: (arg0: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
copyTextToClipboard(
`${window.location.origin}/superset/sqllab?savedQueryId=${id}`,
)
.then(() => {
addSuccessToast(t('Link Copied!'));
})
.catch(() => {
addDangerToast(t('Sorry, your browser does not support copying.'));
});
};
export const testDatabaseConnection = (
connection: DatabaseObject,
handleErrorMsg: (errorMsg: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
SupersetClient.post({
endpoint: 'api/v1/database/test_connection',
body: JSON.stringify(connection),
headers: { 'Content-Type': 'application/json' },
}).then(
() => {
addSuccessToast(t('Connection looks good!'));
},
createErrorHandler((errMsg: Record<string, string[]> | string) => {
handleErrorMsg(t(`${t('ERROR: ')}${parsedErrorMessage(errMsg)}`));
}),
);
};
| superset-frontend/src/views/CRUD/hooks.ts | 1 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.9984087347984314,
0.04793034866452217,
0.00016261370910797268,
0.00017037591896951199,
0.21020358800888062
] |
{
"id": 1,
"code_window": [
" return errorMessage;\n",
" }\n",
" return Object.entries(errorMessage)\n",
" .map(([key, value]) => `(${key}) ${value.join(', ')}`)\n",
" .join('\\n');\n",
"};\n",
"\n",
"export function useListViewResource<D extends object = any>(\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .map(([key, value]) => {\n",
" if (Array.isArray(value)) {\n",
" return `(${key}) ${value.join(', ')}`;\n",
" }\n",
" return `(${key}) ${value}`;\n",
" })\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 47
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# isort:skip_file
import json
from tests.fixtures.world_bank_dashboard import load_world_bank_dashboard_with_slices
import pytest
from flask_appbuilder.models.sqla.interface import SQLAInterface
import prison
import tests.test_app
from superset import db, security_manager
from superset.extensions import appbuilder
from superset.models.dashboard import Dashboard
from superset.views.base_api import BaseSupersetModelRestApi
from .base_tests import SupersetTestCase
class Model1Api(BaseSupersetModelRestApi):
datamodel = SQLAInterface(Dashboard)
allow_browser_login = True
class_permission_name = "Dashboard"
method_permission_name = {
"get_list": "read",
"get": "read",
"export": "read",
"post": "write",
"put": "write",
"delete": "write",
"bulk_delete": "write",
"info": "read",
"related": "read",
}
appbuilder.add_api(Model1Api)
class TestOpenApiSpec(SupersetTestCase):
def test_open_api_spec(self):
"""
API: Test validate OpenAPI spec
:return:
"""
from openapi_spec_validator import validate_spec
self.login(username="admin")
uri = "api/v1/_openapi"
rv = self.client.get(uri)
self.assertEqual(rv.status_code, 200)
response = json.loads(rv.data.decode("utf-8"))
validate_spec(response)
class TestBaseModelRestApi(SupersetTestCase):
@pytest.mark.usefixtures("load_world_bank_dashboard_with_slices")
def test_default_missing_declaration_get(self):
"""
API: Test default missing declaration on get
We want to make sure that not declared list_columns will
not render all columns by default but just the model's pk
"""
# Check get list response
self.login(username="admin")
uri = "api/v1/model1api/"
rv = self.client.get(uri)
self.assertEqual(rv.status_code, 200)
response = json.loads(rv.data.decode("utf-8"))
self.assertEqual(response["list_columns"], ["id"])
for result in response["result"]:
self.assertEqual(list(result.keys()), ["id"])
# Check get response
dashboard = db.session.query(Dashboard).first()
uri = f"api/v1/model1api/{dashboard.id}"
rv = self.client.get(uri)
self.assertEqual(rv.status_code, 200)
response = json.loads(rv.data.decode("utf-8"))
self.assertEqual(response["show_columns"], ["id"])
self.assertEqual(list(response["result"].keys()), ["id"])
def test_default_missing_declaration_put_spec(self):
"""
API: Test default missing declaration on put openapi spec
We want to make sure that not declared edit_columns will
not render all columns by default but just the model's pk
"""
self.login(username="admin")
uri = "api/v1/_openapi"
rv = self.client.get(uri)
# dashboard model accepts all fields are null
self.assertEqual(rv.status_code, 200)
response = json.loads(rv.data.decode("utf-8"))
expected_mutation_spec = {
"properties": {"id": {"format": "int32", "type": "integer"}},
"type": "object",
}
self.assertEqual(
response["components"]["schemas"]["Model1Api.post"], expected_mutation_spec
)
self.assertEqual(
response["components"]["schemas"]["Model1Api.put"], expected_mutation_spec
)
def test_default_missing_declaration_post(self):
"""
API: Test default missing declaration on post
We want to make sure that not declared add_columns will
not accept all columns by default
"""
dashboard_data = {
"dashboard_title": "title1",
"slug": "slug1",
"position_json": '{"a": "A"}',
"css": "css",
"json_metadata": '{"b": "B"}',
"published": True,
}
self.login(username="admin")
uri = "api/v1/model1api/"
rv = self.client.post(uri, json=dashboard_data)
response = json.loads(rv.data.decode("utf-8"))
self.assertEqual(rv.status_code, 422)
expected_response = {
"message": {
"css": ["Unknown field."],
"dashboard_title": ["Unknown field."],
"json_metadata": ["Unknown field."],
"position_json": ["Unknown field."],
"published": ["Unknown field."],
"slug": ["Unknown field."],
}
}
self.assertEqual(response, expected_response)
@pytest.mark.usefixtures("load_world_bank_dashboard_with_slices")
def test_default_missing_declaration_put(self):
"""
API: Test default missing declaration on put
We want to make sure that not declared edit_columns will
not accept all columns by default
"""
dashboard = db.session.query(Dashboard).first()
dashboard_data = {"dashboard_title": "CHANGED", "slug": "CHANGED"}
self.login(username="admin")
uri = f"api/v1/model1api/{dashboard.id}"
rv = self.client.put(uri, json=dashboard_data)
response = json.loads(rv.data.decode("utf-8"))
self.assertEqual(rv.status_code, 422)
expected_response = {
"message": {
"dashboard_title": ["Unknown field."],
"slug": ["Unknown field."],
}
}
self.assertEqual(response, expected_response)
class ApiOwnersTestCaseMixin:
"""
Implements shared tests for owners related field
"""
resource_name: str = ""
def test_get_related_owners(self):
"""
API: Test get related owners
"""
self.login(username="admin")
uri = f"api/v1/{self.resource_name}/related/owners"
rv = self.client.get(uri)
assert rv.status_code == 200
response = json.loads(rv.data.decode("utf-8"))
users = db.session.query(security_manager.user_model).all()
expected_users = [str(user) for user in users]
assert response["count"] == len(users)
# This needs to be implemented like this, because ordering varies between
# postgres and mysql
response_users = [result["text"] for result in response["result"]]
for expected_user in expected_users:
assert expected_user in response_users
def test_get_filter_related_owners(self):
"""
API: Test get filter related owners
"""
self.login(username="admin")
argument = {"filter": "gamma"}
uri = f"api/v1/{self.resource_name}/related/owners?q={prison.dumps(argument)}"
rv = self.client.get(uri)
assert rv.status_code == 200
response = json.loads(rv.data.decode("utf-8"))
assert 3 == response["count"]
sorted_results = sorted(response["result"], key=lambda value: value["text"])
expected_results = [
{"text": "gamma user", "value": 2},
{"text": "gamma2 user", "value": 3},
{"text": "gamma_sqllab user", "value": 4},
]
assert expected_results == sorted_results
def test_get_ids_related_owners(self):
"""
API: Test get filter related owners
"""
self.login(username="admin")
argument = {"filter": "gamma_sqllab", "include_ids": [2]}
uri = f"api/v1/{self.resource_name}/related/owners?q={prison.dumps(argument)}"
rv = self.client.get(uri)
response = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 200
assert 2 == response["count"]
sorted_results = sorted(response["result"], key=lambda value: value["text"])
expected_results = [
{"text": "gamma user", "value": 2},
{"text": "gamma_sqllab user", "value": 4},
]
assert expected_results == sorted_results
def test_get_repeated_ids_related_owners(self):
"""
API: Test get filter related owners
"""
self.login(username="admin")
argument = {"filter": "gamma_sqllab", "include_ids": [2, 4]}
uri = f"api/v1/{self.resource_name}/related/owners?q={prison.dumps(argument)}"
rv = self.client.get(uri)
response = json.loads(rv.data.decode("utf-8"))
assert rv.status_code == 200
assert 2 == response["count"]
sorted_results = sorted(response["result"], key=lambda value: value["text"])
expected_results = [
{"text": "gamma user", "value": 2},
{"text": "gamma_sqllab user", "value": 4},
]
assert expected_results == sorted_results
def test_get_related_fail(self):
"""
API: Test get related fail
"""
self.login(username="admin")
uri = f"api/v1/{self.resource_name}/related/owner"
rv = self.client.get(uri)
assert rv.status_code == 404
| tests/base_api_tests.py | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00022195599740371108,
0.00017435864720027894,
0.00016585871344432235,
0.00017308340466115624,
0.000009653831511968747
] |
{
"id": 1,
"code_window": [
" return errorMessage;\n",
" }\n",
" return Object.entries(errorMessage)\n",
" .map(([key, value]) => `(${key}) ${value.join(', ')}`)\n",
" .join('\\n');\n",
"};\n",
"\n",
"export function useListViewResource<D extends object = any>(\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .map(([key, value]) => {\n",
" if (Array.isArray(value)) {\n",
" return `(${key}) ${value.join(', ')}`;\n",
" }\n",
" return `(${key}) ${value}`;\n",
" })\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 47
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""empty message
Revision ID: c829ff0b37d0
Revises: ('4451805bbaa1', '1d9e835a84f9')
Create Date: 2018-07-22 08:49:48.936117
"""
# revision identifiers, used by Alembic.
revision = "c829ff0b37d0"
down_revision = ("4451805bbaa1", "1d9e835a84f9")
import sqlalchemy as sa
from alembic import op
def upgrade():
pass
def downgrade():
pass
| superset/migrations/versions/c829ff0b37d0_.py | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017647082859184593,
0.00017480937822256237,
0.00017396180192008615,
0.00017440246301703155,
0.0000010080522088173893
] |
{
"id": 1,
"code_window": [
" return errorMessage;\n",
" }\n",
" return Object.entries(errorMessage)\n",
" .map(([key, value]) => `(${key}) ${value.join(', ')}`)\n",
" .join('\\n');\n",
"};\n",
"\n",
"export function useListViewResource<D extends object = any>(\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .map(([key, value]) => {\n",
" if (Array.isArray(value)) {\n",
" return `(${key}) ${value.join(', ')}`;\n",
" }\n",
" return `(${key}) ${value}`;\n",
" })\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 47
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""rename_filter_configuration_in_dashboard_metadata.py
Revision ID: 989bbe479899
Revises: 67da9ef1ef9c
Create Date: 2021-03-24 09:47:21.569508
"""
# revision identifiers, used by Alembic.
revision = "989bbe479899"
down_revision = "67da9ef1ef9c"
import json
from alembic import op
from sqlalchemy import and_, Column, Integer, Text
from sqlalchemy.ext.declarative import declarative_base
from superset import db
Base = declarative_base()
class Dashboard(Base):
"""Declarative class to do query in upgrade"""
__tablename__ = "dashboards"
id = Column(Integer, primary_key=True)
json_metadata = Column(Text)
def upgrade():
bind = op.get_bind()
session = db.Session(bind=bind)
dashboards = (
session.query(Dashboard)
.filter(Dashboard.json_metadata.like('%"filter_configuration"%'))
.all()
)
changes = 0
for dashboard in dashboards:
try:
json_metadata = json.loads(dashboard.json_metadata)
filter_configuration = json_metadata.pop("filter_configuration", None)
if filter_configuration:
changes += 1
json_metadata["native_filter_configuration"] = filter_configuration
dashboard.json_metadata = json.dumps(json_metadata, sort_keys=True)
except Exception as e:
print(e)
print(f"Parsing json_metadata for dashboard {dashboard.id} failed.")
pass
session.commit()
session.close()
print(f"Updated {changes} native filter configurations.")
def downgrade():
bind = op.get_bind()
session = db.Session(bind=bind)
dashboards = (
session.query(Dashboard)
.filter(Dashboard.json_metadata.like('%"native_filter_configuration"%'))
.all()
)
changes = 0
for dashboard in dashboards:
try:
json_metadata = json.loads(dashboard.json_metadata)
native_filter_configuration = json_metadata.pop(
"native_filter_configuration", None
)
if native_filter_configuration:
changes += 1
json_metadata["filter_configuration"] = native_filter_configuration
dashboard.json_metadata = json.dumps(json_metadata, sort_keys=True)
except Exception as e:
print(e)
print(f"Parsing json_metadata for dashboard {dashboard.id} failed.")
pass
session.commit()
session.close()
print(f"Updated {changes} pie chart labels.")
| superset/migrations/versions/989bbe479899_rename_filter_configuration_in_.py | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017647082859184593,
0.00017183709132950753,
0.0001651096681598574,
0.0001725129986880347,
0.0000035288917388243135
] |
{
"id": 2,
"code_window": [
"\n",
"// In the same vein as above, a hook for viewing a single instance of a resource (given id)\n",
"interface SingleViewResourceState<D extends object = any> {\n",
" loading: boolean;\n",
" resource: D | null;\n",
" error: string | Record<string, string[]> | null;\n",
"}\n",
"\n",
"export function useSingleViewResource<D extends object = any>(\n",
" resourceName: string,\n",
" resourceLabel: string, // resourceLabel for translations\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error: string | Record<string, string[] | string> | null;\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 202
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 rison from 'rison';
import { useState, useEffect, useCallback } from 'react';
import { makeApi, SupersetClient, t } from '@superset-ui/core';
import { createErrorHandler } from 'src/views/CRUD/utils';
import { FetchDataConfig } from 'src/components/ListView';
import { FilterValue } from 'src/components/ListView/types';
import Chart, { Slice } from 'src/types/Chart';
import copyTextToClipboard from 'src/utils/copy';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import { FavoriteStatus, ImportResourceName, DatabaseObject } from './types';
interface ListViewResourceState<D extends object = any> {
loading: boolean;
collection: D[];
count: number;
permissions: string[];
lastFetchDataConfig: FetchDataConfig | null;
bulkSelectEnabled: boolean;
lastFetched?: string;
}
const parsedErrorMessage = (
errorMessage: Record<string, string[]> | string,
) => {
if (typeof errorMessage === 'string') {
return errorMessage;
}
return Object.entries(errorMessage)
.map(([key, value]) => `(${key}) ${value.join(', ')}`)
.join('\n');
};
export function useListViewResource<D extends object = any>(
resource: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
infoEnable = true,
defaultCollectionValue: D[] = [],
baseFilters?: FilterValue[], // must be memoized
initialLoadingState = true,
) {
const [state, setState] = useState<ListViewResourceState<D>>({
count: 0,
collection: defaultCollectionValue,
loading: initialLoadingState,
lastFetchDataConfig: null,
permissions: [],
bulkSelectEnabled: false,
});
function updateState(update: Partial<ListViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
function toggleBulkSelect() {
updateState({ bulkSelectEnabled: !state.bulkSelectEnabled });
}
useEffect(() => {
if (!infoEnable) return;
SupersetClient.get({
endpoint: `/api/v1/${resource}/_info?q=${rison.encode({
keys: ['permissions'],
})}`,
}).then(
({ json: infoJson = {} }) => {
updateState({
permissions: infoJson.permissions,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %s info: %s',
resourceLabel,
errMsg,
),
),
),
);
}, []);
function hasPerm(perm: string) {
if (!state.permissions.length) {
return false;
}
return Boolean(state.permissions.find(p => p === perm));
}
const fetchData = useCallback(
({
pageIndex,
pageSize,
sortBy,
filters: filterValues,
}: FetchDataConfig) => {
// set loading state, cache the last config for refreshing data.
updateState({
lastFetchDataConfig: {
filters: filterValues,
pageIndex,
pageSize,
sortBy,
},
loading: true,
});
const filterExps = (baseFilters || [])
.concat(filterValues)
.map(({ id, operator: opr, value }) => ({
col: id,
opr,
value,
}));
const queryParams = rison.encode({
order_column: sortBy[0].id,
order_direction: sortBy[0].desc ? 'desc' : 'asc',
page: pageIndex,
page_size: pageSize,
...(filterExps.length ? { filters: filterExps } : {}),
});
return SupersetClient.get({
endpoint: `/api/v1/${resource}/?q=${queryParams}`,
})
.then(
({ json = {} }) => {
updateState({
collection: json.result,
count: json.count,
lastFetched: new Date().toISOString(),
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
errMsg,
),
),
),
)
.finally(() => {
updateState({ loading: false });
});
},
[baseFilters],
);
return {
state: {
loading: state.loading,
resourceCount: state.count,
resourceCollection: state.collection,
bulkSelectEnabled: state.bulkSelectEnabled,
lastFetched: state.lastFetched,
},
setResourceCollection: (update: D[]) =>
updateState({
collection: update,
}),
hasPerm,
fetchData,
toggleBulkSelect,
refreshData: (provideConfig?: FetchDataConfig) => {
if (state.lastFetchDataConfig) {
return fetchData(state.lastFetchDataConfig);
}
if (provideConfig) {
return fetchData(provideConfig);
}
return null;
},
};
}
// In the same vein as above, a hook for viewing a single instance of a resource (given id)
interface SingleViewResourceState<D extends object = any> {
loading: boolean;
resource: D | null;
error: string | Record<string, string[]> | null;
}
export function useSingleViewResource<D extends object = any>(
resourceName: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<SingleViewResourceState<D>>({
loading: false,
resource: null,
error: null,
});
function updateState(update: Partial<SingleViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
const fetchResource = useCallback(
(resourceID: number) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.get({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const createResource = useCallback(
(resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.id;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while creating %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const updateResource = useCallback(
(resourceID: number, resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.put({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler(errMsg => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
JSON.stringify(errMsg),
),
);
updateState({
error: errMsg,
});
return errMsg;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const clearError = () =>
updateState({
error: null,
});
return {
state,
setResource: (update: D) =>
updateState({
resource: update,
}),
fetchResource,
createResource,
updateResource,
clearError,
};
}
interface ImportResourceState {
loading: boolean;
passwordsNeeded: string[];
alreadyExists: string[];
}
export function useImportResource(
resourceName: ImportResourceName,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<ImportResourceState>({
loading: false,
passwordsNeeded: [],
alreadyExists: [],
});
function updateState(update: Partial<ImportResourceState>) {
setState(currentState => ({ ...currentState, ...update }));
}
/* eslint-disable no-underscore-dangle */
const isNeedsPassword = (payload: any) =>
typeof payload === 'object' &&
Array.isArray(payload._schema) &&
payload._schema.length === 1 &&
payload._schema[0] === 'Must provide a password for the database';
const isAlreadyExists = (payload: any) =>
typeof payload === 'string' &&
payload.includes('already exists and `overwrite=true` was not passed');
const getPasswordsNeeded = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isNeedsPassword(validationErrors))
.map(([fileName]) => fileName);
const getAlreadyExists = (errMsg: Record<string, Record<string, string[]>>) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isAlreadyExists(validationErrors))
.map(([fileName]) => fileName);
const hasTerminalValidation = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.values(errMsg).some(
validationErrors =>
!isNeedsPassword(validationErrors) &&
!isAlreadyExists(validationErrors),
);
const importResource = useCallback(
(
bundle: File,
databasePasswords: Record<string, string> = {},
overwrite = false,
) => {
// Set loading state
updateState({
loading: true,
});
const formData = new FormData();
formData.append('formData', bundle);
/* The import bundle never contains database passwords; if required
* they should be provided by the user during import.
*/
if (databasePasswords) {
formData.append('passwords', JSON.stringify(databasePasswords));
}
/* If the imported model already exists the user needs to confirm
* that they want to overwrite it.
*/
if (overwrite) {
formData.append('overwrite', 'true');
}
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/import/`,
body: formData,
})
.then(() => true)
.catch(response =>
getClientErrorObject(response).then(error => {
const errMsg = error.message || error.error;
if (typeof errMsg === 'string') {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
return false;
}
if (hasTerminalValidation(errMsg)) {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
} else {
updateState({
passwordsNeeded: getPasswordsNeeded(errMsg),
alreadyExists: getAlreadyExists(errMsg),
});
}
return false;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[],
);
return { state, importResource };
}
enum FavStarClassName {
CHART = 'slice',
DASHBOARD = 'Dashboard',
}
type FavoriteStatusResponse = {
result: Array<{
id: string;
value: boolean;
}>;
};
const favoriteApis = {
chart: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/chart/favorite_status/',
}),
dashboard: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/dashboard/favorite_status/',
}),
};
export function useFavoriteStatus(
type: 'chart' | 'dashboard',
ids: Array<string | number>,
handleErrorMsg: (message: string) => void,
) {
const [favoriteStatus, setFavoriteStatus] = useState<FavoriteStatus>({});
const updateFavoriteStatus = (update: FavoriteStatus) =>
setFavoriteStatus(currentState => ({ ...currentState, ...update }));
useEffect(() => {
if (!ids.length) {
return;
}
favoriteApis[type](ids).then(
({ result }) => {
const update = result.reduce((acc, element) => {
acc[element.id] = element.value;
return acc;
}, {});
updateFavoriteStatus(update);
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error fetching the favorite status: %s', errMsg),
),
),
);
}, [ids, type, handleErrorMsg]);
const saveFaveStar = useCallback(
(id: number, isStarred: boolean) => {
const urlSuffix = isStarred ? 'unselect' : 'select';
SupersetClient.get({
endpoint: `/superset/favstar/${
type === 'chart' ? FavStarClassName.CHART : FavStarClassName.DASHBOARD
}/${id}/${urlSuffix}/`,
}).then(
({ json }) => {
updateFavoriteStatus({
[id]: (json as { count: number })?.count > 0,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error saving the favorite status: %s', errMsg),
),
),
);
},
[type],
);
return [saveFaveStar, favoriteStatus] as const;
}
export const useChartEditModal = (
setCharts: (charts: Array<Chart>) => void,
charts: Array<Chart>,
) => {
const [
sliceCurrentlyEditing,
setSliceCurrentlyEditing,
] = useState<Slice | null>(null);
function openChartEditModal(chart: Chart) {
setSliceCurrentlyEditing({
slice_id: chart.id,
slice_name: chart.slice_name,
description: chart.description,
cache_timeout: chart.cache_timeout,
});
}
function closeChartEditModal() {
setSliceCurrentlyEditing(null);
}
function handleChartUpdated(edits: Chart) {
// update the chart in our state with the edited info
const newCharts = charts.map((chart: Chart) =>
chart.id === edits.id ? { ...chart, ...edits } : chart,
);
setCharts(newCharts);
}
return {
sliceCurrentlyEditing,
handleChartUpdated,
openChartEditModal,
closeChartEditModal,
};
};
export const copyQueryLink = (
id: number,
addDangerToast: (arg0: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
copyTextToClipboard(
`${window.location.origin}/superset/sqllab?savedQueryId=${id}`,
)
.then(() => {
addSuccessToast(t('Link Copied!'));
})
.catch(() => {
addDangerToast(t('Sorry, your browser does not support copying.'));
});
};
export const testDatabaseConnection = (
connection: DatabaseObject,
handleErrorMsg: (errorMsg: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
SupersetClient.post({
endpoint: 'api/v1/database/test_connection',
body: JSON.stringify(connection),
headers: { 'Content-Type': 'application/json' },
}).then(
() => {
addSuccessToast(t('Connection looks good!'));
},
createErrorHandler((errMsg: Record<string, string[]> | string) => {
handleErrorMsg(t(`${t('ERROR: ')}${parsedErrorMessage(errMsg)}`));
}),
);
};
| superset-frontend/src/views/CRUD/hooks.ts | 1 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.9960781931877136,
0.046761609613895416,
0.00016631987818982452,
0.0001943965326063335,
0.18679872155189514
] |
{
"id": 2,
"code_window": [
"\n",
"// In the same vein as above, a hook for viewing a single instance of a resource (given id)\n",
"interface SingleViewResourceState<D extends object = any> {\n",
" loading: boolean;\n",
" resource: D | null;\n",
" error: string | Record<string, string[]> | null;\n",
"}\n",
"\n",
"export function useSingleViewResource<D extends object = any>(\n",
" resourceName: string,\n",
" resourceLabel: string, // resourceLabel for translations\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error: string | Record<string, string[] | string> | null;\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 202
} | {
"extends": "prettier",
"plugins": ["prettier"],
"rules": {
"prefer-template": 2,
"new-cap": 2,
"no-restricted-syntax": 2,
"guard-for-in": 2,
"prefer-arrow-callback": 2,
"func-names": 2,
"react/jsx-no-bind": 2,
"no-confusing-arrow": 2,
"jsx-a11y/no-static-element-interactions": 2,
"jsx-a11y/anchor-has-content": 2,
"react/require-default-props": 2,
"no-plusplus": 2,
"no-mixed-operators": 0,
"no-continue": 2,
"no-bitwise": 2,
"no-multi-assign": 2,
"no-restricted-properties": 2,
"no-prototype-builtins": 2,
"class-methods-use-this": 2,
"import/no-named-as-default": 2,
"react/no-unescaped-entities": 2,
"react/no-string-refs": 2,
"react/jsx-indent": 0,
"prettier/prettier": "error"
}
}
| superset-frontend/spec/javascripts/dashboard/.eslintrc | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017495757492724806,
0.00017340233898721635,
0.0001723801251500845,
0.00017313583521172404,
9.818846820053295e-7
] |
{
"id": 2,
"code_window": [
"\n",
"// In the same vein as above, a hook for viewing a single instance of a resource (given id)\n",
"interface SingleViewResourceState<D extends object = any> {\n",
" loading: boolean;\n",
" resource: D | null;\n",
" error: string | Record<string, string[]> | null;\n",
"}\n",
"\n",
"export function useSingleViewResource<D extends object = any>(\n",
" resourceName: string,\n",
" resourceLabel: string, // resourceLabel for translations\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error: string | Record<string, string[] | string> | null;\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 202
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 { DASHBOARD_LIST } from './dashboard_list.helper';
describe('dashboard filters card view', () => {
beforeEach(() => {
cy.login();
cy.visit(DASHBOARD_LIST);
cy.get('[data-test="card-view"]').click();
});
it('should filter by owners correctly', () => {
// filter by owners
cy.get('.Select__control').first().click();
cy.get('.Select__menu').contains('alpha user').click();
cy.get('[data-test="styled-card"]').should('not.exist');
cy.get('.Select__control').first().click();
cy.get('.Select__menu').contains('gamma user').click();
cy.get('[data-test="styled-card"]').should('not.exist');
});
it('should filter by me correctly', () => {
// filter by me
cy.get('.Select__control').first().click();
cy.get('.Select__menu').contains('me').click();
cy.get('[data-test="styled-card"]').its('length').should('be.gt', 0);
cy.get('.Select__control').eq(1).click();
cy.get('.Select__menu').contains('me').click();
cy.get('[data-test="styled-card"]').its('length').should('be.gt', 0);
});
it('should filter by created by correctly', () => {
// filter by created by
cy.get('.Select__control').eq(1).click();
cy.get('.Select__menu').contains('alpha user').click();
cy.get('.ant-card').should('not.exist');
cy.get('.Select__control').eq(1).click();
cy.get('.Select__menu').contains('gamma user').click();
cy.get('.ant-card').should('not.exist');
});
it('should filter by published correctly', () => {
// filter by published
cy.get('.Select__control').eq(2).click();
cy.get('.Select__menu').contains('Published').click({ timeout: 5000 });
cy.get('[data-test="styled-card"]').should('have.length', 2);
cy.get('[data-test="styled-card"]')
.first()
.contains('USA Births Names')
.should('be.visible');
cy.get('.Select__control').eq(1).click();
cy.get('.Select__control').eq(1).type('unpub{enter}');
cy.get('[data-test="styled-card"]').should('have.length', 2);
});
});
describe('dashboard filters list view', () => {
beforeEach(() => {
cy.login();
cy.visit(DASHBOARD_LIST);
cy.get('[data-test="list-view"]').click();
});
it('should filter by owners correctly', () => {
// filter by owners
cy.get('.Select__control').first().click();
cy.get('.Select__menu').contains('alpha user').click();
cy.get('[data-test="table-row"]').should('not.exist');
cy.get('.Select__control').first().click();
cy.get('.Select__menu').contains('gamma user').click();
cy.get('[data-test="table-row"]').should('not.exist');
});
it('should filter by me correctly', () => {
// filter by me
cy.get('.Select__control').first().click();
cy.get('.Select__menu').contains('me').click();
cy.get('[data-test="table-row"]').its('length').should('be.gt', 0);
cy.get('.Select__control').eq(1).click();
cy.get('.Select__menu').contains('me').click();
cy.get('[data-test="table-row"]').its('length').should('be.gt', 0);
});
it('should filter by created by correctly', () => {
// filter by created by
cy.get('.Select__control').eq(1).click();
cy.get('.Select__menu').contains('alpha user').click();
cy.get('[data-test="table-row"]').should('not.exist');
cy.get('.Select__control').eq(1).click();
cy.get('.Select__menu').contains('gamma user').click();
cy.get('[data-test="table-row"]').should('not.exist');
});
xit('should filter by published correctly', () => {
// filter by published
cy.get('.Select__control').eq(2).click();
cy.get('.Select__menu').contains('Published').click();
cy.get('[data-test="table-row"]').should('have.length', 2);
cy.get('[data-test="table-row"]')
.first()
.contains('USA Births Names')
.should('be.visible');
cy.get('.Select__control').eq(2).click();
cy.get('.Select__control').eq(2).type('unpub{enter}');
cy.get('[data-test="table-row"]').should('have.length', 2);
});
});
| superset-frontend/cypress-base/cypress/integration/dashboard_list/filter.test.ts | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017909164307639003,
0.00017641842714510858,
0.00017058885714504868,
0.00017691508401185274,
0.000002121659463227843
] |
{
"id": 2,
"code_window": [
"\n",
"// In the same vein as above, a hook for viewing a single instance of a resource (given id)\n",
"interface SingleViewResourceState<D extends object = any> {\n",
" loading: boolean;\n",
" resource: D | null;\n",
" error: string | Record<string, string[]> | null;\n",
"}\n",
"\n",
"export function useSingleViewResource<D extends object = any>(\n",
" resourceName: string,\n",
" resourceLabel: string, // resourceLabel for translations\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error: string | Record<string, string[] | string> | null;\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 202
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 json
import logging
from typing import Any, Callable, Dict, List, Optional
import yaml
from flask_appbuilder import Model
from sqlalchemy.orm import Session
from sqlalchemy.orm.session import make_transient
from superset import db
from superset.commands.base import BaseCommand
from superset.commands.importers.exceptions import IncorrectVersionError
from superset.connectors.base.models import BaseColumn, BaseDatasource, BaseMetric
from superset.connectors.druid.models import (
DruidCluster,
DruidColumn,
DruidDatasource,
DruidMetric,
)
from superset.connectors.sqla.models import SqlaTable, SqlMetric, TableColumn
from superset.databases.commands.exceptions import DatabaseNotFoundError
from superset.models.core import Database
from superset.utils.dict_import_export import DATABASES_KEY, DRUID_CLUSTERS_KEY
logger = logging.getLogger(__name__)
def lookup_sqla_table(table: SqlaTable) -> Optional[SqlaTable]:
return (
db.session.query(SqlaTable)
.join(Database)
.filter(
SqlaTable.table_name == table.table_name,
SqlaTable.schema == table.schema,
Database.id == table.database_id,
)
.first()
)
def lookup_sqla_database(table: SqlaTable) -> Optional[Database]:
database = (
db.session.query(Database)
.filter_by(database_name=table.params_dict["database_name"])
.one_or_none()
)
if database is None:
raise DatabaseNotFoundError
return database
def lookup_druid_cluster(datasource: DruidDatasource) -> Optional[DruidCluster]:
return db.session.query(DruidCluster).filter_by(id=datasource.cluster_id).first()
def lookup_druid_datasource(datasource: DruidDatasource) -> Optional[DruidDatasource]:
return (
db.session.query(DruidDatasource)
.filter(
DruidDatasource.datasource_name == datasource.datasource_name,
DruidDatasource.cluster_id == datasource.cluster_id,
)
.first()
)
def import_dataset(
i_datasource: BaseDatasource,
database_id: Optional[int] = None,
import_time: Optional[int] = None,
) -> int:
"""Imports the datasource from the object to the database.
Metrics and columns and datasource will be overridden if exists.
This function can be used to import/export dashboards between multiple
superset instances. Audit metadata isn't copied over.
"""
lookup_database: Callable[[BaseDatasource], Optional[Database]]
lookup_datasource: Callable[[BaseDatasource], Optional[BaseDatasource]]
if isinstance(i_datasource, SqlaTable):
lookup_database = lookup_sqla_database
lookup_datasource = lookup_sqla_table
else:
lookup_database = lookup_druid_cluster
lookup_datasource = lookup_druid_datasource
return import_datasource(
db.session,
i_datasource,
lookup_database,
lookup_datasource,
import_time,
database_id,
)
def lookup_sqla_metric(session: Session, metric: SqlMetric) -> SqlMetric:
return (
session.query(SqlMetric)
.filter(
SqlMetric.table_id == metric.table_id,
SqlMetric.metric_name == metric.metric_name,
)
.first()
)
def lookup_druid_metric(session: Session, metric: DruidMetric) -> DruidMetric:
return (
session.query(DruidMetric)
.filter(
DruidMetric.datasource_id == metric.datasource_id,
DruidMetric.metric_name == metric.metric_name,
)
.first()
)
def import_metric(session: Session, metric: BaseMetric) -> BaseMetric:
if isinstance(metric, SqlMetric):
lookup_metric = lookup_sqla_metric
else:
lookup_metric = lookup_druid_metric
return import_simple_obj(session, metric, lookup_metric)
def lookup_sqla_column(session: Session, column: TableColumn) -> TableColumn:
return (
session.query(TableColumn)
.filter(
TableColumn.table_id == column.table_id,
TableColumn.column_name == column.column_name,
)
.first()
)
def lookup_druid_column(session: Session, column: DruidColumn) -> DruidColumn:
return (
session.query(DruidColumn)
.filter(
DruidColumn.datasource_id == column.datasource_id,
DruidColumn.column_name == column.column_name,
)
.first()
)
def import_column(session: Session, column: BaseColumn) -> BaseColumn:
if isinstance(column, TableColumn):
lookup_column = lookup_sqla_column
else:
lookup_column = lookup_druid_column
return import_simple_obj(session, column, lookup_column)
def import_datasource( # pylint: disable=too-many-arguments
session: Session,
i_datasource: Model,
lookup_database: Callable[[Model], Optional[Model]],
lookup_datasource: Callable[[Model], Optional[Model]],
import_time: Optional[int] = None,
database_id: Optional[int] = None,
) -> int:
"""Imports the datasource from the object to the database.
Metrics and columns and datasource will be overrided if exists.
This function can be used to import/export datasources between multiple
superset instances. Audit metadata isn't copies over.
"""
make_transient(i_datasource)
logger.info("Started import of the datasource: %s", i_datasource.to_json())
i_datasource.id = None
i_datasource.database_id = (
database_id
if database_id
else getattr(lookup_database(i_datasource), "id", None)
)
i_datasource.alter_params(import_time=import_time)
# override the datasource
datasource = lookup_datasource(i_datasource)
if datasource:
datasource.override(i_datasource)
session.flush()
else:
datasource = i_datasource.copy()
session.add(datasource)
session.flush()
for metric in i_datasource.metrics:
new_m = metric.copy()
new_m.table_id = datasource.id
logger.info(
"Importing metric %s from the datasource: %s",
new_m.to_json(),
i_datasource.full_name,
)
imported_m = import_metric(session, new_m)
if imported_m.metric_name not in [m.metric_name for m in datasource.metrics]:
datasource.metrics.append(imported_m)
for column in i_datasource.columns:
new_c = column.copy()
new_c.table_id = datasource.id
logger.info(
"Importing column %s from the datasource: %s",
new_c.to_json(),
i_datasource.full_name,
)
imported_c = import_column(session, new_c)
if imported_c.column_name not in [c.column_name for c in datasource.columns]:
datasource.columns.append(imported_c)
session.flush()
return datasource.id
def import_simple_obj(
session: Session, i_obj: Model, lookup_obj: Callable[[Session, Model], Model]
) -> Model:
make_transient(i_obj)
i_obj.id = None
i_obj.table = None
# find if the column was already imported
existing_column = lookup_obj(session, i_obj)
i_obj.table = None
if existing_column:
existing_column.override(i_obj)
session.flush()
return existing_column
session.add(i_obj)
session.flush()
return i_obj
def import_from_dict(
session: Session, data: Dict[str, Any], sync: Optional[List[str]] = None
) -> None:
"""Imports databases and druid clusters from dictionary"""
if not sync:
sync = []
if isinstance(data, dict):
logger.info("Importing %d %s", len(data.get(DATABASES_KEY, [])), DATABASES_KEY)
for database in data.get(DATABASES_KEY, []):
Database.import_from_dict(session, database, sync=sync)
logger.info(
"Importing %d %s", len(data.get(DRUID_CLUSTERS_KEY, [])), DRUID_CLUSTERS_KEY
)
for datasource in data.get(DRUID_CLUSTERS_KEY, []):
DruidCluster.import_from_dict(session, datasource, sync=sync)
session.commit()
else:
logger.info("Supplied object is not a dictionary.")
class ImportDatasetsCommand(BaseCommand):
"""
Import datasources in YAML format.
This is the original unversioned format used to export and import datasources
in Superset.
"""
# pylint: disable=unused-argument
def __init__(
self, contents: Dict[str, str], *args: Any, **kwargs: Any,
):
self.contents = contents
self._configs: Dict[str, Any] = {}
self.sync = []
if kwargs.get("sync_columns"):
self.sync.append("columns")
if kwargs.get("sync_metrics"):
self.sync.append("metrics")
def run(self) -> None:
self.validate()
# TODO (betodealmeida): add rollback in case of error
for file_name, config in self._configs.items():
logger.info("Importing dataset from file %s", file_name)
if isinstance(config, dict):
import_from_dict(db.session, config, sync=self.sync)
else: # list
for dataset in config:
# UI exports don't have the database metadata, so we assume
# the DB exists and has the same name
params = json.loads(dataset["params"])
database = (
db.session.query(Database)
.filter_by(database_name=params["database_name"])
.one()
)
dataset["database_id"] = database.id
SqlaTable.import_from_dict(db.session, dataset, sync=self.sync)
def validate(self) -> None:
# ensure all files are YAML
for file_name, content in self.contents.items():
try:
config = yaml.safe_load(content)
except yaml.parser.ParserError:
logger.exception("Invalid YAML file")
raise IncorrectVersionError(f"{file_name} is not a valid YAML file")
# CLI export
if isinstance(config, dict):
# TODO (betodealmeida): validate with Marshmallow
if DATABASES_KEY not in config and DRUID_CLUSTERS_KEY not in config:
raise IncorrectVersionError(f"{file_name} has no valid keys")
# UI export
elif isinstance(config, list):
# TODO (betodealmeida): validate with Marshmallow
pass
else:
raise IncorrectVersionError(f"{file_name} is not a valid file")
self._configs[file_name] = config
| superset/datasets/commands/importers/v0.py | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.0001784360792953521,
0.0001718929852358997,
0.00016433738346677274,
0.00017232901882380247,
0.0000035533353184291627
] |
{
"id": 3,
"code_window": [
" resource: json.result,\n",
" error: null,\n",
" });\n",
" return json.result;\n",
" },\n",
" createErrorHandler((errMsg: Record<string, string[]>) => {\n",
" handleErrorMsg(\n",
" t(\n",
" 'An error occurred while fetching %ss: %s',\n",
" resourceLabel,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" createErrorHandler((errMsg: Record<string, string[] | string>) => {\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 238
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 {
t,
SupersetClient,
SupersetClientResponse,
logging,
styled,
} from '@superset-ui/core';
import Chart from 'src/types/Chart';
import rison from 'rison';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import { FetchDataConfig } from 'src/components/ListView';
import SupersetText from 'src/utils/textUtils';
import { Dashboard, Filters, SavedQueryObject } from './types';
const createFetchResourceMethod = (method: string) => (
resource: string,
relation: string,
handleError: (error: Response) => void,
userId?: string | number,
) => async (filterValue = '', pageIndex?: number, pageSize?: number) => {
const resourceEndpoint = `/api/v1/${resource}/${method}/${relation}`;
const options =
userId && pageIndex === 0 ? [{ label: 'me', value: userId }] : [];
try {
const queryParams = rison.encode({
...(pageIndex ? { page: pageIndex } : {}),
...(pageSize ? { page_size: pageSize } : {}),
...(filterValue ? { filter: filterValue } : {}),
});
const { json = {} } = await SupersetClient.get({
endpoint: `${resourceEndpoint}?q=${queryParams}`,
});
const data = json?.result?.map(
({ text: label, value }: { text: string; value: any }) => ({
label,
value,
}),
);
return options.concat(data);
} catch (e) {
handleError(e);
}
return [];
};
const getParams = (filters?: Array<Filters>) => {
const params = {
order_column: 'changed_on_delta_humanized',
order_direction: 'desc',
page: 0,
page_size: 3,
filters,
};
if (!filters) delete params.filters;
return rison.encode(params);
};
export const getEditedObjects = (userId: string | number) => {
const filters = {
edited: [
{
col: 'changed_by',
opr: 'rel_o_m',
value: `${userId}`,
},
],
};
const batch = [
SupersetClient.get({
endpoint: `/api/v1/dashboard/?q=${getParams(filters.edited)}`,
}),
SupersetClient.get({
endpoint: `/api/v1/chart/?q=${getParams(filters.edited)}`,
}),
];
return Promise.all(batch)
.then(([editedCharts, editedDashboards]) => {
const res = {
editedDash: editedDashboards.json?.result.slice(0, 3),
editedChart: editedCharts.json?.result.slice(0, 3),
};
return res;
})
.catch(err => err);
};
export const getUserOwnedObjects = (
userId: string | number,
resource: string,
) => {
const filters = {
created: [
{
col: 'created_by',
opr: 'rel_o_m',
value: `${userId}`,
},
],
};
return SupersetClient.get({
endpoint: `/api/v1/${resource}/?q=${getParams(filters.created)}`,
}).then(res => res.json?.result);
};
export const getRecentAcitivtyObjs = (
userId: string | number,
recent: string,
addDangerToast: (arg1: string, arg2: any) => any,
) =>
SupersetClient.get({ endpoint: recent }).then(recentsRes => {
const res: any = {};
if (recentsRes.json.length === 0) {
const newBatch = [
SupersetClient.get({ endpoint: `/api/v1/chart/?q=${getParams()}` }),
SupersetClient.get({
endpoint: `/api/v1/dashboard/?q=${getParams()}`,
}),
];
return Promise.all(newBatch)
.then(([chartRes, dashboardRes]) => {
res.examples = [...chartRes.json.result, ...dashboardRes.json.result];
return res;
})
.catch(errMsg =>
addDangerToast(
t('There was an error fetching your recent activity:'),
errMsg,
),
);
}
res.viewed = recentsRes.json;
return res;
});
export const createFetchRelated = createFetchResourceMethod('related');
export const createFetchDistinct = createFetchResourceMethod('distinct');
export function createErrorHandler(
handleErrorFunc: (errMsg?: string | Record<string, string[]>) => void,
) {
return async (e: SupersetClientResponse | string) => {
const parsedError = await getClientErrorObject(e);
// Taking the first error returned from the API
// @ts-ignore
const errorsArray = parsedError?.errors;
const config = await SupersetText;
if (
errorsArray &&
errorsArray.length &&
config &&
config.ERRORS &&
errorsArray[0].error_type in config.ERRORS
) {
parsedError.message = config.ERRORS[errorsArray[0].error_type];
}
logging.error(e);
handleErrorFunc(parsedError.message || parsedError.error);
};
}
export function handleChartDelete(
{ id, slice_name: sliceName }: Chart,
addSuccessToast: (arg0: string) => void,
addDangerToast: (arg0: string) => void,
refreshData: (arg0?: FetchDataConfig | null) => void,
chartFilter?: string,
userId?: number,
) {
const filters = {
pageIndex: 0,
pageSize: 3,
sortBy: [
{
id: 'changed_on_delta_humanized',
desc: true,
},
],
filters: [
{
id: 'created_by',
operator: 'rel_o_m',
value: `${userId}`,
},
],
};
SupersetClient.delete({
endpoint: `/api/v1/chart/${id}`,
}).then(
() => {
if (chartFilter === 'Mine') refreshData(filters);
else refreshData();
addSuccessToast(t('Deleted: %s', sliceName));
},
() => {
addDangerToast(t('There was an issue deleting: %s', sliceName));
},
);
}
export function handleBulkChartExport(chartsToExport: Chart[]) {
return window.location.assign(
`/api/v1/chart/export/?q=${rison.encode(
chartsToExport.map(({ id }) => id),
)}`,
);
}
export function handleBulkDashboardExport(dashboardsToExport: Dashboard[]) {
return window.location.assign(
`/api/v1/dashboard/export/?q=${rison.encode(
dashboardsToExport.map(({ id }) => id),
)}`,
);
}
export function handleBulkSavedQueryExport(
savedQueriesToExport: SavedQueryObject[],
) {
return window.location.assign(
`/api/v1/saved_query/export/?q=${rison.encode(
savedQueriesToExport.map(({ id }) => id),
)}`,
);
}
export function handleDashboardDelete(
{ id, dashboard_title: dashboardTitle }: Dashboard,
refreshData: (config?: FetchDataConfig | null) => void,
addSuccessToast: (arg0: string) => void,
addDangerToast: (arg0: string) => void,
dashboardFilter?: string,
userId?: number,
) {
return SupersetClient.delete({
endpoint: `/api/v1/dashboard/${id}`,
}).then(
() => {
const filters = {
pageIndex: 0,
pageSize: 3,
sortBy: [
{
id: 'changed_on_delta_humanized',
desc: true,
},
],
filters: [
{
id: 'owners',
operator: 'rel_m_m',
value: `${userId}`,
},
],
};
if (dashboardFilter === 'Mine') refreshData(filters);
else refreshData();
addSuccessToast(t('Deleted: %s', dashboardTitle));
},
createErrorHandler(errMsg =>
addDangerToast(
t('There was an issue deleting %s: %s', dashboardTitle, errMsg),
),
),
);
}
export function shortenSQL(sql: string, maxLines: number) {
let lines: string[] = sql.split('\n');
if (lines.length >= maxLines) {
lines = lines.slice(0, maxLines);
lines.push('...');
}
return lines.join('\n');
}
const breakpoints = [576, 768, 992, 1200];
export const mq = breakpoints.map(bp => `@media (max-width: ${bp}px)`);
export const CardContainer = styled.div`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(31%, 31%));
${[mq[3]]} {
grid-template-columns: repeat(auto-fit, minmax(31%, 31%));
}
${[mq[2]]} {
grid-template-columns: repeat(auto-fit, minmax(48%, 48%));
}
${[mq[1]]} {
grid-template-columns: repeat(auto-fit, minmax(50%, 80%));
}
grid-gap: ${({ theme }) => theme.gridUnit * 8}px;
justify-content: left;
padding: ${({ theme }) => theme.gridUnit * 6}px;
padding-top: ${({ theme }) => theme.gridUnit * 2}px;
`;
export const CardStyles = styled.div`
cursor: pointer;
a {
text-decoration: none;
}
`;
| superset-frontend/src/views/CRUD/utils.tsx | 1 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.0016366909258067608,
0.00025950733106583357,
0.0001644566800678149,
0.00017112697241827846,
0.0002924073487520218
] |
{
"id": 3,
"code_window": [
" resource: json.result,\n",
" error: null,\n",
" });\n",
" return json.result;\n",
" },\n",
" createErrorHandler((errMsg: Record<string, string[]>) => {\n",
" handleErrorMsg(\n",
" t(\n",
" 'An error occurred while fetching %ss: %s',\n",
" resourceLabel,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" createErrorHandler((errMsg: Record<string, string[] | string>) => {\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 238
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/* header has mysterious extra margin */
header.top {
margin-bottom: -20px;
}
body {
h1 {
font-weight: @font-weight-bold;
line-height: @line-height-base;
font-size: @font-size-xxl;
letter-spacing: -0.2px;
margin-top: 12px;
margin-bottom: 12px;
}
h2 {
font-weight: @font-weight-bold;
line-height: @line-height-base;
font-size: @font-size-xl;
margin-top: 12px;
margin-bottom: 8px;
}
h3,
h4,
h5,
h6 {
font-weight: @font-weight-bold;
line-height: @line-height-base;
font-size: @font-size-l;
letter-spacing: 0.2px;
margin-top: 8px;
margin-bottom: 4px;
}
p {
margin: 0 0 8px 0;
}
}
.dashboard .chart-header {
font-size: @font-size-l;
font-weight: @font-weight-bold;
margin-bottom: 4px;
display: flex;
max-width: 100%;
align-items: flex-start;
& > .header-title {
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
flex-grow: 1;
}
& > .header-controls {
display: flex;
& > * {
margin-left: 8px;
}
}
.dropdown.btn-group {
pointer-events: none;
vertical-align: top;
& > * {
pointer-events: auto;
}
}
.dropdown-toggle.btn.btn-default {
background: none;
border: none;
box-shadow: none;
}
.dropdown-menu.dropdown-menu-right {
top: 20px;
}
.divider {
margin: 5px 0;
}
.refresh-tooltip {
display: block;
height: 16px;
margin: 3px 0;
color: @gray;
}
}
.dashboard .chart-header,
.dashboard .dashboard-header {
.dropdown-menu {
padding: 9px 0;
}
.dropdown-menu li {
font-weight: @font-weight-normal;
}
}
.react-bs-container-body {
max-height: 400px;
overflow-y: auto;
}
.hidden,
#pageDropDown {
display: none;
}
.separator .chart-container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
.dashboard .title {
margin: 0 20px;
}
.dashboard-header .dashboard-component-header {
display: flex;
flex-direction: row;
align-items: center;
.editable-title {
margin-right: 8px;
}
.favstar {
font-size: @font-size-xl;
position: relative;
margin-left: 8px;
}
.publish {
position: relative;
margin-left: 8px;
}
}
.slice_container .alert {
margin: 10px;
}
i.danger {
color: @danger;
}
i.warning {
color: @warning;
}
| superset-frontend/src/dashboard/stylesheets/dashboard.less | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.0001748515060171485,
0.0001715247635729611,
0.00016678169777151197,
0.00017129196203313768,
0.0000022241156329982914
] |
{
"id": 3,
"code_window": [
" resource: json.result,\n",
" error: null,\n",
" });\n",
" return json.result;\n",
" },\n",
" createErrorHandler((errMsg: Record<string, string[]>) => {\n",
" handleErrorMsg(\n",
" t(\n",
" 'An error occurred while fetching %ss: %s',\n",
" resourceLabel,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" createErrorHandler((errMsg: Record<string, string[] | string>) => {\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 238
} | ---
name: Presto
menu: Connecting to Databases
route: /docs/databases/presto
index: 22
version: 1
---
## Presto
The [pyhive](https://pypi.org/project/PyHive/) library is the recommended way to connect to Presto through SQLAlchemy.
The expected connection string is formatted as follows:
```
presto://{hostname}:{port}/{database}
```
You can pass in a username and password as well:
```
presto://{username}:{password}@{hostname}:{port}/{database}
```
Here is an example connection string with values:
```
presto://datascientist:[email protected]:8080/hive
```
By default Superset assumes the most recent version of Presto is being used when querying the
datasource. If you’re using an older version of Presto, you can configure it in the extra parameter:
```
{
"version": "0.123"
}
```
| docs/src/pages/docs/Connecting to Databases/presto.mdx | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00016990008589345962,
0.00016648657037876546,
0.00016035747830756009,
0.00016784435138106346,
0.000003736986400326714
] |
{
"id": 3,
"code_window": [
" resource: json.result,\n",
" error: null,\n",
" });\n",
" return json.result;\n",
" },\n",
" createErrorHandler((errMsg: Record<string, string[]>) => {\n",
" handleErrorMsg(\n",
" t(\n",
" 'An error occurred while fetching %ss: %s',\n",
" resourceLabel,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" createErrorHandler((errMsg: Record<string, string[] | string>) => {\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 238
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 { CHART_TYPE, MARKDOWN_TYPE } from './componentTypes';
const USER_CONTENT_COMPONENT_TYPE: string[] = [CHART_TYPE, MARKDOWN_TYPE];
export default function isDashboardEmpty(layout: any): boolean {
// has at least one chart or markdown component
return !Object.values(layout).some(
({ type }: { type?: string }) =>
type && USER_CONTENT_COMPONENT_TYPE.includes(type),
);
}
| superset-frontend/src/dashboard/util/isDashboardEmpty.ts | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017633473908063024,
0.00017480150563642383,
0.00017321828636340797,
0.0001748515060171485,
0.0000012727775811072206
] |
{
"id": 4,
"code_window": [
" error: null,\n",
" });\n",
" return json.id;\n",
" },\n",
" createErrorHandler((errMsg: Record<string, string[]>) => {\n",
" handleErrorMsg(\n",
" t(\n",
" 'An error occurred while creating %ss: %s',\n",
" resourceLabel,\n",
" parsedErrorMessage(errMsg),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" createErrorHandler((errMsg: Record<string, string[] | string>) => {\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 279
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 rison from 'rison';
import { useState, useEffect, useCallback } from 'react';
import { makeApi, SupersetClient, t } from '@superset-ui/core';
import { createErrorHandler } from 'src/views/CRUD/utils';
import { FetchDataConfig } from 'src/components/ListView';
import { FilterValue } from 'src/components/ListView/types';
import Chart, { Slice } from 'src/types/Chart';
import copyTextToClipboard from 'src/utils/copy';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import { FavoriteStatus, ImportResourceName, DatabaseObject } from './types';
interface ListViewResourceState<D extends object = any> {
loading: boolean;
collection: D[];
count: number;
permissions: string[];
lastFetchDataConfig: FetchDataConfig | null;
bulkSelectEnabled: boolean;
lastFetched?: string;
}
const parsedErrorMessage = (
errorMessage: Record<string, string[]> | string,
) => {
if (typeof errorMessage === 'string') {
return errorMessage;
}
return Object.entries(errorMessage)
.map(([key, value]) => `(${key}) ${value.join(', ')}`)
.join('\n');
};
export function useListViewResource<D extends object = any>(
resource: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
infoEnable = true,
defaultCollectionValue: D[] = [],
baseFilters?: FilterValue[], // must be memoized
initialLoadingState = true,
) {
const [state, setState] = useState<ListViewResourceState<D>>({
count: 0,
collection: defaultCollectionValue,
loading: initialLoadingState,
lastFetchDataConfig: null,
permissions: [],
bulkSelectEnabled: false,
});
function updateState(update: Partial<ListViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
function toggleBulkSelect() {
updateState({ bulkSelectEnabled: !state.bulkSelectEnabled });
}
useEffect(() => {
if (!infoEnable) return;
SupersetClient.get({
endpoint: `/api/v1/${resource}/_info?q=${rison.encode({
keys: ['permissions'],
})}`,
}).then(
({ json: infoJson = {} }) => {
updateState({
permissions: infoJson.permissions,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %s info: %s',
resourceLabel,
errMsg,
),
),
),
);
}, []);
function hasPerm(perm: string) {
if (!state.permissions.length) {
return false;
}
return Boolean(state.permissions.find(p => p === perm));
}
const fetchData = useCallback(
({
pageIndex,
pageSize,
sortBy,
filters: filterValues,
}: FetchDataConfig) => {
// set loading state, cache the last config for refreshing data.
updateState({
lastFetchDataConfig: {
filters: filterValues,
pageIndex,
pageSize,
sortBy,
},
loading: true,
});
const filterExps = (baseFilters || [])
.concat(filterValues)
.map(({ id, operator: opr, value }) => ({
col: id,
opr,
value,
}));
const queryParams = rison.encode({
order_column: sortBy[0].id,
order_direction: sortBy[0].desc ? 'desc' : 'asc',
page: pageIndex,
page_size: pageSize,
...(filterExps.length ? { filters: filterExps } : {}),
});
return SupersetClient.get({
endpoint: `/api/v1/${resource}/?q=${queryParams}`,
})
.then(
({ json = {} }) => {
updateState({
collection: json.result,
count: json.count,
lastFetched: new Date().toISOString(),
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
errMsg,
),
),
),
)
.finally(() => {
updateState({ loading: false });
});
},
[baseFilters],
);
return {
state: {
loading: state.loading,
resourceCount: state.count,
resourceCollection: state.collection,
bulkSelectEnabled: state.bulkSelectEnabled,
lastFetched: state.lastFetched,
},
setResourceCollection: (update: D[]) =>
updateState({
collection: update,
}),
hasPerm,
fetchData,
toggleBulkSelect,
refreshData: (provideConfig?: FetchDataConfig) => {
if (state.lastFetchDataConfig) {
return fetchData(state.lastFetchDataConfig);
}
if (provideConfig) {
return fetchData(provideConfig);
}
return null;
},
};
}
// In the same vein as above, a hook for viewing a single instance of a resource (given id)
interface SingleViewResourceState<D extends object = any> {
loading: boolean;
resource: D | null;
error: string | Record<string, string[]> | null;
}
export function useSingleViewResource<D extends object = any>(
resourceName: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<SingleViewResourceState<D>>({
loading: false,
resource: null,
error: null,
});
function updateState(update: Partial<SingleViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
const fetchResource = useCallback(
(resourceID: number) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.get({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const createResource = useCallback(
(resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.id;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while creating %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const updateResource = useCallback(
(resourceID: number, resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.put({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler(errMsg => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
JSON.stringify(errMsg),
),
);
updateState({
error: errMsg,
});
return errMsg;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const clearError = () =>
updateState({
error: null,
});
return {
state,
setResource: (update: D) =>
updateState({
resource: update,
}),
fetchResource,
createResource,
updateResource,
clearError,
};
}
interface ImportResourceState {
loading: boolean;
passwordsNeeded: string[];
alreadyExists: string[];
}
export function useImportResource(
resourceName: ImportResourceName,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<ImportResourceState>({
loading: false,
passwordsNeeded: [],
alreadyExists: [],
});
function updateState(update: Partial<ImportResourceState>) {
setState(currentState => ({ ...currentState, ...update }));
}
/* eslint-disable no-underscore-dangle */
const isNeedsPassword = (payload: any) =>
typeof payload === 'object' &&
Array.isArray(payload._schema) &&
payload._schema.length === 1 &&
payload._schema[0] === 'Must provide a password for the database';
const isAlreadyExists = (payload: any) =>
typeof payload === 'string' &&
payload.includes('already exists and `overwrite=true` was not passed');
const getPasswordsNeeded = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isNeedsPassword(validationErrors))
.map(([fileName]) => fileName);
const getAlreadyExists = (errMsg: Record<string, Record<string, string[]>>) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isAlreadyExists(validationErrors))
.map(([fileName]) => fileName);
const hasTerminalValidation = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.values(errMsg).some(
validationErrors =>
!isNeedsPassword(validationErrors) &&
!isAlreadyExists(validationErrors),
);
const importResource = useCallback(
(
bundle: File,
databasePasswords: Record<string, string> = {},
overwrite = false,
) => {
// Set loading state
updateState({
loading: true,
});
const formData = new FormData();
formData.append('formData', bundle);
/* The import bundle never contains database passwords; if required
* they should be provided by the user during import.
*/
if (databasePasswords) {
formData.append('passwords', JSON.stringify(databasePasswords));
}
/* If the imported model already exists the user needs to confirm
* that they want to overwrite it.
*/
if (overwrite) {
formData.append('overwrite', 'true');
}
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/import/`,
body: formData,
})
.then(() => true)
.catch(response =>
getClientErrorObject(response).then(error => {
const errMsg = error.message || error.error;
if (typeof errMsg === 'string') {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
return false;
}
if (hasTerminalValidation(errMsg)) {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
} else {
updateState({
passwordsNeeded: getPasswordsNeeded(errMsg),
alreadyExists: getAlreadyExists(errMsg),
});
}
return false;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[],
);
return { state, importResource };
}
enum FavStarClassName {
CHART = 'slice',
DASHBOARD = 'Dashboard',
}
type FavoriteStatusResponse = {
result: Array<{
id: string;
value: boolean;
}>;
};
const favoriteApis = {
chart: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/chart/favorite_status/',
}),
dashboard: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/dashboard/favorite_status/',
}),
};
export function useFavoriteStatus(
type: 'chart' | 'dashboard',
ids: Array<string | number>,
handleErrorMsg: (message: string) => void,
) {
const [favoriteStatus, setFavoriteStatus] = useState<FavoriteStatus>({});
const updateFavoriteStatus = (update: FavoriteStatus) =>
setFavoriteStatus(currentState => ({ ...currentState, ...update }));
useEffect(() => {
if (!ids.length) {
return;
}
favoriteApis[type](ids).then(
({ result }) => {
const update = result.reduce((acc, element) => {
acc[element.id] = element.value;
return acc;
}, {});
updateFavoriteStatus(update);
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error fetching the favorite status: %s', errMsg),
),
),
);
}, [ids, type, handleErrorMsg]);
const saveFaveStar = useCallback(
(id: number, isStarred: boolean) => {
const urlSuffix = isStarred ? 'unselect' : 'select';
SupersetClient.get({
endpoint: `/superset/favstar/${
type === 'chart' ? FavStarClassName.CHART : FavStarClassName.DASHBOARD
}/${id}/${urlSuffix}/`,
}).then(
({ json }) => {
updateFavoriteStatus({
[id]: (json as { count: number })?.count > 0,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error saving the favorite status: %s', errMsg),
),
),
);
},
[type],
);
return [saveFaveStar, favoriteStatus] as const;
}
export const useChartEditModal = (
setCharts: (charts: Array<Chart>) => void,
charts: Array<Chart>,
) => {
const [
sliceCurrentlyEditing,
setSliceCurrentlyEditing,
] = useState<Slice | null>(null);
function openChartEditModal(chart: Chart) {
setSliceCurrentlyEditing({
slice_id: chart.id,
slice_name: chart.slice_name,
description: chart.description,
cache_timeout: chart.cache_timeout,
});
}
function closeChartEditModal() {
setSliceCurrentlyEditing(null);
}
function handleChartUpdated(edits: Chart) {
// update the chart in our state with the edited info
const newCharts = charts.map((chart: Chart) =>
chart.id === edits.id ? { ...chart, ...edits } : chart,
);
setCharts(newCharts);
}
return {
sliceCurrentlyEditing,
handleChartUpdated,
openChartEditModal,
closeChartEditModal,
};
};
export const copyQueryLink = (
id: number,
addDangerToast: (arg0: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
copyTextToClipboard(
`${window.location.origin}/superset/sqllab?savedQueryId=${id}`,
)
.then(() => {
addSuccessToast(t('Link Copied!'));
})
.catch(() => {
addDangerToast(t('Sorry, your browser does not support copying.'));
});
};
export const testDatabaseConnection = (
connection: DatabaseObject,
handleErrorMsg: (errorMsg: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
SupersetClient.post({
endpoint: 'api/v1/database/test_connection',
body: JSON.stringify(connection),
headers: { 'Content-Type': 'application/json' },
}).then(
() => {
addSuccessToast(t('Connection looks good!'));
},
createErrorHandler((errMsg: Record<string, string[]> | string) => {
handleErrorMsg(t(`${t('ERROR: ')}${parsedErrorMessage(errMsg)}`));
}),
);
};
| superset-frontend/src/views/CRUD/hooks.ts | 1 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.993192732334137,
0.05479254201054573,
0.00016450826660729945,
0.0001802121987566352,
0.20145279169082642
] |
{
"id": 4,
"code_window": [
" error: null,\n",
" });\n",
" return json.id;\n",
" },\n",
" createErrorHandler((errMsg: Record<string, string[]>) => {\n",
" handleErrorMsg(\n",
" t(\n",
" 'An error occurred while creating %ss: %s',\n",
" resourceLabel,\n",
" parsedErrorMessage(errMsg),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" createErrorHandler((errMsg: Record<string, string[] | string>) => {\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 279
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 React from 'react';
import SyntaxHighlighter from 'react-syntax-highlighter/dist/cjs/light';
import sql from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql';
import github from 'react-syntax-highlighter/dist/cjs/styles/hljs/github';
import { t } from '@superset-ui/core';
import ModalTrigger from '../../components/ModalTrigger';
SyntaxHighlighter.registerLanguage('sql', sql);
interface HighlightedSqlProps {
sql: string;
rawSql?: string;
maxWidth?: number;
maxLines?: number;
shrink?: any;
}
interface HighlightedSqlModalTypes {
rawSql?: string;
sql: string;
}
interface TriggerNodeProps {
shrink: boolean;
sql: string;
maxLines: number;
maxWidth: number;
}
const shrinkSql = (sql: string, maxLines: number, maxWidth: number) => {
const ssql = sql || '';
let lines = ssql.split('\n');
if (lines.length >= maxLines) {
lines = lines.slice(0, maxLines);
lines.push('{...}');
}
return lines
.map(line => {
if (line.length > maxWidth) {
return `${line.slice(0, maxWidth)}{...}`;
}
return line;
})
.join('\n');
};
function TriggerNode({ shrink, sql, maxLines, maxWidth }: TriggerNodeProps) {
return (
<SyntaxHighlighter language="sql" style={github}>
{shrink ? shrinkSql(sql, maxLines, maxWidth) : sql}
</SyntaxHighlighter>
);
}
function HighlightSqlModal({ rawSql, sql }: HighlightedSqlModalTypes) {
return (
<div>
<h4>{t('Source SQL')}</h4>
<SyntaxHighlighter language="sql" style={github}>
{sql}
</SyntaxHighlighter>
{rawSql && rawSql !== sql && (
<div>
<h4>{t('Raw SQL')}</h4>
<SyntaxHighlighter language="sql" style={github}>
{rawSql}
</SyntaxHighlighter>
</div>
)}
</div>
);
}
function HighlightedSql({
sql,
rawSql,
maxWidth = 50,
maxLines = 5,
shrink = false,
}: HighlightedSqlProps) {
return (
<ModalTrigger
modalTitle={t('SQL')}
modalBody={<HighlightSqlModal rawSql={rawSql} sql={sql} />}
triggerNode={
<TriggerNode
shrink={shrink}
sql={sql}
maxLines={maxLines}
maxWidth={maxWidth}
/>
}
/>
);
}
export default HighlightedSql;
| superset-frontend/src/SqlLab/components/HighlightedSql.tsx | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00023961444094311446,
0.0001787356595741585,
0.00016699779371265322,
0.00017026919522322714,
0.000020277224393794313
] |
{
"id": 4,
"code_window": [
" error: null,\n",
" });\n",
" return json.id;\n",
" },\n",
" createErrorHandler((errMsg: Record<string, string[]>) => {\n",
" handleErrorMsg(\n",
" t(\n",
" 'An error occurred while creating %ss: %s',\n",
" resourceLabel,\n",
" parsedErrorMessage(errMsg),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" createErrorHandler((errMsg: Record<string, string[] | string>) => {\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 279
} | #!/usr/bin/env python3
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""
Manually cancel previous GitHub Action workflow runs in queue.
Example:
# Set up
export GITHUB_TOKEN={{ your personal github access token }}
export GITHUB_REPOSITORY=apache/superset
# cancel previous jobs for a PR, will even cancel the running ones
./cancel_github_workflows.py 1042
# cancel previous jobs for a branch
./cancel_github_workflows.py my-branch
# cancel all jobs of a PR, including the latest runs
./cancel_github_workflows.py 1024 --include-last
"""
import os
from typing import Iterable, List, Optional, Union
import click
import requests
from click.exceptions import ClickException
from dateutil import parser
from typing_extensions import Literal
github_token = os.environ.get("GITHUB_TOKEN")
github_repo = os.environ.get("GITHUB_REPOSITORY", "apache/superset")
def request(method: Literal["GET", "POST", "DELETE", "PUT"], endpoint: str, **kwargs):
resp = requests.request(
method,
f"https://api.github.com/{endpoint.lstrip('/')}",
headers={"Authorization": f"Bearer {github_token}"},
**kwargs,
).json()
if "message" in resp:
raise ClickException(f"{endpoint} >> {resp['message']} <<")
return resp
def list_runs(repo: str, params=None):
"""List all github workflow runs.
Returns:
An iterator that will iterate through all pages of matching runs."""
page = 1
total_count = 10000
while page * 100 < total_count:
result = request(
"GET",
f"/repos/{repo}/actions/runs",
params={**params, "per_page": 100, "page": page},
)
total_count = result["total_count"]
for item in result["workflow_runs"]:
yield item
page += 1
def cancel_run(repo: str, run_id: Union[str, int]):
return request("POST", f"/repos/{repo}/actions/runs/{run_id}/cancel")
def get_pull_request(repo: str, pull_number: Union[str, int]):
return request("GET", f"/repos/{repo}/pulls/{pull_number}")
def get_runs(
repo: str,
branch: Optional[str] = None,
user: Optional[str] = None,
statuses: Iterable[str] = ("queued", "in_progress"),
events: Iterable[str] = ("pull_request", "push"),
):
"""Get workflow runs associated with the given branch"""
return [
item
for event in events
for status in statuses
for item in list_runs(repo, {"event": event, "status": status})
if (branch is None or (branch == item["head_branch"]))
and (user is None or (user == item["head_repository"]["owner"]["login"]))
]
def print_commit(commit, branch):
"""Print out commit message for verification"""
indented_message = " \n".join(commit["message"].split("\n"))
date_str = (
parser.parse(commit["timestamp"])
.astimezone(tz=None)
.strftime("%a, %d %b %Y %H:%M:%S")
)
print(
f"""HEAD {commit["id"]} ({branch})
Author: {commit["author"]["name"]} <{commit["author"]["email"]}>
Date: {date_str}
{indented_message}
"""
)
@click.command()
@click.option(
"--repo",
default=github_repo,
help="The github repository name. For example, apache/superset.",
)
@click.option(
"--event",
type=click.Choice(["pull_request", "push", "issue"]),
default=["pull_request", "push"],
show_default=True,
multiple=True,
)
@click.option(
"--include-last/--skip-last",
default=False,
show_default=True,
help="Whether to also cancel the lastest run.",
)
@click.option(
"--include-running/--skip-running",
default=True,
show_default=True,
help="Whether to also cancel running workflows.",
)
@click.argument("branch_or_pull", required=False)
def cancel_github_workflows(
branch_or_pull: Optional[str],
repo: str,
event: List[str],
include_last: bool,
include_running: bool,
):
"""Cancel running or queued GitHub workflows by branch or pull request ID"""
if not github_token:
raise ClickException("Please provide GITHUB_TOKEN as an env variable")
statuses = ("queued", "in_progress") if include_running else ("queued",)
events = event
pr = None
if branch_or_pull is None:
title = "all jobs" if include_last else "all duplicate jobs"
elif branch_or_pull.isdigit():
pr = get_pull_request(repo, pull_number=branch_or_pull)
title = f"pull request #{pr['number']} - {pr['title']}"
else:
title = f"branch [{branch_or_pull}]"
print(
f"\nCancel {'active' if include_running else 'previous'} "
f"workflow runs for {title}\n"
)
if pr:
runs = get_runs(
repo,
statuses=statuses,
events=event,
branch=pr["head"]["ref"],
user=pr["user"]["login"],
)
else:
user = None
branch = branch_or_pull
if branch and ":" in branch:
[user, branch] = branch.split(":", 2)
runs = get_runs(
repo, branch=branch, user=user, statuses=statuses, events=events,
)
# sort old jobs to the front, so to cancel older jobs first
runs = sorted(runs, key=lambda x: x["created_at"])
if runs:
print(
f"Found {len(runs)} potential runs of\n"
f" status: {statuses}\n event: {events}\n"
)
else:
print(f"No {' or '.join(statuses)} workflow runs found.\n")
return
if not include_last:
# Keep the latest run for each workflow and cancel all others
seen = set()
dups = []
for item in reversed(runs):
key = f'{item["event"]}_{item["head_branch"]}_{item["workflow_id"]}'
if key in seen:
dups.append(item)
else:
seen.add(key)
if not dups:
print(
"Only the latest runs are in queue. "
"Use --include-last to force cancelling them.\n"
)
return
runs = dups[::-1]
last_sha = None
print(f"\nCancelling {len(runs)} jobs...\n")
for entry in runs:
head_commit = entry["head_commit"]
if head_commit["id"] != last_sha:
last_sha = head_commit["id"]
print("")
print_commit(head_commit, entry["head_branch"])
try:
print(f"[{entry['status']}] {entry['name']}", end="\r")
cancel_run(repo, entry["id"])
print(f"[Cancled] {entry['name']} ")
except ClickException as error:
print(f"[Error: {error.message}] {entry['name']} ")
print("")
if __name__ == "__main__":
# pylint: disable=no-value-for-parameter
cancel_github_workflows()
| scripts/cancel_github_workflows.py | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017528953321743757,
0.00016861374024301767,
0.00016538557247258723,
0.00016846583457663655,
0.0000024923772343754536
] |
{
"id": 4,
"code_window": [
" error: null,\n",
" });\n",
" return json.id;\n",
" },\n",
" createErrorHandler((errMsg: Record<string, string[]>) => {\n",
" handleErrorMsg(\n",
" t(\n",
" 'An error occurred while creating %ss: %s',\n",
" resourceLabel,\n",
" parsedErrorMessage(errMsg),\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" createErrorHandler((errMsg: Record<string, string[] | string>) => {\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 279
} | <!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
-->
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22C17.5228 22 22 17.5228 22 12C22 9.34784 20.9464 6.8043 19.0711 4.92893C17.1957 3.05357 14.6522 2 12 2ZM12 20C7.58172 20 4 16.4183 4 12C4 7.58172 7.58172 4 12 4C16.4183 4 20 7.58172 20 12C20 14.1217 19.1571 16.1566 17.6569 17.6569C16.1566 19.1571 14.1217 20 12 20ZM12 6C11.4477 6 11 6.44772 11 7V11.42L8.9 12.63C8.50379 12.8545 8.30931 13.3184 8.42695 13.7583C8.54458 14.1983 8.94461 14.5032 9.4 14.5C9.57518 14.5012 9.7476 14.4564 9.9 14.37L12.5 12.87L12.59 12.78L12.75 12.65C12.7891 12.6005 12.8226 12.5468 12.85 12.49C12.8826 12.4363 12.9094 12.3793 12.93 12.32C12.9572 12.2564 12.9741 12.1889 12.98 12.12L13 12V7C13 6.44772 12.5523 6 12 6Z" fill="currentColor"/>
</svg>
| superset-frontend/images/icons/clock.svg | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017757099703885615,
0.0001724558969726786,
0.0001663665025262162,
0.000173430162249133,
0.000004625803285307484
] |
{
"id": 5,
"code_window": [
" const isAlreadyExists = (payload: any) =>\n",
" typeof payload === 'string' &&\n",
" payload.includes('already exists and `overwrite=true` was not passed');\n",
"\n",
" const getPasswordsNeeded = (\n",
" errMsg: Record<string, Record<string, string[]>>,\n",
" ) =>\n",
" Object.entries(errMsg)\n",
" .filter(([, validationErrors]) => isNeedsPassword(validationErrors))\n",
" .map(([fileName]) => fileName);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" errMsg: Record<string, Record<string, string[] | string>>,\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 393
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 rison from 'rison';
import { useState, useEffect, useCallback } from 'react';
import { makeApi, SupersetClient, t } from '@superset-ui/core';
import { createErrorHandler } from 'src/views/CRUD/utils';
import { FetchDataConfig } from 'src/components/ListView';
import { FilterValue } from 'src/components/ListView/types';
import Chart, { Slice } from 'src/types/Chart';
import copyTextToClipboard from 'src/utils/copy';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import { FavoriteStatus, ImportResourceName, DatabaseObject } from './types';
interface ListViewResourceState<D extends object = any> {
loading: boolean;
collection: D[];
count: number;
permissions: string[];
lastFetchDataConfig: FetchDataConfig | null;
bulkSelectEnabled: boolean;
lastFetched?: string;
}
const parsedErrorMessage = (
errorMessage: Record<string, string[]> | string,
) => {
if (typeof errorMessage === 'string') {
return errorMessage;
}
return Object.entries(errorMessage)
.map(([key, value]) => `(${key}) ${value.join(', ')}`)
.join('\n');
};
export function useListViewResource<D extends object = any>(
resource: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
infoEnable = true,
defaultCollectionValue: D[] = [],
baseFilters?: FilterValue[], // must be memoized
initialLoadingState = true,
) {
const [state, setState] = useState<ListViewResourceState<D>>({
count: 0,
collection: defaultCollectionValue,
loading: initialLoadingState,
lastFetchDataConfig: null,
permissions: [],
bulkSelectEnabled: false,
});
function updateState(update: Partial<ListViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
function toggleBulkSelect() {
updateState({ bulkSelectEnabled: !state.bulkSelectEnabled });
}
useEffect(() => {
if (!infoEnable) return;
SupersetClient.get({
endpoint: `/api/v1/${resource}/_info?q=${rison.encode({
keys: ['permissions'],
})}`,
}).then(
({ json: infoJson = {} }) => {
updateState({
permissions: infoJson.permissions,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %s info: %s',
resourceLabel,
errMsg,
),
),
),
);
}, []);
function hasPerm(perm: string) {
if (!state.permissions.length) {
return false;
}
return Boolean(state.permissions.find(p => p === perm));
}
const fetchData = useCallback(
({
pageIndex,
pageSize,
sortBy,
filters: filterValues,
}: FetchDataConfig) => {
// set loading state, cache the last config for refreshing data.
updateState({
lastFetchDataConfig: {
filters: filterValues,
pageIndex,
pageSize,
sortBy,
},
loading: true,
});
const filterExps = (baseFilters || [])
.concat(filterValues)
.map(({ id, operator: opr, value }) => ({
col: id,
opr,
value,
}));
const queryParams = rison.encode({
order_column: sortBy[0].id,
order_direction: sortBy[0].desc ? 'desc' : 'asc',
page: pageIndex,
page_size: pageSize,
...(filterExps.length ? { filters: filterExps } : {}),
});
return SupersetClient.get({
endpoint: `/api/v1/${resource}/?q=${queryParams}`,
})
.then(
({ json = {} }) => {
updateState({
collection: json.result,
count: json.count,
lastFetched: new Date().toISOString(),
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
errMsg,
),
),
),
)
.finally(() => {
updateState({ loading: false });
});
},
[baseFilters],
);
return {
state: {
loading: state.loading,
resourceCount: state.count,
resourceCollection: state.collection,
bulkSelectEnabled: state.bulkSelectEnabled,
lastFetched: state.lastFetched,
},
setResourceCollection: (update: D[]) =>
updateState({
collection: update,
}),
hasPerm,
fetchData,
toggleBulkSelect,
refreshData: (provideConfig?: FetchDataConfig) => {
if (state.lastFetchDataConfig) {
return fetchData(state.lastFetchDataConfig);
}
if (provideConfig) {
return fetchData(provideConfig);
}
return null;
},
};
}
// In the same vein as above, a hook for viewing a single instance of a resource (given id)
interface SingleViewResourceState<D extends object = any> {
loading: boolean;
resource: D | null;
error: string | Record<string, string[]> | null;
}
export function useSingleViewResource<D extends object = any>(
resourceName: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<SingleViewResourceState<D>>({
loading: false,
resource: null,
error: null,
});
function updateState(update: Partial<SingleViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
const fetchResource = useCallback(
(resourceID: number) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.get({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const createResource = useCallback(
(resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.id;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while creating %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const updateResource = useCallback(
(resourceID: number, resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.put({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler(errMsg => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
JSON.stringify(errMsg),
),
);
updateState({
error: errMsg,
});
return errMsg;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const clearError = () =>
updateState({
error: null,
});
return {
state,
setResource: (update: D) =>
updateState({
resource: update,
}),
fetchResource,
createResource,
updateResource,
clearError,
};
}
interface ImportResourceState {
loading: boolean;
passwordsNeeded: string[];
alreadyExists: string[];
}
export function useImportResource(
resourceName: ImportResourceName,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<ImportResourceState>({
loading: false,
passwordsNeeded: [],
alreadyExists: [],
});
function updateState(update: Partial<ImportResourceState>) {
setState(currentState => ({ ...currentState, ...update }));
}
/* eslint-disable no-underscore-dangle */
const isNeedsPassword = (payload: any) =>
typeof payload === 'object' &&
Array.isArray(payload._schema) &&
payload._schema.length === 1 &&
payload._schema[0] === 'Must provide a password for the database';
const isAlreadyExists = (payload: any) =>
typeof payload === 'string' &&
payload.includes('already exists and `overwrite=true` was not passed');
const getPasswordsNeeded = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isNeedsPassword(validationErrors))
.map(([fileName]) => fileName);
const getAlreadyExists = (errMsg: Record<string, Record<string, string[]>>) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isAlreadyExists(validationErrors))
.map(([fileName]) => fileName);
const hasTerminalValidation = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.values(errMsg).some(
validationErrors =>
!isNeedsPassword(validationErrors) &&
!isAlreadyExists(validationErrors),
);
const importResource = useCallback(
(
bundle: File,
databasePasswords: Record<string, string> = {},
overwrite = false,
) => {
// Set loading state
updateState({
loading: true,
});
const formData = new FormData();
formData.append('formData', bundle);
/* The import bundle never contains database passwords; if required
* they should be provided by the user during import.
*/
if (databasePasswords) {
formData.append('passwords', JSON.stringify(databasePasswords));
}
/* If the imported model already exists the user needs to confirm
* that they want to overwrite it.
*/
if (overwrite) {
formData.append('overwrite', 'true');
}
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/import/`,
body: formData,
})
.then(() => true)
.catch(response =>
getClientErrorObject(response).then(error => {
const errMsg = error.message || error.error;
if (typeof errMsg === 'string') {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
return false;
}
if (hasTerminalValidation(errMsg)) {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
} else {
updateState({
passwordsNeeded: getPasswordsNeeded(errMsg),
alreadyExists: getAlreadyExists(errMsg),
});
}
return false;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[],
);
return { state, importResource };
}
enum FavStarClassName {
CHART = 'slice',
DASHBOARD = 'Dashboard',
}
type FavoriteStatusResponse = {
result: Array<{
id: string;
value: boolean;
}>;
};
const favoriteApis = {
chart: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/chart/favorite_status/',
}),
dashboard: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/dashboard/favorite_status/',
}),
};
export function useFavoriteStatus(
type: 'chart' | 'dashboard',
ids: Array<string | number>,
handleErrorMsg: (message: string) => void,
) {
const [favoriteStatus, setFavoriteStatus] = useState<FavoriteStatus>({});
const updateFavoriteStatus = (update: FavoriteStatus) =>
setFavoriteStatus(currentState => ({ ...currentState, ...update }));
useEffect(() => {
if (!ids.length) {
return;
}
favoriteApis[type](ids).then(
({ result }) => {
const update = result.reduce((acc, element) => {
acc[element.id] = element.value;
return acc;
}, {});
updateFavoriteStatus(update);
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error fetching the favorite status: %s', errMsg),
),
),
);
}, [ids, type, handleErrorMsg]);
const saveFaveStar = useCallback(
(id: number, isStarred: boolean) => {
const urlSuffix = isStarred ? 'unselect' : 'select';
SupersetClient.get({
endpoint: `/superset/favstar/${
type === 'chart' ? FavStarClassName.CHART : FavStarClassName.DASHBOARD
}/${id}/${urlSuffix}/`,
}).then(
({ json }) => {
updateFavoriteStatus({
[id]: (json as { count: number })?.count > 0,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error saving the favorite status: %s', errMsg),
),
),
);
},
[type],
);
return [saveFaveStar, favoriteStatus] as const;
}
export const useChartEditModal = (
setCharts: (charts: Array<Chart>) => void,
charts: Array<Chart>,
) => {
const [
sliceCurrentlyEditing,
setSliceCurrentlyEditing,
] = useState<Slice | null>(null);
function openChartEditModal(chart: Chart) {
setSliceCurrentlyEditing({
slice_id: chart.id,
slice_name: chart.slice_name,
description: chart.description,
cache_timeout: chart.cache_timeout,
});
}
function closeChartEditModal() {
setSliceCurrentlyEditing(null);
}
function handleChartUpdated(edits: Chart) {
// update the chart in our state with the edited info
const newCharts = charts.map((chart: Chart) =>
chart.id === edits.id ? { ...chart, ...edits } : chart,
);
setCharts(newCharts);
}
return {
sliceCurrentlyEditing,
handleChartUpdated,
openChartEditModal,
closeChartEditModal,
};
};
export const copyQueryLink = (
id: number,
addDangerToast: (arg0: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
copyTextToClipboard(
`${window.location.origin}/superset/sqllab?savedQueryId=${id}`,
)
.then(() => {
addSuccessToast(t('Link Copied!'));
})
.catch(() => {
addDangerToast(t('Sorry, your browser does not support copying.'));
});
};
export const testDatabaseConnection = (
connection: DatabaseObject,
handleErrorMsg: (errorMsg: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
SupersetClient.post({
endpoint: 'api/v1/database/test_connection',
body: JSON.stringify(connection),
headers: { 'Content-Type': 'application/json' },
}).then(
() => {
addSuccessToast(t('Connection looks good!'));
},
createErrorHandler((errMsg: Record<string, string[]> | string) => {
handleErrorMsg(t(`${t('ERROR: ')}${parsedErrorMessage(errMsg)}`));
}),
);
};
| superset-frontend/src/views/CRUD/hooks.ts | 1 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.9992458820343018,
0.07490085065364838,
0.00016332043742295355,
0.00017264776397496462,
0.2552616000175476
] |
{
"id": 5,
"code_window": [
" const isAlreadyExists = (payload: any) =>\n",
" typeof payload === 'string' &&\n",
" payload.includes('already exists and `overwrite=true` was not passed');\n",
"\n",
" const getPasswordsNeeded = (\n",
" errMsg: Record<string, Record<string, string[]>>,\n",
" ) =>\n",
" Object.entries(errMsg)\n",
" .filter(([, validationErrors]) => isNeedsPassword(validationErrors))\n",
" .map(([fileName]) => fileName);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" errMsg: Record<string, Record<string, string[] | string>>,\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 393
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
describe('Annotations', () => {
beforeEach(() => {
cy.login();
cy.intercept('GET', '/superset/explore_json/**').as('getJson');
cy.intercept('POST', '/superset/explore_json/**').as('postJson');
});
it('Create formula annotation y-axis goal line', () => {
cy.visitChartByName('Num Births Trend');
cy.verifySliceSuccess({ waitAlias: '@postJson' });
const layerLabel = 'Goal line';
cy.get('[data-test=annotation_layers]').click();
cy.get('[data-test="popover-content"]').within(() => {
cy.get('[data-test=annotation-layer-name-header]')
.siblings()
.first()
.within(() => {
cy.get('input').type(layerLabel);
});
cy.get('[data-test=annotation-layer-value-header]')
.siblings()
.first()
.within(() => {
cy.get('input').type('y=1400000');
});
cy.get('button').contains('OK').click();
});
cy.get('button[data-test="run-query-button"]').click();
cy.get('[data-test=annotation_layers]').contains(layerLabel);
cy.verifySliceSuccess({
waitAlias: '@postJson',
chartSelector: 'svg',
});
cy.get('.nv-legend-text').should('have.length', 2);
});
});
| superset-frontend/cypress-base/cypress/integration/explore/annotations.test.ts | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017735440633259714,
0.00017551016935613006,
0.0001739550061756745,
0.0001757340505719185,
0.0000011799403409895604
] |
{
"id": 5,
"code_window": [
" const isAlreadyExists = (payload: any) =>\n",
" typeof payload === 'string' &&\n",
" payload.includes('already exists and `overwrite=true` was not passed');\n",
"\n",
" const getPasswordsNeeded = (\n",
" errMsg: Record<string, Record<string, string[]>>,\n",
" ) =>\n",
" Object.entries(errMsg)\n",
" .filter(([, validationErrors]) => isNeedsPassword(validationErrors))\n",
" .map(([fileName]) => fileName);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" errMsg: Record<string, Record<string, string[] | string>>,\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 393
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
| superset-websocket/utils/client-ws-app/app.js | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.0001765814085956663,
0.00017400464275851846,
0.0001683929149294272,
0.000175591092556715,
0.0000029386822006927105
] |
{
"id": 5,
"code_window": [
" const isAlreadyExists = (payload: any) =>\n",
" typeof payload === 'string' &&\n",
" payload.includes('already exists and `overwrite=true` was not passed');\n",
"\n",
" const getPasswordsNeeded = (\n",
" errMsg: Record<string, Record<string, string[]>>,\n",
" ) =>\n",
" Object.entries(errMsg)\n",
" .filter(([, validationErrors]) => isNeedsPassword(validationErrors))\n",
" .map(([fileName]) => fileName);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" errMsg: Record<string, Record<string, string[] | string>>,\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 393
} | <!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
-->
<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.36155 14.6109C7.36155 15.536 6.60586 16.2917 5.68078 16.2917C4.7557 16.2917 4 15.536 4 14.6109C4 13.6858 4.7557 12.9301 5.68078 12.9301H7.36155V14.6109Z" fill="currentColor"/>
<path d="M8.2085 14.6109C8.2085 13.6858 8.96419 12.9301 9.88927 12.9301C10.8144 12.9301 11.5701 13.6858 11.5701 14.6109V18.8193C11.5701 19.7444 10.8144 20.5001 9.88927 20.5001C8.96419 20.5001 8.2085 19.7444 8.2085 18.8193V14.6109Z" fill="currentColor"/>
<path d="M9.88927 7.86155C8.96419 7.86155 8.2085 7.10586 8.2085 6.18078C8.2085 5.2557 8.96419 4.5 9.88927 4.5C10.8144 4.5 11.5701 5.2557 11.5701 6.18078V7.86155H9.88927Z" fill="currentColor"/>
<path d="M9.88926 8.70845C10.8143 8.70845 11.57 9.46415 11.57 10.3892C11.57 11.3143 10.8143 12.07 9.88926 12.07H5.68079C4.7557 12.07 4 11.3143 4 10.3892C4 9.46415 4.7557 8.70845 5.68079 8.70845H9.88926Z" fill="currentColor"/>
<path d="M16.6385 10.3892C16.6385 9.46415 17.3942 8.70845 18.3193 8.70845C19.2444 8.70845 20.0001 9.46415 20.0001 10.3892C20.0001 11.3143 19.2444 12.07 18.3193 12.07H16.6385V10.3892Z" fill="currentColor"/>
<path d="M15.7917 10.3893C15.7917 11.3143 15.036 12.07 14.111 12.07C13.1859 12.07 12.4302 11.3143 12.4302 10.3893V6.18079C12.4302 5.2557 13.1859 4.5 14.111 4.5C15.036 4.5 15.7917 5.2557 15.7917 6.18079V10.3893Z" fill="currentColor"/>
<path d="M14.111 17.1385C15.036 17.1385 15.7917 17.8942 15.7917 18.8193C15.7917 19.7444 15.036 20.5001 14.111 20.5001C13.1859 20.5001 12.4302 19.7444 12.4302 18.8193V17.1385H14.111Z" fill="currentColor"/>
<path d="M14.111 16.2917C13.1859 16.2917 12.4302 15.536 12.4302 14.6109C12.4302 13.6858 13.1859 12.9301 14.111 12.9301H18.3194C19.2445 12.9301 20.0002 13.6858 20.0002 14.6109C20.0002 15.536 19.2445 16.2917 18.3194 16.2917H14.111Z" fill="currentColor"/>
</svg>
| superset-frontend/images/icons/slack.svg | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00019559114298317581,
0.00018416177772451192,
0.00017773614672478288,
0.00017915808712132275,
0.000008102593710646033
] |
{
"id": 6,
"code_window": [
" ) =>\n",
" Object.entries(errMsg)\n",
" .filter(([, validationErrors]) => isNeedsPassword(validationErrors))\n",
" .map(([fileName]) => fileName);\n",
"\n",
" const getAlreadyExists = (errMsg: Record<string, Record<string, string[]>>) =>\n",
" Object.entries(errMsg)\n",
" .filter(([, validationErrors]) => isAlreadyExists(validationErrors))\n",
" .map(([fileName]) => fileName);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const getAlreadyExists = (\n",
" errMsg: Record<string, Record<string, string[] | string>>,\n",
" ) =>\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 399
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 rison from 'rison';
import { useState, useEffect, useCallback } from 'react';
import { makeApi, SupersetClient, t } from '@superset-ui/core';
import { createErrorHandler } from 'src/views/CRUD/utils';
import { FetchDataConfig } from 'src/components/ListView';
import { FilterValue } from 'src/components/ListView/types';
import Chart, { Slice } from 'src/types/Chart';
import copyTextToClipboard from 'src/utils/copy';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import { FavoriteStatus, ImportResourceName, DatabaseObject } from './types';
interface ListViewResourceState<D extends object = any> {
loading: boolean;
collection: D[];
count: number;
permissions: string[];
lastFetchDataConfig: FetchDataConfig | null;
bulkSelectEnabled: boolean;
lastFetched?: string;
}
const parsedErrorMessage = (
errorMessage: Record<string, string[]> | string,
) => {
if (typeof errorMessage === 'string') {
return errorMessage;
}
return Object.entries(errorMessage)
.map(([key, value]) => `(${key}) ${value.join(', ')}`)
.join('\n');
};
export function useListViewResource<D extends object = any>(
resource: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
infoEnable = true,
defaultCollectionValue: D[] = [],
baseFilters?: FilterValue[], // must be memoized
initialLoadingState = true,
) {
const [state, setState] = useState<ListViewResourceState<D>>({
count: 0,
collection: defaultCollectionValue,
loading: initialLoadingState,
lastFetchDataConfig: null,
permissions: [],
bulkSelectEnabled: false,
});
function updateState(update: Partial<ListViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
function toggleBulkSelect() {
updateState({ bulkSelectEnabled: !state.bulkSelectEnabled });
}
useEffect(() => {
if (!infoEnable) return;
SupersetClient.get({
endpoint: `/api/v1/${resource}/_info?q=${rison.encode({
keys: ['permissions'],
})}`,
}).then(
({ json: infoJson = {} }) => {
updateState({
permissions: infoJson.permissions,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %s info: %s',
resourceLabel,
errMsg,
),
),
),
);
}, []);
function hasPerm(perm: string) {
if (!state.permissions.length) {
return false;
}
return Boolean(state.permissions.find(p => p === perm));
}
const fetchData = useCallback(
({
pageIndex,
pageSize,
sortBy,
filters: filterValues,
}: FetchDataConfig) => {
// set loading state, cache the last config for refreshing data.
updateState({
lastFetchDataConfig: {
filters: filterValues,
pageIndex,
pageSize,
sortBy,
},
loading: true,
});
const filterExps = (baseFilters || [])
.concat(filterValues)
.map(({ id, operator: opr, value }) => ({
col: id,
opr,
value,
}));
const queryParams = rison.encode({
order_column: sortBy[0].id,
order_direction: sortBy[0].desc ? 'desc' : 'asc',
page: pageIndex,
page_size: pageSize,
...(filterExps.length ? { filters: filterExps } : {}),
});
return SupersetClient.get({
endpoint: `/api/v1/${resource}/?q=${queryParams}`,
})
.then(
({ json = {} }) => {
updateState({
collection: json.result,
count: json.count,
lastFetched: new Date().toISOString(),
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
errMsg,
),
),
),
)
.finally(() => {
updateState({ loading: false });
});
},
[baseFilters],
);
return {
state: {
loading: state.loading,
resourceCount: state.count,
resourceCollection: state.collection,
bulkSelectEnabled: state.bulkSelectEnabled,
lastFetched: state.lastFetched,
},
setResourceCollection: (update: D[]) =>
updateState({
collection: update,
}),
hasPerm,
fetchData,
toggleBulkSelect,
refreshData: (provideConfig?: FetchDataConfig) => {
if (state.lastFetchDataConfig) {
return fetchData(state.lastFetchDataConfig);
}
if (provideConfig) {
return fetchData(provideConfig);
}
return null;
},
};
}
// In the same vein as above, a hook for viewing a single instance of a resource (given id)
interface SingleViewResourceState<D extends object = any> {
loading: boolean;
resource: D | null;
error: string | Record<string, string[]> | null;
}
export function useSingleViewResource<D extends object = any>(
resourceName: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<SingleViewResourceState<D>>({
loading: false,
resource: null,
error: null,
});
function updateState(update: Partial<SingleViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
const fetchResource = useCallback(
(resourceID: number) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.get({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const createResource = useCallback(
(resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.id;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while creating %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const updateResource = useCallback(
(resourceID: number, resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.put({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler(errMsg => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
JSON.stringify(errMsg),
),
);
updateState({
error: errMsg,
});
return errMsg;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const clearError = () =>
updateState({
error: null,
});
return {
state,
setResource: (update: D) =>
updateState({
resource: update,
}),
fetchResource,
createResource,
updateResource,
clearError,
};
}
interface ImportResourceState {
loading: boolean;
passwordsNeeded: string[];
alreadyExists: string[];
}
export function useImportResource(
resourceName: ImportResourceName,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<ImportResourceState>({
loading: false,
passwordsNeeded: [],
alreadyExists: [],
});
function updateState(update: Partial<ImportResourceState>) {
setState(currentState => ({ ...currentState, ...update }));
}
/* eslint-disable no-underscore-dangle */
const isNeedsPassword = (payload: any) =>
typeof payload === 'object' &&
Array.isArray(payload._schema) &&
payload._schema.length === 1 &&
payload._schema[0] === 'Must provide a password for the database';
const isAlreadyExists = (payload: any) =>
typeof payload === 'string' &&
payload.includes('already exists and `overwrite=true` was not passed');
const getPasswordsNeeded = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isNeedsPassword(validationErrors))
.map(([fileName]) => fileName);
const getAlreadyExists = (errMsg: Record<string, Record<string, string[]>>) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isAlreadyExists(validationErrors))
.map(([fileName]) => fileName);
const hasTerminalValidation = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.values(errMsg).some(
validationErrors =>
!isNeedsPassword(validationErrors) &&
!isAlreadyExists(validationErrors),
);
const importResource = useCallback(
(
bundle: File,
databasePasswords: Record<string, string> = {},
overwrite = false,
) => {
// Set loading state
updateState({
loading: true,
});
const formData = new FormData();
formData.append('formData', bundle);
/* The import bundle never contains database passwords; if required
* they should be provided by the user during import.
*/
if (databasePasswords) {
formData.append('passwords', JSON.stringify(databasePasswords));
}
/* If the imported model already exists the user needs to confirm
* that they want to overwrite it.
*/
if (overwrite) {
formData.append('overwrite', 'true');
}
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/import/`,
body: formData,
})
.then(() => true)
.catch(response =>
getClientErrorObject(response).then(error => {
const errMsg = error.message || error.error;
if (typeof errMsg === 'string') {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
return false;
}
if (hasTerminalValidation(errMsg)) {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
} else {
updateState({
passwordsNeeded: getPasswordsNeeded(errMsg),
alreadyExists: getAlreadyExists(errMsg),
});
}
return false;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[],
);
return { state, importResource };
}
enum FavStarClassName {
CHART = 'slice',
DASHBOARD = 'Dashboard',
}
type FavoriteStatusResponse = {
result: Array<{
id: string;
value: boolean;
}>;
};
const favoriteApis = {
chart: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/chart/favorite_status/',
}),
dashboard: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/dashboard/favorite_status/',
}),
};
export function useFavoriteStatus(
type: 'chart' | 'dashboard',
ids: Array<string | number>,
handleErrorMsg: (message: string) => void,
) {
const [favoriteStatus, setFavoriteStatus] = useState<FavoriteStatus>({});
const updateFavoriteStatus = (update: FavoriteStatus) =>
setFavoriteStatus(currentState => ({ ...currentState, ...update }));
useEffect(() => {
if (!ids.length) {
return;
}
favoriteApis[type](ids).then(
({ result }) => {
const update = result.reduce((acc, element) => {
acc[element.id] = element.value;
return acc;
}, {});
updateFavoriteStatus(update);
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error fetching the favorite status: %s', errMsg),
),
),
);
}, [ids, type, handleErrorMsg]);
const saveFaveStar = useCallback(
(id: number, isStarred: boolean) => {
const urlSuffix = isStarred ? 'unselect' : 'select';
SupersetClient.get({
endpoint: `/superset/favstar/${
type === 'chart' ? FavStarClassName.CHART : FavStarClassName.DASHBOARD
}/${id}/${urlSuffix}/`,
}).then(
({ json }) => {
updateFavoriteStatus({
[id]: (json as { count: number })?.count > 0,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error saving the favorite status: %s', errMsg),
),
),
);
},
[type],
);
return [saveFaveStar, favoriteStatus] as const;
}
export const useChartEditModal = (
setCharts: (charts: Array<Chart>) => void,
charts: Array<Chart>,
) => {
const [
sliceCurrentlyEditing,
setSliceCurrentlyEditing,
] = useState<Slice | null>(null);
function openChartEditModal(chart: Chart) {
setSliceCurrentlyEditing({
slice_id: chart.id,
slice_name: chart.slice_name,
description: chart.description,
cache_timeout: chart.cache_timeout,
});
}
function closeChartEditModal() {
setSliceCurrentlyEditing(null);
}
function handleChartUpdated(edits: Chart) {
// update the chart in our state with the edited info
const newCharts = charts.map((chart: Chart) =>
chart.id === edits.id ? { ...chart, ...edits } : chart,
);
setCharts(newCharts);
}
return {
sliceCurrentlyEditing,
handleChartUpdated,
openChartEditModal,
closeChartEditModal,
};
};
export const copyQueryLink = (
id: number,
addDangerToast: (arg0: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
copyTextToClipboard(
`${window.location.origin}/superset/sqllab?savedQueryId=${id}`,
)
.then(() => {
addSuccessToast(t('Link Copied!'));
})
.catch(() => {
addDangerToast(t('Sorry, your browser does not support copying.'));
});
};
export const testDatabaseConnection = (
connection: DatabaseObject,
handleErrorMsg: (errorMsg: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
SupersetClient.post({
endpoint: 'api/v1/database/test_connection',
body: JSON.stringify(connection),
headers: { 'Content-Type': 'application/json' },
}).then(
() => {
addSuccessToast(t('Connection looks good!'));
},
createErrorHandler((errMsg: Record<string, string[]> | string) => {
handleErrorMsg(t(`${t('ERROR: ')}${parsedErrorMessage(errMsg)}`));
}),
);
};
| superset-frontend/src/views/CRUD/hooks.ts | 1 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.999061644077301,
0.06212028115987778,
0.0001617386151337996,
0.00017008472059387714,
0.23975017666816711
] |
{
"id": 6,
"code_window": [
" ) =>\n",
" Object.entries(errMsg)\n",
" .filter(([, validationErrors]) => isNeedsPassword(validationErrors))\n",
" .map(([fileName]) => fileName);\n",
"\n",
" const getAlreadyExists = (errMsg: Record<string, Record<string, string[]>>) =>\n",
" Object.entries(errMsg)\n",
" .filter(([, validationErrors]) => isAlreadyExists(validationErrors))\n",
" .map(([fileName]) => fileName);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const getAlreadyExists = (\n",
" errMsg: Record<string, Record<string, string[] | string>>,\n",
" ) =>\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 399
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
from abc import ABC, abstractmethod
from typing import Any
class BaseCommand(ABC):
"""
Base class for all Command like Superset Logic objects
"""
@abstractmethod
def run(self) -> Any:
"""
Run executes the command. Can raise command exceptions
:raises: CommandException
"""
@abstractmethod
def validate(self) -> None:
"""
Validate is normally called by run to validate data.
Will raise exception if validation fails
:raises: CommandException
"""
| superset/commands/base.py | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.0017726885853335261,
0.000572834222111851,
0.000165305333212018,
0.0001766714412951842,
0.0006927517824806273
] |
{
"id": 6,
"code_window": [
" ) =>\n",
" Object.entries(errMsg)\n",
" .filter(([, validationErrors]) => isNeedsPassword(validationErrors))\n",
" .map(([fileName]) => fileName);\n",
"\n",
" const getAlreadyExists = (errMsg: Record<string, Record<string, string[]>>) =>\n",
" Object.entries(errMsg)\n",
" .filter(([, validationErrors]) => isAlreadyExists(validationErrors))\n",
" .map(([fileName]) => fileName);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const getAlreadyExists = (\n",
" errMsg: Record<string, Record<string, string[] | string>>,\n",
" ) =>\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 399
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 { FORM_DATA_DEFAULTS, NUM_METRIC } from './shared.helper';
describe('Visualization > Distribution bar chart', () => {
const VIZ_DEFAULTS = { ...FORM_DATA_DEFAULTS, viz_type: 'dist_bar' };
beforeEach(() => {
cy.login();
cy.intercept('POST', '/superset/explore_json/**').as('getJson');
});
it('should work with adhoc metric', () => {
const formData = {
...VIZ_DEFAULTS,
metrics: NUM_METRIC,
groupby: ['state'],
};
cy.visitChartByParams(JSON.stringify(formData));
cy.verifySliceSuccess({
waitAlias: '@getJson',
querySubstring: NUM_METRIC.label,
chartSelector: 'svg',
});
});
it('should work with series', () => {
const formData = {
...VIZ_DEFAULTS,
metrics: NUM_METRIC,
groupby: ['state'],
columns: ['gender'],
};
cy.visitChartByParams(JSON.stringify(formData));
cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' });
});
it('should work with row limit', () => {
const formData = {
...VIZ_DEFAULTS,
metrics: NUM_METRIC,
groupby: ['state'],
row_limit: 10,
};
cy.visitChartByParams(JSON.stringify(formData));
cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' });
});
it('should work with contribution', () => {
const formData = {
...VIZ_DEFAULTS,
metrics: NUM_METRIC,
groupby: ['state'],
columns: ['gender'],
contribution: true,
};
cy.visitChartByParams(JSON.stringify(formData));
cy.verifySliceSuccess({ waitAlias: '@getJson', chartSelector: 'svg' });
});
});
| superset-frontend/cypress-base/cypress/integration/explore/visualizations/dist_bar.test.js | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017596740508452058,
0.0001738543069222942,
0.0001696913968771696,
0.00017445730918552727,
0.0000017971585748455254
] |
{
"id": 6,
"code_window": [
" ) =>\n",
" Object.entries(errMsg)\n",
" .filter(([, validationErrors]) => isNeedsPassword(validationErrors))\n",
" .map(([fileName]) => fileName);\n",
"\n",
" const getAlreadyExists = (errMsg: Record<string, Record<string, string[]>>) =>\n",
" Object.entries(errMsg)\n",
" .filter(([, validationErrors]) => isAlreadyExists(validationErrors))\n",
" .map(([fileName]) => fileName);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const getAlreadyExists = (\n",
" errMsg: Record<string, Record<string, string[] | string>>,\n",
" ) =>\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 399
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 React from 'react';
import PropTypes from 'prop-types';
const propTypes = {
onUndo: PropTypes.func.isRequired,
onRedo: PropTypes.func.isRequired,
};
class UndoRedoKeyListeners extends React.PureComponent {
constructor(props) {
super(props);
this.handleKeydown = this.handleKeydown.bind(this);
}
componentDidMount() {
document.addEventListener('keydown', this.handleKeydown);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.handleKeydown);
}
handleKeydown(event) {
const controlOrCommand = event.ctrlKey || event.metaKey;
if (controlOrCommand) {
const isZChar = event.key === 'z' || event.keyCode === 90;
const isYChar = event.key === 'y' || event.keyCode === 89;
const isEditingMarkdown =
document && document.querySelector('.dashboard-markdown--editing');
if (!isEditingMarkdown && (isZChar || isYChar)) {
event.preventDefault();
const func = isZChar ? this.props.onUndo : this.props.onRedo;
func();
}
}
}
render() {
return null;
}
}
UndoRedoKeyListeners.propTypes = propTypes;
export default UndoRedoKeyListeners;
| superset-frontend/src/dashboard/components/UndoRedoKeyListeners/index.jsx | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017503148410469294,
0.00017216602282132953,
0.00016699207480996847,
0.0001727159251458943,
0.0000028078184186597355
] |
{
"id": 7,
"code_window": [
" .map(([fileName]) => fileName);\n",
"\n",
" const hasTerminalValidation = (\n",
" errMsg: Record<string, Record<string, string[]>>,\n",
" ) =>\n",
" Object.values(errMsg).some(\n",
" validationErrors =>\n",
" !isNeedsPassword(validationErrors) &&\n",
" !isAlreadyExists(validationErrors),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" errMsg: Record<string, Record<string, string[] | string>>,\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 405
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 rison from 'rison';
import { useState, useEffect, useCallback } from 'react';
import { makeApi, SupersetClient, t } from '@superset-ui/core';
import { createErrorHandler } from 'src/views/CRUD/utils';
import { FetchDataConfig } from 'src/components/ListView';
import { FilterValue } from 'src/components/ListView/types';
import Chart, { Slice } from 'src/types/Chart';
import copyTextToClipboard from 'src/utils/copy';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import { FavoriteStatus, ImportResourceName, DatabaseObject } from './types';
interface ListViewResourceState<D extends object = any> {
loading: boolean;
collection: D[];
count: number;
permissions: string[];
lastFetchDataConfig: FetchDataConfig | null;
bulkSelectEnabled: boolean;
lastFetched?: string;
}
const parsedErrorMessage = (
errorMessage: Record<string, string[]> | string,
) => {
if (typeof errorMessage === 'string') {
return errorMessage;
}
return Object.entries(errorMessage)
.map(([key, value]) => `(${key}) ${value.join(', ')}`)
.join('\n');
};
export function useListViewResource<D extends object = any>(
resource: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
infoEnable = true,
defaultCollectionValue: D[] = [],
baseFilters?: FilterValue[], // must be memoized
initialLoadingState = true,
) {
const [state, setState] = useState<ListViewResourceState<D>>({
count: 0,
collection: defaultCollectionValue,
loading: initialLoadingState,
lastFetchDataConfig: null,
permissions: [],
bulkSelectEnabled: false,
});
function updateState(update: Partial<ListViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
function toggleBulkSelect() {
updateState({ bulkSelectEnabled: !state.bulkSelectEnabled });
}
useEffect(() => {
if (!infoEnable) return;
SupersetClient.get({
endpoint: `/api/v1/${resource}/_info?q=${rison.encode({
keys: ['permissions'],
})}`,
}).then(
({ json: infoJson = {} }) => {
updateState({
permissions: infoJson.permissions,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %s info: %s',
resourceLabel,
errMsg,
),
),
),
);
}, []);
function hasPerm(perm: string) {
if (!state.permissions.length) {
return false;
}
return Boolean(state.permissions.find(p => p === perm));
}
const fetchData = useCallback(
({
pageIndex,
pageSize,
sortBy,
filters: filterValues,
}: FetchDataConfig) => {
// set loading state, cache the last config for refreshing data.
updateState({
lastFetchDataConfig: {
filters: filterValues,
pageIndex,
pageSize,
sortBy,
},
loading: true,
});
const filterExps = (baseFilters || [])
.concat(filterValues)
.map(({ id, operator: opr, value }) => ({
col: id,
opr,
value,
}));
const queryParams = rison.encode({
order_column: sortBy[0].id,
order_direction: sortBy[0].desc ? 'desc' : 'asc',
page: pageIndex,
page_size: pageSize,
...(filterExps.length ? { filters: filterExps } : {}),
});
return SupersetClient.get({
endpoint: `/api/v1/${resource}/?q=${queryParams}`,
})
.then(
({ json = {} }) => {
updateState({
collection: json.result,
count: json.count,
lastFetched: new Date().toISOString(),
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
errMsg,
),
),
),
)
.finally(() => {
updateState({ loading: false });
});
},
[baseFilters],
);
return {
state: {
loading: state.loading,
resourceCount: state.count,
resourceCollection: state.collection,
bulkSelectEnabled: state.bulkSelectEnabled,
lastFetched: state.lastFetched,
},
setResourceCollection: (update: D[]) =>
updateState({
collection: update,
}),
hasPerm,
fetchData,
toggleBulkSelect,
refreshData: (provideConfig?: FetchDataConfig) => {
if (state.lastFetchDataConfig) {
return fetchData(state.lastFetchDataConfig);
}
if (provideConfig) {
return fetchData(provideConfig);
}
return null;
},
};
}
// In the same vein as above, a hook for viewing a single instance of a resource (given id)
interface SingleViewResourceState<D extends object = any> {
loading: boolean;
resource: D | null;
error: string | Record<string, string[]> | null;
}
export function useSingleViewResource<D extends object = any>(
resourceName: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<SingleViewResourceState<D>>({
loading: false,
resource: null,
error: null,
});
function updateState(update: Partial<SingleViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
const fetchResource = useCallback(
(resourceID: number) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.get({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const createResource = useCallback(
(resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.id;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while creating %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const updateResource = useCallback(
(resourceID: number, resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.put({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler(errMsg => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
JSON.stringify(errMsg),
),
);
updateState({
error: errMsg,
});
return errMsg;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const clearError = () =>
updateState({
error: null,
});
return {
state,
setResource: (update: D) =>
updateState({
resource: update,
}),
fetchResource,
createResource,
updateResource,
clearError,
};
}
interface ImportResourceState {
loading: boolean;
passwordsNeeded: string[];
alreadyExists: string[];
}
export function useImportResource(
resourceName: ImportResourceName,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<ImportResourceState>({
loading: false,
passwordsNeeded: [],
alreadyExists: [],
});
function updateState(update: Partial<ImportResourceState>) {
setState(currentState => ({ ...currentState, ...update }));
}
/* eslint-disable no-underscore-dangle */
const isNeedsPassword = (payload: any) =>
typeof payload === 'object' &&
Array.isArray(payload._schema) &&
payload._schema.length === 1 &&
payload._schema[0] === 'Must provide a password for the database';
const isAlreadyExists = (payload: any) =>
typeof payload === 'string' &&
payload.includes('already exists and `overwrite=true` was not passed');
const getPasswordsNeeded = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isNeedsPassword(validationErrors))
.map(([fileName]) => fileName);
const getAlreadyExists = (errMsg: Record<string, Record<string, string[]>>) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isAlreadyExists(validationErrors))
.map(([fileName]) => fileName);
const hasTerminalValidation = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.values(errMsg).some(
validationErrors =>
!isNeedsPassword(validationErrors) &&
!isAlreadyExists(validationErrors),
);
const importResource = useCallback(
(
bundle: File,
databasePasswords: Record<string, string> = {},
overwrite = false,
) => {
// Set loading state
updateState({
loading: true,
});
const formData = new FormData();
formData.append('formData', bundle);
/* The import bundle never contains database passwords; if required
* they should be provided by the user during import.
*/
if (databasePasswords) {
formData.append('passwords', JSON.stringify(databasePasswords));
}
/* If the imported model already exists the user needs to confirm
* that they want to overwrite it.
*/
if (overwrite) {
formData.append('overwrite', 'true');
}
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/import/`,
body: formData,
})
.then(() => true)
.catch(response =>
getClientErrorObject(response).then(error => {
const errMsg = error.message || error.error;
if (typeof errMsg === 'string') {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
return false;
}
if (hasTerminalValidation(errMsg)) {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
} else {
updateState({
passwordsNeeded: getPasswordsNeeded(errMsg),
alreadyExists: getAlreadyExists(errMsg),
});
}
return false;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[],
);
return { state, importResource };
}
enum FavStarClassName {
CHART = 'slice',
DASHBOARD = 'Dashboard',
}
type FavoriteStatusResponse = {
result: Array<{
id: string;
value: boolean;
}>;
};
const favoriteApis = {
chart: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/chart/favorite_status/',
}),
dashboard: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/dashboard/favorite_status/',
}),
};
export function useFavoriteStatus(
type: 'chart' | 'dashboard',
ids: Array<string | number>,
handleErrorMsg: (message: string) => void,
) {
const [favoriteStatus, setFavoriteStatus] = useState<FavoriteStatus>({});
const updateFavoriteStatus = (update: FavoriteStatus) =>
setFavoriteStatus(currentState => ({ ...currentState, ...update }));
useEffect(() => {
if (!ids.length) {
return;
}
favoriteApis[type](ids).then(
({ result }) => {
const update = result.reduce((acc, element) => {
acc[element.id] = element.value;
return acc;
}, {});
updateFavoriteStatus(update);
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error fetching the favorite status: %s', errMsg),
),
),
);
}, [ids, type, handleErrorMsg]);
const saveFaveStar = useCallback(
(id: number, isStarred: boolean) => {
const urlSuffix = isStarred ? 'unselect' : 'select';
SupersetClient.get({
endpoint: `/superset/favstar/${
type === 'chart' ? FavStarClassName.CHART : FavStarClassName.DASHBOARD
}/${id}/${urlSuffix}/`,
}).then(
({ json }) => {
updateFavoriteStatus({
[id]: (json as { count: number })?.count > 0,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error saving the favorite status: %s', errMsg),
),
),
);
},
[type],
);
return [saveFaveStar, favoriteStatus] as const;
}
export const useChartEditModal = (
setCharts: (charts: Array<Chart>) => void,
charts: Array<Chart>,
) => {
const [
sliceCurrentlyEditing,
setSliceCurrentlyEditing,
] = useState<Slice | null>(null);
function openChartEditModal(chart: Chart) {
setSliceCurrentlyEditing({
slice_id: chart.id,
slice_name: chart.slice_name,
description: chart.description,
cache_timeout: chart.cache_timeout,
});
}
function closeChartEditModal() {
setSliceCurrentlyEditing(null);
}
function handleChartUpdated(edits: Chart) {
// update the chart in our state with the edited info
const newCharts = charts.map((chart: Chart) =>
chart.id === edits.id ? { ...chart, ...edits } : chart,
);
setCharts(newCharts);
}
return {
sliceCurrentlyEditing,
handleChartUpdated,
openChartEditModal,
closeChartEditModal,
};
};
export const copyQueryLink = (
id: number,
addDangerToast: (arg0: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
copyTextToClipboard(
`${window.location.origin}/superset/sqllab?savedQueryId=${id}`,
)
.then(() => {
addSuccessToast(t('Link Copied!'));
})
.catch(() => {
addDangerToast(t('Sorry, your browser does not support copying.'));
});
};
export const testDatabaseConnection = (
connection: DatabaseObject,
handleErrorMsg: (errorMsg: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
SupersetClient.post({
endpoint: 'api/v1/database/test_connection',
body: JSON.stringify(connection),
headers: { 'Content-Type': 'application/json' },
}).then(
() => {
addSuccessToast(t('Connection looks good!'));
},
createErrorHandler((errMsg: Record<string, string[]> | string) => {
handleErrorMsg(t(`${t('ERROR: ')}${parsedErrorMessage(errMsg)}`));
}),
);
};
| superset-frontend/src/views/CRUD/hooks.ts | 1 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.9990860223770142,
0.04469893127679825,
0.00016500659694429487,
0.0001716113038128242,
0.20053651928901672
] |
{
"id": 7,
"code_window": [
" .map(([fileName]) => fileName);\n",
"\n",
" const hasTerminalValidation = (\n",
" errMsg: Record<string, Record<string, string[]>>,\n",
" ) =>\n",
" Object.values(errMsg).some(\n",
" validationErrors =>\n",
" !isNeedsPassword(validationErrors) &&\n",
" !isAlreadyExists(validationErrors),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" errMsg: Record<string, Record<string, string[] | string>>,\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 405
} | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
#
# This is an example "local" configuration file. In order to set/override config
# options that ONLY apply to your local environment, simply copy/rename this file
# to docker/pythonpath/superset_config_docker.py
# It ends up being imported by docker/superset_config.py which is loaded by
# superset/config.py
#
SQLALCHEMY_DATABASE_URI = "postgresql+psycopg2://pguser:[email protected]/superset"
SQLALCHEMY_ECHO = True
| docker/pythonpath_dev/superset_config_local.example | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017837977793533355,
0.00017372747242916375,
0.00016946776304394007,
0.00017333491996396333,
0.00000364888865078683
] |
{
"id": 7,
"code_window": [
" .map(([fileName]) => fileName);\n",
"\n",
" const hasTerminalValidation = (\n",
" errMsg: Record<string, Record<string, string[]>>,\n",
" ) =>\n",
" Object.values(errMsg).some(\n",
" validationErrors =>\n",
" !isNeedsPassword(validationErrors) &&\n",
" !isAlreadyExists(validationErrors),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" errMsg: Record<string, Record<string, string[] | string>>,\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 405
} | {
"name": "client-ws-app",
"version": "0.0.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"version": "0.0.0",
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jade": "~1.11.0",
"jsonwebtoken": "^8.5.1",
"morgan": "~1.9.1"
}
},
"node_modules/accepts": {
"version": "1.3.7",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz",
"integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==",
"dependencies": {
"mime-types": "~2.1.24",
"negotiator": "0.6.2"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/acorn": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-2.7.0.tgz",
"integrity": "sha1-q259nYhqrKiwhbwzEreaGYQz8Oc=",
"bin": {
"acorn": "bin/acorn"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/acorn-globals": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-1.0.9.tgz",
"integrity": "sha1-VbtemGkVB7dFedBRNBMhfDgMVM8=",
"dependencies": {
"acorn": "^2.1.0"
}
},
"node_modules/align-text": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/align-text/-/align-text-0.1.4.tgz",
"integrity": "sha1-DNkKVhCT810KmSVsIrcGlDP60Rc=",
"dependencies": {
"kind-of": "^3.0.2",
"longest": "^1.0.1",
"repeat-string": "^1.5.2"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/amdefine": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz",
"integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=",
"engines": {
"node": ">=0.4.2"
}
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI="
},
"node_modules/asap": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/asap/-/asap-1.0.0.tgz",
"integrity": "sha1-sqRdpf36ILBJb8N2jMJ8EvqRan0="
},
"node_modules/basic-auth": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz",
"integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==",
"dependencies": {
"safe-buffer": "5.1.2"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/body-parser": {
"version": "1.18.3",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.3.tgz",
"integrity": "sha1-WykhmP/dVTs6DyDe0FkrlWlVyLQ=",
"dependencies": {
"bytes": "3.0.0",
"content-type": "~1.0.4",
"debug": "2.6.9",
"depd": "~1.1.2",
"http-errors": "~1.6.3",
"iconv-lite": "0.4.23",
"on-finished": "~2.3.0",
"qs": "6.5.2",
"raw-body": "2.3.3",
"type-is": "~1.6.16"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/buffer-equal-constant-time": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
"integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk="
},
"node_modules/bytes": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz",
"integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/camelcase": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz",
"integrity": "sha1-m7UwTS4LVmmLLHWLCKPqqdqlijk=",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/center-align": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/center-align/-/center-align-0.1.3.tgz",
"integrity": "sha1-qg0yYptu6XIgBBHL1EYckHvCt60=",
"dependencies": {
"align-text": "^0.1.3",
"lazy-cache": "^1.0.3"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/character-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/character-parser/-/character-parser-1.2.1.tgz",
"integrity": "sha1-wN3kqxgnE7kZuXCVmhI+zBow/NY="
},
"node_modules/clean-css": {
"version": "3.4.28",
"resolved": "https://registry.npmjs.org/clean-css/-/clean-css-3.4.28.tgz",
"integrity": "sha1-vxlF6C/ICPVWlebd6uwBQA79A/8=",
"dependencies": {
"commander": "2.8.x",
"source-map": "0.4.x"
},
"bin": {
"cleancss": "bin/cleancss"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/clean-css/node_modules/commander": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.8.1.tgz",
"integrity": "sha1-Br42f+v9oMMwqh4qBy09yXYkJdQ=",
"dependencies": {
"graceful-readlink": ">= 1.0.0"
},
"engines": {
"node": ">= 0.6.x"
}
},
"node_modules/cliui": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-2.1.0.tgz",
"integrity": "sha1-S0dXYP+AJkx2LDoXGQMukcf+oNE=",
"dependencies": {
"center-align": "^0.1.1",
"right-align": "^0.1.1",
"wordwrap": "0.0.2"
}
},
"node_modules/cliui/node_modules/wordwrap": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz",
"integrity": "sha1-t5Zpu0LstAn4PVg8rVLKF+qhZD8=",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/commander": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.6.0.tgz",
"integrity": "sha1-nfflL7Kgyw+4kFjugMMQQiXzfh0=",
"engines": {
"node": ">= 0.6.x"
}
},
"node_modules/constantinople": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/constantinople/-/constantinople-3.0.2.tgz",
"integrity": "sha1-S5RdmTeQe82Y7ldRIsOBdRZUQUE=",
"dependencies": {
"acorn": "^2.1.0"
}
},
"node_modules/content-disposition": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz",
"integrity": "sha1-DPaLud318r55YcOoUXjLhdunjLQ=",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/content-type": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz",
"integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie": {
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz",
"integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie-parser": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.4.tgz",
"integrity": "sha512-lo13tqF3JEtFO7FyA49CqbhaFkskRJ0u/UAiINgrIXeRCY41c88/zxtrECl8AKH3B0hj9q10+h3Kt8I7KlW4tw==",
"dependencies": {
"cookie": "0.3.1",
"cookie-signature": "1.0.6"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/cookie-signature": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw="
},
"node_modules/css": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/css/-/css-1.0.8.tgz",
"integrity": "sha1-k4aBHKgrzMnuf7WnMrHioxfIo+c=",
"dependencies": {
"css-parse": "1.0.4",
"css-stringify": "1.0.5"
}
},
"node_modules/css-parse": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/css-parse/-/css-parse-1.0.4.tgz",
"integrity": "sha1-OLBQP7+dqfVOnB29pg4UXHcRe90="
},
"node_modules/css-stringify": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/css-stringify/-/css-stringify-1.0.5.tgz",
"integrity": "sha1-sNBClG2ylTu50pKQCmy19tASIDE="
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/decamelize": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
"integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/depd": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
"integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/destroy": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
"integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
},
"node_modules/ecdsa-sig-formatter": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
"dependencies": {
"safe-buffer": "^5.0.1"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0="
},
"node_modules/encodeurl": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
"integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
},
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/express": {
"version": "4.16.4",
"resolved": "https://registry.npmjs.org/express/-/express-4.16.4.tgz",
"integrity": "sha512-j12Uuyb4FMrd/qQAm6uCHAkPtO8FDTRJZBDd5D2KOL2eLaz1yUNdUB/NOIyq0iU4q4cFarsUCrnFDPBcnksuOg==",
"dependencies": {
"accepts": "~1.3.5",
"array-flatten": "1.1.1",
"body-parser": "1.18.3",
"content-disposition": "0.5.2",
"content-type": "~1.0.4",
"cookie": "0.3.1",
"cookie-signature": "1.0.6",
"debug": "2.6.9",
"depd": "~1.1.2",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "1.1.1",
"fresh": "0.5.2",
"merge-descriptors": "1.0.1",
"methods": "~1.1.2",
"on-finished": "~2.3.0",
"parseurl": "~1.3.2",
"path-to-regexp": "0.1.7",
"proxy-addr": "~2.0.4",
"qs": "6.5.2",
"range-parser": "~1.2.0",
"safe-buffer": "5.1.2",
"send": "0.16.2",
"serve-static": "1.13.2",
"setprototypeof": "1.1.0",
"statuses": "~1.4.0",
"type-is": "~1.6.16",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
},
"engines": {
"node": ">= 0.10.0"
}
},
"node_modules/finalhandler": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.1.tgz",
"integrity": "sha512-Y1GUDo39ez4aHAw7MysnUD5JzYX+WaIj8I57kO3aEPT1fFRL4sr7mjei97FgnwhAyyzRYmQZaTHb2+9uZ1dPtg==",
"dependencies": {
"debug": "2.6.9",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"on-finished": "~2.3.0",
"parseurl": "~1.3.2",
"statuses": "~1.4.0",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/forwarded": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz",
"integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/graceful-readlink": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/graceful-readlink/-/graceful-readlink-1.0.1.tgz",
"integrity": "sha1-TK+tdrxi8C+gObL5Tpo906ORpyU="
},
"node_modules/http-errors": {
"version": "1.6.3",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz",
"integrity": "sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0=",
"dependencies": {
"depd": "~1.1.2",
"inherits": "2.0.3",
"setprototypeof": "1.1.0",
"statuses": ">= 1.4.0 < 2"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/iconv-lite": {
"version": "0.4.23",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.23.tgz",
"integrity": "sha512-neyTUVFtahjf0mB3dZT77u+8O0QB89jFdnBkd5P1JgYPbPaia3gXXOVL2fq8VyU2gMMD7SaN7QukTB/pmXYvDA==",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/inherits": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
"integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4="
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/is-buffer": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz",
"integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w=="
},
"node_modules/is-promise": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz",
"integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o="
},
"node_modules/jade": {
"version": "1.11.0",
"resolved": "https://registry.npmjs.org/jade/-/jade-1.11.0.tgz",
"integrity": "sha1-nIDlOMEtP7lcjZu5VZ+gzAQEBf0=",
"dependencies": {
"character-parser": "1.2.1",
"clean-css": "^3.1.9",
"commander": "~2.6.0",
"constantinople": "~3.0.1",
"jstransformer": "0.0.2",
"mkdirp": "~0.5.0",
"transformers": "2.1.0",
"uglify-js": "^2.4.19",
"void-elements": "~2.0.1",
"with": "~4.0.0"
},
"bin": {
"jade": "bin/jade.js"
}
},
"node_modules/jsonwebtoken": {
"version": "8.5.1",
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz",
"integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==",
"dependencies": {
"jws": "^3.2.2",
"lodash.includes": "^4.3.0",
"lodash.isboolean": "^3.0.3",
"lodash.isinteger": "^4.0.4",
"lodash.isnumber": "^3.0.3",
"lodash.isplainobject": "^4.0.6",
"lodash.isstring": "^4.0.1",
"lodash.once": "^4.0.0",
"ms": "^2.1.1",
"semver": "^5.6.0"
},
"engines": {
"node": ">=4",
"npm": ">=1.4.28"
}
},
"node_modules/jsonwebtoken/node_modules/ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"node_modules/jstransformer": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/jstransformer/-/jstransformer-0.0.2.tgz",
"integrity": "sha1-eq4pqQPRls+glz2IXT5HlH7Ndqs=",
"dependencies": {
"is-promise": "^2.0.0",
"promise": "^6.0.1"
}
},
"node_modules/jwa": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz",
"integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==",
"dependencies": {
"buffer-equal-constant-time": "1.0.1",
"ecdsa-sig-formatter": "1.0.11",
"safe-buffer": "^5.0.1"
}
},
"node_modules/jws": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz",
"integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==",
"dependencies": {
"jwa": "^1.4.1",
"safe-buffer": "^5.0.1"
}
},
"node_modules/kind-of": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
"integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
"dependencies": {
"is-buffer": "^1.1.5"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/lazy-cache": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-1.0.4.tgz",
"integrity": "sha1-odePw6UEdMuAhF07O24dpJpEbo4=",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/lodash.includes": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
"integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8="
},
"node_modules/lodash.isboolean": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
"integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY="
},
"node_modules/lodash.isinteger": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
"integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M="
},
"node_modules/lodash.isnumber": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
"integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w="
},
"node_modules/lodash.isplainobject": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
"integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs="
},
"node_modules/lodash.isstring": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
"integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE="
},
"node_modules/lodash.once": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
"integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w="
},
"node_modules/longest": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz",
"integrity": "sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc=",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/merge-descriptors": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz",
"integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E="
},
"node_modules/methods": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
"integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.4.1.tgz",
"integrity": "sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ==",
"bin": {
"mime": "cli.js"
}
},
"node_modules/mime-db": {
"version": "1.43.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.43.0.tgz",
"integrity": "sha512-+5dsGEEovYbT8UY9yD7eE4XTc4UwJ1jBYlgaQQF38ENsKR3wj/8q8RFZrF9WIZpB2V1ArTVFUva8sAul1NzRzQ==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.26",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.26.tgz",
"integrity": "sha512-01paPWYgLrkqAyrlDorC1uDwl2p3qZT7yl806vW7DvDoxwXi46jsjFbg+WdwotBIk6/MbEhO/dh5aZ5sNj/dWQ==",
"dependencies": {
"mime-db": "1.43.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/minimist": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz",
"integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0="
},
"node_modules/mkdirp": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz",
"integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=",
"dependencies": {
"minimist": "0.0.8"
},
"bin": {
"mkdirp": "bin/cmd.js"
}
},
"node_modules/morgan": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/morgan/-/morgan-1.9.1.tgz",
"integrity": "sha512-HQStPIV4y3afTiCYVxirakhlCfGkI161c76kKFca7Fk1JusM//Qeo1ej2XaMniiNeaZklMVrh3vTtIzpzwbpmA==",
"dependencies": {
"basic-auth": "~2.0.0",
"debug": "2.6.9",
"depd": "~1.1.2",
"on-finished": "~2.3.0",
"on-headers": "~1.0.1"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"node_modules/negotiator": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz",
"integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/on-finished": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
"integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/on-headers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz",
"integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/optimist": {
"version": "0.3.7",
"resolved": "https://registry.npmjs.org/optimist/-/optimist-0.3.7.tgz",
"integrity": "sha1-yQlBrVnkJzMokjB00s8ufLxuwNk=",
"dependencies": {
"wordwrap": "~0.0.2"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/path-to-regexp": {
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
"integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w="
},
"node_modules/promise": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/promise/-/promise-6.1.0.tgz",
"integrity": "sha1-LOcp9rlLRcJoka0GAsXJDgTG7vY=",
"dependencies": {
"asap": "~1.0.0"
}
},
"node_modules/proxy-addr": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.6.tgz",
"integrity": "sha512-dh/frvCBVmSsDYzw6n926jv974gddhkFPfiN8hPOi30Wax25QZyZEGveluCgliBnqmuM+UJmBErbAUFIoDbjOw==",
"dependencies": {
"forwarded": "~0.1.2",
"ipaddr.js": "1.9.1"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/qs": {
"version": "6.5.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz",
"integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==",
"engines": {
"node": ">=0.6"
}
},
"node_modules/range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/raw-body": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.3.3.tgz",
"integrity": "sha512-9esiElv1BrZoI3rCDuOuKCBRbuApGGaDPQfjSflGxdy4oyzqghxu6klEkkVIvBje+FF0BX9coEv8KqW6X/7njw==",
"dependencies": {
"bytes": "3.0.0",
"http-errors": "1.6.3",
"iconv-lite": "0.4.23",
"unpipe": "1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/repeat-string": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz",
"integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=",
"engines": {
"node": ">=0.10"
}
},
"node_modules/right-align": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/right-align/-/right-align-0.1.3.tgz",
"integrity": "sha1-YTObci/mo1FWiSENJOFMlhSGE+8=",
"dependencies": {
"align-text": "^0.1.1"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
"node_modules/semver": {
"version": "5.7.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz",
"integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==",
"bin": {
"semver": "bin/semver"
}
},
"node_modules/send": {
"version": "0.16.2",
"resolved": "https://registry.npmjs.org/send/-/send-0.16.2.tgz",
"integrity": "sha512-E64YFPUssFHEFBvpbbjr44NCLtI1AohxQ8ZSiJjQLskAdKuriYEP6VyGEsRDH8ScozGpkaX1BGvhanqCwkcEZw==",
"dependencies": {
"debug": "2.6.9",
"depd": "~1.1.2",
"destroy": "~1.0.4",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "0.5.2",
"http-errors": "~1.6.2",
"mime": "1.4.1",
"ms": "2.0.0",
"on-finished": "~2.3.0",
"range-parser": "~1.2.0",
"statuses": "~1.4.0"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/serve-static": {
"version": "1.13.2",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.13.2.tgz",
"integrity": "sha512-p/tdJrO4U387R9oMjb1oj7qSMaMfmOyd4j9hOFoxZe2baQszgHcSWjuya/CiT5kgZZKRudHNOA0pYXOl8rQ5nw==",
"dependencies": {
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"parseurl": "~1.3.2",
"send": "0.16.2"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/setprototypeof": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz",
"integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ=="
},
"node_modules/source-map": {
"version": "0.4.4",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz",
"integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=",
"dependencies": {
"amdefine": ">=0.0.4"
},
"engines": {
"node": ">=0.8.0"
}
},
"node_modules/statuses": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz",
"integrity": "sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/transformers": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/transformers/-/transformers-2.1.0.tgz",
"integrity": "sha1-XSPLNVYd2F3Gf7hIIwm0fVPM6ac=",
"dependencies": {
"css": "~1.0.8",
"promise": "~2.0",
"uglify-js": "~2.2.5"
}
},
"node_modules/transformers/node_modules/is-promise": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-1.0.1.tgz",
"integrity": "sha1-MVc3YcBX4zwukaq56W2gjO++duU="
},
"node_modules/transformers/node_modules/promise": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/promise/-/promise-2.0.0.tgz",
"integrity": "sha1-RmSKqdYFr10ucMMCS/WUNtoCuA4=",
"dependencies": {
"is-promise": "~1"
}
},
"node_modules/transformers/node_modules/source-map": {
"version": "0.1.43",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.1.43.tgz",
"integrity": "sha1-wkvBRspRfBRx9drL4lcbK3+eM0Y=",
"dependencies": {
"amdefine": ">=0.0.4"
},
"engines": {
"node": ">=0.8.0"
}
},
"node_modules/transformers/node_modules/uglify-js": {
"version": "2.2.5",
"resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.2.5.tgz",
"integrity": "sha1-puAqcNg5eSuXgEiLe4sYTAlcmcc=",
"dependencies": {
"optimist": "~0.3.5",
"source-map": "~0.1.7"
},
"bin": {
"uglifyjs": "bin/uglifyjs"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"dependencies": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/uglify-js": {
"version": "2.8.29",
"resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.8.29.tgz",
"integrity": "sha1-KcVzMUgFe7Th913zW3qcty5qWd0=",
"dependencies": {
"source-map": "~0.5.1",
"yargs": "~3.10.0"
},
"bin": {
"uglifyjs": "bin/uglifyjs"
},
"engines": {
"node": ">=0.8.0"
},
"optionalDependencies": {
"uglify-to-browserify": "~1.0.0"
}
},
"node_modules/uglify-js/node_modules/source-map": {
"version": "0.5.7",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz",
"integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/uglify-to-browserify": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz",
"integrity": "sha1-bgkk1r2mta/jSeOabWMoUKD4grc=",
"optional": true
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=",
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/void-elements": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/void-elements/-/void-elements-2.0.1.tgz",
"integrity": "sha1-wGavtYK7HLQSjWDqkjkulNXp2+w=",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/window-size": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/window-size/-/window-size-0.1.0.tgz",
"integrity": "sha1-VDjNLqk7IC76Ohn+iIeu58lPnJ0=",
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/with": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/with/-/with-4.0.3.tgz",
"integrity": "sha1-7v0VTp550sjTQXtkeo8U2f7M4U4=",
"dependencies": {
"acorn": "^1.0.1",
"acorn-globals": "^1.0.3"
}
},
"node_modules/with/node_modules/acorn": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-1.2.2.tgz",
"integrity": "sha1-yM4n3grMdtiW0rH6099YjZ6C8BQ=",
"bin": {
"acorn": "bin/acorn"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/wordwrap": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz",
"integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/yargs": {
"version": "3.10.0",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz",
"integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=",
"dependencies": {
"camelcase": "^1.0.2",
"cliui": "^2.1.0",
"decamelize": "^1.0.0",
"window-size": "0.1.0"
}
}
},
"dependencies": {
"accepts": {
"version": "1.3.7",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz",
"integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==",
"requires": {
"mime-types": "~2.1.24",
"negotiator": "0.6.2"
}
},
"acorn": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-2.7.0.tgz",
"integrity": "sha1-q259nYhqrKiwhbwzEreaGYQz8Oc="
},
"acorn-globals": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-1.0.9.tgz",
"integrity": "sha1-VbtemGkVB7dFedBRNBMhfDgMVM8=",
"requires": {
"acorn": "^2.1.0"
}
},
"align-text": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/align-text/-/align-text-0.1.4.tgz",
"integrity": "sha1-DNkKVhCT810KmSVsIrcGlDP60Rc=",
"requires": {
"kind-of": "^3.0.2",
"longest": "^1.0.1",
"repeat-string": "^1.5.2"
}
},
"amdefine": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz",
"integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU="
},
"array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI="
},
"asap": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/asap/-/asap-1.0.0.tgz",
"integrity": "sha1-sqRdpf36ILBJb8N2jMJ8EvqRan0="
},
"basic-auth": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz",
"integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==",
"requires": {
"safe-buffer": "5.1.2"
}
},
"body-parser": {
"version": "1.18.3",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.3.tgz",
"integrity": "sha1-WykhmP/dVTs6DyDe0FkrlWlVyLQ=",
"requires": {
"bytes": "3.0.0",
"content-type": "~1.0.4",
"debug": "2.6.9",
"depd": "~1.1.2",
"http-errors": "~1.6.3",
"iconv-lite": "0.4.23",
"on-finished": "~2.3.0",
"qs": "6.5.2",
"raw-body": "2.3.3",
"type-is": "~1.6.16"
}
},
"buffer-equal-constant-time": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
"integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk="
},
"bytes": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz",
"integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg="
},
"camelcase": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz",
"integrity": "sha1-m7UwTS4LVmmLLHWLCKPqqdqlijk="
},
"center-align": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/center-align/-/center-align-0.1.3.tgz",
"integrity": "sha1-qg0yYptu6XIgBBHL1EYckHvCt60=",
"requires": {
"align-text": "^0.1.3",
"lazy-cache": "^1.0.3"
}
},
"character-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/character-parser/-/character-parser-1.2.1.tgz",
"integrity": "sha1-wN3kqxgnE7kZuXCVmhI+zBow/NY="
},
"clean-css": {
"version": "3.4.28",
"resolved": "https://registry.npmjs.org/clean-css/-/clean-css-3.4.28.tgz",
"integrity": "sha1-vxlF6C/ICPVWlebd6uwBQA79A/8=",
"requires": {
"commander": "2.8.x",
"source-map": "0.4.x"
},
"dependencies": {
"commander": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.8.1.tgz",
"integrity": "sha1-Br42f+v9oMMwqh4qBy09yXYkJdQ=",
"requires": {
"graceful-readlink": ">= 1.0.0"
}
}
}
},
"cliui": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-2.1.0.tgz",
"integrity": "sha1-S0dXYP+AJkx2LDoXGQMukcf+oNE=",
"requires": {
"center-align": "^0.1.1",
"right-align": "^0.1.1",
"wordwrap": "0.0.2"
},
"dependencies": {
"wordwrap": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz",
"integrity": "sha1-t5Zpu0LstAn4PVg8rVLKF+qhZD8="
}
}
},
"commander": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.6.0.tgz",
"integrity": "sha1-nfflL7Kgyw+4kFjugMMQQiXzfh0="
},
"constantinople": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/constantinople/-/constantinople-3.0.2.tgz",
"integrity": "sha1-S5RdmTeQe82Y7ldRIsOBdRZUQUE=",
"requires": {
"acorn": "^2.1.0"
}
},
"content-disposition": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz",
"integrity": "sha1-DPaLud318r55YcOoUXjLhdunjLQ="
},
"content-type": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz",
"integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA=="
},
"cookie": {
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz",
"integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s="
},
"cookie-parser": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.4.tgz",
"integrity": "sha512-lo13tqF3JEtFO7FyA49CqbhaFkskRJ0u/UAiINgrIXeRCY41c88/zxtrECl8AKH3B0hj9q10+h3Kt8I7KlW4tw==",
"requires": {
"cookie": "0.3.1",
"cookie-signature": "1.0.6"
}
},
"cookie-signature": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw="
},
"css": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/css/-/css-1.0.8.tgz",
"integrity": "sha1-k4aBHKgrzMnuf7WnMrHioxfIo+c=",
"requires": {
"css-parse": "1.0.4",
"css-stringify": "1.0.5"
}
},
"css-parse": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/css-parse/-/css-parse-1.0.4.tgz",
"integrity": "sha1-OLBQP7+dqfVOnB29pg4UXHcRe90="
},
"css-stringify": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/css-stringify/-/css-stringify-1.0.5.tgz",
"integrity": "sha1-sNBClG2ylTu50pKQCmy19tASIDE="
},
"debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"requires": {
"ms": "2.0.0"
}
},
"decamelize": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
"integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA="
},
"depd": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
"integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak="
},
"destroy": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
"integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
},
"ecdsa-sig-formatter": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
"requires": {
"safe-buffer": "^5.0.1"
}
},
"ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0="
},
"encodeurl": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
"integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k="
},
"escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
},
"etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc="
},
"express": {
"version": "4.16.4",
"resolved": "https://registry.npmjs.org/express/-/express-4.16.4.tgz",
"integrity": "sha512-j12Uuyb4FMrd/qQAm6uCHAkPtO8FDTRJZBDd5D2KOL2eLaz1yUNdUB/NOIyq0iU4q4cFarsUCrnFDPBcnksuOg==",
"requires": {
"accepts": "~1.3.5",
"array-flatten": "1.1.1",
"body-parser": "1.18.3",
"content-disposition": "0.5.2",
"content-type": "~1.0.4",
"cookie": "0.3.1",
"cookie-signature": "1.0.6",
"debug": "2.6.9",
"depd": "~1.1.2",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "1.1.1",
"fresh": "0.5.2",
"merge-descriptors": "1.0.1",
"methods": "~1.1.2",
"on-finished": "~2.3.0",
"parseurl": "~1.3.2",
"path-to-regexp": "0.1.7",
"proxy-addr": "~2.0.4",
"qs": "6.5.2",
"range-parser": "~1.2.0",
"safe-buffer": "5.1.2",
"send": "0.16.2",
"serve-static": "1.13.2",
"setprototypeof": "1.1.0",
"statuses": "~1.4.0",
"type-is": "~1.6.16",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
}
},
"finalhandler": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.1.tgz",
"integrity": "sha512-Y1GUDo39ez4aHAw7MysnUD5JzYX+WaIj8I57kO3aEPT1fFRL4sr7mjei97FgnwhAyyzRYmQZaTHb2+9uZ1dPtg==",
"requires": {
"debug": "2.6.9",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"on-finished": "~2.3.0",
"parseurl": "~1.3.2",
"statuses": "~1.4.0",
"unpipe": "~1.0.0"
}
},
"forwarded": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz",
"integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ="
},
"fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac="
},
"graceful-readlink": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/graceful-readlink/-/graceful-readlink-1.0.1.tgz",
"integrity": "sha1-TK+tdrxi8C+gObL5Tpo906ORpyU="
},
"http-errors": {
"version": "1.6.3",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz",
"integrity": "sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0=",
"requires": {
"depd": "~1.1.2",
"inherits": "2.0.3",
"setprototypeof": "1.1.0",
"statuses": ">= 1.4.0 < 2"
}
},
"iconv-lite": {
"version": "0.4.23",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.23.tgz",
"integrity": "sha512-neyTUVFtahjf0mB3dZT77u+8O0QB89jFdnBkd5P1JgYPbPaia3gXXOVL2fq8VyU2gMMD7SaN7QukTB/pmXYvDA==",
"requires": {
"safer-buffer": ">= 2.1.2 < 3"
}
},
"inherits": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
"integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4="
},
"ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="
},
"is-buffer": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz",
"integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w=="
},
"is-promise": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz",
"integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o="
},
"jade": {
"version": "1.11.0",
"resolved": "https://registry.npmjs.org/jade/-/jade-1.11.0.tgz",
"integrity": "sha1-nIDlOMEtP7lcjZu5VZ+gzAQEBf0=",
"requires": {
"character-parser": "1.2.1",
"clean-css": "^3.1.9",
"commander": "~2.6.0",
"constantinople": "~3.0.1",
"jstransformer": "0.0.2",
"mkdirp": "~0.5.0",
"transformers": "2.1.0",
"uglify-js": "^2.4.19",
"void-elements": "~2.0.1",
"with": "~4.0.0"
}
},
"jsonwebtoken": {
"version": "8.5.1",
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz",
"integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==",
"requires": {
"jws": "^3.2.2",
"lodash.includes": "^4.3.0",
"lodash.isboolean": "^3.0.3",
"lodash.isinteger": "^4.0.4",
"lodash.isnumber": "^3.0.3",
"lodash.isplainobject": "^4.0.6",
"lodash.isstring": "^4.0.1",
"lodash.once": "^4.0.0",
"ms": "^2.1.1",
"semver": "^5.6.0"
},
"dependencies": {
"ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
}
}
},
"jstransformer": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/jstransformer/-/jstransformer-0.0.2.tgz",
"integrity": "sha1-eq4pqQPRls+glz2IXT5HlH7Ndqs=",
"requires": {
"is-promise": "^2.0.0",
"promise": "^6.0.1"
}
},
"jwa": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz",
"integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==",
"requires": {
"buffer-equal-constant-time": "1.0.1",
"ecdsa-sig-formatter": "1.0.11",
"safe-buffer": "^5.0.1"
}
},
"jws": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz",
"integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==",
"requires": {
"jwa": "^1.4.1",
"safe-buffer": "^5.0.1"
}
},
"kind-of": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
"integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
"requires": {
"is-buffer": "^1.1.5"
}
},
"lazy-cache": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-1.0.4.tgz",
"integrity": "sha1-odePw6UEdMuAhF07O24dpJpEbo4="
},
"lodash.includes": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
"integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8="
},
"lodash.isboolean": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
"integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY="
},
"lodash.isinteger": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
"integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M="
},
"lodash.isnumber": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
"integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w="
},
"lodash.isplainobject": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
"integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs="
},
"lodash.isstring": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
"integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE="
},
"lodash.once": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
"integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w="
},
"longest": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz",
"integrity": "sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc="
},
"media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g="
},
"merge-descriptors": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz",
"integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E="
},
"methods": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
"integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4="
},
"mime": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.4.1.tgz",
"integrity": "sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ=="
},
"mime-db": {
"version": "1.43.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.43.0.tgz",
"integrity": "sha512-+5dsGEEovYbT8UY9yD7eE4XTc4UwJ1jBYlgaQQF38ENsKR3wj/8q8RFZrF9WIZpB2V1ArTVFUva8sAul1NzRzQ=="
},
"mime-types": {
"version": "2.1.26",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.26.tgz",
"integrity": "sha512-01paPWYgLrkqAyrlDorC1uDwl2p3qZT7yl806vW7DvDoxwXi46jsjFbg+WdwotBIk6/MbEhO/dh5aZ5sNj/dWQ==",
"requires": {
"mime-db": "1.43.0"
}
},
"minimist": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz",
"integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0="
},
"mkdirp": {
"version": "0.5.1",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz",
"integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=",
"requires": {
"minimist": "0.0.8"
}
},
"morgan": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/morgan/-/morgan-1.9.1.tgz",
"integrity": "sha512-HQStPIV4y3afTiCYVxirakhlCfGkI161c76kKFca7Fk1JusM//Qeo1ej2XaMniiNeaZklMVrh3vTtIzpzwbpmA==",
"requires": {
"basic-auth": "~2.0.0",
"debug": "2.6.9",
"depd": "~1.1.2",
"on-finished": "~2.3.0",
"on-headers": "~1.0.1"
}
},
"ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"negotiator": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz",
"integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw=="
},
"on-finished": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
"integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=",
"requires": {
"ee-first": "1.1.1"
}
},
"on-headers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz",
"integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA=="
},
"optimist": {
"version": "0.3.7",
"resolved": "https://registry.npmjs.org/optimist/-/optimist-0.3.7.tgz",
"integrity": "sha1-yQlBrVnkJzMokjB00s8ufLxuwNk=",
"requires": {
"wordwrap": "~0.0.2"
}
},
"parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="
},
"path-to-regexp": {
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
"integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w="
},
"promise": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/promise/-/promise-6.1.0.tgz",
"integrity": "sha1-LOcp9rlLRcJoka0GAsXJDgTG7vY=",
"requires": {
"asap": "~1.0.0"
}
},
"proxy-addr": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.6.tgz",
"integrity": "sha512-dh/frvCBVmSsDYzw6n926jv974gddhkFPfiN8hPOi30Wax25QZyZEGveluCgliBnqmuM+UJmBErbAUFIoDbjOw==",
"requires": {
"forwarded": "~0.1.2",
"ipaddr.js": "1.9.1"
}
},
"qs": {
"version": "6.5.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz",
"integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA=="
},
"range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="
},
"raw-body": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.3.3.tgz",
"integrity": "sha512-9esiElv1BrZoI3rCDuOuKCBRbuApGGaDPQfjSflGxdy4oyzqghxu6klEkkVIvBje+FF0BX9coEv8KqW6X/7njw==",
"requires": {
"bytes": "3.0.0",
"http-errors": "1.6.3",
"iconv-lite": "0.4.23",
"unpipe": "1.0.0"
}
},
"repeat-string": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz",
"integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc="
},
"right-align": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/right-align/-/right-align-0.1.3.tgz",
"integrity": "sha1-YTObci/mo1FWiSENJOFMlhSGE+8=",
"requires": {
"align-text": "^0.1.1"
}
},
"safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
"semver": {
"version": "5.7.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz",
"integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ=="
},
"send": {
"version": "0.16.2",
"resolved": "https://registry.npmjs.org/send/-/send-0.16.2.tgz",
"integrity": "sha512-E64YFPUssFHEFBvpbbjr44NCLtI1AohxQ8ZSiJjQLskAdKuriYEP6VyGEsRDH8ScozGpkaX1BGvhanqCwkcEZw==",
"requires": {
"debug": "2.6.9",
"depd": "~1.1.2",
"destroy": "~1.0.4",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "0.5.2",
"http-errors": "~1.6.2",
"mime": "1.4.1",
"ms": "2.0.0",
"on-finished": "~2.3.0",
"range-parser": "~1.2.0",
"statuses": "~1.4.0"
}
},
"serve-static": {
"version": "1.13.2",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.13.2.tgz",
"integrity": "sha512-p/tdJrO4U387R9oMjb1oj7qSMaMfmOyd4j9hOFoxZe2baQszgHcSWjuya/CiT5kgZZKRudHNOA0pYXOl8rQ5nw==",
"requires": {
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"parseurl": "~1.3.2",
"send": "0.16.2"
}
},
"setprototypeof": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz",
"integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ=="
},
"source-map": {
"version": "0.4.4",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz",
"integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=",
"requires": {
"amdefine": ">=0.0.4"
}
},
"statuses": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz",
"integrity": "sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew=="
},
"transformers": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/transformers/-/transformers-2.1.0.tgz",
"integrity": "sha1-XSPLNVYd2F3Gf7hIIwm0fVPM6ac=",
"requires": {
"css": "~1.0.8",
"promise": "~2.0",
"uglify-js": "~2.2.5"
},
"dependencies": {
"is-promise": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-1.0.1.tgz",
"integrity": "sha1-MVc3YcBX4zwukaq56W2gjO++duU="
},
"promise": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/promise/-/promise-2.0.0.tgz",
"integrity": "sha1-RmSKqdYFr10ucMMCS/WUNtoCuA4=",
"requires": {
"is-promise": "~1"
}
},
"source-map": {
"version": "0.1.43",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.1.43.tgz",
"integrity": "sha1-wkvBRspRfBRx9drL4lcbK3+eM0Y=",
"requires": {
"amdefine": ">=0.0.4"
}
},
"uglify-js": {
"version": "2.2.5",
"resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.2.5.tgz",
"integrity": "sha1-puAqcNg5eSuXgEiLe4sYTAlcmcc=",
"requires": {
"optimist": "~0.3.5",
"source-map": "~0.1.7"
}
}
}
},
"type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"requires": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
}
},
"uglify-js": {
"version": "2.8.29",
"resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.8.29.tgz",
"integrity": "sha1-KcVzMUgFe7Th913zW3qcty5qWd0=",
"requires": {
"source-map": "~0.5.1",
"uglify-to-browserify": "~1.0.0",
"yargs": "~3.10.0"
},
"dependencies": {
"source-map": {
"version": "0.5.7",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz",
"integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w="
}
}
},
"uglify-to-browserify": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz",
"integrity": "sha1-bgkk1r2mta/jSeOabWMoUKD4grc=",
"optional": true
},
"unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw="
},
"utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM="
},
"vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw="
},
"void-elements": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/void-elements/-/void-elements-2.0.1.tgz",
"integrity": "sha1-wGavtYK7HLQSjWDqkjkulNXp2+w="
},
"window-size": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/window-size/-/window-size-0.1.0.tgz",
"integrity": "sha1-VDjNLqk7IC76Ohn+iIeu58lPnJ0="
},
"with": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/with/-/with-4.0.3.tgz",
"integrity": "sha1-7v0VTp550sjTQXtkeo8U2f7M4U4=",
"requires": {
"acorn": "^1.0.1",
"acorn-globals": "^1.0.3"
},
"dependencies": {
"acorn": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-1.2.2.tgz",
"integrity": "sha1-yM4n3grMdtiW0rH6099YjZ6C8BQ="
}
}
},
"wordwrap": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz",
"integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc="
},
"yargs": {
"version": "3.10.0",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz",
"integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=",
"requires": {
"camelcase": "^1.0.2",
"cliui": "^2.1.0",
"decamelize": "^1.0.0",
"window-size": "0.1.0"
}
}
}
}
| superset-websocket/utils/client-ws-app/package-lock.json | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.0001776287390384823,
0.00017318299796897918,
0.00016717880498617887,
0.0001731473603285849,
0.0000017141610442195088
] |
{
"id": 7,
"code_window": [
" .map(([fileName]) => fileName);\n",
"\n",
" const hasTerminalValidation = (\n",
" errMsg: Record<string, Record<string, string[]>>,\n",
" ) =>\n",
" Object.values(errMsg).some(\n",
" validationErrors =>\n",
" !isNeedsPassword(validationErrors) &&\n",
" !isAlreadyExists(validationErrors),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" errMsg: Record<string, Record<string, string[] | string>>,\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 405
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 { CHART_LIST } from './chart_list.helper';
describe('chart card view', () => {
beforeEach(() => {
cy.login();
cy.visit(CHART_LIST);
cy.get('[data-test="card-view"]').click();
});
it('should load cards', () => {
cy.get('[data-test="chart-list-view"]');
cy.get('[data-test="styled-card"]').should('be.visible');
cy.get('[data-test="styled-card"]').should('have.length', 25);
});
it('should allow to favorite/unfavorite chart card', () => {
cy.get("[data-test='card-actions']")
.first()
.find("[data-test='favorite-selected']")
.should('not.exist');
cy.get("[data-test='card-actions']")
.find("[data-test='favorite-unselected']")
.first()
.click();
cy.get("[data-test='card-actions']")
.first()
.find("[data-test='favorite-selected']")
.should('be.visible');
cy.get("[data-test='card-actions']")
.first()
.find("[data-test='favorite-unselected']")
.should('not.exist');
cy.get("[data-test='card-actions']")
.first()
.find("[data-test='favorite-unselected']")
.should('not.exist');
cy.get("[data-test='card-actions']")
.first()
.find("[data-test='favorite-selected']")
.click();
cy.get("[data-test='card-actions']")
.first()
.find("[data-test='favorite-unselected']")
.should('be.visible');
cy.get("[data-test='card-actions']")
.first()
.find("[data-test='favorite-selected']")
.should('not.exist');
});
xit('should sort correctly', () => {
// sort Alphabetical
cy.get('.Select__control').last().should('be.visible');
cy.get('.Select__control').last().click();
cy.get('.Select__menu').contains('Alphabetical').click();
cy.get('[data-test="chart-list-view"]').should('be.visible');
cy.get('[data-test="styled-card"]').first().contains('% Rural');
// sort Recently Modified
cy.get('.Select__control').last().should('be.visible');
cy.get('.Select__control').last().click();
cy.get('.Select__menu').contains('Recently Modified').click();
cy.get('[data-test="chart-list-view"]').should('be.visible');
// TODO - next line is/was flaky
cy.get('[data-test="styled-card"]').first().contains('Unicode Cloud');
cy.get('[data-test="styled-card"]')
.last()
.contains('Life Expectancy VS Rural %');
});
// flaky
xit('should delete correctly', () => {
// show delete modal
cy.get('[data-test="more-horiz"]').last().trigger('mouseover');
cy.get('[data-test="chart-list-delete-option"]')
.last()
.should('be.visible');
cy.get('[data-test="chart-list-delete-option"]')
.last()
.contains('Delete')
.click();
cy.get('[data-test="Please Confirm-modal"]').should('be.visible');
cy.get('[data-test="modal-confirm-button"]').should(
'have.attr',
'disabled',
);
cy.get('[data-test="Please Confirm-modal"]').should('be.visible');
cy.get("[data-test='delete-modal-input']").type('DELETE');
cy.get('[data-test="modal-confirm-button"]').should(
'not.have.attr',
'disabled',
);
cy.get('[data-test="modal-cancel-button"]').click();
});
// flaky
xit('should edit correctly', () => {
// show edit modal
cy.get('[data-test="more-horiz"]').last().trigger('mouseover');
cy.get('[data-test="chart-list-edit-option"]').last().should('be.visible');
cy.get('[data-test="chart-list-edit-option"]').last().click();
cy.get('[data-test="properties-edit-modal"]').should('be.visible');
cy.get('[data-test="properties-modal-name-input"]').should(
'not.have.value',
);
cy.get('[data-test="properties-modal-cancel-button"]')
.contains('Cancel')
.click();
});
});
| superset-frontend/cypress-base/cypress/integration/chart_list/card_view.test.ts | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017692790424916893,
0.00017496757209300995,
0.0001722864544717595,
0.00017513232887722552,
0.000001159509565695771
] |
{
"id": 8,
"code_window": [
" () => {\n",
" addSuccessToast(t('Connection looks good!'));\n",
" },\n",
" createErrorHandler((errMsg: Record<string, string[]> | string) => {\n",
" handleErrorMsg(t(`${t('ERROR: ')}${parsedErrorMessage(errMsg)}`));\n",
" }),\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" createErrorHandler((errMsg: Record<string, string[] | string> | string) => {\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 633
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 rison from 'rison';
import { useState, useEffect, useCallback } from 'react';
import { makeApi, SupersetClient, t } from '@superset-ui/core';
import { createErrorHandler } from 'src/views/CRUD/utils';
import { FetchDataConfig } from 'src/components/ListView';
import { FilterValue } from 'src/components/ListView/types';
import Chart, { Slice } from 'src/types/Chart';
import copyTextToClipboard from 'src/utils/copy';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import { FavoriteStatus, ImportResourceName, DatabaseObject } from './types';
interface ListViewResourceState<D extends object = any> {
loading: boolean;
collection: D[];
count: number;
permissions: string[];
lastFetchDataConfig: FetchDataConfig | null;
bulkSelectEnabled: boolean;
lastFetched?: string;
}
const parsedErrorMessage = (
errorMessage: Record<string, string[]> | string,
) => {
if (typeof errorMessage === 'string') {
return errorMessage;
}
return Object.entries(errorMessage)
.map(([key, value]) => `(${key}) ${value.join(', ')}`)
.join('\n');
};
export function useListViewResource<D extends object = any>(
resource: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
infoEnable = true,
defaultCollectionValue: D[] = [],
baseFilters?: FilterValue[], // must be memoized
initialLoadingState = true,
) {
const [state, setState] = useState<ListViewResourceState<D>>({
count: 0,
collection: defaultCollectionValue,
loading: initialLoadingState,
lastFetchDataConfig: null,
permissions: [],
bulkSelectEnabled: false,
});
function updateState(update: Partial<ListViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
function toggleBulkSelect() {
updateState({ bulkSelectEnabled: !state.bulkSelectEnabled });
}
useEffect(() => {
if (!infoEnable) return;
SupersetClient.get({
endpoint: `/api/v1/${resource}/_info?q=${rison.encode({
keys: ['permissions'],
})}`,
}).then(
({ json: infoJson = {} }) => {
updateState({
permissions: infoJson.permissions,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %s info: %s',
resourceLabel,
errMsg,
),
),
),
);
}, []);
function hasPerm(perm: string) {
if (!state.permissions.length) {
return false;
}
return Boolean(state.permissions.find(p => p === perm));
}
const fetchData = useCallback(
({
pageIndex,
pageSize,
sortBy,
filters: filterValues,
}: FetchDataConfig) => {
// set loading state, cache the last config for refreshing data.
updateState({
lastFetchDataConfig: {
filters: filterValues,
pageIndex,
pageSize,
sortBy,
},
loading: true,
});
const filterExps = (baseFilters || [])
.concat(filterValues)
.map(({ id, operator: opr, value }) => ({
col: id,
opr,
value,
}));
const queryParams = rison.encode({
order_column: sortBy[0].id,
order_direction: sortBy[0].desc ? 'desc' : 'asc',
page: pageIndex,
page_size: pageSize,
...(filterExps.length ? { filters: filterExps } : {}),
});
return SupersetClient.get({
endpoint: `/api/v1/${resource}/?q=${queryParams}`,
})
.then(
({ json = {} }) => {
updateState({
collection: json.result,
count: json.count,
lastFetched: new Date().toISOString(),
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
errMsg,
),
),
),
)
.finally(() => {
updateState({ loading: false });
});
},
[baseFilters],
);
return {
state: {
loading: state.loading,
resourceCount: state.count,
resourceCollection: state.collection,
bulkSelectEnabled: state.bulkSelectEnabled,
lastFetched: state.lastFetched,
},
setResourceCollection: (update: D[]) =>
updateState({
collection: update,
}),
hasPerm,
fetchData,
toggleBulkSelect,
refreshData: (provideConfig?: FetchDataConfig) => {
if (state.lastFetchDataConfig) {
return fetchData(state.lastFetchDataConfig);
}
if (provideConfig) {
return fetchData(provideConfig);
}
return null;
},
};
}
// In the same vein as above, a hook for viewing a single instance of a resource (given id)
interface SingleViewResourceState<D extends object = any> {
loading: boolean;
resource: D | null;
error: string | Record<string, string[]> | null;
}
export function useSingleViewResource<D extends object = any>(
resourceName: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<SingleViewResourceState<D>>({
loading: false,
resource: null,
error: null,
});
function updateState(update: Partial<SingleViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
const fetchResource = useCallback(
(resourceID: number) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.get({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const createResource = useCallback(
(resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.id;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while creating %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const updateResource = useCallback(
(resourceID: number, resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.put({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler(errMsg => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
JSON.stringify(errMsg),
),
);
updateState({
error: errMsg,
});
return errMsg;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const clearError = () =>
updateState({
error: null,
});
return {
state,
setResource: (update: D) =>
updateState({
resource: update,
}),
fetchResource,
createResource,
updateResource,
clearError,
};
}
interface ImportResourceState {
loading: boolean;
passwordsNeeded: string[];
alreadyExists: string[];
}
export function useImportResource(
resourceName: ImportResourceName,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<ImportResourceState>({
loading: false,
passwordsNeeded: [],
alreadyExists: [],
});
function updateState(update: Partial<ImportResourceState>) {
setState(currentState => ({ ...currentState, ...update }));
}
/* eslint-disable no-underscore-dangle */
const isNeedsPassword = (payload: any) =>
typeof payload === 'object' &&
Array.isArray(payload._schema) &&
payload._schema.length === 1 &&
payload._schema[0] === 'Must provide a password for the database';
const isAlreadyExists = (payload: any) =>
typeof payload === 'string' &&
payload.includes('already exists and `overwrite=true` was not passed');
const getPasswordsNeeded = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isNeedsPassword(validationErrors))
.map(([fileName]) => fileName);
const getAlreadyExists = (errMsg: Record<string, Record<string, string[]>>) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isAlreadyExists(validationErrors))
.map(([fileName]) => fileName);
const hasTerminalValidation = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.values(errMsg).some(
validationErrors =>
!isNeedsPassword(validationErrors) &&
!isAlreadyExists(validationErrors),
);
const importResource = useCallback(
(
bundle: File,
databasePasswords: Record<string, string> = {},
overwrite = false,
) => {
// Set loading state
updateState({
loading: true,
});
const formData = new FormData();
formData.append('formData', bundle);
/* The import bundle never contains database passwords; if required
* they should be provided by the user during import.
*/
if (databasePasswords) {
formData.append('passwords', JSON.stringify(databasePasswords));
}
/* If the imported model already exists the user needs to confirm
* that they want to overwrite it.
*/
if (overwrite) {
formData.append('overwrite', 'true');
}
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/import/`,
body: formData,
})
.then(() => true)
.catch(response =>
getClientErrorObject(response).then(error => {
const errMsg = error.message || error.error;
if (typeof errMsg === 'string') {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
return false;
}
if (hasTerminalValidation(errMsg)) {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
} else {
updateState({
passwordsNeeded: getPasswordsNeeded(errMsg),
alreadyExists: getAlreadyExists(errMsg),
});
}
return false;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[],
);
return { state, importResource };
}
enum FavStarClassName {
CHART = 'slice',
DASHBOARD = 'Dashboard',
}
type FavoriteStatusResponse = {
result: Array<{
id: string;
value: boolean;
}>;
};
const favoriteApis = {
chart: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/chart/favorite_status/',
}),
dashboard: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/dashboard/favorite_status/',
}),
};
export function useFavoriteStatus(
type: 'chart' | 'dashboard',
ids: Array<string | number>,
handleErrorMsg: (message: string) => void,
) {
const [favoriteStatus, setFavoriteStatus] = useState<FavoriteStatus>({});
const updateFavoriteStatus = (update: FavoriteStatus) =>
setFavoriteStatus(currentState => ({ ...currentState, ...update }));
useEffect(() => {
if (!ids.length) {
return;
}
favoriteApis[type](ids).then(
({ result }) => {
const update = result.reduce((acc, element) => {
acc[element.id] = element.value;
return acc;
}, {});
updateFavoriteStatus(update);
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error fetching the favorite status: %s', errMsg),
),
),
);
}, [ids, type, handleErrorMsg]);
const saveFaveStar = useCallback(
(id: number, isStarred: boolean) => {
const urlSuffix = isStarred ? 'unselect' : 'select';
SupersetClient.get({
endpoint: `/superset/favstar/${
type === 'chart' ? FavStarClassName.CHART : FavStarClassName.DASHBOARD
}/${id}/${urlSuffix}/`,
}).then(
({ json }) => {
updateFavoriteStatus({
[id]: (json as { count: number })?.count > 0,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error saving the favorite status: %s', errMsg),
),
),
);
},
[type],
);
return [saveFaveStar, favoriteStatus] as const;
}
export const useChartEditModal = (
setCharts: (charts: Array<Chart>) => void,
charts: Array<Chart>,
) => {
const [
sliceCurrentlyEditing,
setSliceCurrentlyEditing,
] = useState<Slice | null>(null);
function openChartEditModal(chart: Chart) {
setSliceCurrentlyEditing({
slice_id: chart.id,
slice_name: chart.slice_name,
description: chart.description,
cache_timeout: chart.cache_timeout,
});
}
function closeChartEditModal() {
setSliceCurrentlyEditing(null);
}
function handleChartUpdated(edits: Chart) {
// update the chart in our state with the edited info
const newCharts = charts.map((chart: Chart) =>
chart.id === edits.id ? { ...chart, ...edits } : chart,
);
setCharts(newCharts);
}
return {
sliceCurrentlyEditing,
handleChartUpdated,
openChartEditModal,
closeChartEditModal,
};
};
export const copyQueryLink = (
id: number,
addDangerToast: (arg0: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
copyTextToClipboard(
`${window.location.origin}/superset/sqllab?savedQueryId=${id}`,
)
.then(() => {
addSuccessToast(t('Link Copied!'));
})
.catch(() => {
addDangerToast(t('Sorry, your browser does not support copying.'));
});
};
export const testDatabaseConnection = (
connection: DatabaseObject,
handleErrorMsg: (errorMsg: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
SupersetClient.post({
endpoint: 'api/v1/database/test_connection',
body: JSON.stringify(connection),
headers: { 'Content-Type': 'application/json' },
}).then(
() => {
addSuccessToast(t('Connection looks good!'));
},
createErrorHandler((errMsg: Record<string, string[]> | string) => {
handleErrorMsg(t(`${t('ERROR: ')}${parsedErrorMessage(errMsg)}`));
}),
);
};
| superset-frontend/src/views/CRUD/hooks.ts | 1 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.9937282800674438,
0.01624123938381672,
0.00016420375322923064,
0.00017267290968447924,
0.12316277623176575
] |
{
"id": 8,
"code_window": [
" () => {\n",
" addSuccessToast(t('Connection looks good!'));\n",
" },\n",
" createErrorHandler((errMsg: Record<string, string[]> | string) => {\n",
" handleErrorMsg(t(`${t('ERROR: ')}${parsedErrorMessage(errMsg)}`));\n",
" }),\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" createErrorHandler((errMsg: Record<string, string[] | string> | string) => {\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 633
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""a collection of Annotation-related models"""
from typing import Any, Dict
from flask_appbuilder import Model
from sqlalchemy import Column, DateTime, ForeignKey, Index, Integer, String, Text
from sqlalchemy.orm import relationship
from superset.models.helpers import AuditMixinNullable
class AnnotationLayer(Model, AuditMixinNullable):
"""A logical namespace for a set of annotations"""
__tablename__ = "annotation_layer"
id = Column(Integer, primary_key=True)
name = Column(String(250))
descr = Column(Text)
def __repr__(self) -> str:
return str(self.name)
class Annotation(Model, AuditMixinNullable):
"""Time-related annotation"""
__tablename__ = "annotation"
id = Column(Integer, primary_key=True)
start_dttm = Column(DateTime)
end_dttm = Column(DateTime)
layer_id = Column(Integer, ForeignKey("annotation_layer.id"), nullable=False)
short_descr = Column(String(500))
long_descr = Column(Text)
layer = relationship(AnnotationLayer, backref="annotation")
json_metadata = Column(Text)
__table_args__ = (Index("ti_dag_state", layer_id, start_dttm, end_dttm),)
@property
def data(self) -> Dict[str, Any]:
return {
"layer_id": self.layer_id,
"start_dttm": self.start_dttm,
"end_dttm": self.end_dttm,
"short_descr": self.short_descr,
"long_descr": self.long_descr,
"layer": self.layer.name if self.layer else None,
}
def __repr__(self) -> str:
return str(self.short_descr)
| superset/models/annotations.py | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017446196579840034,
0.00017178048437926918,
0.00016925153613556176,
0.00017183873569592834,
0.0000017942378462976194
] |
{
"id": 8,
"code_window": [
" () => {\n",
" addSuccessToast(t('Connection looks good!'));\n",
" },\n",
" createErrorHandler((errMsg: Record<string, string[]> | string) => {\n",
" handleErrorMsg(t(`${t('ERROR: ')}${parsedErrorMessage(errMsg)}`));\n",
" }),\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" createErrorHandler((errMsg: Record<string, string[] | string> | string) => {\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 633
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/* eslint camelcase: 0 */
import { DYNAMIC_PLUGIN_CONTROLS_READY } from 'src/chart/chartAction';
import { DEFAULT_TIME_RANGE } from 'src/explore/constants';
import { getControlsState } from 'src/explore/store';
import {
getControlConfig,
getFormDataFromControls,
getControlStateFromControlConfig,
} from 'src/explore/controlUtils';
import * as actions from 'src/explore/actions/exploreActions';
export default function exploreReducer(state = {}, action) {
const actionHandlers = {
[DYNAMIC_PLUGIN_CONTROLS_READY]() {
return {
...state,
controls: action.controlsState,
};
},
[actions.TOGGLE_FAVE_STAR]() {
return {
...state,
isStarred: action.isStarred,
};
},
[actions.POST_DATASOURCE_STARTED]() {
return {
...state,
isDatasourceMetaLoading: true,
};
},
[actions.SET_DATASOURCE]() {
const newFormData = { ...state.form_data };
if (action.datasource.type !== state.datasource.type) {
if (action.datasource.type === 'table') {
newFormData.granularity_sqla = action.datasource.granularity_sqla;
newFormData.time_grain_sqla = action.datasource.time_grain_sqla;
delete newFormData.druid_time_origin;
delete newFormData.granularity;
} else {
newFormData.druid_time_origin = action.datasource.druid_time_origin;
newFormData.granularity = action.datasource.granularity;
delete newFormData.granularity_sqla;
delete newFormData.time_grain_sqla;
}
}
const controls = { ...state.controls };
if (
action.datasource.id !== state.datasource.id ||
action.datasource.type !== state.datasource.type
) {
// reset time range filter to default
newFormData.time_range = DEFAULT_TIME_RANGE;
// reset control values for column/metric related controls
Object.entries(controls).forEach(([controlName, controlState]) => {
if (
// for direct column select controls
controlState.valueKey === 'column_name' ||
// for all other controls
'columns' in controlState
) {
// if a control use datasource columns, reset its value to `undefined`,
// then `getControlsState` will pick up the default.
// TODO: filter out only invalid columns and keep others
controls[controlName] = {
...controlState,
value: undefined,
};
newFormData[controlName] = undefined;
}
});
}
const newState = {
...state,
controls,
datasource: action.datasource,
datasource_id: action.datasource.id,
datasource_type: action.datasource.type,
};
return {
...newState,
form_data: newFormData,
controls: getControlsState(newState, newFormData),
};
},
[actions.FETCH_DATASOURCES_STARTED]() {
return {
...state,
isDatasourcesLoading: true,
};
},
[actions.SET_DATASOURCES]() {
return {
...state,
datasources: action.datasources,
};
},
[actions.SET_FIELD_VALUE]() {
const new_form_data = state.form_data;
const { controlName, value, validationErrors } = action;
new_form_data[controlName] = value;
const vizType = new_form_data.viz_type;
// Use the processed control config (with overrides and everything)
// if `controlName` does not existing in current controls,
const controlConfig =
state.controls[action.controlName] ||
getControlConfig(action.controlName, vizType) ||
{};
// will call validators again
const control = {
...getControlStateFromControlConfig(controlConfig, state, action.value),
};
// combine newly detected errors with errors from `onChange` event of
// each control component (passed via reducer action).
const errors = control.validationErrors || [];
(validationErrors || []).forEach(err => {
// skip duplicated errors
if (!errors.includes(err)) {
errors.push(err);
}
});
const hasErrors = errors && errors.length > 0;
const currentControlsState =
action.controlName === 'viz_type' &&
action.value !== state.controls.viz_type.value
? // rebuild the full control state if switching viz type
getControlsState(
state,
getFormDataFromControls({
...state.controls,
viz_type: control,
}),
)
: state.controls;
return {
...state,
form_data: new_form_data,
triggerRender: control.renderTrigger && !hasErrors,
controls: {
...currentControlsState,
[action.controlName]: {
...control,
validationErrors: errors,
},
},
};
},
[actions.SET_EXPLORE_CONTROLS]() {
return {
...state,
controls: getControlsState(state, action.formData),
};
},
[actions.UPDATE_CHART_TITLE]() {
return {
...state,
sliceName: action.sliceName,
};
},
[actions.CREATE_NEW_SLICE]() {
return {
...state,
slice: action.slice,
controls: getControlsState(state, action.form_data),
can_add: action.can_add,
can_download: action.can_download,
can_overwrite: action.can_overwrite,
};
},
[actions.SLICE_UPDATED]() {
return {
...state,
slice: {
...state.slice,
...action.slice,
},
sliceName: action.slice.slice_name ?? state.sliceName,
};
},
};
if (action.type in actionHandlers) {
return actionHandlers[action.type]();
}
return state;
}
| superset-frontend/src/explore/reducers/exploreReducer.js | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017331112758256495,
0.000169588383869268,
0.0001647299068281427,
0.00016948151460383087,
0.000002320806970601552
] |
{
"id": 8,
"code_window": [
" () => {\n",
" addSuccessToast(t('Connection looks good!'));\n",
" },\n",
" createErrorHandler((errMsg: Record<string, string[]> | string) => {\n",
" handleErrorMsg(t(`${t('ERROR: ')}${parsedErrorMessage(errMsg)}`));\n",
" }),\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" createErrorHandler((errMsg: Record<string, string[] | string> | string) => {\n"
],
"file_path": "superset-frontend/src/views/CRUD/hooks.ts",
"type": "replace",
"edit_start_line_idx": 633
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 { t, ChartMetadata, ChartPlugin } from '@superset-ui/core';
import transformProps from './transformProps';
import thumbnail from './images/thumbnail.png';
const metadata = new ChartMetadata({
name: t('Time-series Table'),
description: '',
thumbnail,
useLegacyApi: true,
});
export default class TimeTableChartPlugin extends ChartPlugin {
constructor() {
super({
metadata,
transformProps,
loadChart: () => import('./TimeTable.jsx'),
});
}
}
| superset-frontend/src/visualizations/TimeTable/TimeTableChartPlugin.js | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017407596169505268,
0.00016963272355496883,
0.00016558122297283262,
0.00016943682567216456,
0.0000036166109111945843
] |
{
"id": 9,
"code_window": [
"export const createFetchDistinct = createFetchResourceMethod('distinct');\n",
"\n",
"export function createErrorHandler(\n",
" handleErrorFunc: (errMsg?: string | Record<string, string[]>) => void,\n",
") {\n",
" return async (e: SupersetClientResponse | string) => {\n",
" const parsedError = await getClientErrorObject(e);\n",
" // Taking the first error returned from the API\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" handleErrorFunc: (\n",
" errMsg?: string | Record<string, string[] | string>,\n",
" ) => void,\n"
],
"file_path": "superset-frontend/src/views/CRUD/utils.tsx",
"type": "replace",
"edit_start_line_idx": 158
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 rison from 'rison';
import { useState, useEffect, useCallback } from 'react';
import { makeApi, SupersetClient, t } from '@superset-ui/core';
import { createErrorHandler } from 'src/views/CRUD/utils';
import { FetchDataConfig } from 'src/components/ListView';
import { FilterValue } from 'src/components/ListView/types';
import Chart, { Slice } from 'src/types/Chart';
import copyTextToClipboard from 'src/utils/copy';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import { FavoriteStatus, ImportResourceName, DatabaseObject } from './types';
interface ListViewResourceState<D extends object = any> {
loading: boolean;
collection: D[];
count: number;
permissions: string[];
lastFetchDataConfig: FetchDataConfig | null;
bulkSelectEnabled: boolean;
lastFetched?: string;
}
const parsedErrorMessage = (
errorMessage: Record<string, string[]> | string,
) => {
if (typeof errorMessage === 'string') {
return errorMessage;
}
return Object.entries(errorMessage)
.map(([key, value]) => `(${key}) ${value.join(', ')}`)
.join('\n');
};
export function useListViewResource<D extends object = any>(
resource: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
infoEnable = true,
defaultCollectionValue: D[] = [],
baseFilters?: FilterValue[], // must be memoized
initialLoadingState = true,
) {
const [state, setState] = useState<ListViewResourceState<D>>({
count: 0,
collection: defaultCollectionValue,
loading: initialLoadingState,
lastFetchDataConfig: null,
permissions: [],
bulkSelectEnabled: false,
});
function updateState(update: Partial<ListViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
function toggleBulkSelect() {
updateState({ bulkSelectEnabled: !state.bulkSelectEnabled });
}
useEffect(() => {
if (!infoEnable) return;
SupersetClient.get({
endpoint: `/api/v1/${resource}/_info?q=${rison.encode({
keys: ['permissions'],
})}`,
}).then(
({ json: infoJson = {} }) => {
updateState({
permissions: infoJson.permissions,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %s info: %s',
resourceLabel,
errMsg,
),
),
),
);
}, []);
function hasPerm(perm: string) {
if (!state.permissions.length) {
return false;
}
return Boolean(state.permissions.find(p => p === perm));
}
const fetchData = useCallback(
({
pageIndex,
pageSize,
sortBy,
filters: filterValues,
}: FetchDataConfig) => {
// set loading state, cache the last config for refreshing data.
updateState({
lastFetchDataConfig: {
filters: filterValues,
pageIndex,
pageSize,
sortBy,
},
loading: true,
});
const filterExps = (baseFilters || [])
.concat(filterValues)
.map(({ id, operator: opr, value }) => ({
col: id,
opr,
value,
}));
const queryParams = rison.encode({
order_column: sortBy[0].id,
order_direction: sortBy[0].desc ? 'desc' : 'asc',
page: pageIndex,
page_size: pageSize,
...(filterExps.length ? { filters: filterExps } : {}),
});
return SupersetClient.get({
endpoint: `/api/v1/${resource}/?q=${queryParams}`,
})
.then(
({ json = {} }) => {
updateState({
collection: json.result,
count: json.count,
lastFetched: new Date().toISOString(),
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
errMsg,
),
),
),
)
.finally(() => {
updateState({ loading: false });
});
},
[baseFilters],
);
return {
state: {
loading: state.loading,
resourceCount: state.count,
resourceCollection: state.collection,
bulkSelectEnabled: state.bulkSelectEnabled,
lastFetched: state.lastFetched,
},
setResourceCollection: (update: D[]) =>
updateState({
collection: update,
}),
hasPerm,
fetchData,
toggleBulkSelect,
refreshData: (provideConfig?: FetchDataConfig) => {
if (state.lastFetchDataConfig) {
return fetchData(state.lastFetchDataConfig);
}
if (provideConfig) {
return fetchData(provideConfig);
}
return null;
},
};
}
// In the same vein as above, a hook for viewing a single instance of a resource (given id)
interface SingleViewResourceState<D extends object = any> {
loading: boolean;
resource: D | null;
error: string | Record<string, string[]> | null;
}
export function useSingleViewResource<D extends object = any>(
resourceName: string,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<SingleViewResourceState<D>>({
loading: false,
resource: null,
error: null,
});
function updateState(update: Partial<SingleViewResourceState<D>>) {
setState(currentState => ({ ...currentState, ...update }));
}
const fetchResource = useCallback(
(resourceID: number) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.get({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const createResource = useCallback(
(resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.id;
},
createErrorHandler((errMsg: Record<string, string[]>) => {
handleErrorMsg(
t(
'An error occurred while creating %ss: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
updateState({
error: errMsg,
});
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const updateResource = useCallback(
(resourceID: number, resource: D) => {
// Set loading state
updateState({
loading: true,
});
return SupersetClient.put({
endpoint: `/api/v1/${resourceName}/${resourceID}`,
body: JSON.stringify(resource),
headers: { 'Content-Type': 'application/json' },
})
.then(
({ json = {} }) => {
updateState({
resource: json.result,
error: null,
});
return json.result;
},
createErrorHandler(errMsg => {
handleErrorMsg(
t(
'An error occurred while fetching %ss: %s',
resourceLabel,
JSON.stringify(errMsg),
),
);
updateState({
error: errMsg,
});
return errMsg;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[handleErrorMsg, resourceName, resourceLabel],
);
const clearError = () =>
updateState({
error: null,
});
return {
state,
setResource: (update: D) =>
updateState({
resource: update,
}),
fetchResource,
createResource,
updateResource,
clearError,
};
}
interface ImportResourceState {
loading: boolean;
passwordsNeeded: string[];
alreadyExists: string[];
}
export function useImportResource(
resourceName: ImportResourceName,
resourceLabel: string, // resourceLabel for translations
handleErrorMsg: (errorMsg: string) => void,
) {
const [state, setState] = useState<ImportResourceState>({
loading: false,
passwordsNeeded: [],
alreadyExists: [],
});
function updateState(update: Partial<ImportResourceState>) {
setState(currentState => ({ ...currentState, ...update }));
}
/* eslint-disable no-underscore-dangle */
const isNeedsPassword = (payload: any) =>
typeof payload === 'object' &&
Array.isArray(payload._schema) &&
payload._schema.length === 1 &&
payload._schema[0] === 'Must provide a password for the database';
const isAlreadyExists = (payload: any) =>
typeof payload === 'string' &&
payload.includes('already exists and `overwrite=true` was not passed');
const getPasswordsNeeded = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isNeedsPassword(validationErrors))
.map(([fileName]) => fileName);
const getAlreadyExists = (errMsg: Record<string, Record<string, string[]>>) =>
Object.entries(errMsg)
.filter(([, validationErrors]) => isAlreadyExists(validationErrors))
.map(([fileName]) => fileName);
const hasTerminalValidation = (
errMsg: Record<string, Record<string, string[]>>,
) =>
Object.values(errMsg).some(
validationErrors =>
!isNeedsPassword(validationErrors) &&
!isAlreadyExists(validationErrors),
);
const importResource = useCallback(
(
bundle: File,
databasePasswords: Record<string, string> = {},
overwrite = false,
) => {
// Set loading state
updateState({
loading: true,
});
const formData = new FormData();
formData.append('formData', bundle);
/* The import bundle never contains database passwords; if required
* they should be provided by the user during import.
*/
if (databasePasswords) {
formData.append('passwords', JSON.stringify(databasePasswords));
}
/* If the imported model already exists the user needs to confirm
* that they want to overwrite it.
*/
if (overwrite) {
formData.append('overwrite', 'true');
}
return SupersetClient.post({
endpoint: `/api/v1/${resourceName}/import/`,
body: formData,
})
.then(() => true)
.catch(response =>
getClientErrorObject(response).then(error => {
const errMsg = error.message || error.error;
if (typeof errMsg === 'string') {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
return false;
}
if (hasTerminalValidation(errMsg)) {
handleErrorMsg(
t(
'An error occurred while importing %s: %s',
resourceLabel,
parsedErrorMessage(errMsg),
),
);
} else {
updateState({
passwordsNeeded: getPasswordsNeeded(errMsg),
alreadyExists: getAlreadyExists(errMsg),
});
}
return false;
}),
)
.finally(() => {
updateState({ loading: false });
});
},
[],
);
return { state, importResource };
}
enum FavStarClassName {
CHART = 'slice',
DASHBOARD = 'Dashboard',
}
type FavoriteStatusResponse = {
result: Array<{
id: string;
value: boolean;
}>;
};
const favoriteApis = {
chart: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/chart/favorite_status/',
}),
dashboard: makeApi<Array<string | number>, FavoriteStatusResponse>({
requestType: 'rison',
method: 'GET',
endpoint: '/api/v1/dashboard/favorite_status/',
}),
};
export function useFavoriteStatus(
type: 'chart' | 'dashboard',
ids: Array<string | number>,
handleErrorMsg: (message: string) => void,
) {
const [favoriteStatus, setFavoriteStatus] = useState<FavoriteStatus>({});
const updateFavoriteStatus = (update: FavoriteStatus) =>
setFavoriteStatus(currentState => ({ ...currentState, ...update }));
useEffect(() => {
if (!ids.length) {
return;
}
favoriteApis[type](ids).then(
({ result }) => {
const update = result.reduce((acc, element) => {
acc[element.id] = element.value;
return acc;
}, {});
updateFavoriteStatus(update);
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error fetching the favorite status: %s', errMsg),
),
),
);
}, [ids, type, handleErrorMsg]);
const saveFaveStar = useCallback(
(id: number, isStarred: boolean) => {
const urlSuffix = isStarred ? 'unselect' : 'select';
SupersetClient.get({
endpoint: `/superset/favstar/${
type === 'chart' ? FavStarClassName.CHART : FavStarClassName.DASHBOARD
}/${id}/${urlSuffix}/`,
}).then(
({ json }) => {
updateFavoriteStatus({
[id]: (json as { count: number })?.count > 0,
});
},
createErrorHandler(errMsg =>
handleErrorMsg(
t('There was an error saving the favorite status: %s', errMsg),
),
),
);
},
[type],
);
return [saveFaveStar, favoriteStatus] as const;
}
export const useChartEditModal = (
setCharts: (charts: Array<Chart>) => void,
charts: Array<Chart>,
) => {
const [
sliceCurrentlyEditing,
setSliceCurrentlyEditing,
] = useState<Slice | null>(null);
function openChartEditModal(chart: Chart) {
setSliceCurrentlyEditing({
slice_id: chart.id,
slice_name: chart.slice_name,
description: chart.description,
cache_timeout: chart.cache_timeout,
});
}
function closeChartEditModal() {
setSliceCurrentlyEditing(null);
}
function handleChartUpdated(edits: Chart) {
// update the chart in our state with the edited info
const newCharts = charts.map((chart: Chart) =>
chart.id === edits.id ? { ...chart, ...edits } : chart,
);
setCharts(newCharts);
}
return {
sliceCurrentlyEditing,
handleChartUpdated,
openChartEditModal,
closeChartEditModal,
};
};
export const copyQueryLink = (
id: number,
addDangerToast: (arg0: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
copyTextToClipboard(
`${window.location.origin}/superset/sqllab?savedQueryId=${id}`,
)
.then(() => {
addSuccessToast(t('Link Copied!'));
})
.catch(() => {
addDangerToast(t('Sorry, your browser does not support copying.'));
});
};
export const testDatabaseConnection = (
connection: DatabaseObject,
handleErrorMsg: (errorMsg: string) => void,
addSuccessToast: (arg0: string) => void,
) => {
SupersetClient.post({
endpoint: 'api/v1/database/test_connection',
body: JSON.stringify(connection),
headers: { 'Content-Type': 'application/json' },
}).then(
() => {
addSuccessToast(t('Connection looks good!'));
},
createErrorHandler((errMsg: Record<string, string[]> | string) => {
handleErrorMsg(t(`${t('ERROR: ')}${parsedErrorMessage(errMsg)}`));
}),
);
};
| superset-frontend/src/views/CRUD/hooks.ts | 1 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.998763918876648,
0.18548989295959473,
0.00016581806994508952,
0.00022937334142625332,
0.3734513819217682
] |
{
"id": 9,
"code_window": [
"export const createFetchDistinct = createFetchResourceMethod('distinct');\n",
"\n",
"export function createErrorHandler(\n",
" handleErrorFunc: (errMsg?: string | Record<string, string[]>) => void,\n",
") {\n",
" return async (e: SupersetClientResponse | string) => {\n",
" const parsedError = await getClientErrorObject(e);\n",
" // Taking the first error returned from the API\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" handleErrorFunc: (\n",
" errMsg?: string | Record<string, string[] | string>,\n",
" ) => void,\n"
],
"file_path": "superset-frontend/src/views/CRUD/utils.tsx",
"type": "replace",
"edit_start_line_idx": 158
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 { isFrontendRoute, routes } from './routes';
describe('isFrontendRoute', () => {
it('returns true if a route matches', () => {
routes.forEach(r => {
expect(isFrontendRoute(r.path)).toBe(true);
});
});
it('returns false if a route does not match', () => {
expect(isFrontendRoute('/non-existent/path/')).toBe(false);
});
});
| superset-frontend/src/views/routes.test.tsx | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017636669508647174,
0.00017614199896343052,
0.00017591792857274413,
0.0001761416788212955,
2.093053979024262e-7
] |
{
"id": 9,
"code_window": [
"export const createFetchDistinct = createFetchResourceMethod('distinct');\n",
"\n",
"export function createErrorHandler(\n",
" handleErrorFunc: (errMsg?: string | Record<string, string[]>) => void,\n",
") {\n",
" return async (e: SupersetClientResponse | string) => {\n",
" const parsedError = await getClientErrorObject(e);\n",
" // Taking the first error returned from the API\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" handleErrorFunc: (\n",
" errMsg?: string | Record<string, string[] | string>,\n",
" ) => void,\n"
],
"file_path": "superset-frontend/src/views/CRUD/utils.tsx",
"type": "replace",
"edit_start_line_idx": 158
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
slice_name: Cross Channel Relationship heatmap
viz_type: heatmap
params:
adhoc_filters: []
all_columns_x: channel_1
all_columns_y: channel_2
bottom_margin: auto
canvas_image_rendering: pixelated
datasource: 35__table
left_margin: auto
linear_color_scheme: schemeBlues
metric:
aggregate: SUM
column:
column_name: cnt
description: null
expression: null
filterable: true
groupby: true
id: 1777
is_dttm: false
optionName: _col_cnt
python_date_format: null
type: INT
verbose_name: null
expressionType: SIMPLE
hasCustomLabel: false
isNew: false
label: SUM(cnt)
optionName: metric_i1djbl8i2y_2vdl690dkyu
sqlExpression: null
normalize_across: heatmap
row_limit: 1000
show_legend: true
show_perc: false
show_values: true
sort_x_axis: alpha_asc
sort_y_axis: alpha_asc
time_range: No filter
time_range_endpoints:
- inclusive
- exclusive
url_params: {}
viz_type: heatmap
xscale_interval: null
y_axis_bounds:
- null
- null
y_axis_format: SMART_NUMBER
yscale_interval: null
cache_timeout: null
uuid: 6cb43397-5c62-4f32-bde2-95344c412b5a
version: 1.0.0
dataset_uuid: 473d6113-b44a-48d8-a6ae-e0ef7e2aebb0
| superset/examples/configs/charts/Cross_Channel_Relationship_heatmap_2786.yaml | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.00017864719848148525,
0.0001766773493727669,
0.0001728312490740791,
0.00017731374828144908,
0.0000021162379653105745
] |
{
"id": 9,
"code_window": [
"export const createFetchDistinct = createFetchResourceMethod('distinct');\n",
"\n",
"export function createErrorHandler(\n",
" handleErrorFunc: (errMsg?: string | Record<string, string[]>) => void,\n",
") {\n",
" return async (e: SupersetClientResponse | string) => {\n",
" const parsedError = await getClientErrorObject(e);\n",
" // Taking the first error returned from the API\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" handleErrorFunc: (\n",
" errMsg?: string | Record<string, string[] | string>,\n",
" ) => void,\n"
],
"file_path": "superset-frontend/src/views/CRUD/utils.tsx",
"type": "replace",
"edit_start_line_idx": 158
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 json
import logging
import re
from datetime import datetime
from typing import (
Any,
Callable,
Dict,
List,
Match,
Optional,
Pattern,
Tuple,
TYPE_CHECKING,
Union,
)
from flask_babel import gettext as __
from pytz import _FixedOffset # type: ignore
from sqlalchemy.dialects.postgresql import ARRAY, DOUBLE_PRECISION, ENUM, JSON
from sqlalchemy.dialects.postgresql.base import PGInspector
from sqlalchemy.types import String, TypeEngine
from superset.db_engine_specs.base import BaseEngineSpec, BaseParametersMixin
from superset.errors import SupersetErrorType
from superset.exceptions import SupersetException
from superset.utils import core as utils
from superset.utils.core import ColumnSpec, GenericDataType
if TYPE_CHECKING:
from superset.models.core import Database # pragma: no cover
logger = logging.getLogger()
# Replace psycopg2.tz.FixedOffsetTimezone with pytz, which is serializable by PyArrow
# https://github.com/stub42/pytz/blob/b70911542755aeeea7b5a9e066df5e1c87e8f2c8/src/pytz/reference.py#L25
class FixedOffsetTimezone(_FixedOffset):
pass
# Regular expressions to catch custom errors
CONNECTION_INVALID_USERNAME_REGEX = re.compile(
'role "(?P<username>.*?)" does not exist'
)
CONNECTION_INVALID_PASSWORD_REGEX = re.compile(
'password authentication failed for user "(?P<username>.*?)"'
)
CONNECTION_INVALID_HOSTNAME_REGEX = re.compile(
'could not translate host name "(?P<hostname>.*?)" to address: '
"nodename nor servname provided, or not known"
)
CONNECTION_PORT_CLOSED_REGEX = re.compile(
r"could not connect to server: Connection refused\s+Is the server "
r'running on host "(?P<hostname>.*?)" (\(.*?\) )?and accepting\s+TCP/IP '
r"connections on port (?P<port>.*?)\?"
)
CONNECTION_HOST_DOWN_REGEX = re.compile(
r"could not connect to server: (?P<reason>.*?)\s+Is the server running on "
r'host "(?P<hostname>.*?)" (\(.*?\) )?and accepting\s+TCP/IP '
r"connections on port (?P<port>.*?)\?"
)
CONNECTION_UNKNOWN_DATABASE_REGEX = re.compile(
'database "(?P<database>.*?)" does not exist'
)
class PostgresBaseEngineSpec(BaseEngineSpec):
""" Abstract class for Postgres 'like' databases """
engine = ""
engine_name = "PostgreSQL"
_time_grain_expressions = {
None: "{col}",
"PT1S": "DATE_TRUNC('second', {col})",
"PT1M": "DATE_TRUNC('minute', {col})",
"PT1H": "DATE_TRUNC('hour', {col})",
"P1D": "DATE_TRUNC('day', {col})",
"P1W": "DATE_TRUNC('week', {col})",
"P1M": "DATE_TRUNC('month', {col})",
"P0.25Y": "DATE_TRUNC('quarter', {col})",
"P1Y": "DATE_TRUNC('year', {col})",
}
custom_errors = {
CONNECTION_INVALID_USERNAME_REGEX: (
__('The username "%(username)s" does not exist.'),
SupersetErrorType.CONNECTION_INVALID_USERNAME_ERROR,
),
CONNECTION_INVALID_PASSWORD_REGEX: (
__('The password provided for username "%(username)s" is incorrect.'),
SupersetErrorType.CONNECTION_INVALID_PASSWORD_ERROR,
),
CONNECTION_INVALID_HOSTNAME_REGEX: (
__('The hostname "%(hostname)s" cannot be resolved.'),
SupersetErrorType.CONNECTION_INVALID_HOSTNAME_ERROR,
),
CONNECTION_PORT_CLOSED_REGEX: (
__('Port %(port)s on hostname "%(hostname)s" refused the connection.'),
SupersetErrorType.CONNECTION_PORT_CLOSED_ERROR,
),
CONNECTION_HOST_DOWN_REGEX: (
__(
'The host "%(hostname)s" might be down, and can\'t be '
"reached on port %(port)s."
),
SupersetErrorType.CONNECTION_HOST_DOWN_ERROR,
),
CONNECTION_UNKNOWN_DATABASE_REGEX: (
__('Unable to connect to database "%(database)s".'),
SupersetErrorType.CONNECTION_UNKNOWN_DATABASE_ERROR,
),
}
@classmethod
def fetch_data(
cls, cursor: Any, limit: Optional[int] = None
) -> List[Tuple[Any, ...]]:
cursor.tzinfo_factory = FixedOffsetTimezone
if not cursor.description:
return []
return super().fetch_data(cursor, limit)
@classmethod
def epoch_to_dttm(cls) -> str:
return "(timestamp 'epoch' + {col} * interval '1 second')"
class PostgresEngineSpec(PostgresBaseEngineSpec, BaseParametersMixin):
engine = "postgresql"
engine_aliases = {"postgres"}
drivername = "postgresql+psycopg2"
sqlalchemy_uri_placeholder = (
"postgresql+psycopg2://user:password@host:port/dbname[?key=value&key=value...]"
)
max_column_name_length = 63
try_remove_schema_from_table_name = False
column_type_mappings = (
(
re.compile(r"^double precision", re.IGNORECASE),
DOUBLE_PRECISION(),
GenericDataType.NUMERIC,
),
(
re.compile(r"^array.*", re.IGNORECASE),
lambda match: ARRAY(int(match[2])) if match[2] else String(),
utils.GenericDataType.STRING,
),
(re.compile(r"^json.*", re.IGNORECASE), JSON(), utils.GenericDataType.STRING,),
(re.compile(r"^enum.*", re.IGNORECASE), ENUM(), utils.GenericDataType.STRING,),
)
@classmethod
def get_allow_cost_estimate(cls, extra: Dict[str, Any]) -> bool:
return True
@classmethod
def estimate_statement_cost(cls, statement: str, cursor: Any) -> Dict[str, Any]:
sql = f"EXPLAIN {statement}"
cursor.execute(sql)
result = cursor.fetchone()[0]
match = re.search(r"cost=([\d\.]+)\.\.([\d\.]+)", result)
if match:
return {
"Start-up cost": float(match.group(1)),
"Total cost": float(match.group(2)),
}
return {}
@classmethod
def query_cost_formatter(
cls, raw_cost: List[Dict[str, Any]]
) -> List[Dict[str, str]]:
return [{k: str(v) for k, v in row.items()} for row in raw_cost]
@classmethod
def get_table_names(
cls, database: "Database", inspector: PGInspector, schema: Optional[str]
) -> List[str]:
"""Need to consider foreign tables for PostgreSQL"""
tables = inspector.get_table_names(schema)
tables.extend(inspector.get_foreign_table_names(schema))
return sorted(tables)
@classmethod
def convert_dttm(cls, target_type: str, dttm: datetime) -> Optional[str]:
tt = target_type.upper()
if tt == utils.TemporalType.DATE:
return f"TO_DATE('{dttm.date().isoformat()}', 'YYYY-MM-DD')"
if "TIMESTAMP" in tt or "DATETIME" in tt:
dttm_formatted = dttm.isoformat(sep=" ", timespec="microseconds")
return f"""TO_TIMESTAMP('{dttm_formatted}', 'YYYY-MM-DD HH24:MI:SS.US')"""
return None
@staticmethod
def get_extra_params(database: "Database") -> Dict[str, Any]:
"""
For Postgres, the path to a SSL certificate is placed in `connect_args`.
:param database: database instance from which to extract extras
:raises CertificateException: If certificate is not valid/unparseable
:raises SupersetException: If database extra json payload is unparseable
"""
try:
extra = json.loads(database.extra or "{}")
except json.JSONDecodeError:
raise SupersetException("Unable to parse database extras")
if database.server_cert:
engine_params = extra.get("engine_params", {})
connect_args = engine_params.get("connect_args", {})
connect_args["sslmode"] = connect_args.get("sslmode", "verify-full")
path = utils.create_ssl_cert_file(database.server_cert)
connect_args["sslrootcert"] = path
engine_params["connect_args"] = connect_args
extra["engine_params"] = engine_params
return extra
@classmethod
def get_column_spec( # type: ignore
cls,
native_type: Optional[str],
source: utils.ColumnTypeSource = utils.ColumnTypeSource.GET_TABLE,
column_type_mappings: Tuple[
Tuple[
Pattern[str],
Union[TypeEngine, Callable[[Match[str]], TypeEngine]],
GenericDataType,
],
...,
] = column_type_mappings,
) -> Union[ColumnSpec, None]:
column_spec = super().get_column_spec(native_type)
if column_spec:
return column_spec
return super().get_column_spec(
native_type, column_type_mappings=column_type_mappings
)
| superset/db_engine_specs/postgres.py | 0 | https://github.com/apache/superset/commit/b147fa84e2efbdac4452f099158e34b8ecaefdb7 | [
0.0022869142703711987,
0.0003735191421583295,
0.0001665874879108742,
0.00017474866763222963,
0.0005105154705233872
] |
{
"id": 0,
"code_window": [
" }\n",
"\n",
" return setterFn;\n",
"}\n",
"\n",
"const ROLE_ATTR = 'role';\n",
"function roleSetter(element, value) {\n",
" if (isString(value)) {\n",
" DOM.setAttribute(element, ROLE_ATTR, value);\n",
" } else {\n",
" DOM.removeAttribute(element, ROLE_ATTR);\n",
" if (isPresent(value)) {\n",
" throw new BaseException(\"Invalid role attribute, only string values are allowed, got '\" + stringify(value) + \"'\");\n",
" }\n",
" }\n",
"}\n",
"\n",
"/**\n",
" * Creates the ElementBinders and adds watches to the\n",
" * ProtoChangeDetector.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "replace",
"edit_start_line_idx": 95
} | import {Parser, Lexer, ChangeDetector, ChangeDetection, jitChangeDetection}
from 'angular2/change_detection';
import {ExceptionHandler} from 'angular2/src/core/exception_handler';
import {bootstrap, Component, Viewport, Template, ViewContainer, Compiler, NgElement, Decorator} from 'angular2/angular2';
import {CompilerCache} from 'angular2/src/core/compiler/compiler';
import {DirectiveMetadataReader} from 'angular2/src/core/compiler/directive_metadata_reader';
import {TemplateLoader} from 'angular2/src/core/compiler/template_loader';
import {TemplateResolver} from 'angular2/src/core/compiler/template_resolver';
import {ShadowDomStrategy, NativeShadowDomStrategy, EmulatedUnscopedShadowDomStrategy} from 'angular2/src/core/compiler/shadow_dom_strategy';
import {Content} from 'angular2/src/core/compiler/shadow_dom_emulation/content_tag';
import {DestinationLightDom} from 'angular2/src/core/compiler/shadow_dom_emulation/light_dom';
import {LifeCycle} from 'angular2/src/core/life_cycle/life_cycle';
import {UrlResolver} from 'angular2/src/core/compiler/url_resolver';
import {StyleUrlResolver} from 'angular2/src/core/compiler/style_url_resolver';
import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper';
import {StyleInliner} from 'angular2/src/core/compiler/style_inliner';
import {CssProcessor} from 'angular2/src/core/compiler/css_processor';
import {reflector} from 'angular2/src/reflection/reflection';
import {DOM} from 'angular2/src/dom/dom_adapter';
import {isPresent} from 'angular2/src/facade/lang';
import {window, document, gc} from 'angular2/src/facade/browser';
import {getIntParameter, bindAction} from 'angular2/src/test_lib/benchmark_util';
import {XHR} from 'angular2/src/core/compiler/xhr/xhr';
import {XHRImpl} from 'angular2/src/core/compiler/xhr/xhr_impl';
import {If} from 'angular2/directives';
import {BrowserDomAdapter} from 'angular2/src/dom/browser_adapter';
function setupReflector() {
// TODO: Put the general calls to reflector.register... in a shared file
// as they are needed in all benchmarks...
reflector.registerType(AppComponent, {
'factory': () => new AppComponent(),
'parameters': [],
'annotations' : [
new Component({selector: 'app'}),
new Template({
directives: [TreeComponent],
inline: `<tree [data]='initData'></tree>`
})]
});
reflector.registerType(TreeComponent, {
'factory': () => new TreeComponent(),
'parameters': [],
'annotations' : [
new Component({
selector: 'tree',
bind: {'data': 'data'}
}),
new Template({
directives: [TreeComponent, If],
inline: `<span> {{data.value}} <span template='if data.right != null'><tree [data]='data.right'></tree></span><span template='if data.left != null'><tree [data]='data.left'></tree></span></span>`
})]
});
reflector.registerType(If, {
'factory': (vp) => new If(vp),
'parameters': [[ViewContainer]],
'annotations' : [new Viewport({
selector: '[if]',
bind: {
'condition': 'if'
}
})]
});
reflector.registerType(Compiler, {
'factory': (cd, templateLoader, reader, parser, compilerCache, strategy, tplResolver,
cmpUrlMapper, urlResolver, cssProcessor) =>
new Compiler(cd, templateLoader, reader, parser, compilerCache, strategy, tplResolver,
cmpUrlMapper, urlResolver, cssProcessor),
'parameters': [[ChangeDetection], [TemplateLoader], [DirectiveMetadataReader],
[Parser], [CompilerCache], [ShadowDomStrategy], [TemplateResolver],
[ComponentUrlMapper], [UrlResolver], [CssProcessor]],
'annotations': []
});
reflector.registerType(CompilerCache, {
'factory': () => new CompilerCache(),
'parameters': [],
'annotations': []
});
reflector.registerType(Parser, {
'factory': (lexer) => new Parser(lexer),
'parameters': [[Lexer]],
'annotations': []
});
reflector.registerType(TemplateLoader, {
'factory': (xhr, urlResolver) => new TemplateLoader(xhr, urlResolver),
'parameters': [[XHR], [UrlResolver]],
'annotations': []
});
reflector.registerType(TemplateResolver, {
'factory': () => new TemplateResolver(),
'parameters': [],
'annotations': []
});
reflector.registerType(XHR, {
'factory': () => new XHRImpl(),
'parameters': [],
'annotations': []
});
reflector.registerType(DirectiveMetadataReader, {
'factory': () => new DirectiveMetadataReader(),
'parameters': [],
'annotations': []
});
reflector.registerType(ShadowDomStrategy, {
"factory": (strategy) => strategy,
"parameters": [[NativeShadowDomStrategy]],
"annotations": []
});
reflector.registerType(NativeShadowDomStrategy, {
"factory": (styleUrlResolver) => new NativeShadowDomStrategy(styleUrlResolver),
"parameters": [[StyleUrlResolver]],
"annotations": []
});
reflector.registerType(EmulatedUnscopedShadowDomStrategy, {
"factory": (styleUrlResolver) => new EmulatedUnscopedShadowDomStrategy(styleUrlResolver, null),
"parameters": [[StyleUrlResolver]],
"annotations": []
});
reflector.registerType(StyleUrlResolver, {
"factory": (urlResolver) => new StyleUrlResolver(urlResolver),
"parameters": [[UrlResolver]],
"annotations": []
});
reflector.registerType(Content, {
"factory": (lightDom, el) => new Content(lightDom, el),
"parameters": [[DestinationLightDom], [NgElement]],
"annotations" : [new Decorator({selector: '[content]'})]
});
reflector.registerType(UrlResolver, {
"factory": () => new UrlResolver(),
"parameters": [],
"annotations": []
});
reflector.registerType(Lexer, {
'factory': () => new Lexer(),
'parameters': [],
'annotations': []
});
reflector.registerType(ExceptionHandler, {
"factory": () => new ExceptionHandler(),
"parameters": [],
"annotations": []
});
reflector.registerType(LifeCycle, {
"factory": (exHandler, cd) => new LifeCycle(exHandler, cd),
"parameters": [[ExceptionHandler], [ChangeDetector]],
"annotations": []
});
reflector.registerType(ComponentUrlMapper, {
"factory": () => new ComponentUrlMapper(),
"parameters": [],
"annotations": []
});
reflector.registerType(StyleInliner, {
"factory": (xhr, styleUrlResolver, urlResolver) =>
new StyleInliner(xhr, styleUrlResolver, urlResolver),
"parameters": [[XHR], [StyleUrlResolver], [UrlResolver]],
"annotations": []
});
reflector.registerType(CssProcessor, {
"factory": () => new CssProcessor(null),
"parameters": [],
"annotations": []
});
reflector.registerGetters({
'value': (a) => a.value,
'left': (a) => a.left,
'right': (a) => a.right,
'initData': (a) => a.initData,
'data': (a) => a.data,
'condition': (a) => a.condition,
});
reflector.registerSetters({
'value': (a,v) => a.value = v,
'left': (a,v) => a.left = v,
'right': (a,v) => a.right = v,
'initData': (a,v) => a.initData = v,
'data': (a,v) => a.data = v,
'condition': (a,v) => a.condition = v,
});
}
var BASELINE_TREE_TEMPLATE;
var BASELINE_IF_TEMPLATE;
export function main() {
BrowserDomAdapter.makeCurrent();
var maxDepth = getIntParameter('depth');
setupReflector();
BASELINE_TREE_TEMPLATE = DOM.createTemplate(
'<span>_<template class="ng-binding"></template><template class="ng-binding"></template></span>');
BASELINE_IF_TEMPLATE = DOM.createTemplate(
'<span template="if"><tree></tree></span>');
var app;
var lifeCycle;
var baselineRootTreeComponent;
var count = 0;
function ng2DestroyDom() {
// TODO: We need an initial value as otherwise the getter for data.value will fail
// --> this should be already caught in change detection!
app.initData = new TreeNode('', null, null);
lifeCycle.tick();
}
function profile(create, destroy, name) {
return function() {
window.console.profile(name + ' w GC');
var duration = 0;
var count = 0;
while(count++ < 150) {
gc();
var start = window.performance.now();
create();
duration += window.performance.now() - start;
destroy();
}
window.console.profileEnd(name + ' w GC');
window.console.log(`Iterations: ${count}; time: ${duration / count} ms / iteration`);
window.console.profile(name + ' w/o GC');
duration = 0;
count = 0;
while(count++ < 150) {
var start = window.performance.now();
create();
duration += window.performance.now() - start;
destroy();
}
window.console.profileEnd(name + ' w/o GC');
window.console.log(`Iterations: ${count}; time: ${duration / count} ms / iteration`);
};
}
function ng2CreateDom() {
var values = count++ % 2 == 0 ?
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*'] :
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', '-'];
app.initData = buildTree(maxDepth, values, 0);
lifeCycle.tick();
}
function noop() {}
function initNg2() {
bootstrap(AppComponent).then((injector) => {
lifeCycle = injector.get(LifeCycle);
app = injector.get(AppComponent);
bindAction('#ng2DestroyDom', ng2DestroyDom);
bindAction('#ng2CreateDom', ng2CreateDom);
bindAction('#ng2UpdateDomProfile', profile(ng2CreateDom, noop, 'ng2-update'));
bindAction('#ng2CreateDomProfile', profile(ng2CreateDom, ng2DestroyDom, 'ng2-create'));
});
}
function baselineDestroyDom() {
baselineRootTreeComponent.update(new TreeNode('', null, null));
}
function baselineCreateDom() {
var values = count++ % 2 == 0 ?
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*'] :
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', '-'];
baselineRootTreeComponent.update(buildTree(maxDepth, values, 0));
}
function initBaseline() {
var tree = DOM.createElement('tree');
DOM.appendChild(DOM.querySelector(document, 'baseline'), tree);
baselineRootTreeComponent = new BaseLineTreeComponent(tree);
bindAction('#baselineDestroyDom', baselineDestroyDom);
bindAction('#baselineCreateDom', baselineCreateDom);
bindAction('#baselineUpdateDomProfile', profile(baselineCreateDom, noop, 'baseline-update'));
bindAction('#baselineCreateDomProfile', profile(baselineCreateDom, baselineDestroyDom, 'baseline-create'));
}
initNg2();
initBaseline();
}
class TreeNode {
value:string;
left:TreeNode;
right:TreeNode;
constructor(value, left, right) {
this.value = value;
this.left = left;
this.right = right;
}
}
function buildTree(maxDepth, values, curDepth) {
if (maxDepth === curDepth) return new TreeNode('', null, null);
return new TreeNode(
values[curDepth],
buildTree(maxDepth, values, curDepth+1),
buildTree(maxDepth, values, curDepth+1));
}
// http://jsperf.com/nextsibling-vs-childnodes
class BaseLineTreeComponent {
element;
value:BaseLineInterpolation;
left:BaseLineIf;
right:BaseLineIf;
constructor(element) {
this.element = element;
var clone = DOM.clone(BASELINE_TREE_TEMPLATE.content.firstChild);
var shadowRoot = this.element.createShadowRoot();
DOM.appendChild(shadowRoot, clone);
var child = clone.firstChild;
this.value = new BaseLineInterpolation(child);
child = DOM.nextSibling(child);
this.left = new BaseLineIf(child);
child = DOM.nextSibling(child);
this.right = new BaseLineIf(child);
}
update(value:TreeNode) {
this.value.update(value.value);
this.left.update(value.left);
this.right.update(value.right);
}
}
class BaseLineInterpolation {
value:string;
textNode;
constructor(textNode) {
this.value = null;
this.textNode = textNode;
}
update(value:string) {
if (this.value !== value) {
this.value = value;
DOM.setText(this.textNode, value + ' ');
}
}
}
class BaseLineIf {
condition:boolean;
component:BaseLineTreeComponent;
anchor;
constructor(anchor) {
this.anchor = anchor;
this.condition = false;
this.component = null;
}
update(value:TreeNode) {
var newCondition = isPresent(value);
if (this.condition !== newCondition) {
this.condition = newCondition;
if (isPresent(this.component)) {
DOM.remove(this.component.element);
this.component = null;
}
if (this.condition) {
var element = DOM.firstChild(DOM.clone(BASELINE_IF_TEMPLATE).content);
this.anchor.parentNode.insertBefore(element, DOM.nextSibling(this.anchor));
this.component = new BaseLineTreeComponent(DOM.firstChild(element));
}
}
if (isPresent(this.component)) {
this.component.update(value);
}
}
}
class AppComponent {
initData:TreeNode;
constructor() {
// TODO: We need an initial value as otherwise the getter for data.value will fail
// --> this should be already caught in change detection!
this.initData = new TreeNode('', null, null);
}
}
class TreeComponent {
data:TreeNode;
}
| modules/benchmarks/src/tree/tree_benchmark.js | 1 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.000198247711523436,
0.00017221938469447196,
0.0001651433703955263,
0.00017244966875296086,
0.000005325677193468437
] |
{
"id": 0,
"code_window": [
" }\n",
"\n",
" return setterFn;\n",
"}\n",
"\n",
"const ROLE_ATTR = 'role';\n",
"function roleSetter(element, value) {\n",
" if (isString(value)) {\n",
" DOM.setAttribute(element, ROLE_ATTR, value);\n",
" } else {\n",
" DOM.removeAttribute(element, ROLE_ATTR);\n",
" if (isPresent(value)) {\n",
" throw new BaseException(\"Invalid role attribute, only string values are allowed, got '\" + stringify(value) + \"'\");\n",
" }\n",
" }\n",
"}\n",
"\n",
"/**\n",
" * Creates the ElementBinders and adds watches to the\n",
" * ProtoChangeDetector.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "replace",
"edit_start_line_idx": 95
} | import {describe, it, expect, beforeEach, ddescribe, iit, xit, el} from 'angular2/test_lib';
import {DOM} from 'angular2/src/dom/dom_adapter';
import {SelectorMatcher} from 'angular2/src/core/compiler/selector';
import {CssSelector} from 'angular2/src/core/compiler/selector';
import {List, ListWrapper, MapWrapper} from 'angular2/src/facade/collection';
export function main() {
describe('SelectorMatcher', () => {
var matcher, matched, selectableCollector, s1, s2, s3, s4;
function reset() {
matched = ListWrapper.create();
}
beforeEach(() => {
reset();
s1 = s2 = s3 = s4 = null;
selectableCollector = (selector, context) => {
ListWrapper.push(matched, selector);
ListWrapper.push(matched, context);
}
matcher = new SelectorMatcher();
});
it('should select by element name case insensitive', () => {
matcher.addSelectable(s1 = CssSelector.parse('someTag'), 1);
expect(matcher.match(CssSelector.parse('SOMEOTHERTAG'), selectableCollector)).toEqual(false);
expect(matched).toEqual([]);
expect(matcher.match(CssSelector.parse('SOMETAG'), selectableCollector)).toEqual(true);
expect(matched).toEqual([s1,1]);
});
it('should select by class name case insensitive', () => {
matcher.addSelectable(s1 = CssSelector.parse('.someClass'), 1);
matcher.addSelectable(s2 = CssSelector.parse('.someClass.class2'), 2);
expect(matcher.match(CssSelector.parse('.SOMEOTHERCLASS'), selectableCollector)).toEqual(false);
expect(matched).toEqual([]);
expect(matcher.match(CssSelector.parse('.SOMECLASS'), selectableCollector)).toEqual(true);
expect(matched).toEqual([s1,1]);
reset();
expect(matcher.match(CssSelector.parse('.someClass.class2'), selectableCollector)).toEqual(true);
expect(matched).toEqual([s1,1,s2,2]);
});
it('should select by attr name case insensitive independent of the value', () => {
matcher.addSelectable(s1 = CssSelector.parse('[someAttr]'), 1);
matcher.addSelectable(s2 = CssSelector.parse('[someAttr][someAttr2]'), 2);
expect(matcher.match(CssSelector.parse('[SOMEOTHERATTR]'), selectableCollector)).toEqual(false);
expect(matched).toEqual([]);
expect(matcher.match(CssSelector.parse('[SOMEATTR]'), selectableCollector)).toEqual(true);
expect(matched).toEqual([s1,1]);
reset();
expect(matcher.match(CssSelector.parse('[SOMEATTR=someValue]'), selectableCollector)).toEqual(true);
expect(matched).toEqual([s1,1]);
reset();
expect(matcher.match(CssSelector.parse('[someAttr][someAttr2]'), selectableCollector)).toEqual(true);
expect(matched).toEqual([s1,1,s2,2]);
});
it('should select by attr name only once if the value is from the DOM', () => {
matcher.addSelectable(s1 = CssSelector.parse('[some-decor]'), 1);
var elementSelector = new CssSelector();
var element = el('<div attr></div>');
var empty = DOM.getAttribute(element, 'attr');
elementSelector.addAttribute('some-decor', empty);
matcher.match(elementSelector, selectableCollector);
expect(matched).toEqual([s1,1]);
});
it('should select by attr name and value case insensitive', () => {
matcher.addSelectable(s1 = CssSelector.parse('[someAttr=someValue]'), 1);
expect(matcher.match(CssSelector.parse('[SOMEATTR=SOMEOTHERATTR]'), selectableCollector)).toEqual(false);
expect(matched).toEqual([]);
expect(matcher.match(CssSelector.parse('[SOMEATTR=SOMEVALUE]'), selectableCollector)).toEqual(true);
expect(matched).toEqual([s1,1]);
});
it('should select by element name, class name and attribute name with value', () => {
matcher.addSelectable(s1 = CssSelector.parse('someTag.someClass[someAttr=someValue]'), 1);
expect(matcher.match(CssSelector.parse('someOtherTag.someOtherClass[someOtherAttr]'), selectableCollector)).toEqual(false);
expect(matched).toEqual([]);
expect(matcher.match(CssSelector.parse('someTag.someOtherClass[someOtherAttr]'), selectableCollector)).toEqual(false);
expect(matched).toEqual([]);
expect(matcher.match(CssSelector.parse('someTag.someClass[someOtherAttr]'), selectableCollector)).toEqual(false);
expect(matched).toEqual([]);
expect(matcher.match(CssSelector.parse('someTag.someClass[someAttr]'), selectableCollector)).toEqual(false);
expect(matched).toEqual([]);
expect(matcher.match(CssSelector.parse('someTag.someClass[someAttr=someValue]'), selectableCollector)).toEqual(true);
expect(matched).toEqual([s1,1]);
});
it('should select independent of the order in the css selector', () => {
matcher.addSelectable(s1 = CssSelector.parse('[someAttr].someClass'), 1);
matcher.addSelectable(s2 = CssSelector.parse('.someClass[someAttr]'), 2);
matcher.addSelectable(s3 = CssSelector.parse('.class1.class2'), 3);
matcher.addSelectable(s4 = CssSelector.parse('.class2.class1'), 4);
expect(matcher.match(CssSelector.parse('[someAttr].someClass'), selectableCollector)).toEqual(true);
expect(matched).toEqual([s1,1,s2,2]);
reset();
expect(matcher.match(CssSelector.parse('.someClass[someAttr]'), selectableCollector)).toEqual(true);
expect(matched).toEqual([s1,1,s2,2]);
reset();
expect(matcher.match(CssSelector.parse('.class1.class2'), selectableCollector)).toEqual(true);
expect(matched).toEqual([s3,3,s4,4]);
reset();
expect(matcher.match(CssSelector.parse('.class2.class1'), selectableCollector)).toEqual(true);
expect(matched).toEqual([s4,4,s3,3]);
});
it('should not select with a matching :not selector', () => {
matcher.addSelectable(CssSelector.parse('p:not(.someClass)'), 1);
matcher.addSelectable(CssSelector.parse('p:not([someAttr])'), 2);
matcher.addSelectable(CssSelector.parse(':not(.someClass)'), 3);
matcher.addSelectable(CssSelector.parse(':not(p)'), 4);
matcher.addSelectable(CssSelector.parse(':not(p[someAttr])'), 5);
expect(matcher.match(CssSelector.parse('p.someClass[someAttr]'), selectableCollector)).toEqual(false);
expect(matched).toEqual([]);
});
it('should select with a non matching :not selector', () => {
matcher.addSelectable(s1 = CssSelector.parse('p:not(.someClass)'), 1);
matcher.addSelectable(s2 = CssSelector.parse('p:not(.someOtherClass[someAttr])'), 2);
matcher.addSelectable(s3 = CssSelector.parse(':not(.someClass)'), 3);
matcher.addSelectable(s4 = CssSelector.parse(':not(.someOtherClass[someAttr])'), 4);
expect(matcher.match(CssSelector.parse('p[someOtherAttr].someOtherClass'), selectableCollector)).toEqual(true);
expect(matched).toEqual([s1,1,s2,2,s3,3,s4,4]);
});
});
describe('CssSelector.parse', () => {
it('should detect element names', () => {
var cssSelector = CssSelector.parse('sometag');
expect(cssSelector.element).toEqual('sometag');
expect(cssSelector.toString()).toEqual('sometag');
});
it('should detect class names', () => {
var cssSelector = CssSelector.parse('.someClass');
expect(cssSelector.classNames).toEqual(['someclass']);
expect(cssSelector.toString()).toEqual('.someclass');
});
it('should detect attr names', () => {
var cssSelector = CssSelector.parse('[attrname]');
expect(cssSelector.attrs).toEqual(['attrname', '']);
expect(cssSelector.toString()).toEqual('[attrname]');
});
it('should detect attr values', () => {
var cssSelector = CssSelector.parse('[attrname=attrvalue]');
expect(cssSelector.attrs).toEqual(['attrname', 'attrvalue']);
expect(cssSelector.toString()).toEqual('[attrname=attrvalue]');
});
it('should detect multiple parts', () => {
var cssSelector = CssSelector.parse('sometag[attrname=attrvalue].someclass');
expect(cssSelector.element).toEqual('sometag');
expect(cssSelector.attrs).toEqual(['attrname', 'attrvalue']);
expect(cssSelector.classNames).toEqual(['someclass']);
expect(cssSelector.toString()).toEqual('sometag.someclass[attrname=attrvalue]');
});
it('should detect :not', () => {
var cssSelector = CssSelector.parse('sometag:not([attrname=attrvalue].someclass)');
expect(cssSelector.element).toEqual('sometag');
expect(cssSelector.attrs.length).toEqual(0);
expect(cssSelector.classNames.length).toEqual(0);
var notSelector = cssSelector.notSelector;
expect(notSelector.element).toEqual(null);
expect(notSelector.attrs).toEqual(['attrname', 'attrvalue']);
expect(notSelector.classNames).toEqual(['someclass']);
expect(cssSelector.toString()).toEqual('sometag:not(.someclass[attrname=attrvalue])');
});
it('should detect :not without truthy', () => {
var cssSelector = CssSelector.parse(':not([attrname=attrvalue].someclass)');
expect(cssSelector.element).toEqual("*");
var notSelector = cssSelector.notSelector;
expect(notSelector.attrs).toEqual(['attrname', 'attrvalue']);
expect(notSelector.classNames).toEqual(['someclass']);
expect(cssSelector.toString()).toEqual('*:not(.someclass[attrname=attrvalue])');
});
it('should throw when nested :not', () => {
expect(() => {
CssSelector.parse('sometag:not(:not([attrname=attrvalue].someclass))')
}).toThrowError('Nesting :not is not allowed in a selector');
});
});
} | modules/angular2/test/core/compiler/selector_spec.js | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00018476253899279982,
0.0001736326375976205,
0.00016702104767318815,
0.00017280357133131474,
0.000003323762712170719
] |
{
"id": 0,
"code_window": [
" }\n",
"\n",
" return setterFn;\n",
"}\n",
"\n",
"const ROLE_ATTR = 'role';\n",
"function roleSetter(element, value) {\n",
" if (isString(value)) {\n",
" DOM.setAttribute(element, ROLE_ATTR, value);\n",
" } else {\n",
" DOM.removeAttribute(element, ROLE_ATTR);\n",
" if (isPresent(value)) {\n",
" throw new BaseException(\"Invalid role attribute, only string values are allowed, got '\" + stringify(value) + \"'\");\n",
" }\n",
" }\n",
"}\n",
"\n",
"/**\n",
" * Creates the ElementBinders and adds watches to the\n",
" * ProtoChangeDetector.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "replace",
"edit_start_line_idx": 95
} | import {ddescribe, describe, it, iit, expect, beforeEach} from 'angular2/test_lib';
import {DirectiveMetadataReader} from 'angular2/src/core/compiler/directive_metadata_reader';
import {Decorator, Component, Viewport} from 'angular2/src/core/annotations/annotations';
import {DirectiveMetadata} from 'angular2/src/core/compiler/directive_metadata';
@Decorator({selector: 'someDecorator'})
class SomeDecorator {}
@Component({selector: 'someComponent'})
class SomeComponent {}
@Viewport({selector: 'someViewport'})
class SomeViewport {}
class SomeDirectiveWithoutAnnotation {
}
export function main() {
describe("DirectiveMetadataReader", () => {
var reader;
beforeEach(() => {
reader = new DirectiveMetadataReader();
});
it('should read out the Decorator annotation', () => {
var directiveMetadata = reader.read(SomeDecorator);
expect(directiveMetadata).toEqual(
new DirectiveMetadata(SomeDecorator, new Decorator({selector: 'someDecorator'})));
});
it('should read out the Viewport annotation', () => {
var directiveMetadata = reader.read(SomeViewport);
expect(directiveMetadata).toEqual(
new DirectiveMetadata(SomeViewport, new Viewport({selector: 'someViewport'})));
});
it('should read out the Component annotation', () => {
var directiveMetadata = reader.read(SomeComponent);
expect(directiveMetadata).toEqual(
new DirectiveMetadata(SomeComponent, new Component({selector: 'someComponent'})));
});
it('should throw if not matching annotation is found', () => {
expect(() => {
reader.read(SomeDirectiveWithoutAnnotation);
}).toThrowError('No Directive annotation found on SomeDirectiveWithoutAnnotation');
});
});
}
| modules/angular2/test/core/compiler/directive_metadata_reader_spec.js | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00017560285050421953,
0.00017234911501873285,
0.00016891332052182406,
0.00017247829237021506,
0.0000021634550648741424
] |
{
"id": 0,
"code_window": [
" }\n",
"\n",
" return setterFn;\n",
"}\n",
"\n",
"const ROLE_ATTR = 'role';\n",
"function roleSetter(element, value) {\n",
" if (isString(value)) {\n",
" DOM.setAttribute(element, ROLE_ATTR, value);\n",
" } else {\n",
" DOM.removeAttribute(element, ROLE_ATTR);\n",
" if (isPresent(value)) {\n",
" throw new BaseException(\"Invalid role attribute, only string values are allowed, got '\" + stringify(value) + \"'\");\n",
" }\n",
" }\n",
"}\n",
"\n",
"/**\n",
" * Creates the ElementBinders and adds watches to the\n",
" * ProtoChangeDetector.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "replace",
"edit_start_line_idx": 95
} | import {ParseTreeTransformer} from 'traceur/src/codegeneration/ParseTreeTransformer';
import {ForInStatement} from 'traceur/src/syntax/trees/ParseTrees';
/**
* Transforms for-of into for-in.
*/
export class ForOfTransformer extends ParseTreeTransformer {
/**
* @param {ForOfStatement} tree
* @return {ParseTree}
*/
transformForOfStatement(original) {
var tree = super.transformForOfStatement(original);
return new ForInStatement(tree.location, tree.initializer, tree.collection, tree.body);
}
}
| tools/transpiler/src/codegeneration/ForOfTransformer.js | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00017626347835175693,
0.00017520083929412067,
0.00017413821478839964,
0.00017520083929412067,
0.0000010626317816786468
] |
{
"id": 1,
"code_window": [
" } else if (StringWrapper.startsWith(property, STYLE_PREFIX)) {\n",
" styleParts = StringWrapper.split(property, DOT_REGEXP);\n",
" styleSuffix = styleParts.length > 2 ? ListWrapper.get(styleParts, 2) : '';\n",
" setterFn = styleSetterFactory(ListWrapper.get(styleParts, 1), styleSuffix);\n",
" } else {\n",
" property = this._resolvePropertyName(property);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" } else if (StringWrapper.equals(property, 'innerHtml')) {\n",
" setterFn = (element, value) => DOM.setInnerHTML(element, value);\n"
],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "add",
"edit_start_line_idx": 201
} | import {int, isBlank} from 'angular2/src/facade/lang';
import {DOM} from 'angular2/src/dom/dom_adapter';
import {MapWrapper} from 'angular2/src/facade/collection';
import {Parser, Lexer, ChangeDetector, ChangeDetection}
from 'angular2/change_detection';
import {ExceptionHandler} from 'angular2/src/core/exception_handler';
import {
bootstrap, Component, Viewport, Template, ViewContainer, Compiler, onChange, NgElement, Decorator
} from 'angular2/angular2';
import {reflector} from 'angular2/src/reflection/reflection';
import {CompilerCache} from 'angular2/src/core/compiler/compiler';
import {DirectiveMetadataReader} from 'angular2/src/core/compiler/directive_metadata_reader';
import {ShadowDomStrategy, NativeShadowDomStrategy, EmulatedUnscopedShadowDomStrategy} from 'angular2/src/core/compiler/shadow_dom_strategy';
import {Content} from 'angular2/src/core/compiler/shadow_dom_emulation/content_tag';
import {DestinationLightDom} from 'angular2/src/core/compiler/shadow_dom_emulation/light_dom';
import {TemplateLoader} from 'angular2/src/core/compiler/template_loader';
import {TemplateResolver} from 'angular2/src/core/compiler/template_resolver';
import {LifeCycle} from 'angular2/src/core/life_cycle/life_cycle';
import {XHR} from 'angular2/src/core/compiler/xhr/xhr';
import {XHRImpl} from 'angular2/src/core/compiler/xhr/xhr_impl';
import {UrlResolver} from 'angular2/src/core/compiler/url_resolver';
import {StyleUrlResolver} from 'angular2/src/core/compiler/style_url_resolver';
import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper';
import {StyleInliner} from 'angular2/src/core/compiler/style_inliner';
import {CssProcessor} from 'angular2/src/core/compiler/css_processor';
import {If, For} from 'angular2/directives';
import {App, setupReflectorForApp} from './app';
import {ScrollAreaComponent, setupReflectorForScrollArea} from './scroll_area';
import {ScrollItemComponent, setupReflectorForScrollItem} from './scroll_item';
import {CompanyNameComponent, OpportunityNameComponent, OfferingNameComponent,
AccountCellComponent, StageButtonsComponent, FormattedCellComponent,
setupReflectorForCells}
from './cells';
export function main() {
setupReflector();
bootstrap(App);
}
export function setupReflector() {
setupReflectorForAngular();
setupReflectorForApp();
setupReflectorForScrollArea();
setupReflectorForScrollItem();
setupReflectorForCells();
// TODO: the transpiler is not able to compiles templates used as keys
var evt = `$event`;
reflector.registerGetters({
'scrollAreas': (o) => o.scrollAreas,
'length': (o) => o.length,
'iterableChanges': (o) => o.iterableChanges,
'scrollArea': (o) => o.scrollArea,
'item': (o) => o.item,
'visibleItems': (o) => o.visibleItems,
'condition': (o) => o.condition,
'width': (o) => o.width,
'value': (o) => o.value,
'href': (o) => o.href,
'company': (o) => o.company,
'formattedValue': (o) => o.formattedValue,
'name': (o) => o.name,
'style': (o) => o.style,
'offering': (o) => o.offering,
'account': (o) => o.account,
'accountId': (o) => o.accountId,
'companyNameWidth': (o) => o.companyNameWidth,
'opportunityNameWidth': (o) => o.opportunityNameWidth,
'offeringNameWidth': (o) => o.offeringNameWidth,
'accountCellWidth': (o) => o.accountCellWidth,
'basePointsWidth': (o) => o.basePointsWidth,
'scrollDivStyle': (o) => o.scrollDivStyle,
'paddingStyle': (o) => o.paddingStyle,
'innerStyle': (o) => o.innerStyle,
'opportunity': (o) => o.opportunity,
'itemStyle': (o) => o.itemStyle,
'dueDateWidth': (o) => o.dueDateWidth,
'basePoints': (o) => o.basePoints,
'kickerPoints': (o) => o.kickerPoints,
'kickerPointsWidth': (o) => o.kickerPointsWidth,
'bundles': (o) => o.bundles,
'stageButtonsWidth': (o) => o.stageButtonsWidth,
'bundlesWidth': (o) => o.bundlesWidth,
'disabled': (o) => o.disabled,
'isDisabled': (o) => o.isDisabled,
'dueDate': (o) => o.dueDate,
'endDate': (o) => o.endDate,
'aatStatus': (o) => o.aatStatus,
'stage': (o) => o.stage,
'stages': (o) => o.stages,
'aatStatusWidth': (o) => o.aatStatusWidth,
'endDateWidth': (o) => o.endDateWidth,
evt: (o) => null
});
reflector.registerSetters({
'scrollAreas': (o, v) => o.scrollAreas = v,
'length': (o, v) => o.length = v,
'condition': (o, v) => o.condition = v,
'scrollArea': (o, v) => o.scrollArea = v,
'item': (o, v) => o.item = v,
'visibleItems': (o, v) => o.visibleItems = v,
'iterableChanges': (o, v) => o.iterableChanges = v,
'width': (o, v) => o.width = v,
'value': (o, v) => o.value = v,
'company': (o, v) => o.company = v,
'name': (o, v) => o.name = v,
'offering': (o, v) => o.offering = v,
'account': (o, v) => o.account = v,
'accountId': (o, v) => o.accountId = v,
'formattedValue': (o, v) => o.formattedValue = v,
'stage': (o, v) => o.stage = v,
'stages': (o, v) => o.stages = v,
'disabled': (o, v) => o.disabled = v,
'isDisabled': (o, v) => o.isDisabled = v,
'href': (o, v) => o.href = v,
'companyNameWidth': (o, v) => o.companyNameWidth = v,
'opportunityNameWidth': (o, v) => o.opportunityNameWidth = v,
'offeringNameWidth': (o, v) => o.offeringNameWidth = v,
'accountCellWidth': (o, v) => o.accountCellWidth = v,
'basePointsWidth': (o, v) => o.basePointsWidth = v,
'scrollDivStyle': (o, v) => o.scrollDivStyle = v,
'paddingStyle': (o, v) => o.paddingStyle = v,
'innerStyle': (o, v) => o.innerStyle = v,
'opportunity': (o, v) => o.opportunity = v,
'itemStyle': (o, v) => o.itemStyle = v,
'basePoints': (o, v) => o.basePoints = v,
'kickerPoints': (o, v) => o.kickerPoints = v,
'kickerPointsWidth': (o, v) => o.kickerPointsWidth = v,
'stageButtonsWidth': (o, v) => o.stageButtonsWidth = v,
'dueDate': (o, v) => o.dueDate = v,
'dueDateWidth': (o, v) => o.dueDateWidth = v,
'endDate': (o, v) => o.endDate = v,
'endDateWidth': (o, v) => o.endDate = v,
'aatStatus': (o, v) => o.aatStatus = v,
'aatStatusWidth': (o, v) => o.aatStatusWidth = v,
'bundles': (o, v) => o.bundles = v,
'bundlesWidth': (o, v) => o.bundlesWidth = v,
evt: (o, v) => null,
'style': (o, m) => {
//if (isBlank(m)) return;
// HACK
MapWrapper.forEach(m, function(v, k) {
o.style.setProperty(k, v);
});
}
});
reflector.registerMethods({
'onScroll': (o, args) => {
// HACK
o.onScroll(args[0]);
},
'setStage': (o, args) => o.setStage(args[0])
});
}
export function setupReflectorForAngular() {
reflector.registerType(If, {
'factory': (vp) => new If(vp),
'parameters': [[ViewContainer]],
'annotations' : [new Viewport({
selector: '[if]',
bind: {
'condition': 'if'
}
})]
});
reflector.registerType(For, {
'factory': (vp) => new For(vp),
'parameters': [[ViewContainer]],
'annotations' : [new Viewport({
selector: '[for]',
bind: {
'iterableChanges': 'of | iterableDiff'
}
})]
});
reflector.registerType(Compiler, {
"factory": (changeDetection, templateLoader, reader, parser, compilerCache, shadowDomStrategy,
tplResolver, cmpUrlMapper, urlResolver, cssProcessor) =>
new Compiler(changeDetection, templateLoader, reader, parser, compilerCache, shadowDomStrategy,
tplResolver, cmpUrlMapper, urlResolver, cssProcessor),
"parameters": [[ChangeDetection], [TemplateLoader], [DirectiveMetadataReader], [Parser],
[CompilerCache], [ShadowDomStrategy], [TemplateResolver], [ComponentUrlMapper],
[UrlResolver], [CssProcessor]],
"annotations": []
});
reflector.registerType(CompilerCache, {
'factory': () => new CompilerCache(),
'parameters': [],
'annotations': []
});
reflector.registerType(Parser, {
'factory': (lexer) => new Parser(lexer),
'parameters': [[Lexer]],
'annotations': []
});
reflector.registerType(TemplateLoader, {
"factory": (xhr, urlResolver) => new TemplateLoader(xhr, urlResolver),
"parameters": [[XHR], [UrlResolver]],
"annotations": []
});
reflector.registerType(TemplateResolver, {
"factory": () => new TemplateResolver(),
"parameters": [],
"annotations": []
});
reflector.registerType(XHR, {
"factory": () => new XHRImpl(),
"parameters": [],
"annotations": []
});
reflector.registerType(DirectiveMetadataReader, {
'factory': () => new DirectiveMetadataReader(),
'parameters': [],
'annotations': []
});
reflector.registerType(Lexer, {
'factory': () => new Lexer(),
'parameters': [],
'annotations': []
});
reflector.registerType(ExceptionHandler, {
"factory": () => new ExceptionHandler(),
"parameters": [],
"annotations": []
});
reflector.registerType(LifeCycle, {
"factory": (exHandler, cd) => new LifeCycle(exHandler, cd),
"parameters": [[ExceptionHandler], [ChangeDetector]],
"annotations": []
});
reflector.registerType(ShadowDomStrategy, {
"factory": (strategy) => strategy,
"parameters": [[NativeShadowDomStrategy]],
"annotations": []
});
reflector.registerType(NativeShadowDomStrategy, {
"factory": (styleUrlResolver) => new NativeShadowDomStrategy(styleUrlResolver),
"parameters": [[StyleUrlResolver]],
"annotations": []
});
reflector.registerType(EmulatedUnscopedShadowDomStrategy, {
"factory": (styleUrlResolver) => new EmulatedUnscopedShadowDomStrategy(styleUrlResolver, null),
"parameters": [[StyleUrlResolver]],
"annotations": []
});
reflector.registerType(StyleUrlResolver, {
"factory": (urlResolver) => new StyleUrlResolver(urlResolver),
"parameters": [[UrlResolver]],
"annotations": []
});
reflector.registerType(UrlResolver, {
"factory": () => new UrlResolver(),
"parameters": [],
"annotations": []
});
reflector.registerType(ComponentUrlMapper, {
"factory": () => new ComponentUrlMapper(),
"parameters": [],
"annotations": []
});
reflector.registerType(Content, {
"factory": (lightDom, el) => new Content(lightDom, el),
"parameters": [[DestinationLightDom], [NgElement]],
"annotations" : [new Decorator({selector: '[content]'})]
});
reflector.registerType(StyleInliner, {
"factory": (xhr, styleUrlResolver, urlResolver) =>
new StyleInliner(xhr, styleUrlResolver, urlResolver),
"parameters": [[XHR], [StyleUrlResolver], [UrlResolver]],
"annotations": []
});
reflector.registerType(CssProcessor, {
"factory": () => new CssProcessor(null),
"parameters": [],
"annotations": []
});
}
| modules/benchmarks/src/naive_infinite_scroll/index.js | 1 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00017845530237536877,
0.0001750676892697811,
0.00017067477165255696,
0.00017515086801722646,
0.0000019843178051814903
] |
{
"id": 1,
"code_window": [
" } else if (StringWrapper.startsWith(property, STYLE_PREFIX)) {\n",
" styleParts = StringWrapper.split(property, DOT_REGEXP);\n",
" styleSuffix = styleParts.length > 2 ? ListWrapper.get(styleParts, 2) : '';\n",
" setterFn = styleSetterFactory(ListWrapper.get(styleParts, 1), styleSuffix);\n",
" } else {\n",
" property = this._resolvePropertyName(property);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" } else if (StringWrapper.equals(property, 'innerHtml')) {\n",
" setterFn = (element, value) => DOM.setInnerHTML(element, value);\n"
],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "add",
"edit_start_line_idx": 201
} | import {
afterEach,
AsyncTestCompleter,
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from 'angular2/test_lib';
import { DateWrapper, Json, RegExpWrapper, isPresent } from 'angular2/src/facade/lang';
import { PromiseWrapper } from 'angular2/src/facade/async';
import {
bind, Injector,
SampleDescription,
MeasureValues,
Options
} from 'benchpress/common';
import { JsonFileReporter } from 'benchpress/src/reporter/json_file_reporter';
export function main() {
describe('file reporter', () => {
var loggedFile;
function createReporter({sampleId, descriptions, metrics, path}) {
var bindings = [
JsonFileReporter.BINDINGS,
bind(SampleDescription).toValue(new SampleDescription(sampleId, descriptions, metrics)),
bind(JsonFileReporter.PATH).toValue(path),
bind(Options.NOW).toValue( () => DateWrapper.fromMillis(1234) ),
bind(Options.WRITE_FILE).toValue((filename, content) => {
loggedFile = {
'filename': filename,
'content': content
};
return PromiseWrapper.resolve(null);
})
];
return new Injector(bindings).get(JsonFileReporter);
}
it('should write all data into a file', inject([AsyncTestCompleter], (async) => {
createReporter({
sampleId: 'someId',
descriptions: [{ 'a': 2 }],
path: 'somePath',
metrics: {
'script': 'script time'
}
}).reportSample([
mv(0, 0, { 'a': 3, 'b': 6})
], [mv(0, 0, {
'a': 3, 'b': 6
}), mv(1, 1, {
'a': 5, 'b': 9
})]);
var regExp = RegExpWrapper.create('somePath/someId_\\d+\\.json');
expect(isPresent(RegExpWrapper.firstMatch(regExp, loggedFile['filename']))).toBe(true);
var parsedContent = Json.parse(loggedFile['content']);
expect(parsedContent).toEqual({
"description": {
"id": "someId",
"description": {
"a": 2
},
"metrics": {"script": "script time"}
},
"completeSample": [{
"timeStamp": "1970-01-01T00:00:00.000Z",
"runIndex": 0,
"values": {
"a": 3,
"b": 6
}
}],
"validSample": [
{
"timeStamp": "1970-01-01T00:00:00.000Z",
"runIndex": 0,
"values": {
"a": 3,
"b": 6
}
},
{
"timeStamp": "1970-01-01T00:00:00.001Z",
"runIndex": 1,
"values": {
"a": 5,
"b": 9
}
}
]
});
async.done();
}));
});
}
function mv(runIndex, time, values) {
return new MeasureValues(runIndex, DateWrapper.fromMillis(time), values);
}
| modules/benchpress/test/reporter/json_file_reporter_spec.js | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00017695069254841655,
0.00017335262964479625,
0.0001691120269242674,
0.0001738989376462996,
0.0000021426462808449287
] |
{
"id": 1,
"code_window": [
" } else if (StringWrapper.startsWith(property, STYLE_PREFIX)) {\n",
" styleParts = StringWrapper.split(property, DOT_REGEXP);\n",
" styleSuffix = styleParts.length > 2 ? ListWrapper.get(styleParts, 2) : '';\n",
" setterFn = styleSetterFactory(ListWrapper.get(styleParts, 1), styleSuffix);\n",
" } else {\n",
" property = this._resolvePropertyName(property);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" } else if (StringWrapper.equals(property, 'innerHtml')) {\n",
" setterFn = (element, value) => DOM.setInnerHTML(element, value);\n"
],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "add",
"edit_start_line_idx": 201
} | # Overview
* High level description of all of the components. | modules/angular2/docs/core/00_index.md | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00016373346443288028,
0.00016373346443288028,
0.00016373346443288028,
0.00016373346443288028,
0
] |
{
"id": 1,
"code_window": [
" } else if (StringWrapper.startsWith(property, STYLE_PREFIX)) {\n",
" styleParts = StringWrapper.split(property, DOT_REGEXP);\n",
" styleSuffix = styleParts.length > 2 ? ListWrapper.get(styleParts, 2) : '';\n",
" setterFn = styleSetterFactory(ListWrapper.get(styleParts, 1), styleSuffix);\n",
" } else {\n",
" property = this._resolvePropertyName(property);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" } else if (StringWrapper.equals(property, 'innerHtml')) {\n",
" setterFn = (element, value) => DOM.setInnerHTML(element, value);\n"
],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "add",
"edit_start_line_idx": 201
} | <!doctype html>
<html>
<body>
<h2>Params</h2>
<form>
Elements:
<input type="number" name="elements" placeholder="elements" value="150">
<br>
<button>Apply</button>
</form>
<h2>Actions</h2>
<p>
<button id="compileWithBindings">CompileWithBindings</button>
<button id="compileNoBindings">CompileNoBindings</button>
</p>
<template id="templateNoBindings">
<div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4">
<div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4">
<div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4">
<div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4">
<div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4">
</div>
</div>
</div>
</div>
</div>
</template>
<template id="templateWithBindings">
<div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4">
{{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}}
<div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4">
{{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}}
<div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4">
{{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}}
<div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4">
{{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}}
<div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4">
{{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}}
</div>
</div>
</div>
</div>
</div>
</template>
$SCRIPTS$
</body>
</html> | modules/benchmarks/src/compiler/compiler_benchmark.html | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.0013830772368237376,
0.0003716164792422205,
0.00016676707309670746,
0.00017085477884393185,
0.00045234261779114604
] |
{
"id": 2,
"code_window": [
" } else {\n",
" property = this._resolvePropertyName(property);\n",
" //TODO(pk): special casing innerHtml, see: https://github.com/angular/angular/issues/789\n",
" if (StringWrapper.equals(property, 'innerHTML')) {\n",
" setterFn = (element, value) => DOM.setInnerHTML(element, value);\n",
" } else if (DOM.hasProperty(compileElement.element, property) || StringWrapper.equals(property, 'innerHtml')) {\n",
" setterFn = reflector.setter(property);\n",
" }\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" var propertySetterFn = reflector.setter(property);\n",
" setterFn = function(receiver, value) {\n",
" if (DOM.hasProperty(receiver, property)) {\n",
" return propertySetterFn(receiver, value);\n",
" }\n"
],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "replace",
"edit_start_line_idx": 203
} | import {DOM} from 'angular2/src/dom/dom_adapter';
import {BrowserDomAdapter} from 'angular2/src/dom/browser_adapter';
import {isBlank, Type} from 'angular2/src/facade/lang';
import {document} from 'angular2/src/facade/browser';
import {MapWrapper} from 'angular2/src/facade/collection';
import {DirectiveMetadata} from 'angular2/src/core/compiler/directive_metadata';
import {NativeShadowDomStrategy} from 'angular2/src/core/compiler/shadow_dom_strategy';
import {Parser, Lexer, ProtoRecordRange, dynamicChangeDetection} from 'angular2/change_detection';
import {Compiler, CompilerCache} from 'angular2/src/core/compiler/compiler';
import {DirectiveMetadataReader} from 'angular2/src/core/compiler/directive_metadata_reader';
import {Component} from 'angular2/src/core/annotations/annotations';
import {Decorator} from 'angular2/src/core/annotations/annotations';
import {Template} from 'angular2/src/core/annotations/template';
import {TemplateLoader} from 'angular2/src/core/compiler/template_loader';
import {TemplateResolver} from 'angular2/src/core/compiler/template_resolver';
import {UrlResolver} from 'angular2/src/core/compiler/url_resolver';
import {StyleUrlResolver} from 'angular2/src/core/compiler/style_url_resolver';
import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper';
import {CssProcessor} from 'angular2/src/core/compiler/css_processor';
import {reflector} from 'angular2/src/reflection/reflection';
import {getIntParameter, bindAction} from 'angular2/src/test_lib/benchmark_util';
function setupReflector() {
reflector.registerType(BenchmarkComponent, {
"factory": () => new BenchmarkComponent(),
"parameters": [],
"annotations" : [new Component()]
});
reflector.registerType(Dir0, {
"factory": () => new Dir0(),
"parameters": [],
"annotations" : [new Decorator({selector: '[dir0]', bind: {'prop': 'attr0'}})]
});
reflector.registerType(Dir1, {
"factory": (dir0) => new Dir1(dir0),
"parameters": [[Dir0]],
"annotations" : [new Decorator({selector: '[dir1]', bind: {'prop': 'attr1'}})]
});
reflector.registerType(Dir2, {
"factory": (dir1) => new Dir2(dir1),
"parameters": [[Dir1]],
"annotations" : [new Decorator({selector: '[dir2]', bind: {'prop': 'attr2'}})]
});
reflector.registerType(Dir3, {
"factory": (dir2) => new Dir3(dir2),
"parameters": [[Dir2]],
"annotations" : [new Decorator({selector: '[dir3]', bind: {'prop': 'attr3'}})]
});
reflector.registerType(Dir4, {
"factory": (dir3) => new Dir4(dir3),
"parameters": [[Dir3]],
"annotations" : [new Decorator({selector: '[dir4]', bind: {'prop': 'attr4'}})]
});
reflector.registerGetters({
"inter0": (a) => a.inter0, "inter1": (a) => a.inter1,
"inter2": (a) => a.inter2, "inter3": (a) => a.inter3, "inter4": (a) => a.inter4,
"value0": (a) => a.value0, "value1": (a) => a.value1,
"value2": (a) => a.value2, "value3": (a) => a.value3, "value4": (a) => a.value4,
"prop" : (a) => a.prop
});
reflector.registerSetters({
"inter0": (a,v) => a.inter0 = v, "inter1": (a,v) => a.inter1 = v,
"inter2": (a,v) => a.inter2 = v, "inter3": (a,v) => a.inter3 = v, "inter4": (a,v) => a.inter4 = v,
"value0": (a,v) => a.value0 = v, "value1": (a,v) => a.value1 = v,
"value2": (a,v) => a.value2 = v, "value3": (a,v) => a.value3 = v, "value4": (a,v) => a.value4 = v,
"prop": (a,v) => a.prop = v
});
}
export function main() {
BrowserDomAdapter.makeCurrent();
var count = getIntParameter('elements');
setupReflector();
var reader = new DirectiveMetadataReader();
var cache = new CompilerCache();
var templateResolver = new FakeTemplateResolver();
var urlResolver = new UrlResolver();
var styleUrlResolver = new StyleUrlResolver(urlResolver);
var compiler = new Compiler(
dynamicChangeDetection,
new TemplateLoader(null, urlResolver),
reader,
new Parser(new Lexer()),
cache,
new NativeShadowDomStrategy(styleUrlResolver),
templateResolver,
new ComponentUrlMapper(),
urlResolver,
new CssProcessor(null)
);
var templateNoBindings = createTemplateHtml('templateNoBindings', count);
var templateWithBindings = createTemplateHtml('templateWithBindings', count);
function compileNoBindings() {
templateResolver.setTemplateHtml(templateNoBindings);
cache.clear();
compiler.compile(BenchmarkComponent);
}
function compileWithBindings() {
templateResolver.setTemplateHtml(templateWithBindings);
cache.clear();
compiler.compile(BenchmarkComponent);
}
bindAction('#compileNoBindings', compileNoBindings);
bindAction('#compileWithBindings', compileWithBindings);
}
function createTemplateHtml(templateId, repeatCount) {
var template = DOM.querySelectorAll(document, `#${templateId}`)[0];
var content = DOM.getInnerHTML(template);
var result = '';
for (var i=0; i<repeatCount; i++) {
result += content;
}
return result;
}
@Decorator({
selector: '[dir0]',
bind: {
'prop': 'attr0'
}
})
class Dir0 {}
@Decorator({
selector: '[dir1]',
bind: {
'prop': 'attr1'
}
})
class Dir1 {
constructor(dir0:Dir0) {}
}
@Decorator({
selector: '[dir2]',
bind: {
'prop': 'attr2'
}
})
class Dir2 {
constructor(dir1:Dir1) {}
}
@Decorator({
selector: '[dir3]',
bind: {
'prop': 'attr3'
}
})
class Dir3 {
constructor(dir2:Dir2) {}
}
@Decorator({
selector: '[dir4]',
bind: {
'prop': 'attr4'
}
})
class Dir4 {
constructor(dir3:Dir3) {}
}
@Component()
class BenchmarkComponent {}
class FakeTemplateResolver extends TemplateResolver {
_template: Template;
constructor() {
super();
}
setTemplateHtml(html: string) {
this._template = new Template({
inline: html,
directives: [Dir0, Dir1, Dir2, Dir3, Dir4]
});
}
resolve(component: Type): Template {
return this._template;
}
}
| modules/benchmarks/src/compiler/compiler_benchmark.js | 1 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.001140179461799562,
0.00022294113296084106,
0.00016645537107251585,
0.00017320457845926285,
0.00020576262613758445
] |
{
"id": 2,
"code_window": [
" } else {\n",
" property = this._resolvePropertyName(property);\n",
" //TODO(pk): special casing innerHtml, see: https://github.com/angular/angular/issues/789\n",
" if (StringWrapper.equals(property, 'innerHTML')) {\n",
" setterFn = (element, value) => DOM.setInnerHTML(element, value);\n",
" } else if (DOM.hasProperty(compileElement.element, property) || StringWrapper.equals(property, 'innerHtml')) {\n",
" setterFn = reflector.setter(property);\n",
" }\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" var propertySetterFn = reflector.setter(property);\n",
" setterFn = function(receiver, value) {\n",
" if (DOM.hasProperty(receiver, property)) {\n",
" return propertySetterFn(receiver, value);\n",
" }\n"
],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "replace",
"edit_start_line_idx": 203
} | var mockPackage = require('../mocks/mockPackage');
var Dgeni = require('dgeni');
describe('atParser service', function() {
var dgeni, injector, parser;
var fileContent =
'import {CONST} from "facade/lang";\n' +
'\n' +
'/**\n' +
'* A parameter annotation that creates a synchronous eager dependency.\n' +
'*\n' +
'* class AComponent {\n' +
'* constructor(@Inject("aServiceToken") aService) {}\n' +
'* }\n' +
'*\n' +
'*/\n' +
'export class Inject {\n' +
'token;\n' +
'@CONST()\n' +
'constructor({a,b}:{a:string, b:string}) {\n' +
'this.token = a;\n' +
'}\n' +
'}';
beforeEach(function() {
dgeni = new Dgeni([mockPackage()]);
injector = dgeni.configureInjector();
parser = injector.get('atParser');
});
it('should extract the comments from the file', function() {
var result = parser.parseModule({
content: fileContent,
relativePath: 'di/src/annotations.js'
});
expect(result.comments[0].range.toString()).toEqual(
'/**\n' +
'* A parameter annotation that creates a synchronous eager dependency.\n' +
'*\n' +
'* class AComponent {\n' +
'* constructor(@Inject("aServiceToken") aService) {}\n' +
'* }\n' +
'*\n' +
'*/'
);
});
it('should extract a module AST from the file', function() {
var result = parser.parseModule({
content: fileContent,
relativePath: 'di/src/annotations.js'
});
expect(result.moduleTree.moduleName).toEqual('di/src/annotations');
expect(result.moduleTree.scriptItemList[0].type).toEqual('IMPORT_DECLARATION');
expect(result.moduleTree.scriptItemList[1].type).toEqual('EXPORT_DECLARATION');
});
it('should attach comments to their following AST', function() {
var result = parser.parseModule({
content: fileContent,
relativePath: 'di/src/annotations.js'
});
expect(result.moduleTree.scriptItemList[1].commentBefore.range.toString()).toEqual(
'/**\n' +
'* A parameter annotation that creates a synchronous eager dependency.\n' +
'*\n' +
'* class AComponent {\n' +
'* constructor(@Inject("aServiceToken") aService) {}\n' +
'* }\n' +
'*\n' +
'*/'
);
});
}); | docs/dgeni-package/services/atParser.spec.js | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.0001759754668455571,
0.00017294556892011315,
0.00016903576033655554,
0.00017252597899641842,
0.0000019055889879382448
] |
{
"id": 2,
"code_window": [
" } else {\n",
" property = this._resolvePropertyName(property);\n",
" //TODO(pk): special casing innerHtml, see: https://github.com/angular/angular/issues/789\n",
" if (StringWrapper.equals(property, 'innerHTML')) {\n",
" setterFn = (element, value) => DOM.setInnerHTML(element, value);\n",
" } else if (DOM.hasProperty(compileElement.element, property) || StringWrapper.equals(property, 'innerHtml')) {\n",
" setterFn = reflector.setter(property);\n",
" }\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" var propertySetterFn = reflector.setter(property);\n",
" setterFn = function(receiver, value) {\n",
" if (DOM.hasProperty(receiver, property)) {\n",
" return propertySetterFn(receiver, value);\n",
" }\n"
],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "replace",
"edit_start_line_idx": 203
} | import {describe, it, expect} from 'angular2/test_lib';
function same(a, b) {
return a === b;
}
function notSame(a, b) {
if ((a !== a) && (b !== b)) return true;
return a !== b;
}
export function main() {
describe('equals', function() {
it('should work', function() {
var obj = {};
expect(same({}, {}) == false).toBe(true);
expect(same(obj, obj) == true).toBe(true);
expect(notSame({}, {}) == true).toBe(true);
expect(notSame(obj, obj) == false).toBe(true);
});
});
}
| tools/transpiler/spec/equals_spec.js | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00017838012718129903,
0.00017147045582532883,
0.00016783522733021528,
0.0001681960275163874,
0.000004888092007604428
] |
{
"id": 2,
"code_window": [
" } else {\n",
" property = this._resolvePropertyName(property);\n",
" //TODO(pk): special casing innerHtml, see: https://github.com/angular/angular/issues/789\n",
" if (StringWrapper.equals(property, 'innerHTML')) {\n",
" setterFn = (element, value) => DOM.setInnerHTML(element, value);\n",
" } else if (DOM.hasProperty(compileElement.element, property) || StringWrapper.equals(property, 'innerHtml')) {\n",
" setterFn = reflector.setter(property);\n",
" }\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" var propertySetterFn = reflector.setter(property);\n",
" setterFn = function(receiver, value) {\n",
" if (DOM.hasProperty(receiver, property)) {\n",
" return propertySetterFn(receiver, value);\n",
" }\n"
],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "replace",
"edit_start_line_idx": 203
} | #!/bin/bash
set -e -x
DART_CHANNEL=$1
ARCH=$2
AVAILABLE_DART_VERSION=$(curl "https://storage.googleapis.com/dart-archive/channels/${DART_CHANNEL}/release/latest/VERSION" | python -c \
'import sys, json; print(json.loads(sys.stdin.read())["version"])')
echo Fetch Dart channel: ${DART_CHANNEL}
URL_PREFIX=https://storage.googleapis.com/dart-archive/channels/${DART_CHANNEL}/release/latest
DART_SDK_URL="$URL_PREFIX/sdk/dartsdk-$ARCH-release.zip"
DARTIUM_URL="$URL_PREFIX/dartium/dartium-$ARCH-release.zip"
download_and_unzip() {
ZIPFILE=${1/*\//}
curl -O -L $1 && unzip -q $ZIPFILE && rm $ZIPFILE
}
# TODO: do these downloads in parallel
download_and_unzip $DART_SDK_URL
download_and_unzip $DARTIUM_URL
echo Fetched new dart version $(<dart-sdk/version)
if [[ -n $DARTIUM_URL ]]; then
mv dartium-* chromium
fi
| scripts/ci/install_dart.sh | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00017254293197765946,
0.00016718904953449965,
0.00016351271187886596,
0.00016635027714073658,
0.0000038082225728430785
] |
{
"id": 3,
"code_window": [
" }\n",
" }\n",
"\n",
" if (isPresent(setterFn)) {\n",
" protoView.bindElementProperty(expression.ast, property, setterFn);\n",
" }\n",
" });\n",
" }\n",
"\n",
" _bindEvents(protoView, compileElement) {\n",
" MapWrapper.forEach(compileElement.eventBindings, (expression, eventName) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" protoView.bindElementProperty(expression.ast, property, setterFn);\n"
],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "replace",
"edit_start_line_idx": 211
} | import {DOM} from 'angular2/src/dom/dom_adapter';
import {BrowserDomAdapter} from 'angular2/src/dom/browser_adapter';
import {isBlank, Type} from 'angular2/src/facade/lang';
import {document} from 'angular2/src/facade/browser';
import {MapWrapper} from 'angular2/src/facade/collection';
import {DirectiveMetadata} from 'angular2/src/core/compiler/directive_metadata';
import {NativeShadowDomStrategy} from 'angular2/src/core/compiler/shadow_dom_strategy';
import {Parser, Lexer, ProtoRecordRange, dynamicChangeDetection} from 'angular2/change_detection';
import {Compiler, CompilerCache} from 'angular2/src/core/compiler/compiler';
import {DirectiveMetadataReader} from 'angular2/src/core/compiler/directive_metadata_reader';
import {Component} from 'angular2/src/core/annotations/annotations';
import {Decorator} from 'angular2/src/core/annotations/annotations';
import {Template} from 'angular2/src/core/annotations/template';
import {TemplateLoader} from 'angular2/src/core/compiler/template_loader';
import {TemplateResolver} from 'angular2/src/core/compiler/template_resolver';
import {UrlResolver} from 'angular2/src/core/compiler/url_resolver';
import {StyleUrlResolver} from 'angular2/src/core/compiler/style_url_resolver';
import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper';
import {CssProcessor} from 'angular2/src/core/compiler/css_processor';
import {reflector} from 'angular2/src/reflection/reflection';
import {getIntParameter, bindAction} from 'angular2/src/test_lib/benchmark_util';
function setupReflector() {
reflector.registerType(BenchmarkComponent, {
"factory": () => new BenchmarkComponent(),
"parameters": [],
"annotations" : [new Component()]
});
reflector.registerType(Dir0, {
"factory": () => new Dir0(),
"parameters": [],
"annotations" : [new Decorator({selector: '[dir0]', bind: {'prop': 'attr0'}})]
});
reflector.registerType(Dir1, {
"factory": (dir0) => new Dir1(dir0),
"parameters": [[Dir0]],
"annotations" : [new Decorator({selector: '[dir1]', bind: {'prop': 'attr1'}})]
});
reflector.registerType(Dir2, {
"factory": (dir1) => new Dir2(dir1),
"parameters": [[Dir1]],
"annotations" : [new Decorator({selector: '[dir2]', bind: {'prop': 'attr2'}})]
});
reflector.registerType(Dir3, {
"factory": (dir2) => new Dir3(dir2),
"parameters": [[Dir2]],
"annotations" : [new Decorator({selector: '[dir3]', bind: {'prop': 'attr3'}})]
});
reflector.registerType(Dir4, {
"factory": (dir3) => new Dir4(dir3),
"parameters": [[Dir3]],
"annotations" : [new Decorator({selector: '[dir4]', bind: {'prop': 'attr4'}})]
});
reflector.registerGetters({
"inter0": (a) => a.inter0, "inter1": (a) => a.inter1,
"inter2": (a) => a.inter2, "inter3": (a) => a.inter3, "inter4": (a) => a.inter4,
"value0": (a) => a.value0, "value1": (a) => a.value1,
"value2": (a) => a.value2, "value3": (a) => a.value3, "value4": (a) => a.value4,
"prop" : (a) => a.prop
});
reflector.registerSetters({
"inter0": (a,v) => a.inter0 = v, "inter1": (a,v) => a.inter1 = v,
"inter2": (a,v) => a.inter2 = v, "inter3": (a,v) => a.inter3 = v, "inter4": (a,v) => a.inter4 = v,
"value0": (a,v) => a.value0 = v, "value1": (a,v) => a.value1 = v,
"value2": (a,v) => a.value2 = v, "value3": (a,v) => a.value3 = v, "value4": (a,v) => a.value4 = v,
"prop": (a,v) => a.prop = v
});
}
export function main() {
BrowserDomAdapter.makeCurrent();
var count = getIntParameter('elements');
setupReflector();
var reader = new DirectiveMetadataReader();
var cache = new CompilerCache();
var templateResolver = new FakeTemplateResolver();
var urlResolver = new UrlResolver();
var styleUrlResolver = new StyleUrlResolver(urlResolver);
var compiler = new Compiler(
dynamicChangeDetection,
new TemplateLoader(null, urlResolver),
reader,
new Parser(new Lexer()),
cache,
new NativeShadowDomStrategy(styleUrlResolver),
templateResolver,
new ComponentUrlMapper(),
urlResolver,
new CssProcessor(null)
);
var templateNoBindings = createTemplateHtml('templateNoBindings', count);
var templateWithBindings = createTemplateHtml('templateWithBindings', count);
function compileNoBindings() {
templateResolver.setTemplateHtml(templateNoBindings);
cache.clear();
compiler.compile(BenchmarkComponent);
}
function compileWithBindings() {
templateResolver.setTemplateHtml(templateWithBindings);
cache.clear();
compiler.compile(BenchmarkComponent);
}
bindAction('#compileNoBindings', compileNoBindings);
bindAction('#compileWithBindings', compileWithBindings);
}
function createTemplateHtml(templateId, repeatCount) {
var template = DOM.querySelectorAll(document, `#${templateId}`)[0];
var content = DOM.getInnerHTML(template);
var result = '';
for (var i=0; i<repeatCount; i++) {
result += content;
}
return result;
}
@Decorator({
selector: '[dir0]',
bind: {
'prop': 'attr0'
}
})
class Dir0 {}
@Decorator({
selector: '[dir1]',
bind: {
'prop': 'attr1'
}
})
class Dir1 {
constructor(dir0:Dir0) {}
}
@Decorator({
selector: '[dir2]',
bind: {
'prop': 'attr2'
}
})
class Dir2 {
constructor(dir1:Dir1) {}
}
@Decorator({
selector: '[dir3]',
bind: {
'prop': 'attr3'
}
})
class Dir3 {
constructor(dir2:Dir2) {}
}
@Decorator({
selector: '[dir4]',
bind: {
'prop': 'attr4'
}
})
class Dir4 {
constructor(dir3:Dir3) {}
}
@Component()
class BenchmarkComponent {}
class FakeTemplateResolver extends TemplateResolver {
_template: Template;
constructor() {
super();
}
setTemplateHtml(html: string) {
this._template = new Template({
inline: html,
directives: [Dir0, Dir1, Dir2, Dir3, Dir4]
});
}
resolve(component: Type): Template {
return this._template;
}
}
| modules/benchmarks/src/compiler/compiler_benchmark.js | 1 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.0002465276629664004,
0.00017632904928177595,
0.00016507881809957325,
0.00017279581516049802,
0.000016474510630359873
] |
{
"id": 3,
"code_window": [
" }\n",
" }\n",
"\n",
" if (isPresent(setterFn)) {\n",
" protoView.bindElementProperty(expression.ast, property, setterFn);\n",
" }\n",
" });\n",
" }\n",
"\n",
" _bindEvents(protoView, compileElement) {\n",
" MapWrapper.forEach(compileElement.eventBindings, (expression, eventName) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" protoView.bindElementProperty(expression.ast, property, setterFn);\n"
],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "replace",
"edit_start_line_idx": 211
} | import {Injector, bind, OpaqueToken} from 'angular2/di';
import {Type, isBlank, isPresent, BaseException, assertionsEnabled, print, stringify} from 'angular2/src/facade/lang';
import {BrowserDomAdapter} from 'angular2/src/dom/browser_adapter';
import {DOM} from 'angular2/src/dom/dom_adapter';
import {Compiler, CompilerCache} from './compiler/compiler';
import {ProtoView} from './compiler/view';
import {Reflector, reflector} from 'angular2/src/reflection/reflection';
import {Parser, Lexer, ChangeDetection, dynamicChangeDetection, jitChangeDetection} from 'angular2/change_detection';
import {ExceptionHandler} from './exception_handler';
import {TemplateLoader} from './compiler/template_loader';
import {TemplateResolver} from './compiler/template_resolver';
import {DirectiveMetadataReader} from './compiler/directive_metadata_reader';
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
import {VmTurnZone} from 'angular2/src/core/zone/vm_turn_zone';
import {LifeCycle} from 'angular2/src/core/life_cycle/life_cycle';
import {ShadowDomStrategy, NativeShadowDomStrategy, EmulatedUnscopedShadowDomStrategy} from 'angular2/src/core/compiler/shadow_dom_strategy';
import {XHR} from 'angular2/src/core/compiler/xhr/xhr';
import {XHRImpl} from 'angular2/src/core/compiler/xhr/xhr_impl';
import {EventManager, DomEventsPlugin} from 'angular2/src/core/events/event_manager';
import {HammerGesturesPlugin} from 'angular2/src/core/events/hammer_gestures';
import {Binding} from 'angular2/src/di/binding';
import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper';
import {UrlResolver} from 'angular2/src/core/compiler/url_resolver';
import {StyleUrlResolver} from 'angular2/src/core/compiler/style_url_resolver';
import {StyleInliner} from 'angular2/src/core/compiler/style_inliner';
import {CssProcessor} from 'angular2/src/core/compiler/css_processor';
import {Component} from 'angular2/src/core/annotations/annotations';
var _rootInjector: Injector;
// Contains everything that is safe to share between applications.
var _rootBindings = [
bind(Reflector).toValue(reflector)
];
export var appViewToken = new OpaqueToken('AppView');
export var appChangeDetectorToken = new OpaqueToken('AppChangeDetector');
export var appElementToken = new OpaqueToken('AppElement');
export var appComponentAnnotatedTypeToken = new OpaqueToken('AppComponentAnnotatedType');
export var appDocumentToken = new OpaqueToken('AppDocument');
function _injectorBindings(appComponentType): List<Binding> {
return [
bind(appDocumentToken).toValue(DOM.defaultDoc()),
bind(appComponentAnnotatedTypeToken).toFactory((reader) => {
// TODO(rado): investigate whether to support bindings on root component.
return reader.read(appComponentType);
}, [DirectiveMetadataReader]),
bind(appElementToken).toFactory((appComponentAnnotatedType, appDocument) => {
var selector = appComponentAnnotatedType.annotation.selector;
var element = DOM.querySelector(appDocument, selector);
if (isBlank(element)) {
throw new BaseException(`The app selector "${selector}" did not match any elements`);
}
return element;
}, [appComponentAnnotatedTypeToken, appDocumentToken]),
bind(appViewToken).toAsyncFactory((changeDetection, compiler, injector, appElement,
appComponentAnnotatedType, strategy, eventManager) => {
var annotation = appComponentAnnotatedType.annotation;
if(!isBlank(annotation) && !(annotation instanceof Component)) {
var type = appComponentAnnotatedType.type;
throw new BaseException(`Only Components can be bootstrapped; ` +
`Directive of ${stringify(type)} is not a Component`);
}
return compiler.compile(appComponentAnnotatedType.type).then(
(protoView) => {
var appProtoView = ProtoView.createRootProtoView(protoView, appElement,
appComponentAnnotatedType, changeDetection.createProtoChangeDetector('root'),
strategy);
// The light Dom of the app element is not considered part of
// the angular application. Thus the context and lightDomInjector are
// empty.
var view = appProtoView.instantiate(null, eventManager);
view.hydrate(injector, null, null, new Object(), null);
return view;
});
}, [ChangeDetection, Compiler, Injector, appElementToken, appComponentAnnotatedTypeToken,
ShadowDomStrategy, EventManager]),
bind(appChangeDetectorToken).toFactory((rootView) => rootView.changeDetector,
[appViewToken]),
bind(appComponentType).toFactory((rootView) => rootView.elementInjectors[0].getComponent(),
[appViewToken]),
bind(LifeCycle).toFactory((exceptionHandler) => new LifeCycle(exceptionHandler, null, assertionsEnabled()),[ExceptionHandler]),
bind(EventManager).toFactory((zone) => {
var plugins = [new HammerGesturesPlugin(), new DomEventsPlugin()];
return new EventManager(plugins, zone);
}, [VmTurnZone]),
bind(ShadowDomStrategy).toFactory(
(styleUrlResolver, doc) => new EmulatedUnscopedShadowDomStrategy(styleUrlResolver, doc.head),
[StyleUrlResolver, appDocumentToken]),
Compiler,
CompilerCache,
TemplateResolver,
bind(ChangeDetection).toValue(dynamicChangeDetection),
TemplateLoader,
DirectiveMetadataReader,
Parser,
Lexer,
ExceptionHandler,
bind(XHR).toValue(new XHRImpl()),
ComponentUrlMapper,
UrlResolver,
StyleUrlResolver,
StyleInliner,
bind(CssProcessor).toFactory(() => new CssProcessor(null), []),
];
}
function _createVmZone(givenReporter:Function): VmTurnZone {
var defaultErrorReporter = (exception, stackTrace) => {
var longStackTrace = ListWrapper.join(stackTrace, "\n\n-----async gap-----\n");
print(`${exception}\n\n${longStackTrace}`);
throw exception;
};
var reporter = isPresent(givenReporter) ? givenReporter : defaultErrorReporter;
var zone = new VmTurnZone({enableLongStackTrace: assertionsEnabled()});
zone.initCallbacks({onErrorHandler: reporter});
return zone;
}
/**
* Bootstrapping for Angular applications.
*
* You instantiate an Angular application by explicitly specifying a component to use as the root component for your
* application via the `bootstrap()` method.
*
* ## Simple Example
*
* Assuming this `index.html`:
*
* ```html
* <html>
* <!-- load Angular script tags here. -->
* <body>
* <my-app>loading...</my-app>
* </body>
* </html>
* ```
*
* An application is bootstrapped inside an existing browser DOM, typically `index.html`. Unlike Angular 1, Angular 2
* does not compile/process bindings in `index.html`. This is mainly for security reasons, as well as architectural
* changes in Angular 2. This means that `index.html` can safely be processed using server-side technologies such as
* bindings. (which may use double-curly `{{ syntax }}` without collision from Angular 2 component double-curly
* `{{ syntax }}`.)
*
* We can use this script code:
*
* ```
* @Component({
* selector: 'my-app'
* })
* @Template({
* inline: 'Hello {{ name }}!'
* })
* class MyApp {
* name:string;
*
* constructor() {
* this.name = 'World';
* }
* }
*
* main() {
* return bootstrap(MyApp);
* }
* ```
*
* When the app developer invokes `bootstrap()` with the root component `MyApp` as its argument, Angular performs the
* following tasks:
*
* 1. It uses the component's `selector` property to locate the DOM element which needs to be upgraded into
* the angular component.
* 2. It creates a new child injector (from the primordial injector) and configures the injector with the component's
* `services`. Optionally, you can also override the injector configuration for an app by invoking
* `bootstrap` with the `componentServiceBindings` argument.
* 3. It creates a new [Zone] and connects it to the angular application's change detection domain instance.
* 4. It creates a shadow DOM on the selected component's host element and loads the template into it.
* 5. It instantiates the specified component.
* 6. Finally, Angular performs change detection to apply the initial data bindings for the application.
*
*
* ## Instantiating Multiple Applications on a Single Page
*
* There are two ways to do this.
*
*
* ### Isolated Applications
*
* Angular creates a new application each time that the `bootstrap()` method is invoked. When multiple applications
* are created for a page, Angular treats each application as independent within an isolated change detection and
* [Zone] domain. If you need to share data between applications, use the strategy described in the next
* section, "Applications That Share Change Detection."
*
*
* ### Applications That Share Change Detection
*
* If you need to bootstrap multiple applications that share common data, the applications must share a common
* change detection and zone. To do that, create a meta-component that lists the application components in its template.
* By only invoking the `bootstrap()` method once, with the meta-component as its argument, you ensure that only a single
* change detection zone is created and therefore data can be shared across the applications.
*
*
* ## Primordial Injector
*
* When working within a browser window, there are many singleton resources: cookies, title, location, and others.
* Angular services that represent these resources must likewise be shared across all Angular applications that
* occupy the same browser window. For this reason, Angular creates exactly one global primordial injector which stores
* all shared services, and each angular application injector has the primordial injector as its parent.
*
* Each application has its own private injector as well. When there are multiple applications on a page, Angular treats
* each application injector's services as private to that application.
*
*
* # API
* - [appComponentType]: The root component which should act as the application. This is a reference to a [Type]
* which is annotated with `@Component(...)`.
* - [componentServiceBindings]: An additional set of bindings that can be added to the [Component.services] to
* override default injection behavior.
* - [errorReporter]: `function(exception:any, stackTrace:string)` a default error reporter for unhandled exceptions.
*
* Returns a [Promise] with the application`s private [Injector].
*
* @publicModule angular2/angular2
*/
export function bootstrap(appComponentType: Type,
componentServiceBindings: List<Binding>=null,
errorReporter: Function=null): Promise<Injector> {
BrowserDomAdapter.makeCurrent();
var bootstrapProcess = PromiseWrapper.completer();
var zone = _createVmZone(errorReporter);
zone.run(() => {
// TODO(rado): prepopulate template cache, so applications with only
// index.html and main.js are possible.
var appInjector = _createAppInjector(appComponentType, componentServiceBindings, zone);
PromiseWrapper.then(appInjector.asyncGet(appViewToken),
(rootView) => {
// retrieve life cycle: may have already been created if injected in root component
var lc=appInjector.get(LifeCycle);
lc.registerWith(zone, rootView.changeDetector);
lc.tick(); //the first tick that will bootstrap the app
bootstrapProcess.resolve(appInjector);
},
(err) => {
bootstrapProcess.reject(err)
});
});
return bootstrapProcess.promise;
}
function _createAppInjector(appComponentType: Type, bindings: List<Binding>, zone: VmTurnZone): Injector {
if (isBlank(_rootInjector)) _rootInjector = new Injector(_rootBindings);
var mergedBindings = isPresent(bindings) ?
ListWrapper.concat(_injectorBindings(appComponentType), bindings) :
_injectorBindings(appComponentType);
ListWrapper.push(mergedBindings, bind(VmTurnZone).toValue(zone));
return _rootInjector.createChild(mergedBindings);
}
| modules/angular2/src/core/application.js | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.004858777858316898,
0.0003439093707129359,
0.0001604738790774718,
0.00016752794908825308,
0.0008855090127326548
] |
{
"id": 3,
"code_window": [
" }\n",
" }\n",
"\n",
" if (isPresent(setterFn)) {\n",
" protoView.bindElementProperty(expression.ast, property, setterFn);\n",
" }\n",
" });\n",
" }\n",
"\n",
" _bindEvents(protoView, compileElement) {\n",
" MapWrapper.forEach(compileElement.eventBindings, (expression, eventName) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" protoView.bindElementProperty(expression.ast, property, setterFn);\n"
],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "replace",
"edit_start_line_idx": 211
} | module.exports = function AttachCommentTreeVisitor(ParseTreeVisitor, log) {
function AttachCommentTreeVisitorImpl() {
ParseTreeVisitor.call(this);
}
AttachCommentTreeVisitorImpl.prototype = {
__proto__: ParseTreeVisitor.prototype,
visit: function(tree, comments) {
this.comments = comments;
this.index = 0;
this.currentComment = this.comments[this.index];
if (this.currentComment) log.silly('comment: ' +
this.currentComment.range.start.line + ' - ' +
this.currentComment.range.end.line + ' : ' +
this.currentComment.range.toString());
ParseTreeVisitor.prototype.visit.call(this, tree);
},
// Really we ought to subclass ParseTreeVisitor but this is fiddly in ES5 so
// it is easier to simply override the prototype's method on the instance
visitAny: function(tree) {
if (tree && tree.location && tree.location.start && this.currentComment &&
this.currentComment.range.end.offset < tree.location.start.offset) {
log.silly('tree: ' + tree.constructor.name + ' - ' + tree.location.start.line);
while (this.currentComment &&
this.currentComment.range.end.offset < tree.location.start.offset) {
log.silly('comment: ' + this.currentComment.range.start.line + ' - ' +
this.currentComment.range.end.line + ' : ' +
this.currentComment.range.toString());
tree.commentBefore = this.currentComment;
this.currentComment.treeAfter = tree;
this.index++;
this.currentComment = this.comments[this.index];
}
}
return ParseTreeVisitor.prototype.visitAny.call(this, tree);
}
};
return AttachCommentTreeVisitorImpl;
}; | docs/dgeni-package/services/AttachCommentTreeVisitor.js | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00017359477351419628,
0.00016854520072229207,
0.0001638629473745823,
0.0001675830571912229,
0.000004195811015961226
] |
{
"id": 3,
"code_window": [
" }\n",
" }\n",
"\n",
" if (isPresent(setterFn)) {\n",
" protoView.bindElementProperty(expression.ast, property, setterFn);\n",
" }\n",
" });\n",
" }\n",
"\n",
" _bindEvents(protoView, compileElement) {\n",
" MapWrapper.forEach(compileElement.eventBindings, (expression, eventName) => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" protoView.bindElementProperty(expression.ast, property, setterFn);\n"
],
"file_path": "modules/angular2/src/core/compiler/pipeline/element_binder_builder.js",
"type": "replace",
"edit_start_line_idx": 211
} | import {SelectorMatcher} from "angular2/src/core/compiler/selector";
import {CssSelector} from "angular2/src/core/compiler/selector";
import {StringWrapper, Math} from 'angular2/src/facade/lang';
import {ListWrapper} from 'angular2/src/facade/collection';
import {getIntParameter, bindAction} from 'angular2/src/test_lib/benchmark_util';
import {BrowserDomAdapter} from 'angular2/src/dom/browser_adapter';
export function main() {
BrowserDomAdapter.makeCurrent();
var count = getIntParameter('selectors');
var fixedMatcher;
var fixedSelectorStrings = [];
var fixedSelectors = [];
for (var i=0; i<count; i++) {
ListWrapper.push(fixedSelectorStrings, randomSelector());
}
for (var i=0; i<count; i++) {
ListWrapper.push(fixedSelectors, CssSelector.parse(fixedSelectorStrings[i]));
}
fixedMatcher = new SelectorMatcher();
for (var i=0; i<count; i++) {
fixedMatcher.addSelectable(fixedSelectors[i], i);
}
function parse() {
var result = [];
for (var i=0; i<count; i++) {
ListWrapper.push(result, CssSelector.parse(fixedSelectorStrings[i]));
}
return result;
}
function addSelectable() {
var matcher = new SelectorMatcher();
for (var i=0; i<count; i++) {
matcher.addSelectable(fixedSelectors[i], i);
}
return matcher;
}
function match() {
var matchCount = 0;
for (var i=0; i<count; i++) {
fixedMatcher.match(fixedSelectors[i], (selector, selected) => {
matchCount += selected;
});
}
return matchCount;
}
bindAction('#parse', parse);
bindAction('#addSelectable', addSelectable);
bindAction('#match', match);
}
function randomSelector() {
var res = randomStr(5);
for (var i=0; i<3; i++) {
res += '.'+randomStr(5);
}
for (var i=0; i<3; i++) {
res += '['+randomStr(3)+'='+randomStr(6)+']';
}
return res;
}
function randomStr(len){
var s = '';
while (s.length < len) {
s += randomChar();
}
return s;
}
function randomChar(){
var n = randomNum(62);
if(n<10) return n.toString(); //1-10
if(n<36) return StringWrapper.fromCharCode(n+55); //A-Z
return StringWrapper.fromCharCode(n+61); //a-z
}
function randomNum(max) {
return Math.floor(Math.random() * max);
}
| modules/benchmarks/src/compiler/selector_benchmark.js | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00017701076285447925,
0.0001718083512969315,
0.00016506780229974538,
0.00017143384320661426,
0.0000037091729154781206
] |
{
"id": 4,
"code_window": [
" });\n",
" }));\n",
"\n",
" it('should consume directive watch expression change.', inject([AsyncTestCompleter], (async) => {\n",
" var tpl =\n",
" '<div>' +\n",
" '<div my-dir [elprop]=\"ctxProp\"></div>' +\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should ignore bindings to unknown properties', inject([AsyncTestCompleter], (async) => {\n",
" tplResolver.setTemplate(MyComp, new Template({inline: '<div unknown=\"{{ctxProp}}\"></div>'}));\n",
"\n",
" compiler.compile(MyComp).then((pv) => {\n",
" createView(pv);\n",
"\n",
" ctx.ctxProp = 'Some value';\n",
" cd.detectChanges();\n",
" expect(DOM.hasProperty(view.nodes[0], 'unknown')).toBeFalsy();\n",
"\n",
" async.done();\n",
" });\n",
" }));\n",
"\n"
],
"file_path": "modules/angular2/test/core/compiler/integration_spec.js",
"type": "add",
"edit_start_line_idx": 188
} | import {DOM} from 'angular2/src/dom/dom_adapter';
import {BrowserDomAdapter} from 'angular2/src/dom/browser_adapter';
import {isBlank, Type} from 'angular2/src/facade/lang';
import {document} from 'angular2/src/facade/browser';
import {MapWrapper} from 'angular2/src/facade/collection';
import {DirectiveMetadata} from 'angular2/src/core/compiler/directive_metadata';
import {NativeShadowDomStrategy} from 'angular2/src/core/compiler/shadow_dom_strategy';
import {Parser, Lexer, ProtoRecordRange, dynamicChangeDetection} from 'angular2/change_detection';
import {Compiler, CompilerCache} from 'angular2/src/core/compiler/compiler';
import {DirectiveMetadataReader} from 'angular2/src/core/compiler/directive_metadata_reader';
import {Component} from 'angular2/src/core/annotations/annotations';
import {Decorator} from 'angular2/src/core/annotations/annotations';
import {Template} from 'angular2/src/core/annotations/template';
import {TemplateLoader} from 'angular2/src/core/compiler/template_loader';
import {TemplateResolver} from 'angular2/src/core/compiler/template_resolver';
import {UrlResolver} from 'angular2/src/core/compiler/url_resolver';
import {StyleUrlResolver} from 'angular2/src/core/compiler/style_url_resolver';
import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper';
import {CssProcessor} from 'angular2/src/core/compiler/css_processor';
import {reflector} from 'angular2/src/reflection/reflection';
import {getIntParameter, bindAction} from 'angular2/src/test_lib/benchmark_util';
function setupReflector() {
reflector.registerType(BenchmarkComponent, {
"factory": () => new BenchmarkComponent(),
"parameters": [],
"annotations" : [new Component()]
});
reflector.registerType(Dir0, {
"factory": () => new Dir0(),
"parameters": [],
"annotations" : [new Decorator({selector: '[dir0]', bind: {'prop': 'attr0'}})]
});
reflector.registerType(Dir1, {
"factory": (dir0) => new Dir1(dir0),
"parameters": [[Dir0]],
"annotations" : [new Decorator({selector: '[dir1]', bind: {'prop': 'attr1'}})]
});
reflector.registerType(Dir2, {
"factory": (dir1) => new Dir2(dir1),
"parameters": [[Dir1]],
"annotations" : [new Decorator({selector: '[dir2]', bind: {'prop': 'attr2'}})]
});
reflector.registerType(Dir3, {
"factory": (dir2) => new Dir3(dir2),
"parameters": [[Dir2]],
"annotations" : [new Decorator({selector: '[dir3]', bind: {'prop': 'attr3'}})]
});
reflector.registerType(Dir4, {
"factory": (dir3) => new Dir4(dir3),
"parameters": [[Dir3]],
"annotations" : [new Decorator({selector: '[dir4]', bind: {'prop': 'attr4'}})]
});
reflector.registerGetters({
"inter0": (a) => a.inter0, "inter1": (a) => a.inter1,
"inter2": (a) => a.inter2, "inter3": (a) => a.inter3, "inter4": (a) => a.inter4,
"value0": (a) => a.value0, "value1": (a) => a.value1,
"value2": (a) => a.value2, "value3": (a) => a.value3, "value4": (a) => a.value4,
"prop" : (a) => a.prop
});
reflector.registerSetters({
"inter0": (a,v) => a.inter0 = v, "inter1": (a,v) => a.inter1 = v,
"inter2": (a,v) => a.inter2 = v, "inter3": (a,v) => a.inter3 = v, "inter4": (a,v) => a.inter4 = v,
"value0": (a,v) => a.value0 = v, "value1": (a,v) => a.value1 = v,
"value2": (a,v) => a.value2 = v, "value3": (a,v) => a.value3 = v, "value4": (a,v) => a.value4 = v,
"prop": (a,v) => a.prop = v
});
}
export function main() {
BrowserDomAdapter.makeCurrent();
var count = getIntParameter('elements');
setupReflector();
var reader = new DirectiveMetadataReader();
var cache = new CompilerCache();
var templateResolver = new FakeTemplateResolver();
var urlResolver = new UrlResolver();
var styleUrlResolver = new StyleUrlResolver(urlResolver);
var compiler = new Compiler(
dynamicChangeDetection,
new TemplateLoader(null, urlResolver),
reader,
new Parser(new Lexer()),
cache,
new NativeShadowDomStrategy(styleUrlResolver),
templateResolver,
new ComponentUrlMapper(),
urlResolver,
new CssProcessor(null)
);
var templateNoBindings = createTemplateHtml('templateNoBindings', count);
var templateWithBindings = createTemplateHtml('templateWithBindings', count);
function compileNoBindings() {
templateResolver.setTemplateHtml(templateNoBindings);
cache.clear();
compiler.compile(BenchmarkComponent);
}
function compileWithBindings() {
templateResolver.setTemplateHtml(templateWithBindings);
cache.clear();
compiler.compile(BenchmarkComponent);
}
bindAction('#compileNoBindings', compileNoBindings);
bindAction('#compileWithBindings', compileWithBindings);
}
function createTemplateHtml(templateId, repeatCount) {
var template = DOM.querySelectorAll(document, `#${templateId}`)[0];
var content = DOM.getInnerHTML(template);
var result = '';
for (var i=0; i<repeatCount; i++) {
result += content;
}
return result;
}
@Decorator({
selector: '[dir0]',
bind: {
'prop': 'attr0'
}
})
class Dir0 {}
@Decorator({
selector: '[dir1]',
bind: {
'prop': 'attr1'
}
})
class Dir1 {
constructor(dir0:Dir0) {}
}
@Decorator({
selector: '[dir2]',
bind: {
'prop': 'attr2'
}
})
class Dir2 {
constructor(dir1:Dir1) {}
}
@Decorator({
selector: '[dir3]',
bind: {
'prop': 'attr3'
}
})
class Dir3 {
constructor(dir2:Dir2) {}
}
@Decorator({
selector: '[dir4]',
bind: {
'prop': 'attr4'
}
})
class Dir4 {
constructor(dir3:Dir3) {}
}
@Component()
class BenchmarkComponent {}
class FakeTemplateResolver extends TemplateResolver {
_template: Template;
constructor() {
super();
}
setTemplateHtml(html: string) {
this._template = new Template({
inline: html,
directives: [Dir0, Dir1, Dir2, Dir3, Dir4]
});
}
resolve(component: Type): Template {
return this._template;
}
}
| modules/benchmarks/src/compiler/compiler_benchmark.js | 1 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.0002495542576070875,
0.00017932138871401548,
0.00016674972721375525,
0.0001723140594549477,
0.000022540405552717857
] |
{
"id": 4,
"code_window": [
" });\n",
" }));\n",
"\n",
" it('should consume directive watch expression change.', inject([AsyncTestCompleter], (async) => {\n",
" var tpl =\n",
" '<div>' +\n",
" '<div my-dir [elprop]=\"ctxProp\"></div>' +\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should ignore bindings to unknown properties', inject([AsyncTestCompleter], (async) => {\n",
" tplResolver.setTemplate(MyComp, new Template({inline: '<div unknown=\"{{ctxProp}}\"></div>'}));\n",
"\n",
" compiler.compile(MyComp).then((pv) => {\n",
" createView(pv);\n",
"\n",
" ctx.ctxProp = 'Some value';\n",
" cd.detectChanges();\n",
" expect(DOM.hasProperty(view.nodes[0], 'unknown')).toBeFalsy();\n",
"\n",
" async.done();\n",
" });\n",
" }));\n",
"\n"
],
"file_path": "modules/angular2/test/core/compiler/integration_spec.js",
"type": "add",
"edit_start_line_idx": 188
} | import {bootstrap, Component, Template} from 'angular2/angular2';
import {reflector} from 'angular2/src/reflection/reflection';
import {ReflectionCapabilities} from 'angular2/src/reflection/reflection_capabilities';
@Component({selector: 'gestures-app'})
@Template({url: 'template.html'})
class GesturesCmp {
swipeDirection: string;
pinchScale: number;
rotateAngle: number;
constructor() {
this.swipeDirection = '-';
this.pinchScale = 1;
this.rotateAngle = 0;
}
onSwipe(event) {
this.swipeDirection = event.deltaX > 0 ? 'right' : 'left';
}
onPinch(event) {
this.pinchScale = event.scale;
}
onRotate(event) {
this.rotateAngle = event.rotation;
}
}
export function main() {
reflector.reflectionCapabilities = new ReflectionCapabilities();
bootstrap(GesturesCmp);
}
| modules/examples/src/gestures/index.js | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.0001749744260450825,
0.0001721272710710764,
0.00016797501302789897,
0.00017277980805374682,
0.000002561328528827289
] |
{
"id": 4,
"code_window": [
" });\n",
" }));\n",
"\n",
" it('should consume directive watch expression change.', inject([AsyncTestCompleter], (async) => {\n",
" var tpl =\n",
" '<div>' +\n",
" '<div my-dir [elprop]=\"ctxProp\"></div>' +\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should ignore bindings to unknown properties', inject([AsyncTestCompleter], (async) => {\n",
" tplResolver.setTemplate(MyComp, new Template({inline: '<div unknown=\"{{ctxProp}}\"></div>'}));\n",
"\n",
" compiler.compile(MyComp).then((pv) => {\n",
" createView(pv);\n",
"\n",
" ctx.ctxProp = 'Some value';\n",
" cd.detectChanges();\n",
" expect(DOM.hasProperty(view.nodes[0], 'unknown')).toBeFalsy();\n",
"\n",
" async.done();\n",
" });\n",
" }));\n",
"\n"
],
"file_path": "modules/angular2/test/core/compiler/integration_spec.js",
"type": "add",
"edit_start_line_idx": 188
} | export var Bar1 = 'BAR1';
export var Bar2 = 'BAR2';
export function Bar3() {}
| tools/transpiler/spec/bar.js | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.0001712064549792558,
0.0001712064549792558,
0.0001712064549792558,
0.0001712064549792558,
0
] |
{
"id": 4,
"code_window": [
" });\n",
" }));\n",
"\n",
" it('should consume directive watch expression change.', inject([AsyncTestCompleter], (async) => {\n",
" var tpl =\n",
" '<div>' +\n",
" '<div my-dir [elprop]=\"ctxProp\"></div>' +\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should ignore bindings to unknown properties', inject([AsyncTestCompleter], (async) => {\n",
" tplResolver.setTemplate(MyComp, new Template({inline: '<div unknown=\"{{ctxProp}}\"></div>'}));\n",
"\n",
" compiler.compile(MyComp).then((pv) => {\n",
" createView(pv);\n",
"\n",
" ctx.ctxProp = 'Some value';\n",
" cd.detectChanges();\n",
" expect(DOM.hasProperty(view.nodes[0], 'unknown')).toBeFalsy();\n",
"\n",
" async.done();\n",
" });\n",
" }));\n",
"\n"
],
"file_path": "modules/angular2/test/core/compiler/integration_spec.js",
"type": "add",
"edit_start_line_idx": 188
} | library bar;
import 'package:angular2/src/core/annotations/annotations.dart';
import 'package:angular2/src/core/annotations/template.dart';
@Component(selector: '[soup]')
@Template(inline: 'Salad')
class MyComponent {
MyComponent();
}
| modules/angular2/test/transform/integration/two_annotations_files/bar.dart | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00017460626258980483,
0.0001719995343592018,
0.00016939282068051398,
0.0001719995343592018,
0.000002606720954645425
] |
{
"id": 5,
"code_window": [
" \"value0\": (a,v) => a.value0 = v, \"value1\": (a,v) => a.value1 = v,\n",
" \"value2\": (a,v) => a.value2 = v, \"value3\": (a,v) => a.value3 = v, \"value4\": (a,v) => a.value4 = v,\n",
"\n",
" \"prop\": (a,v) => a.prop = v\n",
" });\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"attr0\": (a,v) => a.attr0 = v, \"attr1\": (a,v) => a.attr1 = v,\n",
" \"attr2\": (a,v) => a.attr2 = v, \"attr3\": (a,v) => a.attr3 = v, \"attr4\": (a,v) => a.attr4 = v,\n",
"\n"
],
"file_path": "modules/benchmarks/src/compiler/compiler_benchmark.js",
"type": "add",
"edit_start_line_idx": 80
} | import {DOM} from 'angular2/src/dom/dom_adapter';
import {BrowserDomAdapter} from 'angular2/src/dom/browser_adapter';
import {isBlank, Type} from 'angular2/src/facade/lang';
import {document} from 'angular2/src/facade/browser';
import {MapWrapper} from 'angular2/src/facade/collection';
import {DirectiveMetadata} from 'angular2/src/core/compiler/directive_metadata';
import {NativeShadowDomStrategy} from 'angular2/src/core/compiler/shadow_dom_strategy';
import {Parser, Lexer, ProtoRecordRange, dynamicChangeDetection} from 'angular2/change_detection';
import {Compiler, CompilerCache} from 'angular2/src/core/compiler/compiler';
import {DirectiveMetadataReader} from 'angular2/src/core/compiler/directive_metadata_reader';
import {Component} from 'angular2/src/core/annotations/annotations';
import {Decorator} from 'angular2/src/core/annotations/annotations';
import {Template} from 'angular2/src/core/annotations/template';
import {TemplateLoader} from 'angular2/src/core/compiler/template_loader';
import {TemplateResolver} from 'angular2/src/core/compiler/template_resolver';
import {UrlResolver} from 'angular2/src/core/compiler/url_resolver';
import {StyleUrlResolver} from 'angular2/src/core/compiler/style_url_resolver';
import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper';
import {CssProcessor} from 'angular2/src/core/compiler/css_processor';
import {reflector} from 'angular2/src/reflection/reflection';
import {getIntParameter, bindAction} from 'angular2/src/test_lib/benchmark_util';
function setupReflector() {
reflector.registerType(BenchmarkComponent, {
"factory": () => new BenchmarkComponent(),
"parameters": [],
"annotations" : [new Component()]
});
reflector.registerType(Dir0, {
"factory": () => new Dir0(),
"parameters": [],
"annotations" : [new Decorator({selector: '[dir0]', bind: {'prop': 'attr0'}})]
});
reflector.registerType(Dir1, {
"factory": (dir0) => new Dir1(dir0),
"parameters": [[Dir0]],
"annotations" : [new Decorator({selector: '[dir1]', bind: {'prop': 'attr1'}})]
});
reflector.registerType(Dir2, {
"factory": (dir1) => new Dir2(dir1),
"parameters": [[Dir1]],
"annotations" : [new Decorator({selector: '[dir2]', bind: {'prop': 'attr2'}})]
});
reflector.registerType(Dir3, {
"factory": (dir2) => new Dir3(dir2),
"parameters": [[Dir2]],
"annotations" : [new Decorator({selector: '[dir3]', bind: {'prop': 'attr3'}})]
});
reflector.registerType(Dir4, {
"factory": (dir3) => new Dir4(dir3),
"parameters": [[Dir3]],
"annotations" : [new Decorator({selector: '[dir4]', bind: {'prop': 'attr4'}})]
});
reflector.registerGetters({
"inter0": (a) => a.inter0, "inter1": (a) => a.inter1,
"inter2": (a) => a.inter2, "inter3": (a) => a.inter3, "inter4": (a) => a.inter4,
"value0": (a) => a.value0, "value1": (a) => a.value1,
"value2": (a) => a.value2, "value3": (a) => a.value3, "value4": (a) => a.value4,
"prop" : (a) => a.prop
});
reflector.registerSetters({
"inter0": (a,v) => a.inter0 = v, "inter1": (a,v) => a.inter1 = v,
"inter2": (a,v) => a.inter2 = v, "inter3": (a,v) => a.inter3 = v, "inter4": (a,v) => a.inter4 = v,
"value0": (a,v) => a.value0 = v, "value1": (a,v) => a.value1 = v,
"value2": (a,v) => a.value2 = v, "value3": (a,v) => a.value3 = v, "value4": (a,v) => a.value4 = v,
"prop": (a,v) => a.prop = v
});
}
export function main() {
BrowserDomAdapter.makeCurrent();
var count = getIntParameter('elements');
setupReflector();
var reader = new DirectiveMetadataReader();
var cache = new CompilerCache();
var templateResolver = new FakeTemplateResolver();
var urlResolver = new UrlResolver();
var styleUrlResolver = new StyleUrlResolver(urlResolver);
var compiler = new Compiler(
dynamicChangeDetection,
new TemplateLoader(null, urlResolver),
reader,
new Parser(new Lexer()),
cache,
new NativeShadowDomStrategy(styleUrlResolver),
templateResolver,
new ComponentUrlMapper(),
urlResolver,
new CssProcessor(null)
);
var templateNoBindings = createTemplateHtml('templateNoBindings', count);
var templateWithBindings = createTemplateHtml('templateWithBindings', count);
function compileNoBindings() {
templateResolver.setTemplateHtml(templateNoBindings);
cache.clear();
compiler.compile(BenchmarkComponent);
}
function compileWithBindings() {
templateResolver.setTemplateHtml(templateWithBindings);
cache.clear();
compiler.compile(BenchmarkComponent);
}
bindAction('#compileNoBindings', compileNoBindings);
bindAction('#compileWithBindings', compileWithBindings);
}
function createTemplateHtml(templateId, repeatCount) {
var template = DOM.querySelectorAll(document, `#${templateId}`)[0];
var content = DOM.getInnerHTML(template);
var result = '';
for (var i=0; i<repeatCount; i++) {
result += content;
}
return result;
}
@Decorator({
selector: '[dir0]',
bind: {
'prop': 'attr0'
}
})
class Dir0 {}
@Decorator({
selector: '[dir1]',
bind: {
'prop': 'attr1'
}
})
class Dir1 {
constructor(dir0:Dir0) {}
}
@Decorator({
selector: '[dir2]',
bind: {
'prop': 'attr2'
}
})
class Dir2 {
constructor(dir1:Dir1) {}
}
@Decorator({
selector: '[dir3]',
bind: {
'prop': 'attr3'
}
})
class Dir3 {
constructor(dir2:Dir2) {}
}
@Decorator({
selector: '[dir4]',
bind: {
'prop': 'attr4'
}
})
class Dir4 {
constructor(dir3:Dir3) {}
}
@Component()
class BenchmarkComponent {}
class FakeTemplateResolver extends TemplateResolver {
_template: Template;
constructor() {
super();
}
setTemplateHtml(html: string) {
this._template = new Template({
inline: html,
directives: [Dir0, Dir1, Dir2, Dir3, Dir4]
});
}
resolve(component: Type): Template {
return this._template;
}
}
| modules/benchmarks/src/compiler/compiler_benchmark.js | 1 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.9980371594429016,
0.047728460282087326,
0.0001664274459471926,
0.00017727747035678476,
0.21249550580978394
] |
{
"id": 5,
"code_window": [
" \"value0\": (a,v) => a.value0 = v, \"value1\": (a,v) => a.value1 = v,\n",
" \"value2\": (a,v) => a.value2 = v, \"value3\": (a,v) => a.value3 = v, \"value4\": (a,v) => a.value4 = v,\n",
"\n",
" \"prop\": (a,v) => a.prop = v\n",
" });\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"attr0\": (a,v) => a.attr0 = v, \"attr1\": (a,v) => a.attr1 = v,\n",
" \"attr2\": (a,v) => a.attr2 = v, \"attr3\": (a,v) => a.attr3 = v, \"attr4\": (a,v) => a.attr4 = v,\n",
"\n"
],
"file_path": "modules/benchmarks/src/compiler/compiler_benchmark.js",
"type": "add",
"edit_start_line_idx": 80
} | <!doctype html>
<html>
<title>Hello Angular 2.0 (Reflection)</title>
<body>
<hello-app>
Loading...
</hello-app>
$SCRIPTS$
</body>
</html>
| modules/examples/src/hello_world/index.html | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00017816068429965526,
0.0001779539161361754,
0.00017774716252461076,
0.0001779539161361754,
2.0676088752225041e-7
] |
{
"id": 5,
"code_window": [
" \"value0\": (a,v) => a.value0 = v, \"value1\": (a,v) => a.value1 = v,\n",
" \"value2\": (a,v) => a.value2 = v, \"value3\": (a,v) => a.value3 = v, \"value4\": (a,v) => a.value4 = v,\n",
"\n",
" \"prop\": (a,v) => a.prop = v\n",
" });\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"attr0\": (a,v) => a.attr0 = v, \"attr1\": (a,v) => a.attr1 = v,\n",
" \"attr2\": (a,v) => a.attr2 = v, \"attr3\": (a,v) => a.attr3 = v, \"attr4\": (a,v) => a.attr4 = v,\n",
"\n"
],
"file_path": "modules/benchmarks/src/compiler/compiler_benchmark.js",
"type": "add",
"edit_start_line_idx": 80
} | library angular2.test.transform.common.logger;
import 'package:code_transformers/messages/build_logger.dart';
class NullLogger implements BuildLogger {
const NullLogger();
void info(String message, {AssetId asset, SourceSpan span}) {}
void fine(String message, {AssetId asset, SourceSpan span}) {}
void warning(String message, {AssetId asset, SourceSpan span}) {}
void error(String message, {AssetId asset, SourceSpan span}) {
throw new NullLoggerError(message, asset, span);
}
Future writeOutput() => null;
Future addLogFilesFromAsset(AssetId id, [int nextNumber = 1]) => null;
}
class NullLoggerError extends Error {
final String message;
final AssetId asset;
final SourceSpan span;
NullLoggerError(message, asset, span);
}
| modules/angular2/test/transform/common/logger.dart | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.0006811980274505913,
0.0003407988988328725,
0.0001679296838119626,
0.00017326899978797883,
0.00024070839572232217
] |
{
"id": 5,
"code_window": [
" \"value0\": (a,v) => a.value0 = v, \"value1\": (a,v) => a.value1 = v,\n",
" \"value2\": (a,v) => a.value2 = v, \"value3\": (a,v) => a.value3 = v, \"value4\": (a,v) => a.value4 = v,\n",
"\n",
" \"prop\": (a,v) => a.prop = v\n",
" });\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"attr0\": (a,v) => a.attr0 = v, \"attr1\": (a,v) => a.attr1 = v,\n",
" \"attr2\": (a,v) => a.attr2 = v, \"attr3\": (a,v) => a.attr3 = v, \"attr4\": (a,v) => a.attr4 = v,\n",
"\n"
],
"file_path": "modules/benchmarks/src/compiler/compiler_benchmark.js",
"type": "add",
"edit_start_line_idx": 80
} | export var CLASS_FIELD_DECLARATION = 'CLASS_FIELD_DECLARATION';
export var PROPERTY_CONSTRUCTOR_ASSIGNMENT = 'PROPERTY_CONSTRUCTOR_ASSIGNMENT';
export var NAMED_PARAMETER_LIST = 'NAMED_PARAMETER_LIST';
export var OBJECT_PATTERN_BINDING_ELEMENT = 'OBJECT_PATTERN_BINDING_ELEMENT';
export var IMPLEMENTS_DECLARATION = "IMPLEMENTS_DECLARATION";
| tools/transpiler/src/syntax/trees/ParseTreeType.js | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00023040585801936686,
0.00023040585801936686,
0.00023040585801936686,
0.00023040585801936686,
0
] |
{
"id": 6,
"code_window": [
" 'aatStatusWidth': (o, v) => o.aatStatusWidth = v,\n",
" 'bundles': (o, v) => o.bundles = v,\n",
" 'bundlesWidth': (o, v) => o.bundlesWidth = v,\n",
" evt: (o, v) => null,\n",
" 'style': (o, m) => {\n",
" //if (isBlank(m)) return;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'if': (o, v) => {},\n",
" 'of': (o, v) => {},\n",
" 'cellWidth': (o, v) => o.cellWidth = v,\n"
],
"file_path": "modules/benchmarks/src/naive_infinite_scroll/index.js",
"type": "add",
"edit_start_line_idx": 141
} | import {int, isPresent, isBlank, Type, BaseException, StringWrapper, RegExpWrapper, isString, stringify} from 'angular2/src/facade/lang';
import {DOM} from 'angular2/src/dom/dom_adapter';
import {ListWrapper, List, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {reflector} from 'angular2/src/reflection/reflection';
import {Parser, ProtoChangeDetector} from 'angular2/change_detection';
import {DirectiveMetadata} from '../directive_metadata';
import {CompileStep} from './compile_step';
import {CompileElement} from './compile_element';
import {CompileControl} from './compile_control';
import {dashCaseToCamelCase, camelCaseToDashCase} from './util';
var DOT_REGEXP = RegExpWrapper.create('\\.');
const ATTRIBUTE_PREFIX = 'attr.';
var attributeSettersCache = StringMapWrapper.create();
function _isValidAttributeValue(attrName:string, value: any) {
if (attrName == "role") {
return isString(value);
} else {
return isPresent(value);
}
}
function attributeSetterFactory(attrName:string) {
var setterFn = StringMapWrapper.get(attributeSettersCache, attrName);
var dashCasedAttributeName;
if (isBlank(setterFn)) {
dashCasedAttributeName = camelCaseToDashCase(attrName);
setterFn = function(element, value) {
if (_isValidAttributeValue(dashCasedAttributeName, value)) {
DOM.setAttribute(element, dashCasedAttributeName, stringify(value));
} else {
DOM.removeAttribute(element, dashCasedAttributeName);
if (isPresent(value)) {
throw new BaseException("Invalid " + dashCasedAttributeName + " attribute, only string values are allowed, got '" + stringify(value) + "'");
}
}
};
StringMapWrapper.set(attributeSettersCache, attrName, setterFn);
}
return setterFn;
}
const CLASS_PREFIX = 'class.';
var classSettersCache = StringMapWrapper.create();
function classSetterFactory(className:string) {
var setterFn = StringMapWrapper.get(classSettersCache, className);
if (isBlank(setterFn)) {
setterFn = function(element, value) {
if (value) {
DOM.addClass(element, className);
} else {
DOM.removeClass(element, className);
}
};
StringMapWrapper.set(classSettersCache, className, setterFn);
}
return setterFn;
}
const STYLE_PREFIX = 'style.';
var styleSettersCache = StringMapWrapper.create();
function styleSetterFactory(styleName:string, stylesuffix:string) {
var cacheKey = styleName + stylesuffix;
var setterFn = StringMapWrapper.get(styleSettersCache, cacheKey);
var dashCasedStyleName;
if (isBlank(setterFn)) {
dashCasedStyleName = camelCaseToDashCase(styleName);
setterFn = function(element, value) {
var valAsStr;
if (isPresent(value)) {
valAsStr = stringify(value);
DOM.setStyle(element, dashCasedStyleName, valAsStr + stylesuffix);
} else {
DOM.removeStyle(element, dashCasedStyleName);
}
};
StringMapWrapper.set(classSettersCache, cacheKey, setterFn);
}
return setterFn;
}
const ROLE_ATTR = 'role';
function roleSetter(element, value) {
if (isString(value)) {
DOM.setAttribute(element, ROLE_ATTR, value);
} else {
DOM.removeAttribute(element, ROLE_ATTR);
if (isPresent(value)) {
throw new BaseException("Invalid role attribute, only string values are allowed, got '" + stringify(value) + "'");
}
}
}
/**
* Creates the ElementBinders and adds watches to the
* ProtoChangeDetector.
*
* Fills:
* - CompileElement#inheritedElementBinder
*
* Reads:
* - (in parent) CompileElement#inheritedElementBinder
* - CompileElement#hasBindings
* - CompileElement#inheritedProtoView
* - CompileElement#inheritedProtoElementInjector
* - CompileElement#textNodeBindings
* - CompileElement#propertyBindings
* - CompileElement#eventBindings
* - CompileElement#decoratorDirectives
* - CompileElement#componentDirective
* - CompileElement#viewportDirective
*
* Note: This actually only needs the CompileElements with the flags
* `hasBindings` and `isViewRoot`,
* and only needs the actual HTMLElement for the ones
* with the flag `isViewRoot`.
*/
export class ElementBinderBuilder extends CompileStep {
_parser:Parser;
constructor(parser:Parser) {
super();
this._parser = parser;
}
process(parent:CompileElement, current:CompileElement, control:CompileControl) {
var elementBinder = null;
var parentElementBinder = null;
var distanceToParentBinder = this._getDistanceToParentBinder(parent, current);
if (isPresent(parent)) {
parentElementBinder = parent.inheritedElementBinder;
}
if (current.hasBindings) {
var protoView = current.inheritedProtoView;
var protoInjectorWasBuilt = isBlank(parent) ? true :
current.inheritedProtoElementInjector !== parent.inheritedProtoElementInjector;
var currentProtoElementInjector = protoInjectorWasBuilt ?
current.inheritedProtoElementInjector : null;
elementBinder = protoView.bindElement(parentElementBinder, distanceToParentBinder,
currentProtoElementInjector, current.componentDirective, current.viewportDirective);
current.distanceToParentBinder = 0;
if (isPresent(current.textNodeBindings)) {
this._bindTextNodes(protoView, current);
}
if (isPresent(current.propertyBindings)) {
this._bindElementProperties(protoView, current);
}
if (isPresent(current.eventBindings)) {
this._bindEvents(protoView, current);
}
if (isPresent(current.contentTagSelector)) {
elementBinder.contentTagSelector = current.contentTagSelector;
}
var directives = current.getAllDirectives();
this._bindDirectiveProperties(directives, current);
this._bindDirectiveEvents(directives, current);
} else if (isPresent(parent)) {
elementBinder = parentElementBinder;
current.distanceToParentBinder = distanceToParentBinder;
}
current.inheritedElementBinder = elementBinder;
}
_getDistanceToParentBinder(parent, current) {
return isPresent(parent) ? parent.distanceToParentBinder + 1 : 0;
}
_bindTextNodes(protoView, compileElement) {
MapWrapper.forEach(compileElement.textNodeBindings, (expression, indexInParent) => {
protoView.bindTextNode(indexInParent, expression);
});
}
_bindElementProperties(protoView, compileElement) {
MapWrapper.forEach(compileElement.propertyBindings, (expression, property) => {
var setterFn, styleParts, styleSuffix;
if (StringWrapper.startsWith(property, ATTRIBUTE_PREFIX)) {
setterFn = attributeSetterFactory(StringWrapper.substring(property, ATTRIBUTE_PREFIX.length));
} else if (StringWrapper.startsWith(property, CLASS_PREFIX)) {
setterFn = classSetterFactory(StringWrapper.substring(property, CLASS_PREFIX.length));
} else if (StringWrapper.startsWith(property, STYLE_PREFIX)) {
styleParts = StringWrapper.split(property, DOT_REGEXP);
styleSuffix = styleParts.length > 2 ? ListWrapper.get(styleParts, 2) : '';
setterFn = styleSetterFactory(ListWrapper.get(styleParts, 1), styleSuffix);
} else {
property = this._resolvePropertyName(property);
//TODO(pk): special casing innerHtml, see: https://github.com/angular/angular/issues/789
if (StringWrapper.equals(property, 'innerHTML')) {
setterFn = (element, value) => DOM.setInnerHTML(element, value);
} else if (DOM.hasProperty(compileElement.element, property) || StringWrapper.equals(property, 'innerHtml')) {
setterFn = reflector.setter(property);
}
}
if (isPresent(setterFn)) {
protoView.bindElementProperty(expression.ast, property, setterFn);
}
});
}
_bindEvents(protoView, compileElement) {
MapWrapper.forEach(compileElement.eventBindings, (expression, eventName) => {
protoView.bindEvent(eventName, expression);
});
}
_bindDirectiveEvents(directives: List<DirectiveMetadata>, compileElement: CompileElement) {
for (var directiveIndex = 0; directiveIndex < directives.length; directiveIndex++) {
var directive = directives[directiveIndex];
var annotation = directive.annotation;
if (isBlank(annotation.events)) continue;
var protoView = compileElement.inheritedProtoView;
StringMapWrapper.forEach(annotation.events, (action, eventName) => {
var expression = this._parser.parseAction(action, compileElement.elementDescription);
protoView.bindEvent(eventName, expression, directiveIndex);
});
}
}
_bindDirectiveProperties(directives: List<DirectiveMetadata>,
compileElement: CompileElement) {
var protoView = compileElement.inheritedProtoView;
for (var directiveIndex = 0; directiveIndex < directives.length; directiveIndex++) {
var directive = ListWrapper.get(directives, directiveIndex);
var annotation = directive.annotation;
if (isBlank(annotation.bind)) continue;
StringMapWrapper.forEach(annotation.bind, (bindConfig, dirProp) => {
var pipes = this._splitBindConfig(bindConfig);
var elProp = ListWrapper.removeAt(pipes, 0);
var bindingAst = isPresent(compileElement.propertyBindings) ?
MapWrapper.get(compileElement.propertyBindings, dashCaseToCamelCase(elProp)) :
null;
if (isBlank(bindingAst)) {
var attributeValue = MapWrapper.get(compileElement.attrs(), elProp);
if (isPresent(attributeValue)) {
bindingAst = this._parser.wrapLiteralPrimitive(attributeValue, compileElement.elementDescription);
}
}
// Bindings are optional, so this binding only needs to be set up if an expression is given.
if (isPresent(bindingAst)) {
var fullExpAstWithBindPipes = this._parser.addPipes(bindingAst, pipes);
protoView.bindDirectiveProperty(
directiveIndex,
fullExpAstWithBindPipes,
dirProp,
reflector.setter(dashCaseToCamelCase(dirProp))
);
}
});
}
}
_splitBindConfig(bindConfig:string) {
return ListWrapper.map(bindConfig.split('|'), (s) => s.trim());
}
_resolvePropertyName(attrName:string) {
var mappedPropName = StringMapWrapper.get(DOM.attrToPropMap, attrName);
return isPresent(mappedPropName) ? mappedPropName : attrName;
}
}
| modules/angular2/src/core/compiler/pipeline/element_binder_builder.js | 1 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00023253711697179824,
0.00017260626191273332,
0.00015920917212497443,
0.00017157169349957258,
0.000012054435501340777
] |
{
"id": 6,
"code_window": [
" 'aatStatusWidth': (o, v) => o.aatStatusWidth = v,\n",
" 'bundles': (o, v) => o.bundles = v,\n",
" 'bundlesWidth': (o, v) => o.bundlesWidth = v,\n",
" evt: (o, v) => null,\n",
" 'style': (o, m) => {\n",
" //if (isBlank(m)) return;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'if': (o, v) => {},\n",
" 'of': (o, v) => {},\n",
" 'cellWidth': (o, v) => o.cellWidth = v,\n"
],
"file_path": "modules/benchmarks/src/naive_infinite_scroll/index.js",
"type": "add",
"edit_start_line_idx": 141
} | library scroll_app;
import 'dart:async';
import 'dart:html';
import 'package:angular/angular.dart';
import 'package:angular2/src/test_lib/benchmark_util.dart';
@Component(
selector: 'scroll-app',
template: '''
<div>
<div style="display: flex">
<scroll-area scroll-top="scrollTop"></scroll-area>
</div>
<div ng-if="scrollAreas.length > 0">
<p>Following tables are only here to add weight to the UI:</p>
<scroll-area ng-repeat="scrollArea in scrollAreas"></scroll-area>
</div>
</div>
''')
class App implements ShadowRootAware {
final VmTurnZone ngZone;
List<int> scrollAreas;
int scrollTop = 0;
int iterationCount;
int scrollIncrement;
App(this.ngZone) {
int appSize = getIntParameter('appSize');
iterationCount = getIntParameter('iterationCount');
scrollIncrement = getIntParameter('scrollIncrement');
appSize = appSize > 1 ? appSize - 1 : 0; // draw at least one table
scrollAreas = new List.generate(appSize, (i) => i);
}
@override
void onShadowRoot(ShadowRoot shadowRoot) {
bindAction('#run-btn', () {
runBenchmark();
});
bindAction('#reset-btn', () {
scrollTop = 0;
});
}
void runBenchmark() {
int n = iterationCount;
scheduleScroll() {
new Future(() {
scrollTop += scrollIncrement;
n--;
if (n > 0) {
scheduleScroll();
}
});
}
scheduleScroll();
}
}
| modules/benchmarks_external/src/naive_infinite_scroll/app.dart | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.0004274072707630694,
0.00021803613344673067,
0.00017095198563765734,
0.0001774527772795409,
0.00009366396989207715
] |
{
"id": 6,
"code_window": [
" 'aatStatusWidth': (o, v) => o.aatStatusWidth = v,\n",
" 'bundles': (o, v) => o.bundles = v,\n",
" 'bundlesWidth': (o, v) => o.bundlesWidth = v,\n",
" evt: (o, v) => null,\n",
" 'style': (o, m) => {\n",
" //if (isBlank(m)) return;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'if': (o, v) => {},\n",
" 'of': (o, v) => {},\n",
" 'cellWidth': (o, v) => o.cellWidth = v,\n"
],
"file_path": "modules/benchmarks/src/naive_infinite_scroll/index.js",
"type": "add",
"edit_start_line_idx": 141
} | library angular2.transform.reflection_remover.ast_tester;
import 'package:analyzer/src/generated/ast.dart';
import 'package:analyzer/src/generated/element.dart';
/// An object that checks for [ReflectionCapabilities] syntactically, that is,
/// without resolution information.
class AstTester {
static const REFLECTION_CAPABILITIES_NAME = 'ReflectionCapabilities';
const AstTester();
bool isNewReflectionCapabilities(InstanceCreationExpression node) =>
'${node.constructorName.type.name}' == REFLECTION_CAPABILITIES_NAME;
bool isReflectionCapabilitiesImport(ImportDirective node) {
return node.uri.stringValue.endsWith("reflection_capabilities.dart");
}
}
/// An object that checks for [ReflectionCapabilities] using a fully resolved
/// Ast.
class ResolvedTester implements AstTester {
final ClassElement _forbiddenClass;
ResolvedTester(this._forbiddenClass);
bool isNewReflectionCapabilities(InstanceCreationExpression node) {
var typeElement = node.constructorName.type.name.bestElement;
return typeElement != null && typeElement == _forbiddenClass;
}
bool isReflectionCapabilitiesImport(ImportDirective node) {
return node.uriElement == _forbiddenClass.library;
}
}
| modules/angular2/src/transform/reflection_remover/ast_tester.dart | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.0001710912329144776,
0.00016763315943535417,
0.00016447564121335745,
0.00016748289635870606,
0.000002629117034302908
] |
{
"id": 6,
"code_window": [
" 'aatStatusWidth': (o, v) => o.aatStatusWidth = v,\n",
" 'bundles': (o, v) => o.bundles = v,\n",
" 'bundlesWidth': (o, v) => o.bundlesWidth = v,\n",
" evt: (o, v) => null,\n",
" 'style': (o, m) => {\n",
" //if (isBlank(m)) return;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'if': (o, v) => {},\n",
" 'of': (o, v) => {},\n",
" 'cellWidth': (o, v) => o.cellWidth = v,\n"
],
"file_path": "modules/benchmarks/src/naive_infinite_scroll/index.js",
"type": "add",
"edit_start_line_idx": 141
} | library angular2.transform.reflection_remover.transformer;
import 'dart:async';
import 'package:angular2/src/transform/common/logging.dart' as log;
import 'package:angular2/src/transform/common/names.dart';
import 'package:angular2/src/transform/common/options.dart';
import 'package:barback/barback.dart';
import 'remove_reflection_capabilities.dart';
/// Transformer responsible for removing the import and instantiation of
/// [ReflectionCapabilities].
///
/// The goal of this is to break the app's dependency on dart:mirrors.
///
/// This transformer assumes that [DirectiveProcessor] and [DirectiveLinker]
/// have already been run and that a .ng_deps.dart file has been generated for
/// [options.entryPoint]. The instantiation of [ReflectionCapabilities] is
/// replaced by calling `setupReflection` in that .ng_deps.dart file.
class ReflectionRemover extends Transformer {
final TransformerOptions options;
ReflectionRemover(this.options);
@override
bool isPrimary(AssetId id) => options.reflectionEntryPoint == id.path;
@override
Future apply(Transform transform) async {
log.init(transform);
try {
var newEntryPoint = new AssetId(
transform.primaryInput.id.package, options.entryPoint)
.changeExtension(DEPS_EXTENSION);
var assetCode = await transform.primaryInput.readAsString();
transform.addOutput(new Asset.fromString(transform.primaryInput.id,
removeReflectionCapabilities(
assetCode, transform.primaryInput.id.path, newEntryPoint.path)));
} catch (ex, stackTrace) {
log.logger.error('Removing reflection failed.\n'
'Exception: $ex\n'
'Stack Trace: $stackTrace');
}
}
}
| modules/angular2/src/transform/reflection_remover/transformer.dart | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.0001781336759449914,
0.00017482522525824606,
0.00016981003864202648,
0.00017695828864816576,
0.0000033148137390526244
] |
{
"id": 7,
"code_window": [
" 'right': (a,v) => a.right = v,\n",
" 'initData': (a,v) => a.initData = v,\n",
" 'data': (a,v) => a.data = v,\n",
" 'condition': (a,v) => a.condition = v,\n",
" });\n",
"}\n",
"\n",
"var BASELINE_TREE_TEMPLATE;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'if': (a,v) => a['if'] = v,\n"
],
"file_path": "modules/benchmarks/src/tree/tree_benchmark.js",
"type": "add",
"edit_start_line_idx": 208
} | import {
AsyncTestCompleter,
beforeEach,
ddescribe,
xdescribe,
describe,
el,
expect,
iit,
inject,
it,
xit,
} from 'angular2/test_lib';
import {DOM} from 'angular2/src/dom/dom_adapter';
import {Type, isPresent, BaseException, assertionsEnabled, isJsObject} from 'angular2/src/facade/lang';
import {PromiseWrapper} from 'angular2/src/facade/async';
import {Injector, bind} from 'angular2/di';
import {Lexer, Parser, dynamicChangeDetection,
DynamicChangeDetection, Pipe, PipeRegistry} from 'angular2/change_detection';
import {Compiler, CompilerCache} from 'angular2/src/core/compiler/compiler';
import {DirectiveMetadataReader} from 'angular2/src/core/compiler/directive_metadata_reader';
import {ShadowDomStrategy, EmulatedUnscopedShadowDomStrategy} from 'angular2/src/core/compiler/shadow_dom_strategy';
import {PrivateComponentLocation} from 'angular2/src/core/compiler/private_component_location';
import {PrivateComponentLoader} from 'angular2/src/core/compiler/private_component_loader';
import {TemplateLoader} from 'angular2/src/core/compiler/template_loader';
import {MockTemplateResolver} from 'angular2/src/mock/template_resolver_mock';
import {BindingPropagationConfig} from 'angular2/src/core/compiler/binding_propagation_config';
import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper';
import {UrlResolver} from 'angular2/src/core/compiler/url_resolver';
import {StyleUrlResolver} from 'angular2/src/core/compiler/style_url_resolver';
import {CssProcessor} from 'angular2/src/core/compiler/css_processor';
import {EventManager} from 'angular2/src/core/events/event_manager';
import {Decorator, Component, Viewport, DynamicComponent} from 'angular2/src/core/annotations/annotations';
import {Template} from 'angular2/src/core/annotations/template';
import {Parent, Ancestor} from 'angular2/src/core/annotations/visibility';
import {EventEmitter} from 'angular2/src/core/annotations/di';
import {If} from 'angular2/src/directives/if';
import {ViewContainer} from 'angular2/src/core/compiler/view_container';
export function main() {
describe('integration tests', function() {
var directiveMetadataReader, shadowDomStrategy, compiler, tplResolver;
function createCompiler(tplResolver, changedDetection) {
var urlResolver = new UrlResolver();
return new Compiler(changedDetection,
new TemplateLoader(null, null),
directiveMetadataReader,
new Parser(new Lexer()),
new CompilerCache(),
shadowDomStrategy,
tplResolver,
new ComponentUrlMapper(),
urlResolver,
new CssProcessor(null)
);
}
beforeEach( () => {
tplResolver = new MockTemplateResolver();
directiveMetadataReader = new DirectiveMetadataReader();
var urlResolver = new UrlResolver();
shadowDomStrategy = new EmulatedUnscopedShadowDomStrategy(new StyleUrlResolver(urlResolver), null);
compiler = createCompiler(tplResolver, dynamicChangeDetection);
});
describe('react to record changes', function() {
var view, ctx, cd;
function createView(pv) {
ctx = new MyComp();
view = pv.instantiate(null, null);
view.hydrate(new Injector([
bind(Compiler).toValue(compiler),
bind(DirectiveMetadataReader).toValue(directiveMetadataReader),
bind(ShadowDomStrategy).toValue(shadowDomStrategy),
bind(EventManager).toValue(null),
PrivateComponentLoader
]), null, null, ctx, null);
cd = view.changeDetector;
}
it('should consume text node changes', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({inline: '<div>{{ctxProp}}</div>'}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
ctx.ctxProp = 'Hello World!';
cd.detectChanges();
expect(DOM.getInnerHTML(view.nodes[0])).toEqual('Hello World!');
async.done();
});
}));
it('should consume element binding changes', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({inline: '<div [id]="ctxProp"></div>'}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
ctx.ctxProp = 'Hello World!';
cd.detectChanges();
expect(view.nodes[0].id).toEqual('Hello World!');
async.done();
});
}));
it('should consume binding to aria-* attributes', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({inline: '<div [attr.aria-label]="ctxProp"></div>'}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
ctx.ctxProp = 'Initial aria label';
cd.detectChanges();
expect(DOM.getAttribute(view.nodes[0], 'aria-label')).toEqual('Initial aria label');
ctx.ctxProp = 'Changed aria label';
cd.detectChanges();
expect(DOM.getAttribute(view.nodes[0], 'aria-label')).toEqual('Changed aria label');
async.done();
});
}));
it('should consume binding to property names where attr name and property name do not match', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({inline: '<div [tabindex]="ctxNumProp"></div>'}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
cd.detectChanges();
expect(view.nodes[0].tabIndex).toEqual(0);
ctx.ctxNumProp = 5;
cd.detectChanges();
expect(view.nodes[0].tabIndex).toEqual(5);
async.done();
});
}));
it('should consume binding to camel-cased properties using dash-cased syntax in templates', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({inline: '<input [read-only]="ctxBoolProp">'}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
cd.detectChanges();
expect(view.nodes[0].readOnly).toBeFalsy();
ctx.ctxBoolProp = true;
cd.detectChanges();
expect(view.nodes[0].readOnly).toBeTruthy();
async.done();
});
}));
it('should consume binding to inner-html', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({inline: '<div inner-html="{{ctxProp}}"></div>'}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
ctx.ctxProp = 'Some <span>HTML</span>';
cd.detectChanges();
expect(DOM.getInnerHTML(view.nodes[0])).toEqual('Some <span>HTML</span>');
ctx.ctxProp = 'Some other <div>HTML</div>';
cd.detectChanges();
expect(DOM.getInnerHTML(view.nodes[0])).toEqual('Some other <div>HTML</div>');
async.done();
});
}));
it('should consume directive watch expression change.', inject([AsyncTestCompleter], (async) => {
var tpl =
'<div>' +
'<div my-dir [elprop]="ctxProp"></div>' +
'<div my-dir elprop="Hi there!"></div>' +
'<div my-dir elprop="Hi {{\'there!\'}}"></div>' +
'<div my-dir elprop="One more {{ctxProp}}"></div>' +
'</div>'
tplResolver.setTemplate(MyComp, new Template({inline: tpl, directives: [MyDir]}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
ctx.ctxProp = 'Hello World!';
cd.detectChanges();
expect(view.elementInjectors[0].get(MyDir).dirProp).toEqual('Hello World!');
expect(view.elementInjectors[1].get(MyDir).dirProp).toEqual('Hi there!');
expect(view.elementInjectors[2].get(MyDir).dirProp).toEqual('Hi there!');
expect(view.elementInjectors[3].get(MyDir).dirProp).toEqual('One more Hello World!');
async.done();
});
}));
it("should support pipes in bindings and bind config", inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp,
new Template({
inline: '<component-with-pipes #comp [prop]="ctxProp | double"></component-with-pipes>',
directives: [ComponentWithPipes]
}));
var registry = new PipeRegistry({
"double" : [new DoublePipeFactory()]
});
var changeDetection = new DynamicChangeDetection(registry);
var compiler = createCompiler(tplResolver, changeDetection);
compiler.compile(MyComp).then((pv) => {
createView(pv);
ctx.ctxProp = 'a';
cd.detectChanges();
var comp = view.locals.get("comp");
// it is doubled twice: once in the binding, second time in the bind config
expect(comp.prop).toEqual('aaaa');
async.done();
});
}));
it('should support nested components.', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({
inline: '<child-cmp></child-cmp>',
directives: [ChildComp]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
cd.detectChanges();
expect(view.nodes).toHaveText('hello');
async.done();
});
}));
// GH issue 328 - https://github.com/angular/angular/issues/328
it('should support different directive types on a single node', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp,
new Template({
inline: '<child-cmp my-dir [elprop]="ctxProp"></child-cmp>',
directives: [MyDir, ChildComp]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
ctx.ctxProp = 'Hello World!';
cd.detectChanges();
var elInj = view.elementInjectors[0];
expect(elInj.get(MyDir).dirProp).toEqual('Hello World!');
expect(elInj.get(ChildComp).dirProp).toEqual(null);
async.done();
});
}));
it('should support directives where a binding attribute is not given', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp,
new Template({
// No attribute "el-prop" specified.
inline: '<p my-dir></p>',
directives: [MyDir]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
async.done();
});
}));
it('should support directives where a selector matches property binding', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp,
new Template({
inline: '<p [id]="ctxProp"></p>',
directives: [IdComponent]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
ctx.ctxProp = 'some_id';
cd.detectChanges();
expect(view.nodes[0].id).toEqual('some_id');
expect(view.nodes).toHaveText('Matched on id with some_id');
ctx.ctxProp = 'other_id';
cd.detectChanges();
expect(view.nodes[0].id).toEqual('other_id');
expect(view.nodes).toHaveText('Matched on id with other_id');
async.done();
});
}));
it('should support template directives via `<template>` elements.', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp,
new Template({
inline: '<div><template some-viewport var-greeting="some-tmpl"><copy-me>{{greeting}}</copy-me></template></div>',
directives: [SomeViewport]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
cd.detectChanges();
var childNodesOfWrapper = view.nodes[0].childNodes;
// 1 template + 2 copies.
expect(childNodesOfWrapper.length).toBe(3);
expect(childNodesOfWrapper[1].childNodes[0].nodeValue).toEqual('hello');
expect(childNodesOfWrapper[2].childNodes[0].nodeValue).toEqual('again');
async.done();
});
}));
it('should support template directives via `template` attribute.', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({
inline: '<div><copy-me template="some-viewport: var greeting=some-tmpl">{{greeting}}</copy-me></div>',
directives: [SomeViewport]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
cd.detectChanges();
var childNodesOfWrapper = view.nodes[0].childNodes;
// 1 template + 2 copies.
expect(childNodesOfWrapper.length).toBe(3);
expect(childNodesOfWrapper[1].childNodes[0].nodeValue).toEqual('hello');
expect(childNodesOfWrapper[2].childNodes[0].nodeValue).toEqual('again');
async.done();
});
}));
it('should assign the component instance to a var-', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({
inline: '<p><child-cmp var-alice></child-cmp></p>',
directives: [ChildComp]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
expect(view.locals).not.toBe(null);
expect(view.locals.get('alice')).toBeAnInstanceOf(ChildComp);
async.done();
})
}));
it('should assign two component instances each with a var-', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({
inline: '<p><child-cmp var-alice></child-cmp><child-cmp var-bob></p>',
directives: [ChildComp]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
expect(view.locals).not.toBe(null);
expect(view.locals.get('alice')).toBeAnInstanceOf(ChildComp);
expect(view.locals.get('bob')).toBeAnInstanceOf(ChildComp);
expect(view.locals.get('alice')).not.toBe(view.locals.get('bob'));
async.done();
})
}));
it('should assign the component instance to a var- with shorthand syntax', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({
inline: '<child-cmp #alice></child-cmp>',
directives: [ChildComp]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
expect(view.locals).not.toBe(null);
expect(view.locals.get('alice')).toBeAnInstanceOf(ChildComp);
async.done();
})
}));
it('should assign the element instance to a user-defined variable', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp,
new Template({inline: '<p><div var-alice><i>Hello</i></div></p>'}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
expect(view.locals).not.toBe(null);
var value = view.locals.get('alice');
expect(value).not.toBe(null);
expect(value.tagName.toLowerCase()).toEqual('div');
async.done();
})
}));
it('should assign the element instance to a user-defined variable with camelCase using dash-case', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp,
new Template({inline: '<p><div var-super-alice><i>Hello</i></div></p>'}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
expect(view.locals).not.toBe(null);
var value = view.locals.get('superAlice');
expect(value).not.toBe(null);
expect(value.tagName.toLowerCase()).toEqual('div');
async.done();
})
}));
it('should provide binding configuration config to the component', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({
inline: '<push-cmp #cmp></push-cmp>',
directives: [[[PushBasedComp]]]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
var cmp = view.locals.get('cmp');
cd.detectChanges();
expect(cmp.numberOfChecks).toEqual(1);
cd.detectChanges();
expect(cmp.numberOfChecks).toEqual(1);
cmp.propagate();
cd.detectChanges();
expect(cmp.numberOfChecks).toEqual(2);
async.done();
})
}));
it('should create a component that injects a @Parent', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({
inline: '<some-directive><cmp-with-parent #child></cmp-with-parent></some-directive>',
directives: [SomeDirective, CompWithParent]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
var childComponent = view.locals.get('child');
expect(childComponent.myParent).toBeAnInstanceOf(SomeDirective);
async.done();
})
}));
it('should create a component that injects an @Ancestor', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({
inline: `
<some-directive>
<p>
<cmp-with-ancestor #child></cmp-with-ancestor>
</p>
</some-directive>`,
directives: [SomeDirective, CompWithAncestor]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
var childComponent = view.locals.get('child');
expect(childComponent.myAncestor).toBeAnInstanceOf(SomeDirective);
async.done();
})
}));
it('should create a component that injects an @Ancestor through viewport directive', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({
inline: `
<some-directive>
<p *if="true">
<cmp-with-ancestor #child></cmp-with-ancestor>
</p>
</some-directive>`,
directives: [SomeDirective, CompWithAncestor, If]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
cd.detectChanges();
var subview = view.viewContainers[1].get(0);
var childComponent = subview.locals.get('child');
expect(childComponent.myAncestor).toBeAnInstanceOf(SomeDirective);
async.done();
});
}));
it('should support events', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({
inline: '<div emitter listener></div>',
directives: [DecoratorEmitingEvent, DecoratorListeningEvent]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
var injector = view.elementInjectors[0];
var emitter = injector.get(DecoratorEmitingEvent);
var listener = injector.get(DecoratorListeningEvent);
expect(emitter.msg).toEqual('');
expect(listener.msg).toEqual('');
emitter.fireEvent('fired !');
expect(emitter.msg).toEqual('fired !');
expect(listener.msg).toEqual('fired !');
async.done();
});
}));
it('should support dynamic components', inject([AsyncTestCompleter], (async) => {
tplResolver.setTemplate(MyComp, new Template({
inline: '<dynamic-comp #dynamic></dynamic-comp>',
directives: [DynamicComp]
}));
compiler.compile(MyComp).then((pv) => {
createView(pv);
var dynamicComponent = view.locals.get("dynamic");
expect(dynamicComponent).toBeAnInstanceOf(DynamicComp);
dynamicComponent.done.then((_) => {
cd.detectChanges();
expect(view.nodes).toHaveText('hello');
async.done();
});
});
}));
});
xdescribe('Missing directive checks', () => {
if (assertionsEnabled()) {
function expectCompileError(inlineTpl, errMessage, done) {
tplResolver.setTemplate(MyComp, new Template({inline: inlineTpl}));
PromiseWrapper.then(compiler.compile(MyComp),
(value) => {
throw new BaseException("Test failure: should not have come here as an exception was expected");
},
(err) => {
expect(err.message).toEqual(errMessage);
done();
}
);
}
it('should raise an error if no directive is registered for a template with template bindings', inject([AsyncTestCompleter], (async) => {
expectCompileError(
'<div><div template="if: foo"></div></div>',
'Missing directive to handle \'if\' in <div template="if: foo">',
() => async.done()
);
}));
it('should raise an error for missing template directive (1)', inject([AsyncTestCompleter], (async) => {
expectCompileError(
'<div><template foo></template></div>',
'Missing directive to handle: <template foo>',
() => async.done()
);
}));
it('should raise an error for missing template directive (2)', inject([AsyncTestCompleter], (async) => {
expectCompileError(
'<div><template *if="condition"></template></div>',
'Missing directive to handle: <template *if="condition">',
() => async.done()
);
}));
it('should raise an error for missing template directive (3)', inject([AsyncTestCompleter], (async) => {
expectCompileError(
'<div *if="condition"></div>',
'Missing directive to handle \'if\' in MyComp: <div *if="condition">',
() => async.done()
);
}));
}
});
});
}
@DynamicComponent({
selector: 'dynamic-comp'
})
class DynamicComp {
done;
constructor(loader:PrivateComponentLoader, location:PrivateComponentLocation) {
this.done = loader.load(HelloCmp, location);
}
}
@Component({
selector: 'hello-cmp'
})
@Template({
inline: "{{greeting}}"
})
class HelloCmp {
greeting:string;
constructor() {
this.greeting = "hello";
}
}
@Decorator({
selector: '[my-dir]',
bind: {'dirProp':'elprop'}
})
class MyDir {
dirProp:string;
constructor() {
this.dirProp = '';
}
}
@Component({selector: 'push-cmp'})
@Template({inline: '{{field}}'})
class PushBasedComp {
numberOfChecks:number;
bpc:BindingPropagationConfig;
constructor(bpc:BindingPropagationConfig) {
this.numberOfChecks = 0;
this.bpc = bpc;
bpc.shouldBePropagated();
}
get field(){
this.numberOfChecks++;
return "fixed";
}
propagate() {
this.bpc.shouldBePropagatedFromRoot();
}
}
@Component()
class MyComp {
ctxProp:string;
ctxNumProp;
ctxBoolProp;
constructor() {
this.ctxProp = 'initial value';
this.ctxNumProp = 0;
this.ctxBoolProp = false;
}
}
@Component({
selector: 'component-with-pipes',
bind: {
"prop": "prop | double"
}
})
@Template({
inline: ''
})
class ComponentWithPipes {
prop:string;
}
@Component({
selector: 'child-cmp',
services: [MyService]
})
@Template({
directives: [MyDir],
inline: '{{ctxProp}}'
})
class ChildComp {
ctxProp:string;
dirProp:string;
constructor(service: MyService) {
this.ctxProp = service.greeting;
this.dirProp = null;
}
}
@Decorator({
selector: 'some-directive'
})
class SomeDirective { }
@Component({
selector: 'cmp-with-parent'
})
@Template({
inline: '<p>Component with an injected parent</p>',
directives: [SomeDirective]
})
class CompWithParent {
myParent: SomeDirective;
constructor(@Parent() someComp: SomeDirective) {
this.myParent = someComp;
}
}
@Component({
selector: 'cmp-with-ancestor'
})
@Template({
inline: '<p>Component with an injected ancestor</p>',
directives: [SomeDirective]
})
class CompWithAncestor {
myAncestor: SomeDirective;
constructor(@Ancestor() someComp: SomeDirective) {
this.myAncestor = someComp;
}
}
@Component({
selector: '[child-cmp2]',
services: [MyService]
})
class ChildComp2 {
ctxProp:string;
dirProp:string;
constructor(service: MyService) {
this.ctxProp = service.greeting;
this.dirProp = null;
}
}
@Viewport({
selector: '[some-viewport]'
})
class SomeViewport {
constructor(container: ViewContainer) {
container.create().setLocal('some-tmpl', 'hello');
container.create().setLocal('some-tmpl', 'again');
}
}
class MyService {
greeting:string;
constructor() {
this.greeting = 'hello';
}
}
class DoublePipe extends Pipe {
supports(obj) {
return true;
}
transform(value) {
return `${value}${value}`;
}
}
class DoublePipeFactory {
supports(obj) {
return true;
}
create() {
return new DoublePipe();
}
}
@Decorator({
selector: '[emitter]',
events: {'event': 'onEvent($event)'}
})
class DecoratorEmitingEvent {
msg: string;
emitter;
constructor(@EventEmitter('event') emitter:Function) {
this.msg = '';
this.emitter = emitter;
}
fireEvent(msg: string) {
this.emitter(msg);
}
onEvent(msg: string) {
this.msg = msg;
}
}
@Decorator({
selector: '[listener]',
events: {'event': 'onEvent($event)'}
})
class DecoratorListeningEvent {
msg: string;
constructor() {
this.msg = '';
}
onEvent(msg: string) {
this.msg = msg;
}
}
@Component({
selector: '[id]',
bind: {'id': 'id'}
})
@Template({
inline: '<div>Matched on id with {{id}}</div>'
})
class IdComponent {
id: string;
}
| modules/angular2/test/core/compiler/integration_spec.js | 1 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00028348955675028265,
0.00017733179265633225,
0.00016421206237282604,
0.00017581606516614556,
0.000015929008441162296
] |
{
"id": 7,
"code_window": [
" 'right': (a,v) => a.right = v,\n",
" 'initData': (a,v) => a.initData = v,\n",
" 'data': (a,v) => a.data = v,\n",
" 'condition': (a,v) => a.condition = v,\n",
" });\n",
"}\n",
"\n",
"var BASELINE_TREE_TEMPLATE;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'if': (a,v) => a['if'] = v,\n"
],
"file_path": "modules/benchmarks/src/tree/tree_benchmark.js",
"type": "add",
"edit_start_line_idx": 208
} | export var Bar1 = 'BAR1';
export var Bar2 = 'BAR2';
export function Bar3() {}
| tools/transpiler/spec/bar.js | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.0001759202714310959,
0.0001759202714310959,
0.0001759202714310959,
0.0001759202714310959,
0
] |
{
"id": 7,
"code_window": [
" 'right': (a,v) => a.right = v,\n",
" 'initData': (a,v) => a.initData = v,\n",
" 'data': (a,v) => a.data = v,\n",
" 'condition': (a,v) => a.condition = v,\n",
" });\n",
"}\n",
"\n",
"var BASELINE_TREE_TEMPLATE;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'if': (a,v) => a['if'] = v,\n"
],
"file_path": "modules/benchmarks/src/tree/tree_benchmark.js",
"type": "add",
"edit_start_line_idx": 208
} | # http://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
| .editorconfig | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.0001986412680707872,
0.00018519879085943103,
0.0001717563281999901,
0.00018519879085943103,
0.000013442469935398549
] |
{
"id": 7,
"code_window": [
" 'right': (a,v) => a.right = v,\n",
" 'initData': (a,v) => a.initData = v,\n",
" 'data': (a,v) => a.data = v,\n",
" 'condition': (a,v) => a.condition = v,\n",
" });\n",
"}\n",
"\n",
"var BASELINE_TREE_TEMPLATE;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'if': (a,v) => a['if'] = v,\n"
],
"file_path": "modules/benchmarks/src/tree/tree_benchmark.js",
"type": "add",
"edit_start_line_idx": 208
} | library foo;
import 'foo.dart';
import 'package:angular2/src/core/annotations/annotations.dart';
bool _visited = false;
void setupReflection(reflector) {
if (_visited) return;
_visited = true;
reflector
..registerType(DependencyComponent, {
'factory': () => new DependencyComponent(),
'parameters': const [],
'annotations': const [const Component(selector: '[salad]')]
});
}
| modules/angular2/test/transform/directive_linker/simple_export_files/expected/foo.ng_deps.dart | 0 | https://github.com/angular/angular/commit/0fb9f3bd6c6efb471da8069a2c6eb2f843ce8050 | [
0.00017515970102977008,
0.00016973898163996637,
0.00016431826225016266,
0.00016973898163996637,
0.000005420719389803708
] |
{
"id": 0,
"code_window": [
"\n",
" if (!types.isRelation(attribute.type)) {\n",
" continue;\n",
" }\n",
"\n",
" if (populateMap[key] === false) {\n",
" continue;\n",
" }\n",
"\n",
" // make sure id is present for future populate queries\n",
" if (_.has('id', meta.attributes)) {\n",
" qb.addSelect('id');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/database/lib/query/helpers/populate.js",
"type": "replace",
"edit_start_line_idx": 85
} | /* eslint-disable max-classes-per-file */
'use strict';
/**
* Converts the standard Strapi REST query params to a more usable format for querying
* You can read more here: https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest-api.html#filters
*/
const { has, isEmpty, isObject, isPlainObject, cloneDeep, get, mergeAll } = require('lodash/fp');
const _ = require('lodash');
const parseType = require('./parse-type');
const contentTypesUtils = require('./content-types');
const { PUBLISHED_AT_ATTRIBUTE } = contentTypesUtils.constants;
class InvalidOrderError extends Error {
constructor() {
super();
this.message = 'Invalid order. order can only be one of asc|desc|ASC|DESC';
}
}
class InvalidSortError extends Error {
constructor() {
super();
this.message =
'Invalid sort parameter. Expected a string, an array of strings, a sort object or an array of sort objects';
}
}
const validateOrder = (order) => {
if (!['asc', 'desc'].includes(order.toLocaleLowerCase())) {
throw new InvalidOrderError();
}
};
const convertCountQueryParams = (countQuery) => {
return parseType({ type: 'boolean', value: countQuery });
};
/**
* Sort query parser
* @param {string} sortQuery - ex: id:asc,price:desc
*/
const convertSortQueryParams = (sortQuery) => {
if (typeof sortQuery === 'string') {
return sortQuery.split(',').map((value) => convertSingleSortQueryParam(value));
}
if (Array.isArray(sortQuery)) {
return sortQuery.flatMap((sortValue) => convertSortQueryParams(sortValue));
}
if (_.isPlainObject(sortQuery)) {
return convertNestedSortQueryParam(sortQuery);
}
throw new InvalidSortError();
};
const convertSingleSortQueryParam = (sortQuery) => {
// split field and order param with default order to ascending
const [field, order = 'asc'] = sortQuery.split(':');
if (field.length === 0) {
throw new Error('Field cannot be empty');
}
validateOrder(order);
return _.set({}, field, order);
};
const convertNestedSortQueryParam = (sortQuery) => {
const transformedSort = {};
for (const field of Object.keys(sortQuery)) {
const order = sortQuery[field];
// this is a deep sort
if (_.isPlainObject(order)) {
transformedSort[field] = convertNestedSortQueryParam(order);
} else {
validateOrder(order);
transformedSort[field] = order;
}
}
return transformedSort;
};
/**
* Start query parser
* @param {string} startQuery
*/
const convertStartQueryParams = (startQuery) => {
const startAsANumber = _.toNumber(startQuery);
if (!_.isInteger(startAsANumber) || startAsANumber < 0) {
throw new Error(`convertStartQueryParams expected a positive integer got ${startAsANumber}`);
}
return startAsANumber;
};
/**
* Limit query parser
* @param {string} limitQuery
*/
const convertLimitQueryParams = (limitQuery) => {
const limitAsANumber = _.toNumber(limitQuery);
if (!_.isInteger(limitAsANumber) || (limitAsANumber !== -1 && limitAsANumber < 0)) {
throw new Error(`convertLimitQueryParams expected a positive integer got ${limitAsANumber}`);
}
if (limitAsANumber === -1) return null;
return limitAsANumber;
};
class InvalidPopulateError extends Error {
constructor() {
super();
this.message =
'Invalid populate parameter. Expected a string, an array of strings, a populate object';
}
}
// NOTE: we could support foo.* or foo.bar.* etc later on
const convertPopulateQueryParams = (populate, schema, depth = 0) => {
if (depth === 0 && populate === '*') {
return true;
}
if (typeof populate === 'string') {
return populate.split(',').map((value) => _.trim(value));
}
if (Array.isArray(populate)) {
// map convert
return _.uniq(
populate.flatMap((value) => {
if (typeof value !== 'string') {
throw new InvalidPopulateError();
}
return value.split(',').map((value) => _.trim(value));
})
);
}
if (_.isPlainObject(populate)) {
return convertPopulateObject(populate, schema);
}
throw new InvalidPopulateError();
};
const convertPopulateObject = (populate, schema) => {
if (!schema) {
return {};
}
const { attributes } = schema;
return Object.entries(populate).reduce((acc, [key, subPopulate]) => {
const attribute = attributes[key];
if (!attribute) {
return acc;
}
// FIXME: This is a temporary solution for dynamic zones that should be
// fixed when we'll implement a more accurate way to query them
if (attribute.type === 'dynamiczone') {
const populates = attribute.components
.map((uid) => strapi.getModel(uid))
.map((schema) => convertNestedPopulate(subPopulate, schema));
return {
...acc,
[key]: mergeAll(populates),
};
}
// NOTE: Retrieve the target schema UID.
// Only handles basic relations, medias and component since it's not possible
// to populate with options for a dynamic zone or a polymorphic relation
let targetSchemaUID;
if (attribute.type === 'relation') {
targetSchemaUID = attribute.target;
} else if (attribute.type === 'component') {
targetSchemaUID = attribute.component;
} else if (attribute.type === 'media') {
targetSchemaUID = 'plugin::upload.file';
} else {
return acc;
}
const targetSchema = strapi.getModel(targetSchemaUID);
if (!targetSchema) {
return acc;
}
return {
...acc,
[key]: convertNestedPopulate(subPopulate, targetSchema),
};
}, {});
};
const convertNestedPopulate = (subPopulate, schema) => {
if (subPopulate === '*') {
return true;
}
if (_.isString(subPopulate)) {
return parseType({ type: 'boolean', value: subPopulate, forceCast: true });
}
if (_.isBoolean(subPopulate)) {
return subPopulate;
}
if (!_.isPlainObject(subPopulate)) {
throw new Error(`Invalid nested populate. Expected '*' or an object`);
}
// TODO: We will need to consider a way to add limitation / pagination
const { sort, filters, fields, populate, count } = subPopulate;
const query = {};
if (sort) {
query.orderBy = convertSortQueryParams(sort);
}
if (filters) {
query.where = convertFiltersQueryParams(filters, schema);
}
if (fields) {
query.select = convertFieldsQueryParams(fields);
}
if (populate) {
query.populate = convertPopulateQueryParams(populate, schema);
}
if (count) {
query.count = convertCountQueryParams(count);
}
return query;
};
const convertFieldsQueryParams = (fields, depth = 0) => {
if (depth === 0 && fields === '*') {
return undefined;
}
if (typeof fields === 'string') {
const fieldsValues = fields.split(',').map((value) => _.trim(value));
return _.uniq(['id', ...fieldsValues]);
}
if (Array.isArray(fields)) {
// map convert
const fieldsValues = fields.flatMap((value) => convertFieldsQueryParams(value, depth + 1));
return _.uniq(['id', ...fieldsValues]);
}
throw new Error('Invalid fields parameter. Expected a string or an array of strings');
};
const convertFiltersQueryParams = (filters, schema) => {
// Filters need to be either an array or an object
// Here we're only checking for 'object' type since typeof [] => object and typeof {} => object
if (!isObject(filters)) {
throw new Error('The filters parameter must be an object or an array');
}
// Don't mutate the original object
const filtersCopy = cloneDeep(filters);
return convertAndSanitizeFilters(filtersCopy, schema);
};
const convertAndSanitizeFilters = (filters, schema) => {
if (!isPlainObject(filters)) {
return filters;
}
if (Array.isArray(filters)) {
return (
filters
// Sanitize each filter
.map((filter) => convertAndSanitizeFilters(filter, schema))
// Filter out empty filters
.filter((filter) => !isObject(filter) || !isEmpty(filter))
);
}
const removeOperator = (operator) => delete filters[operator];
// Here, `key` can either be an operator or an attribute name
for (const [key, value] of Object.entries(filters)) {
const attribute = get(key, schema.attributes);
// Handle attributes
if (attribute) {
// Relations
if (attribute.type === 'relation') {
filters[key] = convertAndSanitizeFilters(value, strapi.getModel(attribute.target));
}
// Components
else if (attribute.type === 'component') {
filters[key] = convertAndSanitizeFilters(value, strapi.getModel(attribute.component));
}
// Media
else if (attribute.type === 'media') {
filters[key] = convertAndSanitizeFilters(value, strapi.getModel('plugin::upload.file'));
}
// Dynamic Zones
else if (attribute.type === 'dynamiczone') {
removeOperator(key);
}
// Password attributes
else if (attribute.type === 'password') {
// Always remove password attributes from filters object
removeOperator(key);
}
// Scalar attributes
else {
filters[key] = convertAndSanitizeFilters(value, schema);
}
}
// Handle operators
else if (['$null', '$notNull'].includes(key)) {
filters[key] = parseType({ type: 'boolean', value: filters[key], forceCast: true });
} else if (isObject(value)) {
filters[key] = convertAndSanitizeFilters(value, schema);
}
// Remove empty objects & arrays
if (isPlainObject(filters[key]) && isEmpty(filters[key])) {
removeOperator(key);
}
}
return filters;
};
const convertPublicationStateParams = (type, params = {}, query = {}) => {
if (!type) {
return;
}
const { publicationState } = params;
if (!_.isNil(publicationState)) {
if (!contentTypesUtils.constants.DP_PUB_STATES.includes(publicationState)) {
throw new Error(
`Invalid publicationState. Expected one of 'preview','live' received: ${publicationState}.`
);
}
// NOTE: this is the query layer filters not the entity service filters
query.filters = ({ meta }) => {
if (publicationState === 'live' && has(PUBLISHED_AT_ATTRIBUTE, meta.attributes)) {
return { [PUBLISHED_AT_ATTRIBUTE]: { $notNull: true } };
}
};
}
};
module.exports = {
convertSortQueryParams,
convertStartQueryParams,
convertLimitQueryParams,
convertPopulateQueryParams,
convertFiltersQueryParams,
convertFieldsQueryParams,
convertPublicationStateParams,
};
| packages/core/utils/lib/convert-query-params.js | 1 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.009780278429389,
0.0017802994698286057,
0.00016546981350984424,
0.0003118630265817046,
0.0029198818374425173
] |
{
"id": 0,
"code_window": [
"\n",
" if (!types.isRelation(attribute.type)) {\n",
" continue;\n",
" }\n",
"\n",
" if (populateMap[key] === false) {\n",
" continue;\n",
" }\n",
"\n",
" // make sure id is present for future populate queries\n",
" if (_.has('id', meta.attributes)) {\n",
" qb.addSelect('id');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/database/lib/query/helpers/populate.js",
"type": "replace",
"edit_start_line_idx": 85
} | import { hasPermissions } from '@strapi/helper-plugin';
import getGeneralLinks from '../getGeneralLinks';
jest.mock('@strapi/helper-plugin');
describe('getGeneralLinks', () => {
it('resolves valid general links from real data', async () => {
hasPermissions.mockImplementation(() => Promise.resolve(true));
const permissions = [
{
id: 458,
action: 'plugin::i18n.locale.read',
subject: null,
properties: {},
conditions: [],
},
{
id: 459,
action: 'plugin::content-manager.explorer.create',
subject: 'api::article.article',
properties: {
fields: ['Name'],
locales: ['en'],
},
conditions: [],
},
{
id: 460,
action: 'plugin::content-manager.explorer.read',
subject: 'api::article.article',
properties: {
fields: ['Name'],
locales: ['en'],
},
conditions: [],
},
{
id: 461,
action: 'plugin::content-manager.explorer.read',
subject: 'api::article.article',
properties: {
fields: ['Name'],
locales: ['fr-FR'],
},
conditions: [],
},
{
id: 462,
action: 'plugin::content-manager.explorer.update',
subject: 'api::article.article',
properties: {
fields: ['Name'],
locales: ['fr-FR'],
},
conditions: [],
},
];
const generalSectionRawLinks = [
{
icon: 'list',
label: 'app.components.LeftMenuLinkContainer.listPlugins',
to: '/list-plugins',
isDisplayed: false,
permissions: [
{
action: 'admin::marketplace.read',
subject: null,
},
{
action: 'admin::marketplace.plugins.install',
subject: null,
},
{
action: 'admin::marketplace.plugins.uninstall',
subject: null,
},
],
notificationsCount: 0,
},
{
icon: 'shopping-basket',
label: 'app.components.LeftMenuLinkContainer.installNewPlugin',
to: '/marketplace',
isDisplayed: false,
permissions: [
{
action: 'admin::marketplace.read',
subject: null,
},
{
action: 'admin::marketplace.plugins.install',
subject: null,
},
{
action: 'admin::marketplace.plugins.uninstall',
subject: null,
},
],
notificationsCount: 0,
},
{
icon: 'cog',
label: 'app.components.LeftMenuLinkContainer.settings',
isDisplayed: true,
to: '/settings',
permissions: [],
notificationsCount: 0,
},
];
const expected = [
{
icon: 'list',
label: 'app.components.LeftMenuLinkContainer.listPlugins',
to: '/list-plugins',
isDisplayed: false,
permissions: [
{
action: 'admin::marketplace.read',
subject: null,
},
{
action: 'admin::marketplace.plugins.install',
subject: null,
},
{
action: 'admin::marketplace.plugins.uninstall',
subject: null,
},
],
notificationsCount: 0,
},
{
icon: 'shopping-basket',
label: 'app.components.LeftMenuLinkContainer.installNewPlugin',
to: '/marketplace',
isDisplayed: false,
permissions: [
{
action: 'admin::marketplace.read',
subject: null,
},
{
action: 'admin::marketplace.plugins.install',
subject: null,
},
{
action: 'admin::marketplace.plugins.uninstall',
subject: null,
},
],
notificationsCount: 0,
},
{
icon: 'cog',
label: 'app.components.LeftMenuLinkContainer.settings',
isDisplayed: true,
to: '/settings',
permissions: [],
notificationsCount: 0,
},
];
const actual = await getGeneralLinks(permissions, generalSectionRawLinks, false);
expect(actual).toEqual(expected);
});
it('resolves an empty array when the to (/settings) is not in the authorized links', async () => {
hasPermissions.mockImplementation(() => Promise.resolve(false));
const permissions = [
{
id: 458,
action: 'plugin::i18n.locale.read',
subject: null,
properties: {},
conditions: [],
},
{
id: 459,
action: 'plugin::content-manager.explorer.create',
subject: 'api::article.article',
properties: {
fields: ['Name'],
locales: ['en'],
},
conditions: [],
},
{
id: 460,
action: 'plugin::content-manager.explorer.read',
subject: 'api::article.article',
properties: {
fields: ['Name'],
locales: ['en'],
},
conditions: [],
},
{
id: 461,
action: 'plugin::content-manager.explorer.read',
subject: 'api::article.article',
properties: {
fields: ['Name'],
locales: ['fr-FR'],
},
conditions: [],
},
{
id: 462,
action: 'plugin::content-manager.explorer.update',
subject: 'api::article.article',
properties: {
fields: ['Name'],
locales: ['fr-FR'],
},
conditions: [],
},
];
const generalSectionRawLinks = [
{
icon: 'list',
label: 'app.components.LeftMenuLinkContainer.listPlugins',
to: '/list-plugins',
isDisplayed: false,
permissions: [],
notificationsCount: 0,
},
{
icon: 'shopping-basket',
label: 'app.components.LeftMenuLinkContainer.installNewPlugin',
to: '/marketplace',
isDisplayed: false,
permissions: [],
notificationsCount: 0,
},
{
icon: 'cog',
label: 'app.components.LeftMenuLinkContainer.settings',
isDisplayed: false,
to: '/settings',
permissions: [],
notificationsCount: 0,
},
];
const expected = [];
const actual = await getGeneralLinks(permissions, generalSectionRawLinks, false);
expect(actual).toEqual(expected);
});
});
| packages/core/admin/admin/src/hooks/useMenu/utils/tests/getGeneralLinks.test.js | 0 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.00017730552644934505,
0.00017582612053956836,
0.0001712652447167784,
0.00017611075600143522,
0.000001186129111374612
] |
{
"id": 0,
"code_window": [
"\n",
" if (!types.isRelation(attribute.type)) {\n",
" continue;\n",
" }\n",
"\n",
" if (populateMap[key] === false) {\n",
" continue;\n",
" }\n",
"\n",
" // make sure id is present for future populate queries\n",
" if (_.has('id', meta.attributes)) {\n",
" qb.addSelect('id');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/database/lib/query/helpers/populate.js",
"type": "replace",
"edit_start_line_idx": 85
} | import updateValues from '../updateValues';
describe('ADMIN | COMPONENTS | Permissions | utils | updateValues', () => {
it('should not the conditions values of given object', () => {
const simpleObject = {
properties: {
enabled: true,
},
conditions: 'test',
};
const expected = {
properties: {
enabled: false,
},
conditions: 'test',
};
expect(updateValues(simpleObject, false)).toEqual(expected);
});
it('set the leafs of an object with the second argument passed to the function', () => {
const complexeObject = {
conditions: 'test',
properties: {
enabled: true,
f1: {
enabled: true,
f1: {
conditions: 'test',
enabled: false,
f2: {
enabled: true,
},
},
},
},
};
const expected = {
conditions: 'test',
properties: {
enabled: false,
f1: {
enabled: false,
f1: {
conditions: 'test',
enabled: false,
f2: {
enabled: false,
},
},
},
},
};
expect(updateValues(complexeObject, false)).toEqual(expected);
});
});
| packages/core/admin/admin/src/pages/SettingsPage/pages/Roles/EditPage/components/Permissions/utils/tests/updateValues.test.js | 0 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.00017843098612502217,
0.00017591523646842688,
0.0001742606400512159,
0.00017553658108226955,
0.0000013602850685856538
] |
{
"id": 0,
"code_window": [
"\n",
" if (!types.isRelation(attribute.type)) {\n",
" continue;\n",
" }\n",
"\n",
" if (populateMap[key] === false) {\n",
" continue;\n",
" }\n",
"\n",
" // make sure id is present for future populate queries\n",
" if (_.has('id', meta.attributes)) {\n",
" qb.addSelect('id');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/database/lib/query/helpers/populate.js",
"type": "replace",
"edit_start_line_idx": 85
} | 'use strict';
const _ = require('lodash');
const removeUndefined = (obj) => _.pickBy(obj, (value) => typeof value !== 'undefined');
module.exports = {
removeUndefined,
};
| packages/core/utils/lib/object-formatting.js | 0 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.0013353168033063412,
0.0013353168033063412,
0.0013353168033063412,
0.0013353168033063412,
0
] |
{
"id": 1,
"code_window": [
"\n",
"/**\n",
" * Converts the standard Strapi REST query params to a more usable format for querying\n",
" * You can read more here: https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest-api.html#filters\n",
" */\n",
"const { has, isEmpty, isObject, isPlainObject, cloneDeep, get, mergeAll } = require('lodash/fp');\n",
"const _ = require('lodash');\n",
"const parseType = require('./parse-type');\n",
"const contentTypesUtils = require('./content-types');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const {\n",
" has,\n",
" isEmpty,\n",
" isObject,\n",
" isPlainObject,\n",
" cloneDeep,\n",
" get,\n",
" mergeAll,\n",
" isBoolean,\n",
"} = require('lodash/fp');\n"
],
"file_path": "packages/core/utils/lib/convert-query-params.js",
"type": "replace",
"edit_start_line_idx": 8
} | /* eslint-disable max-classes-per-file */
'use strict';
/**
* Converts the standard Strapi REST query params to a more usable format for querying
* You can read more here: https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest-api.html#filters
*/
const { has, isEmpty, isObject, isPlainObject, cloneDeep, get, mergeAll } = require('lodash/fp');
const _ = require('lodash');
const parseType = require('./parse-type');
const contentTypesUtils = require('./content-types');
const { PUBLISHED_AT_ATTRIBUTE } = contentTypesUtils.constants;
class InvalidOrderError extends Error {
constructor() {
super();
this.message = 'Invalid order. order can only be one of asc|desc|ASC|DESC';
}
}
class InvalidSortError extends Error {
constructor() {
super();
this.message =
'Invalid sort parameter. Expected a string, an array of strings, a sort object or an array of sort objects';
}
}
const validateOrder = (order) => {
if (!['asc', 'desc'].includes(order.toLocaleLowerCase())) {
throw new InvalidOrderError();
}
};
const convertCountQueryParams = (countQuery) => {
return parseType({ type: 'boolean', value: countQuery });
};
/**
* Sort query parser
* @param {string} sortQuery - ex: id:asc,price:desc
*/
const convertSortQueryParams = (sortQuery) => {
if (typeof sortQuery === 'string') {
return sortQuery.split(',').map((value) => convertSingleSortQueryParam(value));
}
if (Array.isArray(sortQuery)) {
return sortQuery.flatMap((sortValue) => convertSortQueryParams(sortValue));
}
if (_.isPlainObject(sortQuery)) {
return convertNestedSortQueryParam(sortQuery);
}
throw new InvalidSortError();
};
const convertSingleSortQueryParam = (sortQuery) => {
// split field and order param with default order to ascending
const [field, order = 'asc'] = sortQuery.split(':');
if (field.length === 0) {
throw new Error('Field cannot be empty');
}
validateOrder(order);
return _.set({}, field, order);
};
const convertNestedSortQueryParam = (sortQuery) => {
const transformedSort = {};
for (const field of Object.keys(sortQuery)) {
const order = sortQuery[field];
// this is a deep sort
if (_.isPlainObject(order)) {
transformedSort[field] = convertNestedSortQueryParam(order);
} else {
validateOrder(order);
transformedSort[field] = order;
}
}
return transformedSort;
};
/**
* Start query parser
* @param {string} startQuery
*/
const convertStartQueryParams = (startQuery) => {
const startAsANumber = _.toNumber(startQuery);
if (!_.isInteger(startAsANumber) || startAsANumber < 0) {
throw new Error(`convertStartQueryParams expected a positive integer got ${startAsANumber}`);
}
return startAsANumber;
};
/**
* Limit query parser
* @param {string} limitQuery
*/
const convertLimitQueryParams = (limitQuery) => {
const limitAsANumber = _.toNumber(limitQuery);
if (!_.isInteger(limitAsANumber) || (limitAsANumber !== -1 && limitAsANumber < 0)) {
throw new Error(`convertLimitQueryParams expected a positive integer got ${limitAsANumber}`);
}
if (limitAsANumber === -1) return null;
return limitAsANumber;
};
class InvalidPopulateError extends Error {
constructor() {
super();
this.message =
'Invalid populate parameter. Expected a string, an array of strings, a populate object';
}
}
// NOTE: we could support foo.* or foo.bar.* etc later on
const convertPopulateQueryParams = (populate, schema, depth = 0) => {
if (depth === 0 && populate === '*') {
return true;
}
if (typeof populate === 'string') {
return populate.split(',').map((value) => _.trim(value));
}
if (Array.isArray(populate)) {
// map convert
return _.uniq(
populate.flatMap((value) => {
if (typeof value !== 'string') {
throw new InvalidPopulateError();
}
return value.split(',').map((value) => _.trim(value));
})
);
}
if (_.isPlainObject(populate)) {
return convertPopulateObject(populate, schema);
}
throw new InvalidPopulateError();
};
const convertPopulateObject = (populate, schema) => {
if (!schema) {
return {};
}
const { attributes } = schema;
return Object.entries(populate).reduce((acc, [key, subPopulate]) => {
const attribute = attributes[key];
if (!attribute) {
return acc;
}
// FIXME: This is a temporary solution for dynamic zones that should be
// fixed when we'll implement a more accurate way to query them
if (attribute.type === 'dynamiczone') {
const populates = attribute.components
.map((uid) => strapi.getModel(uid))
.map((schema) => convertNestedPopulate(subPopulate, schema));
return {
...acc,
[key]: mergeAll(populates),
};
}
// NOTE: Retrieve the target schema UID.
// Only handles basic relations, medias and component since it's not possible
// to populate with options for a dynamic zone or a polymorphic relation
let targetSchemaUID;
if (attribute.type === 'relation') {
targetSchemaUID = attribute.target;
} else if (attribute.type === 'component') {
targetSchemaUID = attribute.component;
} else if (attribute.type === 'media') {
targetSchemaUID = 'plugin::upload.file';
} else {
return acc;
}
const targetSchema = strapi.getModel(targetSchemaUID);
if (!targetSchema) {
return acc;
}
return {
...acc,
[key]: convertNestedPopulate(subPopulate, targetSchema),
};
}, {});
};
const convertNestedPopulate = (subPopulate, schema) => {
if (subPopulate === '*') {
return true;
}
if (_.isString(subPopulate)) {
return parseType({ type: 'boolean', value: subPopulate, forceCast: true });
}
if (_.isBoolean(subPopulate)) {
return subPopulate;
}
if (!_.isPlainObject(subPopulate)) {
throw new Error(`Invalid nested populate. Expected '*' or an object`);
}
// TODO: We will need to consider a way to add limitation / pagination
const { sort, filters, fields, populate, count } = subPopulate;
const query = {};
if (sort) {
query.orderBy = convertSortQueryParams(sort);
}
if (filters) {
query.where = convertFiltersQueryParams(filters, schema);
}
if (fields) {
query.select = convertFieldsQueryParams(fields);
}
if (populate) {
query.populate = convertPopulateQueryParams(populate, schema);
}
if (count) {
query.count = convertCountQueryParams(count);
}
return query;
};
const convertFieldsQueryParams = (fields, depth = 0) => {
if (depth === 0 && fields === '*') {
return undefined;
}
if (typeof fields === 'string') {
const fieldsValues = fields.split(',').map((value) => _.trim(value));
return _.uniq(['id', ...fieldsValues]);
}
if (Array.isArray(fields)) {
// map convert
const fieldsValues = fields.flatMap((value) => convertFieldsQueryParams(value, depth + 1));
return _.uniq(['id', ...fieldsValues]);
}
throw new Error('Invalid fields parameter. Expected a string or an array of strings');
};
const convertFiltersQueryParams = (filters, schema) => {
// Filters need to be either an array or an object
// Here we're only checking for 'object' type since typeof [] => object and typeof {} => object
if (!isObject(filters)) {
throw new Error('The filters parameter must be an object or an array');
}
// Don't mutate the original object
const filtersCopy = cloneDeep(filters);
return convertAndSanitizeFilters(filtersCopy, schema);
};
const convertAndSanitizeFilters = (filters, schema) => {
if (!isPlainObject(filters)) {
return filters;
}
if (Array.isArray(filters)) {
return (
filters
// Sanitize each filter
.map((filter) => convertAndSanitizeFilters(filter, schema))
// Filter out empty filters
.filter((filter) => !isObject(filter) || !isEmpty(filter))
);
}
const removeOperator = (operator) => delete filters[operator];
// Here, `key` can either be an operator or an attribute name
for (const [key, value] of Object.entries(filters)) {
const attribute = get(key, schema.attributes);
// Handle attributes
if (attribute) {
// Relations
if (attribute.type === 'relation') {
filters[key] = convertAndSanitizeFilters(value, strapi.getModel(attribute.target));
}
// Components
else if (attribute.type === 'component') {
filters[key] = convertAndSanitizeFilters(value, strapi.getModel(attribute.component));
}
// Media
else if (attribute.type === 'media') {
filters[key] = convertAndSanitizeFilters(value, strapi.getModel('plugin::upload.file'));
}
// Dynamic Zones
else if (attribute.type === 'dynamiczone') {
removeOperator(key);
}
// Password attributes
else if (attribute.type === 'password') {
// Always remove password attributes from filters object
removeOperator(key);
}
// Scalar attributes
else {
filters[key] = convertAndSanitizeFilters(value, schema);
}
}
// Handle operators
else if (['$null', '$notNull'].includes(key)) {
filters[key] = parseType({ type: 'boolean', value: filters[key], forceCast: true });
} else if (isObject(value)) {
filters[key] = convertAndSanitizeFilters(value, schema);
}
// Remove empty objects & arrays
if (isPlainObject(filters[key]) && isEmpty(filters[key])) {
removeOperator(key);
}
}
return filters;
};
const convertPublicationStateParams = (type, params = {}, query = {}) => {
if (!type) {
return;
}
const { publicationState } = params;
if (!_.isNil(publicationState)) {
if (!contentTypesUtils.constants.DP_PUB_STATES.includes(publicationState)) {
throw new Error(
`Invalid publicationState. Expected one of 'preview','live' received: ${publicationState}.`
);
}
// NOTE: this is the query layer filters not the entity service filters
query.filters = ({ meta }) => {
if (publicationState === 'live' && has(PUBLISHED_AT_ATTRIBUTE, meta.attributes)) {
return { [PUBLISHED_AT_ATTRIBUTE]: { $notNull: true } };
}
};
}
};
module.exports = {
convertSortQueryParams,
convertStartQueryParams,
convertLimitQueryParams,
convertPopulateQueryParams,
convertFiltersQueryParams,
convertFieldsQueryParams,
convertPublicationStateParams,
};
| packages/core/utils/lib/convert-query-params.js | 1 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.9983760118484497,
0.3508511781692505,
0.00016489774861838669,
0.0069236746057868,
0.45296168327331543
] |
{
"id": 1,
"code_window": [
"\n",
"/**\n",
" * Converts the standard Strapi REST query params to a more usable format for querying\n",
" * You can read more here: https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest-api.html#filters\n",
" */\n",
"const { has, isEmpty, isObject, isPlainObject, cloneDeep, get, mergeAll } = require('lodash/fp');\n",
"const _ = require('lodash');\n",
"const parseType = require('./parse-type');\n",
"const contentTypesUtils = require('./content-types');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const {\n",
" has,\n",
" isEmpty,\n",
" isObject,\n",
" isPlainObject,\n",
" cloneDeep,\n",
" get,\n",
" mergeAll,\n",
" isBoolean,\n",
"} = require('lodash/fp');\n"
],
"file_path": "packages/core/utils/lib/convert-query-params.js",
"type": "replace",
"edit_start_line_idx": 8
} | /**
*
* LibraryContext
*
*/
import { createContext } from 'react';
const LibraryContext = createContext();
export default LibraryContext;
| packages/core/helper-plugin/lib/src/contexts/LibraryContext.js | 0 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.00017219941946677864,
0.00016804595361463726,
0.00016389248776249588,
0.00016804595361463726,
0.00000415346585214138
] |
{
"id": 1,
"code_window": [
"\n",
"/**\n",
" * Converts the standard Strapi REST query params to a more usable format for querying\n",
" * You can read more here: https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest-api.html#filters\n",
" */\n",
"const { has, isEmpty, isObject, isPlainObject, cloneDeep, get, mergeAll } = require('lodash/fp');\n",
"const _ = require('lodash');\n",
"const parseType = require('./parse-type');\n",
"const contentTypesUtils = require('./content-types');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const {\n",
" has,\n",
" isEmpty,\n",
" isObject,\n",
" isPlainObject,\n",
" cloneDeep,\n",
" get,\n",
" mergeAll,\n",
" isBoolean,\n",
"} = require('lodash/fp');\n"
],
"file_path": "packages/core/utils/lib/convert-query-params.js",
"type": "replace",
"edit_start_line_idx": 8
} | /**
*
* PluginIcon
*
*/
import React from 'react';
import Puzzle from '@strapi/icons/Puzzle';
const PluginIcon = () => <Puzzle />;
export default PluginIcon;
| examples/getstarted/src/plugins/myplugin/admin/src/components/PluginIcon/index.js | 0 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.000173669119249098,
0.00017241117893718183,
0.00017115323862526566,
0.00017241117893718183,
0.0000012579403119161725
] |
{
"id": 1,
"code_window": [
"\n",
"/**\n",
" * Converts the standard Strapi REST query params to a more usable format for querying\n",
" * You can read more here: https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest-api.html#filters\n",
" */\n",
"const { has, isEmpty, isObject, isPlainObject, cloneDeep, get, mergeAll } = require('lodash/fp');\n",
"const _ = require('lodash');\n",
"const parseType = require('./parse-type');\n",
"const contentTypesUtils = require('./content-types');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const {\n",
" has,\n",
" isEmpty,\n",
" isObject,\n",
" isPlainObject,\n",
" cloneDeep,\n",
" get,\n",
" mergeAll,\n",
" isBoolean,\n",
"} = require('lodash/fp');\n"
],
"file_path": "packages/core/utils/lib/convert-query-params.js",
"type": "replace",
"edit_start_line_idx": 8
} | /*
*
* LanguageToggle
*
*/
import React from 'react';
import { useIntl } from 'react-intl';
import { SimpleMenu, MenuItem } from '@strapi/design-system/SimpleMenu';
import useLocalesProvider from '../../../components/LocalesProvider/useLocalesProvider';
const LocaleToggle = () => {
const { changeLocale, localeNames } = useLocalesProvider();
const { locale } = useIntl();
return (
<SimpleMenu label={localeNames[locale]}>
{Object.keys(localeNames).map((lang) => (
<MenuItem onClick={() => changeLocale(lang)} key={lang}>
{localeNames[lang]}
</MenuItem>
))}
</SimpleMenu>
);
};
export default LocaleToggle;
| packages/core/admin/admin/src/layouts/UnauthenticatedLayout/LocaleToggle/index.js | 0 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.0001733871758915484,
0.0001711145741865039,
0.0001676092651905492,
0.00017234726692549884,
0.0000025147194264718564
] |
{
"id": 2,
"code_window": [
" // fixed when we'll implement a more accurate way to query them\n",
" if (attribute.type === 'dynamiczone') {\n",
" const populates = attribute.components\n",
" .map((uid) => strapi.getModel(uid))\n",
" .map((schema) => convertNestedPopulate(subPopulate, schema));\n",
"\n",
" return {\n",
" ...acc,\n",
" [key]: mergeAll(populates),\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .map((schema) => {\n",
" const populate = convertNestedPopulate(subPopulate, schema);\n",
" return isBoolean(populate) && populate ? {} : populate;\n",
" })\n",
" .filter((populate) => populate !== false);\n",
"\n",
" if (isEmpty(populates)) {\n",
" return acc;\n",
" }\n"
],
"file_path": "packages/core/utils/lib/convert-query-params.js",
"type": "replace",
"edit_start_line_idx": 176
} | /* eslint-disable max-classes-per-file */
'use strict';
/**
* Converts the standard Strapi REST query params to a more usable format for querying
* You can read more here: https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest-api.html#filters
*/
const { has, isEmpty, isObject, isPlainObject, cloneDeep, get, mergeAll } = require('lodash/fp');
const _ = require('lodash');
const parseType = require('./parse-type');
const contentTypesUtils = require('./content-types');
const { PUBLISHED_AT_ATTRIBUTE } = contentTypesUtils.constants;
class InvalidOrderError extends Error {
constructor() {
super();
this.message = 'Invalid order. order can only be one of asc|desc|ASC|DESC';
}
}
class InvalidSortError extends Error {
constructor() {
super();
this.message =
'Invalid sort parameter. Expected a string, an array of strings, a sort object or an array of sort objects';
}
}
const validateOrder = (order) => {
if (!['asc', 'desc'].includes(order.toLocaleLowerCase())) {
throw new InvalidOrderError();
}
};
const convertCountQueryParams = (countQuery) => {
return parseType({ type: 'boolean', value: countQuery });
};
/**
* Sort query parser
* @param {string} sortQuery - ex: id:asc,price:desc
*/
const convertSortQueryParams = (sortQuery) => {
if (typeof sortQuery === 'string') {
return sortQuery.split(',').map((value) => convertSingleSortQueryParam(value));
}
if (Array.isArray(sortQuery)) {
return sortQuery.flatMap((sortValue) => convertSortQueryParams(sortValue));
}
if (_.isPlainObject(sortQuery)) {
return convertNestedSortQueryParam(sortQuery);
}
throw new InvalidSortError();
};
const convertSingleSortQueryParam = (sortQuery) => {
// split field and order param with default order to ascending
const [field, order = 'asc'] = sortQuery.split(':');
if (field.length === 0) {
throw new Error('Field cannot be empty');
}
validateOrder(order);
return _.set({}, field, order);
};
const convertNestedSortQueryParam = (sortQuery) => {
const transformedSort = {};
for (const field of Object.keys(sortQuery)) {
const order = sortQuery[field];
// this is a deep sort
if (_.isPlainObject(order)) {
transformedSort[field] = convertNestedSortQueryParam(order);
} else {
validateOrder(order);
transformedSort[field] = order;
}
}
return transformedSort;
};
/**
* Start query parser
* @param {string} startQuery
*/
const convertStartQueryParams = (startQuery) => {
const startAsANumber = _.toNumber(startQuery);
if (!_.isInteger(startAsANumber) || startAsANumber < 0) {
throw new Error(`convertStartQueryParams expected a positive integer got ${startAsANumber}`);
}
return startAsANumber;
};
/**
* Limit query parser
* @param {string} limitQuery
*/
const convertLimitQueryParams = (limitQuery) => {
const limitAsANumber = _.toNumber(limitQuery);
if (!_.isInteger(limitAsANumber) || (limitAsANumber !== -1 && limitAsANumber < 0)) {
throw new Error(`convertLimitQueryParams expected a positive integer got ${limitAsANumber}`);
}
if (limitAsANumber === -1) return null;
return limitAsANumber;
};
class InvalidPopulateError extends Error {
constructor() {
super();
this.message =
'Invalid populate parameter. Expected a string, an array of strings, a populate object';
}
}
// NOTE: we could support foo.* or foo.bar.* etc later on
const convertPopulateQueryParams = (populate, schema, depth = 0) => {
if (depth === 0 && populate === '*') {
return true;
}
if (typeof populate === 'string') {
return populate.split(',').map((value) => _.trim(value));
}
if (Array.isArray(populate)) {
// map convert
return _.uniq(
populate.flatMap((value) => {
if (typeof value !== 'string') {
throw new InvalidPopulateError();
}
return value.split(',').map((value) => _.trim(value));
})
);
}
if (_.isPlainObject(populate)) {
return convertPopulateObject(populate, schema);
}
throw new InvalidPopulateError();
};
const convertPopulateObject = (populate, schema) => {
if (!schema) {
return {};
}
const { attributes } = schema;
return Object.entries(populate).reduce((acc, [key, subPopulate]) => {
const attribute = attributes[key];
if (!attribute) {
return acc;
}
// FIXME: This is a temporary solution for dynamic zones that should be
// fixed when we'll implement a more accurate way to query them
if (attribute.type === 'dynamiczone') {
const populates = attribute.components
.map((uid) => strapi.getModel(uid))
.map((schema) => convertNestedPopulate(subPopulate, schema));
return {
...acc,
[key]: mergeAll(populates),
};
}
// NOTE: Retrieve the target schema UID.
// Only handles basic relations, medias and component since it's not possible
// to populate with options for a dynamic zone or a polymorphic relation
let targetSchemaUID;
if (attribute.type === 'relation') {
targetSchemaUID = attribute.target;
} else if (attribute.type === 'component') {
targetSchemaUID = attribute.component;
} else if (attribute.type === 'media') {
targetSchemaUID = 'plugin::upload.file';
} else {
return acc;
}
const targetSchema = strapi.getModel(targetSchemaUID);
if (!targetSchema) {
return acc;
}
return {
...acc,
[key]: convertNestedPopulate(subPopulate, targetSchema),
};
}, {});
};
const convertNestedPopulate = (subPopulate, schema) => {
if (subPopulate === '*') {
return true;
}
if (_.isString(subPopulate)) {
return parseType({ type: 'boolean', value: subPopulate, forceCast: true });
}
if (_.isBoolean(subPopulate)) {
return subPopulate;
}
if (!_.isPlainObject(subPopulate)) {
throw new Error(`Invalid nested populate. Expected '*' or an object`);
}
// TODO: We will need to consider a way to add limitation / pagination
const { sort, filters, fields, populate, count } = subPopulate;
const query = {};
if (sort) {
query.orderBy = convertSortQueryParams(sort);
}
if (filters) {
query.where = convertFiltersQueryParams(filters, schema);
}
if (fields) {
query.select = convertFieldsQueryParams(fields);
}
if (populate) {
query.populate = convertPopulateQueryParams(populate, schema);
}
if (count) {
query.count = convertCountQueryParams(count);
}
return query;
};
const convertFieldsQueryParams = (fields, depth = 0) => {
if (depth === 0 && fields === '*') {
return undefined;
}
if (typeof fields === 'string') {
const fieldsValues = fields.split(',').map((value) => _.trim(value));
return _.uniq(['id', ...fieldsValues]);
}
if (Array.isArray(fields)) {
// map convert
const fieldsValues = fields.flatMap((value) => convertFieldsQueryParams(value, depth + 1));
return _.uniq(['id', ...fieldsValues]);
}
throw new Error('Invalid fields parameter. Expected a string or an array of strings');
};
const convertFiltersQueryParams = (filters, schema) => {
// Filters need to be either an array or an object
// Here we're only checking for 'object' type since typeof [] => object and typeof {} => object
if (!isObject(filters)) {
throw new Error('The filters parameter must be an object or an array');
}
// Don't mutate the original object
const filtersCopy = cloneDeep(filters);
return convertAndSanitizeFilters(filtersCopy, schema);
};
const convertAndSanitizeFilters = (filters, schema) => {
if (!isPlainObject(filters)) {
return filters;
}
if (Array.isArray(filters)) {
return (
filters
// Sanitize each filter
.map((filter) => convertAndSanitizeFilters(filter, schema))
// Filter out empty filters
.filter((filter) => !isObject(filter) || !isEmpty(filter))
);
}
const removeOperator = (operator) => delete filters[operator];
// Here, `key` can either be an operator or an attribute name
for (const [key, value] of Object.entries(filters)) {
const attribute = get(key, schema.attributes);
// Handle attributes
if (attribute) {
// Relations
if (attribute.type === 'relation') {
filters[key] = convertAndSanitizeFilters(value, strapi.getModel(attribute.target));
}
// Components
else if (attribute.type === 'component') {
filters[key] = convertAndSanitizeFilters(value, strapi.getModel(attribute.component));
}
// Media
else if (attribute.type === 'media') {
filters[key] = convertAndSanitizeFilters(value, strapi.getModel('plugin::upload.file'));
}
// Dynamic Zones
else if (attribute.type === 'dynamiczone') {
removeOperator(key);
}
// Password attributes
else if (attribute.type === 'password') {
// Always remove password attributes from filters object
removeOperator(key);
}
// Scalar attributes
else {
filters[key] = convertAndSanitizeFilters(value, schema);
}
}
// Handle operators
else if (['$null', '$notNull'].includes(key)) {
filters[key] = parseType({ type: 'boolean', value: filters[key], forceCast: true });
} else if (isObject(value)) {
filters[key] = convertAndSanitizeFilters(value, schema);
}
// Remove empty objects & arrays
if (isPlainObject(filters[key]) && isEmpty(filters[key])) {
removeOperator(key);
}
}
return filters;
};
const convertPublicationStateParams = (type, params = {}, query = {}) => {
if (!type) {
return;
}
const { publicationState } = params;
if (!_.isNil(publicationState)) {
if (!contentTypesUtils.constants.DP_PUB_STATES.includes(publicationState)) {
throw new Error(
`Invalid publicationState. Expected one of 'preview','live' received: ${publicationState}.`
);
}
// NOTE: this is the query layer filters not the entity service filters
query.filters = ({ meta }) => {
if (publicationState === 'live' && has(PUBLISHED_AT_ATTRIBUTE, meta.attributes)) {
return { [PUBLISHED_AT_ATTRIBUTE]: { $notNull: true } };
}
};
}
};
module.exports = {
convertSortQueryParams,
convertStartQueryParams,
convertLimitQueryParams,
convertPopulateQueryParams,
convertFiltersQueryParams,
convertFieldsQueryParams,
convertPublicationStateParams,
};
| packages/core/utils/lib/convert-query-params.js | 1 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.9984838366508484,
0.054344452917575836,
0.00016477734607178718,
0.0005209835362620652,
0.21580703556537628
] |
{
"id": 2,
"code_window": [
" // fixed when we'll implement a more accurate way to query them\n",
" if (attribute.type === 'dynamiczone') {\n",
" const populates = attribute.components\n",
" .map((uid) => strapi.getModel(uid))\n",
" .map((schema) => convertNestedPopulate(subPopulate, schema));\n",
"\n",
" return {\n",
" ...acc,\n",
" [key]: mergeAll(populates),\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .map((schema) => {\n",
" const populate = convertNestedPopulate(subPopulate, schema);\n",
" return isBoolean(populate) && populate ? {} : populate;\n",
" })\n",
" .filter((populate) => populate !== false);\n",
"\n",
" if (isEmpty(populates)) {\n",
" return acc;\n",
" }\n"
],
"file_path": "packages/core/utils/lib/convert-query-params.js",
"type": "replace",
"edit_start_line_idx": 176
} | root = true
[*]
end_of_line = lf
insert_final_newline = false
indent_style = space
indent_size = 2
| packages/plugins/users-permissions/.editorconfig | 0 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.0001738026476232335,
0.0001738026476232335,
0.0001738026476232335,
0.0001738026476232335,
0
] |
{
"id": 2,
"code_window": [
" // fixed when we'll implement a more accurate way to query them\n",
" if (attribute.type === 'dynamiczone') {\n",
" const populates = attribute.components\n",
" .map((uid) => strapi.getModel(uid))\n",
" .map((schema) => convertNestedPopulate(subPopulate, schema));\n",
"\n",
" return {\n",
" ...acc,\n",
" [key]: mergeAll(populates),\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .map((schema) => {\n",
" const populate = convertNestedPopulate(subPopulate, schema);\n",
" return isBoolean(populate) && populate ? {} : populate;\n",
" })\n",
" .filter((populate) => populate !== false);\n",
"\n",
" if (isEmpty(populates)) {\n",
" return acc;\n",
" }\n"
],
"file_path": "packages/core/utils/lib/convert-query-params.js",
"type": "replace",
"edit_start_line_idx": 176
} | import React from 'react';
import { render } from '@testing-library/react';
import LocalesProvider from '../index';
describe('LocalesProvider', () => {
it('should not crash', () => {
const { container } = render(
<LocalesProvider
changeLocale={jest.fn()}
localeNames={{ en: 'English' }}
messages={{ en: {} }}
>
<div>Test</div>
</LocalesProvider>
);
expect(container.firstChild).toMatchInlineSnapshot(`
<div>
Test
</div>
`);
});
});
| packages/core/admin/admin/src/components/LocalesProvider/tests/index.test.js | 0 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.00017773547733668238,
0.00017436376947443932,
0.00017171866784337908,
0.0001736371632432565,
0.000002509510750314803
] |
{
"id": 2,
"code_window": [
" // fixed when we'll implement a more accurate way to query them\n",
" if (attribute.type === 'dynamiczone') {\n",
" const populates = attribute.components\n",
" .map((uid) => strapi.getModel(uid))\n",
" .map((schema) => convertNestedPopulate(subPopulate, schema));\n",
"\n",
" return {\n",
" ...acc,\n",
" [key]: mergeAll(populates),\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .map((schema) => {\n",
" const populate = convertNestedPopulate(subPopulate, schema);\n",
" return isBoolean(populate) && populate ? {} : populate;\n",
" })\n",
" .filter((populate) => populate !== false);\n",
"\n",
" if (isEmpty(populates)) {\n",
" return acc;\n",
" }\n"
],
"file_path": "packages/core/utils/lib/convert-query-params.js",
"type": "replace",
"edit_start_line_idx": 176
} | {} | packages/generators/generators/lib/files/js/plugin/admin/src/translations/en.json | 0 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.00017203496827278286,
0.00017203496827278286,
0.00017203496827278286,
0.00017203496827278286,
0
] |
{
"id": 3,
"code_window": [
" if (!targetSchema) {\n",
" return acc;\n",
" }\n",
"\n",
" return {\n",
" ...acc,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" const populateObject = convertNestedPopulate(subPopulate, targetSchema);\n",
"\n",
" if (!populateObject) {\n",
" return acc;\n",
" }\n",
"\n"
],
"file_path": "packages/core/utils/lib/convert-query-params.js",
"type": "add",
"edit_start_line_idx": 205
} | /* eslint-disable max-classes-per-file */
'use strict';
/**
* Converts the standard Strapi REST query params to a more usable format for querying
* You can read more here: https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest-api.html#filters
*/
const { has, isEmpty, isObject, isPlainObject, cloneDeep, get, mergeAll } = require('lodash/fp');
const _ = require('lodash');
const parseType = require('./parse-type');
const contentTypesUtils = require('./content-types');
const { PUBLISHED_AT_ATTRIBUTE } = contentTypesUtils.constants;
class InvalidOrderError extends Error {
constructor() {
super();
this.message = 'Invalid order. order can only be one of asc|desc|ASC|DESC';
}
}
class InvalidSortError extends Error {
constructor() {
super();
this.message =
'Invalid sort parameter. Expected a string, an array of strings, a sort object or an array of sort objects';
}
}
const validateOrder = (order) => {
if (!['asc', 'desc'].includes(order.toLocaleLowerCase())) {
throw new InvalidOrderError();
}
};
const convertCountQueryParams = (countQuery) => {
return parseType({ type: 'boolean', value: countQuery });
};
/**
* Sort query parser
* @param {string} sortQuery - ex: id:asc,price:desc
*/
const convertSortQueryParams = (sortQuery) => {
if (typeof sortQuery === 'string') {
return sortQuery.split(',').map((value) => convertSingleSortQueryParam(value));
}
if (Array.isArray(sortQuery)) {
return sortQuery.flatMap((sortValue) => convertSortQueryParams(sortValue));
}
if (_.isPlainObject(sortQuery)) {
return convertNestedSortQueryParam(sortQuery);
}
throw new InvalidSortError();
};
const convertSingleSortQueryParam = (sortQuery) => {
// split field and order param with default order to ascending
const [field, order = 'asc'] = sortQuery.split(':');
if (field.length === 0) {
throw new Error('Field cannot be empty');
}
validateOrder(order);
return _.set({}, field, order);
};
const convertNestedSortQueryParam = (sortQuery) => {
const transformedSort = {};
for (const field of Object.keys(sortQuery)) {
const order = sortQuery[field];
// this is a deep sort
if (_.isPlainObject(order)) {
transformedSort[field] = convertNestedSortQueryParam(order);
} else {
validateOrder(order);
transformedSort[field] = order;
}
}
return transformedSort;
};
/**
* Start query parser
* @param {string} startQuery
*/
const convertStartQueryParams = (startQuery) => {
const startAsANumber = _.toNumber(startQuery);
if (!_.isInteger(startAsANumber) || startAsANumber < 0) {
throw new Error(`convertStartQueryParams expected a positive integer got ${startAsANumber}`);
}
return startAsANumber;
};
/**
* Limit query parser
* @param {string} limitQuery
*/
const convertLimitQueryParams = (limitQuery) => {
const limitAsANumber = _.toNumber(limitQuery);
if (!_.isInteger(limitAsANumber) || (limitAsANumber !== -1 && limitAsANumber < 0)) {
throw new Error(`convertLimitQueryParams expected a positive integer got ${limitAsANumber}`);
}
if (limitAsANumber === -1) return null;
return limitAsANumber;
};
class InvalidPopulateError extends Error {
constructor() {
super();
this.message =
'Invalid populate parameter. Expected a string, an array of strings, a populate object';
}
}
// NOTE: we could support foo.* or foo.bar.* etc later on
const convertPopulateQueryParams = (populate, schema, depth = 0) => {
if (depth === 0 && populate === '*') {
return true;
}
if (typeof populate === 'string') {
return populate.split(',').map((value) => _.trim(value));
}
if (Array.isArray(populate)) {
// map convert
return _.uniq(
populate.flatMap((value) => {
if (typeof value !== 'string') {
throw new InvalidPopulateError();
}
return value.split(',').map((value) => _.trim(value));
})
);
}
if (_.isPlainObject(populate)) {
return convertPopulateObject(populate, schema);
}
throw new InvalidPopulateError();
};
const convertPopulateObject = (populate, schema) => {
if (!schema) {
return {};
}
const { attributes } = schema;
return Object.entries(populate).reduce((acc, [key, subPopulate]) => {
const attribute = attributes[key];
if (!attribute) {
return acc;
}
// FIXME: This is a temporary solution for dynamic zones that should be
// fixed when we'll implement a more accurate way to query them
if (attribute.type === 'dynamiczone') {
const populates = attribute.components
.map((uid) => strapi.getModel(uid))
.map((schema) => convertNestedPopulate(subPopulate, schema));
return {
...acc,
[key]: mergeAll(populates),
};
}
// NOTE: Retrieve the target schema UID.
// Only handles basic relations, medias and component since it's not possible
// to populate with options for a dynamic zone or a polymorphic relation
let targetSchemaUID;
if (attribute.type === 'relation') {
targetSchemaUID = attribute.target;
} else if (attribute.type === 'component') {
targetSchemaUID = attribute.component;
} else if (attribute.type === 'media') {
targetSchemaUID = 'plugin::upload.file';
} else {
return acc;
}
const targetSchema = strapi.getModel(targetSchemaUID);
if (!targetSchema) {
return acc;
}
return {
...acc,
[key]: convertNestedPopulate(subPopulate, targetSchema),
};
}, {});
};
const convertNestedPopulate = (subPopulate, schema) => {
if (subPopulate === '*') {
return true;
}
if (_.isString(subPopulate)) {
return parseType({ type: 'boolean', value: subPopulate, forceCast: true });
}
if (_.isBoolean(subPopulate)) {
return subPopulate;
}
if (!_.isPlainObject(subPopulate)) {
throw new Error(`Invalid nested populate. Expected '*' or an object`);
}
// TODO: We will need to consider a way to add limitation / pagination
const { sort, filters, fields, populate, count } = subPopulate;
const query = {};
if (sort) {
query.orderBy = convertSortQueryParams(sort);
}
if (filters) {
query.where = convertFiltersQueryParams(filters, schema);
}
if (fields) {
query.select = convertFieldsQueryParams(fields);
}
if (populate) {
query.populate = convertPopulateQueryParams(populate, schema);
}
if (count) {
query.count = convertCountQueryParams(count);
}
return query;
};
const convertFieldsQueryParams = (fields, depth = 0) => {
if (depth === 0 && fields === '*') {
return undefined;
}
if (typeof fields === 'string') {
const fieldsValues = fields.split(',').map((value) => _.trim(value));
return _.uniq(['id', ...fieldsValues]);
}
if (Array.isArray(fields)) {
// map convert
const fieldsValues = fields.flatMap((value) => convertFieldsQueryParams(value, depth + 1));
return _.uniq(['id', ...fieldsValues]);
}
throw new Error('Invalid fields parameter. Expected a string or an array of strings');
};
const convertFiltersQueryParams = (filters, schema) => {
// Filters need to be either an array or an object
// Here we're only checking for 'object' type since typeof [] => object and typeof {} => object
if (!isObject(filters)) {
throw new Error('The filters parameter must be an object or an array');
}
// Don't mutate the original object
const filtersCopy = cloneDeep(filters);
return convertAndSanitizeFilters(filtersCopy, schema);
};
const convertAndSanitizeFilters = (filters, schema) => {
if (!isPlainObject(filters)) {
return filters;
}
if (Array.isArray(filters)) {
return (
filters
// Sanitize each filter
.map((filter) => convertAndSanitizeFilters(filter, schema))
// Filter out empty filters
.filter((filter) => !isObject(filter) || !isEmpty(filter))
);
}
const removeOperator = (operator) => delete filters[operator];
// Here, `key` can either be an operator or an attribute name
for (const [key, value] of Object.entries(filters)) {
const attribute = get(key, schema.attributes);
// Handle attributes
if (attribute) {
// Relations
if (attribute.type === 'relation') {
filters[key] = convertAndSanitizeFilters(value, strapi.getModel(attribute.target));
}
// Components
else if (attribute.type === 'component') {
filters[key] = convertAndSanitizeFilters(value, strapi.getModel(attribute.component));
}
// Media
else if (attribute.type === 'media') {
filters[key] = convertAndSanitizeFilters(value, strapi.getModel('plugin::upload.file'));
}
// Dynamic Zones
else if (attribute.type === 'dynamiczone') {
removeOperator(key);
}
// Password attributes
else if (attribute.type === 'password') {
// Always remove password attributes from filters object
removeOperator(key);
}
// Scalar attributes
else {
filters[key] = convertAndSanitizeFilters(value, schema);
}
}
// Handle operators
else if (['$null', '$notNull'].includes(key)) {
filters[key] = parseType({ type: 'boolean', value: filters[key], forceCast: true });
} else if (isObject(value)) {
filters[key] = convertAndSanitizeFilters(value, schema);
}
// Remove empty objects & arrays
if (isPlainObject(filters[key]) && isEmpty(filters[key])) {
removeOperator(key);
}
}
return filters;
};
const convertPublicationStateParams = (type, params = {}, query = {}) => {
if (!type) {
return;
}
const { publicationState } = params;
if (!_.isNil(publicationState)) {
if (!contentTypesUtils.constants.DP_PUB_STATES.includes(publicationState)) {
throw new Error(
`Invalid publicationState. Expected one of 'preview','live' received: ${publicationState}.`
);
}
// NOTE: this is the query layer filters not the entity service filters
query.filters = ({ meta }) => {
if (publicationState === 'live' && has(PUBLISHED_AT_ATTRIBUTE, meta.attributes)) {
return { [PUBLISHED_AT_ATTRIBUTE]: { $notNull: true } };
}
};
}
};
module.exports = {
convertSortQueryParams,
convertStartQueryParams,
convertLimitQueryParams,
convertPopulateQueryParams,
convertFiltersQueryParams,
convertFieldsQueryParams,
convertPublicationStateParams,
};
| packages/core/utils/lib/convert-query-params.js | 1 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.9944955706596375,
0.03351089730858803,
0.0001658979308558628,
0.00017213058890774846,
0.15858997404575348
] |
{
"id": 3,
"code_window": [
" if (!targetSchema) {\n",
" return acc;\n",
" }\n",
"\n",
" return {\n",
" ...acc,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" const populateObject = convertNestedPopulate(subPopulate, targetSchema);\n",
"\n",
" if (!populateObject) {\n",
" return acc;\n",
" }\n",
"\n"
],
"file_path": "packages/core/utils/lib/convert-query-params.js",
"type": "add",
"edit_start_line_idx": 205
} | # @strapi/provider-email-nodemailer
## Resources
- [LICENSE](LICENSE)
## Links
- [Strapi website](https://strapi.io/)
- [Strapi documentation](https://docs.strapi.io)
- [Strapi community on Discord](https://discord.strapi.io)
- [Strapi news on Twitter](https://twitter.com/strapijs)
## Installation
```bash
# using yarn
yarn add @strapi/provider-email-nodemailer
# using npm
npm install @strapi/provider-email-nodemailer --save
```
## Example
**Path -** `config/plugins.js`
```js
module.exports = ({ env }) => ({
// ...
email: {
config: {
provider: 'nodemailer',
providerOptions: {
host: env('SMTP_HOST', 'smtp.example.com'),
port: env('SMTP_PORT', 587),
auth: {
user: env('SMTP_USERNAME'),
pass: env('SMTP_PASSWORD'),
},
// ... any custom nodemailer options
},
settings: {
defaultFrom: '[email protected]',
defaultReplyTo: '[email protected]',
},
},
},
// ...
});
```
Check out the available options for nodemailer: https://nodemailer.com/about/
### Development mode
You can override the default configurations for specific environments. E.g. for
`NODE_ENV=development` in **config/env/development/plugins.js**:
```js
module.exports = ({ env }) => ({
email: {
provider: 'nodemailer',
providerOptions: {
host: 'localhost',
port: 1025,
ignoreTLS: true,
},
},
});
```
The above setting is useful for local development with
[maildev](https://github.com/maildev/maildev).
### Custom authentication mechanisms
It is also possible to use custom authentication methods.
Here is an example for a NTLM authentication:
```js
const nodemailerNTLMAuth = require('nodemailer-ntlm-auth');
module.exports = ({ env }) => ({
email: {
provider: 'nodemailer',
providerOptions: {
host: env('SMTP_HOST', 'smtp.example.com'),
port: env('SMTP_PORT', 587),
auth: {
type: 'custom',
method: 'NTLM',
user: env('SMTP_USERNAME'),
pass: env('SMTP_PASSWORD'),
},
customAuth: {
NTLM: nodemailerNTLMAuth,
},
},
settings: {
defaultFrom: '[email protected]',
defaultReplyTo: '[email protected]',
},
},
});
```
## Usage
> :warning: The Shipper Email (or defaultfrom) may also need to be changed in the `Email Templates` tab on the admin panel for emails to send properly
To send an email from anywhere inside Strapi:
```js
await strapi
.plugin('email')
.service('email')
.send({
to: '[email protected]',
from: '[email protected]',
subject: 'Hello world',
text: 'Hello world',
html: `<h4>Hello world</h4>`,
});
```
The following fields are supported:
| Field | Description |
| ----------- | ----------------------------------------------------------------- |
| from | Email address of the sender |
| to | Comma separated list or an array of recipients |
| replyTo | Email address to which replies are sent |
| cc | Comma separated list or an array of recipients |
| bcc | Comma separated list or an array of recipients |
| subject | Subject of the email |
| text | Plaintext version of the message |
| html | HTML version of the message |
| attachments | Array of objects See: https://nodemailer.com/message/attachments/ |
## Troubleshooting
Check your firewall to ensure that requests are allowed. If it doesn't work with
```js
port: 465,
secure: true
```
try using
```js
port: 587,
secure: false
```
to test if it works correctly.
| packages/providers/email-nodemailer/README.md | 0 | https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d | [
0.00019549344142433256,
0.00017065202700905502,
0.00016368634533137083,
0.0001705149479676038,
0.000007007493422861444
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.