hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 2,
"code_window": [
"import { useRouteMatch, useHistory } from 'react-router-dom';\n",
"import { useQuery } from 'react-query';\n",
"import { useFetchClient } from '../../../../../hooks';\n",
"import { formatAPIErrors } from '../../../../../utils';\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 17
} | import React from 'react';
import { CheckPagePermissions } from '@strapi/helper-plugin';
import adminPermissions from '../../../../../permissions';
import ListPage from '../ListPage';
const ProtectedListPage = () => (
<CheckPagePermissions permissions={adminPermissions.settings.roles.main}>
<ListPage />
</CheckPagePermissions>
);
export default ProtectedListPage;
| packages/core/admin/admin/src/pages/SettingsPage/pages/Roles/ProtectedListPage/index.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017218578432220966,
0.00017207168275490403,
0.00017195756663568318,
0.00017207168275490403,
1.1410884326323867e-7
]
|
{
"id": 2,
"code_window": [
"import { useRouteMatch, useHistory } from 'react-router-dom';\n",
"import { useQuery } from 'react-query';\n",
"import { useFetchClient } from '../../../../../hooks';\n",
"import { formatAPIErrors } from '../../../../../utils';\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 17
} | 'use strict';
const { createCoreController } = require('@strapi/strapi').factories;
module.exports = createCoreController('api::tag.tag');
| examples/getstarted/src/api/tag/controllers/tag.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.000169849387020804,
0.000169849387020804,
0.000169849387020804,
0.000169849387020804,
0
]
|
{
"id": 3,
"code_window": [
"import { formatAPIErrors } from '../../../../../utils';\n",
"import { schema } from './utils';\n",
"import LoadingView from './components/LoadingView';\n",
"import FormHead from './components/FormHead';\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { axiosInstance } from '../../../../../core/utils';\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "add",
"edit_start_line_idx": 19
} | import React, { useEffect, useState, useRef, useReducer } from 'react';
import { useIntl } from 'react-intl';
import {
SettingsPageTitle,
useFocusWhenNavigate,
Form,
useOverlayBlocker,
useNotification,
useTracking,
useGuidedTour,
useRBAC,
} from '@strapi/helper-plugin';
import { Main } from '@strapi/design-system/Main';
import { Formik } from 'formik';
import { get as getProperty } from 'lodash';
import { useRouteMatch, useHistory } from 'react-router-dom';
import { useQuery } from 'react-query';
import { useFetchClient } from '../../../../../hooks';
import { formatAPIErrors } from '../../../../../utils';
import { schema } from './utils';
import LoadingView from './components/LoadingView';
import FormHead from './components/FormHead';
import FormBody from './components/FormBody';
import adminPermissions from '../../../../../permissions';
import { ApiTokenPermissionsContextProvider } from '../../../../../contexts/ApiTokenPermissions';
import init from './init';
import reducer, { initialState } from './reducer';
const MSG_ERROR_NAME_TAKEN = 'Name already taken';
const ApiTokenCreateView = () => {
const { get, post, put } = useFetchClient();
useFocusWhenNavigate();
const { formatMessage } = useIntl();
const { lockApp, unlockApp } = useOverlayBlocker();
const toggleNotification = useNotification();
const history = useHistory();
const [apiToken, setApiToken] = useState(
history.location.state?.apiToken.accessKey
? {
...history.location.state.apiToken,
}
: null
);
const { trackUsage } = useTracking();
const trackUsageRef = useRef(trackUsage);
const { setCurrentStep } = useGuidedTour();
const {
allowedActions: { canCreate, canUpdate, canRegenerate },
} = useRBAC(adminPermissions.settings['api-tokens']);
const [state, dispatch] = useReducer(reducer, initialState, (state) => init(state, {}));
const {
params: { id },
} = useRouteMatch('/settings/api-tokens/:id');
const isCreating = id === 'create';
useQuery(
'content-api-permissions',
async () => {
const [permissions, routes] = await Promise.all(
['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => {
const { data } = await get(url);
return data.data;
})
);
dispatch({
type: 'UPDATE_PERMISSIONS_LAYOUT',
value: permissions,
});
dispatch({
type: 'UPDATE_ROUTES',
value: routes,
});
if (apiToken) {
if (apiToken?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (apiToken?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (apiToken?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: apiToken?.permissions,
});
}
}
},
{
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
useEffect(() => {
trackUsageRef.current(isCreating ? 'didAddTokenFromList' : 'didEditTokenFromList');
}, [isCreating]);
const { status } = useQuery(
['api-token', id],
async () => {
const {
data: { data },
} = await get(`/admin/api-tokens/${id}`);
setApiToken({
...data,
});
if (data?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (data?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (data?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: data?.permissions,
});
}
return data;
},
{
enabled: !isCreating && !apiToken,
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
const handleSubmit = async (body, actions) => {
trackUsageRef.current(isCreating ? 'willCreateToken' : 'willEditToken');
lockApp();
const lifespanVal =
body.lifespan && parseInt(body.lifespan, 10) && body.lifespan !== '0'
? parseInt(body.lifespan, 10)
: null;
try {
const {
data: { data: response },
} = isCreating
? await post(`/admin/api-tokens`, {
...body,
lifespan: lifespanVal,
permissions: body.type === 'custom' ? state.selectedActions : null,
})
: await put(`/admin/api-tokens/${id}`, {
name: body.name,
description: body.description,
type: body.type,
permissions: body.type === 'custom' ? state.selectedActions : null,
});
if (isCreating) {
history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });
setCurrentStep('apiTokens.success');
}
unlockApp();
setApiToken({
...response,
});
toggleNotification({
type: 'success',
message: isCreating
? formatMessage({
id: 'notification.success.tokencreated',
defaultMessage: 'API Token successfully created',
})
: formatMessage({
id: 'notification.success.tokenedited',
defaultMessage: 'API Token successfully edited',
}),
});
trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {
type: apiToken.type,
});
} catch (err) {
const errors = formatAPIErrors(err.response.data);
actions.setErrors(errors);
if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) {
toggleNotification({
type: 'warning',
message: getProperty(
err,
'response.data.message',
'notification.error.tokennamenotunique'
),
});
} else {
toggleNotification({
type: 'warning',
message: getProperty(err, 'response.data.message', 'notification.error'),
});
}
unlockApp();
}
};
const [hasChangedPermissions, setHasChangedPermissions] = useState(false);
const handleChangeCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'ON_CHANGE',
value,
});
};
const handleChangeSelectAllCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'SELECT_ALL_IN_PERMISSION',
value,
});
};
const setSelectedAction = ({ target: { value } }) => {
dispatch({
type: 'SET_SELECTED_ACTION',
value,
});
};
const providerValue = {
...state,
onChange: handleChangeCheckbox,
onChangeSelectAll: handleChangeSelectAllCheckbox,
setSelectedAction,
};
const canEditInputs = (canUpdate && !isCreating) || (canCreate && isCreating);
const isLoading = !isCreating && !apiToken && status !== 'success';
if (isLoading) {
return <LoadingView apiTokenName={apiToken?.name} />;
}
return (
<ApiTokenPermissionsContextProvider value={providerValue}>
<Main>
<SettingsPageTitle name="API Tokens" />
<Formik
validationSchema={schema}
validateOnChange={false}
initialValues={{
name: apiToken?.name || '',
description: apiToken?.description || '',
type: apiToken?.type,
lifespan: apiToken?.lifespan ? apiToken.lifespan.toString() : apiToken?.lifespan,
}}
enableReinitialize
onSubmit={(body, actions) => handleSubmit(body, actions)}
>
{({ errors, handleChange, isSubmitting, values, setFieldValue }) => {
if (hasChangedPermissions && values?.type !== 'custom') {
setFieldValue('type', 'custom');
}
return (
<Form>
<FormHead
apiToken={apiToken}
setApiToken={setApiToken}
canEditInputs={canEditInputs}
canRegenerate={canRegenerate}
isSubmitting={isSubmitting}
/>
<FormBody
apiToken={apiToken}
errors={errors}
onChange={handleChange}
canEditInputs={canEditInputs}
isCreating={isCreating}
values={values}
onDispatch={dispatch}
setHasChangedPermissions={setHasChangedPermissions}
/>
</Form>
);
}}
</Formik>
</Main>
</ApiTokenPermissionsContextProvider>
);
};
export default ApiTokenCreateView;
| packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js | 1 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.004933725111186504,
0.0004187682643532753,
0.00016415963182225823,
0.00016845106438267976,
0.0008961076382547617
]
|
{
"id": 3,
"code_window": [
"import { formatAPIErrors } from '../../../../../utils';\n",
"import { schema } from './utils';\n",
"import LoadingView from './components/LoadingView';\n",
"import FormHead from './components/FormHead';\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { axiosInstance } from '../../../../../core/utils';\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "add",
"edit_start_line_idx": 19
} | 'use strict';
/* eslint-disable no-unused-vars */
module.exports = (config, webpack) => {
// Note: we provide webpack above so you should not `require` it
// Perform customizations to webpack config
// Important: return the modified config
return config;
};
| packages/generators/app/lib/resources/files/ts/src/admin/webpack.config.example.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.0001695325772743672,
0.0001695325772743672,
0.0001695325772743672,
0.0001695325772743672,
0
]
|
{
"id": 3,
"code_window": [
"import { formatAPIErrors } from '../../../../../utils';\n",
"import { schema } from './utils';\n",
"import LoadingView from './components/LoadingView';\n",
"import FormHead from './components/FormHead';\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { axiosInstance } from '../../../../../core/utils';\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "add",
"edit_start_line_idx": 19
} | /**
*
* DraftAndPublishToggle
*
*/
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { useIntl } from 'react-intl';
import { Dialog, DialogBody, DialogFooter } from '@strapi/design-system/Dialog';
import { ToggleInput } from '@strapi/design-system/ToggleInput';
import { Typography } from '@strapi/design-system/Typography';
import { Flex } from '@strapi/design-system/Flex';
import { Stack } from '@strapi/design-system/Stack';
import { Button } from '@strapi/design-system/Button';
import ExclamationMarkCircle from '@strapi/icons/ExclamationMarkCircle';
import { getTrad } from '../../utils';
const TypographyTextAlign = styled(Typography)`
text-align: center;
`;
const DraftAndPublishToggle = ({
description,
disabled,
intlLabel,
isCreating,
name,
onChange,
value,
}) => {
const { formatMessage } = useIntl();
const [showWarning, setShowWarning] = useState(false);
const label = intlLabel.id
? formatMessage(
{ id: intlLabel.id, defaultMessage: intlLabel.defaultMessage },
{ ...intlLabel.values }
)
: name;
const hint = description
? formatMessage(
{ id: description.id, defaultMessage: description.defaultMessage },
{ ...description.values }
)
: '';
const handleToggle = () => setShowWarning((prev) => !prev);
const handleConfirm = () => {
onChange({ target: { name, value: false } });
handleToggle();
};
const handleChange = ({ target: { checked } }) => {
if (!checked && !isCreating) {
handleToggle();
return;
}
onChange({ target: { name, value: checked } });
};
return (
<>
<ToggleInput
checked={value || false}
disabled={disabled}
hint={hint}
label={label}
name={name}
offLabel={formatMessage({
id: 'app.components.ToggleCheckbox.off-label',
defaultMessage: 'Off',
})}
onLabel={formatMessage({
id: 'app.components.ToggleCheckbox.on-label',
defaultMessage: 'On',
})}
onChange={handleChange}
/>
{showWarning && (
<Dialog onClose={handleToggle} title="Confirmation" isOpen={showWarning}>
<DialogBody icon={<ExclamationMarkCircle />}>
<Stack spacing={2}>
<Flex justifyContent="center">
<TypographyTextAlign id="confirm-description">
{formatMessage({
id: getTrad('popUpWarning.draft-publish.message'),
defaultMessage:
'If you disable the Draft/Publish system, your drafts will be deleted.',
})}
</TypographyTextAlign>
</Flex>
<Flex justifyContent="center">
<Typography id="confirm-description">
{formatMessage({
id: getTrad('popUpWarning.draft-publish.second-message'),
defaultMessage: 'Are you sure you want to disable it?',
})}
</Typography>
</Flex>
</Stack>
</DialogBody>
<DialogFooter
startAction={
<Button onClick={handleToggle} variant="tertiary">
{formatMessage({
id: 'components.popUpWarning.button.cancel',
defaultMessage: 'No, cancel',
})}
</Button>
}
endAction={
<Button variant="danger-light" onClick={handleConfirm}>
{formatMessage({
id: getTrad('popUpWarning.draft-publish.button.confirm'),
defaultMessage: 'Yes, disable',
})}
</Button>
}
/>
</Dialog>
)}
</>
);
};
DraftAndPublishToggle.defaultProps = {
description: null,
disabled: false,
value: false,
};
DraftAndPublishToggle.propTypes = {
description: PropTypes.shape({
id: PropTypes.string.isRequired,
defaultMessage: PropTypes.string.isRequired,
values: PropTypes.object,
}),
disabled: PropTypes.bool,
intlLabel: PropTypes.shape({
id: PropTypes.string.isRequired,
defaultMessage: PropTypes.string.isRequired,
values: PropTypes.object,
}).isRequired,
isCreating: PropTypes.bool.isRequired,
name: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
value: PropTypes.bool,
};
export default DraftAndPublishToggle;
| packages/core/content-type-builder/admin/src/components/DraftAndPublishToggle/index.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017361613572575152,
0.00016849106759764254,
0.00016328618221450597,
0.00016833608970046043,
0.0000028278718673391268
]
|
{
"id": 3,
"code_window": [
"import { formatAPIErrors } from '../../../../../utils';\n",
"import { schema } from './utils';\n",
"import LoadingView from './components/LoadingView';\n",
"import FormHead from './components/FormHead';\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { axiosInstance } from '../../../../../core/utils';\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "add",
"edit_start_line_idx": 19
} | 'use strict';
const { isFunction } = require('lodash/fp');
const { ApplicationError } = require('@strapi/utils').errors;
/**
* @typedef RegisteredTypeDef
*
* @property {string} name
* @property {NexusAcceptedTypeDef} definition
* @property {object} config
*/
/**
* Create a new type registry
*/
const createTypeRegistry = () => {
const registry = new Map();
return {
/**
* Register a new type definition
* @param {string} name The name of the type
* @param {NexusAcceptedTypeDef} definition The Nexus definition for the type
* @param {object} [config] An optional config object with any metadata inside
*/
register(name, definition, config = {}) {
if (registry.has(name)) {
throw new ApplicationError(`"${name}" has already been registered`);
}
registry.set(name, { name, definition, config });
return this;
},
/**
* Register many types definitions at once
* @param {[string, NexusAcceptedTypeDef][]} definitionsEntries
* @param {object | function} [config]
*/
registerMany(definitionsEntries, config = {}) {
for (const [name, definition] of definitionsEntries) {
this.register(name, definition, isFunction(config) ? config(name, definition) : config);
}
return this;
},
/**
* Check if the given type name has already been added to the registry
* @param {string} name
* @return {boolean}
*/
has(name) {
return registry.has(name);
},
/**
* Get the type definition for `name`
* @param {string} name - The name of the type
*/
get(name) {
return registry.get(name);
},
/**
* Transform and return the registry as an object
* @return {Object<string, RegisteredTypeDef>}
*/
toObject() {
return Object.fromEntries(registry.entries());
},
/**
* Return the name of every registered type
* @return {string[]}
*/
get types() {
return Array.from(registry.keys());
},
/**
* Return all the registered definitions as an array
* @return {RegisteredTypeDef[]}
*/
get definitions() {
return Array.from(registry.values());
},
/**
* Filter and return the types definitions that matches the given predicate
* @param {function(RegisteredTypeDef): boolean} predicate
* @return {RegisteredTypeDef[]}
*/
where(predicate) {
return this.definitions.filter(predicate);
},
};
};
module.exports = () => ({
new: createTypeRegistry,
});
| packages/plugins/graphql/server/services/type-registry.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017233361722901464,
0.00016850157408043742,
0.00016555281763430685,
0.0001686583855189383,
0.0000020395725641719764
]
|
{
"id": 4,
"code_window": [
"import reducer, { initialState } from './reducer';\n",
"\n",
"const MSG_ERROR_NAME_TAKEN = 'Name already taken';\n",
"\n",
"const ApiTokenCreateView = () => {\n",
" const { get, post, put } = useFetchClient();\n",
" useFocusWhenNavigate();\n",
" const { formatMessage } = useIntl();\n",
" const { lockApp, unlockApp } = useOverlayBlocker();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 31
} | import React, { useEffect, useState, useRef, useReducer } from 'react';
import { useIntl } from 'react-intl';
import {
SettingsPageTitle,
useFocusWhenNavigate,
Form,
useOverlayBlocker,
useNotification,
useTracking,
useGuidedTour,
useRBAC,
} from '@strapi/helper-plugin';
import { Main } from '@strapi/design-system/Main';
import { Formik } from 'formik';
import { get as getProperty } from 'lodash';
import { useRouteMatch, useHistory } from 'react-router-dom';
import { useQuery } from 'react-query';
import { useFetchClient } from '../../../../../hooks';
import { formatAPIErrors } from '../../../../../utils';
import { schema } from './utils';
import LoadingView from './components/LoadingView';
import FormHead from './components/FormHead';
import FormBody from './components/FormBody';
import adminPermissions from '../../../../../permissions';
import { ApiTokenPermissionsContextProvider } from '../../../../../contexts/ApiTokenPermissions';
import init from './init';
import reducer, { initialState } from './reducer';
const MSG_ERROR_NAME_TAKEN = 'Name already taken';
const ApiTokenCreateView = () => {
const { get, post, put } = useFetchClient();
useFocusWhenNavigate();
const { formatMessage } = useIntl();
const { lockApp, unlockApp } = useOverlayBlocker();
const toggleNotification = useNotification();
const history = useHistory();
const [apiToken, setApiToken] = useState(
history.location.state?.apiToken.accessKey
? {
...history.location.state.apiToken,
}
: null
);
const { trackUsage } = useTracking();
const trackUsageRef = useRef(trackUsage);
const { setCurrentStep } = useGuidedTour();
const {
allowedActions: { canCreate, canUpdate, canRegenerate },
} = useRBAC(adminPermissions.settings['api-tokens']);
const [state, dispatch] = useReducer(reducer, initialState, (state) => init(state, {}));
const {
params: { id },
} = useRouteMatch('/settings/api-tokens/:id');
const isCreating = id === 'create';
useQuery(
'content-api-permissions',
async () => {
const [permissions, routes] = await Promise.all(
['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => {
const { data } = await get(url);
return data.data;
})
);
dispatch({
type: 'UPDATE_PERMISSIONS_LAYOUT',
value: permissions,
});
dispatch({
type: 'UPDATE_ROUTES',
value: routes,
});
if (apiToken) {
if (apiToken?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (apiToken?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (apiToken?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: apiToken?.permissions,
});
}
}
},
{
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
useEffect(() => {
trackUsageRef.current(isCreating ? 'didAddTokenFromList' : 'didEditTokenFromList');
}, [isCreating]);
const { status } = useQuery(
['api-token', id],
async () => {
const {
data: { data },
} = await get(`/admin/api-tokens/${id}`);
setApiToken({
...data,
});
if (data?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (data?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (data?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: data?.permissions,
});
}
return data;
},
{
enabled: !isCreating && !apiToken,
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
const handleSubmit = async (body, actions) => {
trackUsageRef.current(isCreating ? 'willCreateToken' : 'willEditToken');
lockApp();
const lifespanVal =
body.lifespan && parseInt(body.lifespan, 10) && body.lifespan !== '0'
? parseInt(body.lifespan, 10)
: null;
try {
const {
data: { data: response },
} = isCreating
? await post(`/admin/api-tokens`, {
...body,
lifespan: lifespanVal,
permissions: body.type === 'custom' ? state.selectedActions : null,
})
: await put(`/admin/api-tokens/${id}`, {
name: body.name,
description: body.description,
type: body.type,
permissions: body.type === 'custom' ? state.selectedActions : null,
});
if (isCreating) {
history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });
setCurrentStep('apiTokens.success');
}
unlockApp();
setApiToken({
...response,
});
toggleNotification({
type: 'success',
message: isCreating
? formatMessage({
id: 'notification.success.tokencreated',
defaultMessage: 'API Token successfully created',
})
: formatMessage({
id: 'notification.success.tokenedited',
defaultMessage: 'API Token successfully edited',
}),
});
trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {
type: apiToken.type,
});
} catch (err) {
const errors = formatAPIErrors(err.response.data);
actions.setErrors(errors);
if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) {
toggleNotification({
type: 'warning',
message: getProperty(
err,
'response.data.message',
'notification.error.tokennamenotunique'
),
});
} else {
toggleNotification({
type: 'warning',
message: getProperty(err, 'response.data.message', 'notification.error'),
});
}
unlockApp();
}
};
const [hasChangedPermissions, setHasChangedPermissions] = useState(false);
const handleChangeCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'ON_CHANGE',
value,
});
};
const handleChangeSelectAllCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'SELECT_ALL_IN_PERMISSION',
value,
});
};
const setSelectedAction = ({ target: { value } }) => {
dispatch({
type: 'SET_SELECTED_ACTION',
value,
});
};
const providerValue = {
...state,
onChange: handleChangeCheckbox,
onChangeSelectAll: handleChangeSelectAllCheckbox,
setSelectedAction,
};
const canEditInputs = (canUpdate && !isCreating) || (canCreate && isCreating);
const isLoading = !isCreating && !apiToken && status !== 'success';
if (isLoading) {
return <LoadingView apiTokenName={apiToken?.name} />;
}
return (
<ApiTokenPermissionsContextProvider value={providerValue}>
<Main>
<SettingsPageTitle name="API Tokens" />
<Formik
validationSchema={schema}
validateOnChange={false}
initialValues={{
name: apiToken?.name || '',
description: apiToken?.description || '',
type: apiToken?.type,
lifespan: apiToken?.lifespan ? apiToken.lifespan.toString() : apiToken?.lifespan,
}}
enableReinitialize
onSubmit={(body, actions) => handleSubmit(body, actions)}
>
{({ errors, handleChange, isSubmitting, values, setFieldValue }) => {
if (hasChangedPermissions && values?.type !== 'custom') {
setFieldValue('type', 'custom');
}
return (
<Form>
<FormHead
apiToken={apiToken}
setApiToken={setApiToken}
canEditInputs={canEditInputs}
canRegenerate={canRegenerate}
isSubmitting={isSubmitting}
/>
<FormBody
apiToken={apiToken}
errors={errors}
onChange={handleChange}
canEditInputs={canEditInputs}
isCreating={isCreating}
values={values}
onDispatch={dispatch}
setHasChangedPermissions={setHasChangedPermissions}
/>
</Form>
);
}}
</Formik>
</Main>
</ApiTokenPermissionsContextProvider>
);
};
export default ApiTokenCreateView;
| packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js | 1 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.9989815354347229,
0.1627769023180008,
0.00016714117373339832,
0.00023562536807730794,
0.35625866055488586
]
|
{
"id": 4,
"code_window": [
"import reducer, { initialState } from './reducer';\n",
"\n",
"const MSG_ERROR_NAME_TAKEN = 'Name already taken';\n",
"\n",
"const ApiTokenCreateView = () => {\n",
" const { get, post, put } = useFetchClient();\n",
" useFocusWhenNavigate();\n",
" const { formatMessage } = useIntl();\n",
" const { lockApp, unlockApp } = useOverlayBlocker();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 31
} | 'use strict';
const { createTestBuilder } = require('../../../../../../test/helpers/builder');
const { createStrapiInstance } = require('../../../../../../test/helpers/strapi');
const { createAuthRequest } = require('../../../../../../test/helpers/request');
const builder = createTestBuilder();
let strapi;
let rq;
const ct = {
displayName: 'withpassword',
singularName: 'withpassword',
pluralName: 'withpasswords',
attributes: {
field: {
type: 'password',
},
},
};
describe('Test type password', () => {
beforeAll(async () => {
await builder.addContentType(ct).build();
strapi = await createStrapiInstance();
rq = await createAuthRequest({ strapi });
});
afterAll(async () => {
await strapi.destroy();
await builder.cleanup();
});
test('Create entry with value input JSON', async () => {
const res = await rq.post('/content-manager/collection-types/api::withpassword.withpassword', {
body: {
field: 'somePassword',
},
});
expect(res.statusCode).toBe(200);
expect(res.body.field).toBeUndefined();
});
test.todo('Should be private by default');
test('Create entry with value input Formdata', async () => {
const res = await rq.post('/content-manager/collection-types/api::withpassword.withpassword', {
body: {
field: '1234567',
},
});
expect(res.statusCode).toBe(200);
expect(res.body.field).toBeUndefined();
});
test('Reading entry returns correct value', async () => {
const res = await rq.get('/content-manager/collection-types/api::withpassword.withpassword');
expect(res.statusCode).toBe(200);
expect(Array.isArray(res.body.results)).toBe(true);
res.body.results.forEach((element) => {
expect(element.field).toBeUndefined();
});
});
test('Updating entry sets the right value and format', async () => {
const res = await rq.post('/content-manager/collection-types/api::withpassword.withpassword', {
body: {
field: 'somePassword',
},
});
const updateRes = await rq.put(
`/content-manager/collection-types/api::withpassword.withpassword/${res.body.id}`,
{
body: {
field: 'otherPwd',
},
}
);
expect(updateRes.statusCode).toBe(200);
expect(updateRes.body).toMatchObject({
id: res.body.id,
});
expect(res.body.field).toBeUndefined();
});
});
| packages/core/content-manager/server/tests/fields/password.test.api.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017617274716030806,
0.0001720339641906321,
0.00016595283523201942,
0.00017270285752601922,
0.0000032164598451345228
]
|
{
"id": 4,
"code_window": [
"import reducer, { initialState } from './reducer';\n",
"\n",
"const MSG_ERROR_NAME_TAKEN = 'Name already taken';\n",
"\n",
"const ApiTokenCreateView = () => {\n",
" const { get, post, put } = useFetchClient();\n",
" useFocusWhenNavigate();\n",
" const { formatMessage } = useIntl();\n",
" const { lockApp, unlockApp } = useOverlayBlocker();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 31
} | import { parseDate } from '../parseDate';
describe('parseDate', () => {
it('should return a date', () => {
expect(parseDate('2021-11-05T15:37:29.592Z') instanceof Date).toBeTruthy();
});
it('should return null if the passed params has not the right format', () => {
expect(parseDate('test')).toBeNull();
});
});
| packages/core/helper-plugin/lib/src/components/DateTimePicker/tests/parseDate.test.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017571926582604647,
0.00017506832955405116,
0.00017441737873014063,
0.00017506832955405116,
6.509435479529202e-7
]
|
{
"id": 4,
"code_window": [
"import reducer, { initialState } from './reducer';\n",
"\n",
"const MSG_ERROR_NAME_TAKEN = 'Name already taken';\n",
"\n",
"const ApiTokenCreateView = () => {\n",
" const { get, post, put } = useFetchClient();\n",
" useFocusWhenNavigate();\n",
" const { formatMessage } = useIntl();\n",
" const { lockApp, unlockApp } = useOverlayBlocker();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 31
} | 'use strict';
const { propEq } = require('lodash/fp');
module.exports = ({ strapi }) => {
/**
* Check if the given attribute is a Strapi scalar
* @param {object} attribute
* @return {boolean}
*/
const isStrapiScalar = (attribute) => {
return strapi.plugin('graphql').service('constants').STRAPI_SCALARS.includes(attribute.type);
};
/**
* Check if the given attribute is a GraphQL scalar
* @param {object} attribute
* @return {boolean}
*/
const isGraphQLScalar = (attribute) => {
return strapi.plugin('graphql').service('constants').GRAPHQL_SCALARS.includes(attribute.type);
};
/**
* Check if the given attribute is a polymorphic relation
* @param {object} attribute
* @return {boolean}
*/
const isMorphRelation = (attribute) => {
return isRelation(attribute) && attribute.relation.includes('morph');
};
/**
* Check if the given attribute is a media
* @param {object} attribute
* @return {boolean}
*/
const isMedia = propEq('type', 'media');
/**
* Check if the given attribute is a relation
* @param {object} attribute
* @return {boolean}
*/
const isRelation = propEq('type', 'relation');
/**
* Check if the given attribute is an enum
* @param {object} attribute
* @return {boolean}
*/
const isEnumeration = propEq('type', 'enumeration');
/**
* Check if the given attribute is a component
* @param {object} attribute
* @return {boolean}
*/
const isComponent = propEq('type', 'component');
/**
* Check if the given attribute is a dynamic zone
* @param {object} attribute
* @return {boolean}
*/
const isDynamicZone = propEq('type', 'dynamiczone');
return {
isStrapiScalar,
isGraphQLScalar,
isMorphRelation,
isMedia,
isRelation,
isEnumeration,
isComponent,
isDynamicZone,
};
};
| packages/plugins/graphql/server/services/utils/attributes.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017695844871923327,
0.00017467964789830148,
0.00017106237646657974,
0.00017451337771490216,
0.0000016665177327013225
]
|
{
"id": 5,
"code_window": [
" async () => {\n",
" const [permissions, routes] = await Promise.all(\n",
" ['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => {\n",
" const { data } = await get(url);\n",
"\n",
" return data.data;\n",
" })\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { data } = await axiosInstance.get(url);\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 62
} | import React, { useEffect, useState, useRef, useReducer } from 'react';
import { useIntl } from 'react-intl';
import {
SettingsPageTitle,
useFocusWhenNavigate,
Form,
useOverlayBlocker,
useNotification,
useTracking,
useGuidedTour,
useRBAC,
} from '@strapi/helper-plugin';
import { Main } from '@strapi/design-system/Main';
import { Formik } from 'formik';
import { get as getProperty } from 'lodash';
import { useRouteMatch, useHistory } from 'react-router-dom';
import { useQuery } from 'react-query';
import { useFetchClient } from '../../../../../hooks';
import { formatAPIErrors } from '../../../../../utils';
import { schema } from './utils';
import LoadingView from './components/LoadingView';
import FormHead from './components/FormHead';
import FormBody from './components/FormBody';
import adminPermissions from '../../../../../permissions';
import { ApiTokenPermissionsContextProvider } from '../../../../../contexts/ApiTokenPermissions';
import init from './init';
import reducer, { initialState } from './reducer';
const MSG_ERROR_NAME_TAKEN = 'Name already taken';
const ApiTokenCreateView = () => {
const { get, post, put } = useFetchClient();
useFocusWhenNavigate();
const { formatMessage } = useIntl();
const { lockApp, unlockApp } = useOverlayBlocker();
const toggleNotification = useNotification();
const history = useHistory();
const [apiToken, setApiToken] = useState(
history.location.state?.apiToken.accessKey
? {
...history.location.state.apiToken,
}
: null
);
const { trackUsage } = useTracking();
const trackUsageRef = useRef(trackUsage);
const { setCurrentStep } = useGuidedTour();
const {
allowedActions: { canCreate, canUpdate, canRegenerate },
} = useRBAC(adminPermissions.settings['api-tokens']);
const [state, dispatch] = useReducer(reducer, initialState, (state) => init(state, {}));
const {
params: { id },
} = useRouteMatch('/settings/api-tokens/:id');
const isCreating = id === 'create';
useQuery(
'content-api-permissions',
async () => {
const [permissions, routes] = await Promise.all(
['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => {
const { data } = await get(url);
return data.data;
})
);
dispatch({
type: 'UPDATE_PERMISSIONS_LAYOUT',
value: permissions,
});
dispatch({
type: 'UPDATE_ROUTES',
value: routes,
});
if (apiToken) {
if (apiToken?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (apiToken?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (apiToken?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: apiToken?.permissions,
});
}
}
},
{
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
useEffect(() => {
trackUsageRef.current(isCreating ? 'didAddTokenFromList' : 'didEditTokenFromList');
}, [isCreating]);
const { status } = useQuery(
['api-token', id],
async () => {
const {
data: { data },
} = await get(`/admin/api-tokens/${id}`);
setApiToken({
...data,
});
if (data?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (data?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (data?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: data?.permissions,
});
}
return data;
},
{
enabled: !isCreating && !apiToken,
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
const handleSubmit = async (body, actions) => {
trackUsageRef.current(isCreating ? 'willCreateToken' : 'willEditToken');
lockApp();
const lifespanVal =
body.lifespan && parseInt(body.lifespan, 10) && body.lifespan !== '0'
? parseInt(body.lifespan, 10)
: null;
try {
const {
data: { data: response },
} = isCreating
? await post(`/admin/api-tokens`, {
...body,
lifespan: lifespanVal,
permissions: body.type === 'custom' ? state.selectedActions : null,
})
: await put(`/admin/api-tokens/${id}`, {
name: body.name,
description: body.description,
type: body.type,
permissions: body.type === 'custom' ? state.selectedActions : null,
});
if (isCreating) {
history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });
setCurrentStep('apiTokens.success');
}
unlockApp();
setApiToken({
...response,
});
toggleNotification({
type: 'success',
message: isCreating
? formatMessage({
id: 'notification.success.tokencreated',
defaultMessage: 'API Token successfully created',
})
: formatMessage({
id: 'notification.success.tokenedited',
defaultMessage: 'API Token successfully edited',
}),
});
trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {
type: apiToken.type,
});
} catch (err) {
const errors = formatAPIErrors(err.response.data);
actions.setErrors(errors);
if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) {
toggleNotification({
type: 'warning',
message: getProperty(
err,
'response.data.message',
'notification.error.tokennamenotunique'
),
});
} else {
toggleNotification({
type: 'warning',
message: getProperty(err, 'response.data.message', 'notification.error'),
});
}
unlockApp();
}
};
const [hasChangedPermissions, setHasChangedPermissions] = useState(false);
const handleChangeCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'ON_CHANGE',
value,
});
};
const handleChangeSelectAllCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'SELECT_ALL_IN_PERMISSION',
value,
});
};
const setSelectedAction = ({ target: { value } }) => {
dispatch({
type: 'SET_SELECTED_ACTION',
value,
});
};
const providerValue = {
...state,
onChange: handleChangeCheckbox,
onChangeSelectAll: handleChangeSelectAllCheckbox,
setSelectedAction,
};
const canEditInputs = (canUpdate && !isCreating) || (canCreate && isCreating);
const isLoading = !isCreating && !apiToken && status !== 'success';
if (isLoading) {
return <LoadingView apiTokenName={apiToken?.name} />;
}
return (
<ApiTokenPermissionsContextProvider value={providerValue}>
<Main>
<SettingsPageTitle name="API Tokens" />
<Formik
validationSchema={schema}
validateOnChange={false}
initialValues={{
name: apiToken?.name || '',
description: apiToken?.description || '',
type: apiToken?.type,
lifespan: apiToken?.lifespan ? apiToken.lifespan.toString() : apiToken?.lifespan,
}}
enableReinitialize
onSubmit={(body, actions) => handleSubmit(body, actions)}
>
{({ errors, handleChange, isSubmitting, values, setFieldValue }) => {
if (hasChangedPermissions && values?.type !== 'custom') {
setFieldValue('type', 'custom');
}
return (
<Form>
<FormHead
apiToken={apiToken}
setApiToken={setApiToken}
canEditInputs={canEditInputs}
canRegenerate={canRegenerate}
isSubmitting={isSubmitting}
/>
<FormBody
apiToken={apiToken}
errors={errors}
onChange={handleChange}
canEditInputs={canEditInputs}
isCreating={isCreating}
values={values}
onDispatch={dispatch}
setHasChangedPermissions={setHasChangedPermissions}
/>
</Form>
);
}}
</Formik>
</Main>
</ApiTokenPermissionsContextProvider>
);
};
export default ApiTokenCreateView;
| packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js | 1 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.9983735084533691,
0.1158239096403122,
0.0001665001327637583,
0.00017349841073155403,
0.2914271354675293
]
|
{
"id": 5,
"code_window": [
" async () => {\n",
" const [permissions, routes] = await Promise.all(\n",
" ['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => {\n",
" const { data } = await get(url);\n",
"\n",
" return data.data;\n",
" })\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { data } = await axiosInstance.get(url);\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 62
} | 'use strict';
const { curry, pipe, merge, set, pick, omit, includes, isArray, prop } = require('lodash/fp');
/**
* Domain representation of an Action (RBAC)
* @typedef {Object} Action
* @property {string} actionId - The unique identifier of the action
* @property {string} section - The section linked to the action
* @property {string} displayName - The human readable name of an action
* @property {string} category - The main category of an action
* @property {string} [subCategory] - The secondary category of an action (only for settings and plugins section)
* @property {string} [pluginName] - The plugin which provide the action
* @property {string[]} [subjects] - A list of subjects on which the action can be applied
* @property {Object} options - The options of an action
* @property {string[]} options.applyToProperties - The list of properties that can be associated with an action
*/
/**
* Set of attributes used to create a new {@link Action} object
* @typedef {Action, { uid: string }} CreateActionPayload
*/
/**
* Return the default attributes of a new {@link Action}
* @return Partial<Action>
*/
const getDefaultActionAttributes = () => ({
options: {
applyToProperties: null,
},
});
/**
* Get the list of all the valid attributes of an {@link Action}
* @return {string[]}
*/
const actionFields = [
'section',
'displayName',
'category',
'subCategory',
'pluginName',
'subjects',
'options',
'actionId',
];
/**
* Remove unwanted attributes from an {@link Action}
* @type {function(action: Action | CreateActionPayload): Action}
*/
const sanitizeActionAttributes = pick(actionFields);
/**
* Create and return an identifier for an {@link CreateActionPayload}.
* The format is based on the action's source ({@link CreateActionPayload.pluginName} or 'application') and {@link CreateActionPayload.uid}.
* @param {CreateActionPayload} attributes
* @return {string}
*/
const computeActionId = (attributes) => {
const { pluginName, uid } = attributes;
if (!pluginName) {
return `api::${uid}`;
}
if (pluginName === 'admin') {
return `admin::${uid}`;
}
return `plugin::${pluginName}.${uid}`;
};
/**
* Assign an actionId attribute to an {@link CreateActionPayload} object
* @param {CreateActionPayload} attrs - Payload used to create an action
* @return {CreateActionPayload}
*/
const assignActionId = (attrs) => set('actionId', computeActionId(attrs), attrs);
/**
* Transform an action by adding or removing the {@link Action.subCategory} attribute
* @param {Action} action - The action to process
* @return {Action}
*/
const assignOrOmitSubCategory = (action) => {
const shouldHaveSubCategory = ['settings', 'plugins'].includes(action.section);
return shouldHaveSubCategory
? set('subCategory', action.subCategory || 'general', action)
: omit('subCategory', action);
};
/**
* Check if a property can be applied to an {@link Action}
* @type (function(property: string, action: Action): boolean) | (function(property: string): (function(action: Action): boolean))
* @return {boolean} Return true if the property can be applied for the given action
*/
const appliesToProperty = curry((property, action) => {
return pipe(prop('options.applyToProperties'), includes(property))(action);
});
/**
* Check if an action applies to a subject
* @param {string} subject
* @param {Action} action
* @return {boolean}
*/
const appliesToSubject = curry((subject, action) => {
return isArray(action.subjects) && includes(subject, action.subjects);
});
/**
* Transform the given attributes into a domain representation of an Action
* @type (function(payload: CreateActionPayload): Action)
* @param {CreateActionPayload} payload - The action payload containing the attributes needed to create an {@link Action}
* @return {Action} A newly created {@link Action}
*/
const create = pipe(
// Create and assign an action identifier to the action
// (need to be done before the sanitizeActionAttributes since we need the uid here)
assignActionId,
// Add or remove the sub category field based on the pluginName attribute
assignOrOmitSubCategory,
// Remove unwanted attributes from the payload
sanitizeActionAttributes,
// Complete the action creation by adding default values for some attributes
merge(getDefaultActionAttributes())
);
module.exports = {
actionFields,
appliesToProperty,
appliesToSubject,
assignActionId,
assignOrOmitSubCategory,
create,
computeActionId,
getDefaultActionAttributes,
sanitizeActionAttributes,
};
| packages/core/admin/server/domain/action/index.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.0006150059634819627,
0.00020010983280371875,
0.00016520243661943823,
0.00017094187205657363,
0.00011092417116742581
]
|
{
"id": 5,
"code_window": [
" async () => {\n",
" const [permissions, routes] = await Promise.all(\n",
" ['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => {\n",
" const { data } = await get(url);\n",
"\n",
" return data.data;\n",
" })\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { data } = await axiosInstance.get(url);\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 62
} | 'use strict';
const { curry } = require('lodash/fp');
const pipeAsync = require('../pipe-async');
const traverseEntity = require('../traverse-entity');
const { removePassword, removePrivate } = require('./visitors');
const sanitizePasswords = curry((schema, entity) => {
return traverseEntity(removePassword, { schema }, entity);
});
const sanitizePrivates = curry((schema, entity) => {
return traverseEntity(removePrivate, { schema }, entity);
});
const defaultSanitizeOutput = curry((schema, entity) => {
return pipeAsync(sanitizePrivates(schema), sanitizePasswords(schema))(entity);
});
module.exports = {
sanitizePasswords,
sanitizePrivates,
defaultSanitizeOutput,
};
| packages/core/utils/lib/sanitize/sanitizers.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017575731908436865,
0.00017155497334897518,
0.00016940024215728045,
0.00016950737335719168,
0.0000029718255518673686
]
|
{
"id": 5,
"code_window": [
" async () => {\n",
" const [permissions, routes] = await Promise.all(\n",
" ['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => {\n",
" const { data } = await get(url);\n",
"\n",
" return data.data;\n",
" })\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { data } = await axiosInstance.get(url);\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 62
} | 'use strict';
// Adapted from https://github.com/tleunen/babel-plugin-module-resolver/blob/master/src/resolvePath.js
const path = require('path');
const normalizeOptions = require('./normalizeOptions');
const mapToRelative = require('./mapToRelative');
const { nodeResolvePath, replaceExtension, toLocalPath, toPosixPath } = require('./utils');
function getRelativePath(sourcePath, currentFile, absFileInRoot, opts) {
const realSourceFileExtension = path.extname(absFileInRoot);
const sourceFileExtension = path.extname(sourcePath);
let relativePath = mapToRelative(opts.cwd, currentFile, absFileInRoot);
if (realSourceFileExtension !== sourceFileExtension) {
relativePath = replaceExtension(relativePath, opts);
}
return toLocalPath(toPosixPath(relativePath));
}
function findPathInRoots(sourcePath, { extensions, roots }) {
// Search the source path inside every custom root directory
const resolvedEESourceFile = nodeResolvePath(
`./${sourcePath.replace('ee_else_ce', '')}`,
roots.eeRoot,
extensions
);
const resolvedCESourceFile = nodeResolvePath(
`./${sourcePath.replace('ee_else_ce', '')}`,
roots.ceRoot,
extensions
);
return { resolvedEESourceFile, resolvedCESourceFile };
}
function resolvePathFromRootConfig(sourcePath, currentFile, opts) {
const absFileInRoot = findPathInRoots(sourcePath, opts);
const relativeEEPath = getRelativePath(
sourcePath,
currentFile,
absFileInRoot.resolvedEESourceFile,
opts
);
const relativeCEPath = getRelativePath(
sourcePath,
currentFile,
absFileInRoot.resolvedCESourceFile,
opts
);
return { relativeCEPath, relativeEEPath };
}
function resolvePath(sourcePath, currentFile, opts) {
const normalizedOpts = normalizeOptions(currentFile, opts);
// File param is a relative path from the environment current working directory
// (not from cwd param)
const absoluteCurrentFile = path.resolve(currentFile);
const resolvedPaths = resolvePathFromRootConfig(sourcePath, absoluteCurrentFile, normalizedOpts);
return resolvedPaths;
}
module.exports = resolvePath;
| packages/utils/babel-plugin-switch-ee-ce/lib/resolvePath.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017656154523137957,
0.00017486837168689817,
0.00017192559607792646,
0.0001753336691763252,
0.0000015352717355199275
]
|
{
"id": 6,
"code_window": [
" const { status } = useQuery(\n",
" ['api-token', id],\n",
" async () => {\n",
" const {\n",
" data: { data },\n",
" } = await get(`/admin/api-tokens/${id}`);\n",
"\n",
" setApiToken({\n",
" ...data,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" } = await axiosInstance.get(`/admin/api-tokens/${id}`);\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 116
} | import { useEffect, useRef } from 'react';
import { getFetchClient } from '../../utils/getFetchClient';
const cancelToken = () => {
const controller = new AbortController();
return controller;
};
const useFetchClient = () => {
const controller = useRef(null);
if (controller.current === null) {
controller.current = cancelToken();
}
useEffect(() => {
return () => {
// when unmount cancel the axios request
controller.current.abort();
};
}, []);
const defaultOptions = {
signal: controller.current.signal,
};
return getFetchClient(defaultOptions);
};
export default useFetchClient;
| packages/core/admin/admin/src/hooks/useFetchClient/index.js | 1 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017748416576068848,
0.00017234277038369328,
0.00016954343300312757,
0.0001711717341095209,
0.0000030912510737834964
]
|
{
"id": 6,
"code_window": [
" const { status } = useQuery(\n",
" ['api-token', id],\n",
" async () => {\n",
" const {\n",
" data: { data },\n",
" } = await get(`/admin/api-tokens/${id}`);\n",
"\n",
" setApiToken({\n",
" ...data,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" } = await axiosInstance.get(`/admin/api-tokens/${id}`);\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 116
} | 16
| .nvmrc | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.0001741468586260453,
0.0001741468586260453,
0.0001741468586260453,
0.0001741468586260453,
0
]
|
{
"id": 6,
"code_window": [
" const { status } = useQuery(\n",
" ['api-token', id],\n",
" async () => {\n",
" const {\n",
" data: { data },\n",
" } = await get(`/admin/api-tokens/${id}`);\n",
"\n",
" setApiToken({\n",
" ...data,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" } = await axiosInstance.get(`/admin/api-tokens/${id}`);\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 116
} | const data = {
contentTypesPermissions: {
'plugin::users-permissions.user': {
conditions: [],
attributes: {
email: {
actions: [
'plugin::content-manager.explorer.create',
'plugin::content-manager.explorer.update',
],
},
firstname: {
actions: [
'plugin::content-manager.explorer.create',
'plugin::content-manager.explorer.update',
],
},
lastname: {
actions: [
'plugin::content-manager.explorer.create',
'plugin::content-manager.explorer.update',
],
},
'role.data.name': {
actions: ['plugin::content-manager.explorer.read'],
},
roles: {
actions: ['plugin::content-manager.explorer.create'],
},
},
},
'api::category.category': {
conditions: {
'plugin::content-manager.explorer.delete': ['is_creator'],
'plugin::content-manager.explorer.read': ['is_someone', 'is_someone_else'],
},
contentTypeActions: {
'plugin::content-manager.explorer.delete': true,
},
attributes: {
name: {
actions: ['plugin::content-manager.explorer.read'],
},
addresses: {
actions: ['plugin::content-manager.explorer.read'],
},
postal_code: {
actions: ['plugin::content-manager.explorer.update'],
},
},
},
},
pluginsAndSettingsPermissions: [
{
action: 'plugin::upload.assets.update',
conditions: ['admin::is-creator'],
fields: null,
subject: null,
},
{
action: 'plugin::upload.assets.create',
conditions: [],
fields: null,
subject: null,
},
],
};
export default data;
| packages/core/admin/admin/src/utils/tests/data.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.0021052502561360598,
0.00048231054097414017,
0.0001668609183980152,
0.0001712046650936827,
0.0006654205499216914
]
|
{
"id": 6,
"code_window": [
" const { status } = useQuery(\n",
" ['api-token', id],\n",
" async () => {\n",
" const {\n",
" data: { data },\n",
" } = await get(`/admin/api-tokens/${id}`);\n",
"\n",
" setApiToken({\n",
" ...data,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" } = await axiosInstance.get(`/admin/api-tokens/${id}`);\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 116
} | import React, { memo, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import get from 'lodash/get';
import upperFirst from 'lodash/upperFirst';
import { useIntl } from 'react-intl';
import styled from 'styled-components';
import { BaseCheckbox } from '@strapi/design-system/BaseCheckbox';
import { Box } from '@strapi/design-system/Box';
import { Flex } from '@strapi/design-system/Flex';
import { Typography } from '@strapi/design-system/Typography';
import IS_DISABLED from 'ee_else_ce/pages/SettingsPage/pages/Roles/EditPage/components/ContentTypeCollapse/CollapsePropertyMatrix/SubActionRow/utils/constants';
import { usePermissionsDataManager } from '../../../../../../../../../hooks';
import CollapseLabel from '../../../CollapseLabel';
import Curve from '../../../Curve';
import HiddenAction from '../../../HiddenAction';
import { cellWidth, rowHeight } from '../../../Permissions/utils/constants';
import RequiredSign from '../../../RequiredSign';
import { getCheckboxState } from '../../../utils';
import { activeStyle } from '../../utils';
import CarretIcon from '../CarretIcon';
const Cell = styled(Flex)`
width: ${cellWidth};
position: relative;
`;
const RowWrapper = styled(Flex)`
height: ${rowHeight};
`;
const Wrapper = styled(Box)`
padding-left: ${31 / 16}rem;
`;
const LeftBorderTimeline = styled(Box)`
border-left: ${({ isVisible, theme }) =>
isVisible ? `4px solid ${theme.colors.primary200}` : '4px solid transparent'};
`;
const RowStyle = styled(Flex)`
padding-left: ${({ theme }) => theme.spaces[4]};
width: ${({ level }) => 145 - level * 36}px;
${({ isCollapsable, theme }) =>
isCollapsable &&
`
${CarretIcon} {
display: block;
color: ${theme.colors.neutral100};
}
&:hover {
${activeStyle(theme)}
}
`}
${({ isActive, theme }) => isActive && activeStyle(theme)};
`;
const TopTimeline = styled.div`
padding-top: ${({ theme }) => theme.spaces[2]};
margin-top: ${({ theme }) => theme.spaces[2]};
width: ${4 / 16}rem;
background-color: ${({ theme }) => theme.colors.primary200};
border-top-left-radius: 2px;
border-top-right-radius: 2px;
`;
const SubActionRow = ({
childrenForm,
isFormDisabled,
recursiveLevel,
pathToDataFromActionRow,
propertyActions,
parentName,
propertyName,
}) => {
const { formatMessage } = useIntl();
const { modifiedData, onChangeParentCheckbox, onChangeSimpleCheckbox } =
usePermissionsDataManager();
const [rowToOpen, setRowToOpen] = useState(null);
const handleClickToggleSubLevel = (name) => {
setRowToOpen((prev) => {
if (prev === name) {
return null;
}
return name;
});
};
const displayedRecursiveChildren = useMemo(() => {
if (!rowToOpen) {
return null;
}
return childrenForm.find(({ value }) => value === rowToOpen);
}, [rowToOpen, childrenForm]);
return (
<Wrapper>
<TopTimeline />
{childrenForm.map(({ label, value, required, children: subChildrenForm }, index) => {
const isVisible = index + 1 < childrenForm.length;
const isArrayType = Array.isArray(subChildrenForm);
const isActive = rowToOpen === value;
return (
<LeftBorderTimeline key={value} isVisible={isVisible}>
<RowWrapper>
<Curve color="primary200" />
<Flex style={{ flex: 1 }}>
<RowStyle level={recursiveLevel} isActive={isActive} isCollapsable={isArrayType}>
<CollapseLabel
alignItems="center"
isCollapsable={isArrayType}
{...(isArrayType && {
onClick: () => handleClickToggleSubLevel(value),
'aria-expanded': isActive,
onKeyDown: ({ key }) =>
(key === 'Enter' || key === ' ') && handleClickToggleSubLevel(value),
tabIndex: 0,
role: 'button',
})}
title={label}
>
<Typography ellipsis>{upperFirst(label)}</Typography>
{required && <RequiredSign />}
<CarretIcon $isActive={isActive} />
</CollapseLabel>
</RowStyle>
<Flex style={{ flex: 1 }}>
{propertyActions.map(
({ actionId, label: propertyLabel, isActionRelatedToCurrentProperty }) => {
if (!isActionRelatedToCurrentProperty) {
return <HiddenAction key={actionId} />;
}
/*
* Usually we use a 'dot' in order to know the key path of an object for which we want to change the value.
* Since an action and a subject are both separated by '.' or '::' we chose to use the '..' separators
*/
const checkboxName = [
...pathToDataFromActionRow.split('..'),
actionId,
'properties',
propertyName,
...parentName.split('..'),
value,
];
const checkboxValue = get(modifiedData, checkboxName, false);
if (!subChildrenForm) {
return (
<Cell key={propertyLabel} justifyContent="center" alignItems="center">
<BaseCheckbox
disabled={isFormDisabled || IS_DISABLED}
name={checkboxName.join('..')}
aria-label={formatMessage(
{
id: `Settings.permissions.select-by-permission`,
defaultMessage: 'Select {label} permission',
},
{ label: `${parentName} ${label} ${propertyLabel}` }
)}
// Keep same signature as packages/core/admin/admin/src/components/Roles/Permissions/index.js l.91
onValueChange={(value) => {
onChangeSimpleCheckbox({
target: {
name: checkboxName.join('..'),
value,
},
});
}}
value={checkboxValue}
/>
</Cell>
);
}
const { hasAllActionsSelected, hasSomeActionsSelected } =
getCheckboxState(checkboxValue);
return (
<Cell key={propertyLabel} justifyContent="center" alignItems="center">
<BaseCheckbox
key={propertyLabel}
disabled={isFormDisabled || IS_DISABLED}
name={checkboxName.join('..')}
aria-label={formatMessage(
{
id: `Settings.permissions.select-by-permission`,
defaultMessage: 'Select {label} permission',
},
{ label: `${parentName} ${label} ${propertyLabel}` }
)}
// Keep same signature as packages/core/admin/admin/src/components/Roles/Permissions/index.js l.91
onValueChange={(value) => {
onChangeParentCheckbox({
target: {
name: checkboxName.join('..'),
value,
},
});
}}
value={hasAllActionsSelected}
indeterminate={hasSomeActionsSelected}
/>
</Cell>
);
}
)}
</Flex>
</Flex>
</RowWrapper>
{displayedRecursiveChildren && isActive && (
<Box paddingBottom={2}>
<SubActionRow
isFormDisabled={isFormDisabled}
parentName={`${parentName}..${value}`}
pathToDataFromActionRow={pathToDataFromActionRow}
propertyActions={propertyActions}
propertyName={propertyName}
recursiveLevel={recursiveLevel + 1}
childrenForm={displayedRecursiveChildren.children}
/>
</Box>
)}
</LeftBorderTimeline>
);
})}
</Wrapper>
);
};
SubActionRow.propTypes = {
childrenForm: PropTypes.array.isRequired,
isFormDisabled: PropTypes.bool.isRequired,
parentName: PropTypes.string.isRequired,
pathToDataFromActionRow: PropTypes.string.isRequired,
propertyActions: PropTypes.array.isRequired,
propertyName: PropTypes.string.isRequired,
recursiveLevel: PropTypes.number.isRequired,
};
export default memo(SubActionRow);
| packages/core/admin/admin/src/pages/SettingsPage/pages/Roles/EditPage/components/ContentTypeCollapse/CollapsePropertyMatrix/SubActionRow/index.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00042127096094191074,
0.00019573741883505136,
0.0001676413812674582,
0.0001722033484838903,
0.00006680082879029214
]
|
{
"id": 7,
"code_window": [
"\n",
" try {\n",
" const {\n",
" data: { data: response },\n",
" } = isCreating\n",
" ? await post(`/admin/api-tokens`, {\n",
" ...body,\n",
" lifespan: lifespanVal,\n",
" permissions: body.type === 'custom' ? state.selectedActions : null,\n",
" })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ? await axiosInstance.post(`/admin/api-tokens`, {\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 164
} | import React, { useEffect, useState, useRef, useReducer } from 'react';
import { useIntl } from 'react-intl';
import {
SettingsPageTitle,
useFocusWhenNavigate,
Form,
useOverlayBlocker,
useNotification,
useTracking,
useGuidedTour,
useRBAC,
} from '@strapi/helper-plugin';
import { Main } from '@strapi/design-system/Main';
import { Formik } from 'formik';
import { get as getProperty } from 'lodash';
import { useRouteMatch, useHistory } from 'react-router-dom';
import { useQuery } from 'react-query';
import { useFetchClient } from '../../../../../hooks';
import { formatAPIErrors } from '../../../../../utils';
import { schema } from './utils';
import LoadingView from './components/LoadingView';
import FormHead from './components/FormHead';
import FormBody from './components/FormBody';
import adminPermissions from '../../../../../permissions';
import { ApiTokenPermissionsContextProvider } from '../../../../../contexts/ApiTokenPermissions';
import init from './init';
import reducer, { initialState } from './reducer';
const MSG_ERROR_NAME_TAKEN = 'Name already taken';
const ApiTokenCreateView = () => {
const { get, post, put } = useFetchClient();
useFocusWhenNavigate();
const { formatMessage } = useIntl();
const { lockApp, unlockApp } = useOverlayBlocker();
const toggleNotification = useNotification();
const history = useHistory();
const [apiToken, setApiToken] = useState(
history.location.state?.apiToken.accessKey
? {
...history.location.state.apiToken,
}
: null
);
const { trackUsage } = useTracking();
const trackUsageRef = useRef(trackUsage);
const { setCurrentStep } = useGuidedTour();
const {
allowedActions: { canCreate, canUpdate, canRegenerate },
} = useRBAC(adminPermissions.settings['api-tokens']);
const [state, dispatch] = useReducer(reducer, initialState, (state) => init(state, {}));
const {
params: { id },
} = useRouteMatch('/settings/api-tokens/:id');
const isCreating = id === 'create';
useQuery(
'content-api-permissions',
async () => {
const [permissions, routes] = await Promise.all(
['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => {
const { data } = await get(url);
return data.data;
})
);
dispatch({
type: 'UPDATE_PERMISSIONS_LAYOUT',
value: permissions,
});
dispatch({
type: 'UPDATE_ROUTES',
value: routes,
});
if (apiToken) {
if (apiToken?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (apiToken?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (apiToken?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: apiToken?.permissions,
});
}
}
},
{
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
useEffect(() => {
trackUsageRef.current(isCreating ? 'didAddTokenFromList' : 'didEditTokenFromList');
}, [isCreating]);
const { status } = useQuery(
['api-token', id],
async () => {
const {
data: { data },
} = await get(`/admin/api-tokens/${id}`);
setApiToken({
...data,
});
if (data?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (data?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (data?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: data?.permissions,
});
}
return data;
},
{
enabled: !isCreating && !apiToken,
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
const handleSubmit = async (body, actions) => {
trackUsageRef.current(isCreating ? 'willCreateToken' : 'willEditToken');
lockApp();
const lifespanVal =
body.lifespan && parseInt(body.lifespan, 10) && body.lifespan !== '0'
? parseInt(body.lifespan, 10)
: null;
try {
const {
data: { data: response },
} = isCreating
? await post(`/admin/api-tokens`, {
...body,
lifespan: lifespanVal,
permissions: body.type === 'custom' ? state.selectedActions : null,
})
: await put(`/admin/api-tokens/${id}`, {
name: body.name,
description: body.description,
type: body.type,
permissions: body.type === 'custom' ? state.selectedActions : null,
});
if (isCreating) {
history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });
setCurrentStep('apiTokens.success');
}
unlockApp();
setApiToken({
...response,
});
toggleNotification({
type: 'success',
message: isCreating
? formatMessage({
id: 'notification.success.tokencreated',
defaultMessage: 'API Token successfully created',
})
: formatMessage({
id: 'notification.success.tokenedited',
defaultMessage: 'API Token successfully edited',
}),
});
trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {
type: apiToken.type,
});
} catch (err) {
const errors = formatAPIErrors(err.response.data);
actions.setErrors(errors);
if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) {
toggleNotification({
type: 'warning',
message: getProperty(
err,
'response.data.message',
'notification.error.tokennamenotunique'
),
});
} else {
toggleNotification({
type: 'warning',
message: getProperty(err, 'response.data.message', 'notification.error'),
});
}
unlockApp();
}
};
const [hasChangedPermissions, setHasChangedPermissions] = useState(false);
const handleChangeCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'ON_CHANGE',
value,
});
};
const handleChangeSelectAllCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'SELECT_ALL_IN_PERMISSION',
value,
});
};
const setSelectedAction = ({ target: { value } }) => {
dispatch({
type: 'SET_SELECTED_ACTION',
value,
});
};
const providerValue = {
...state,
onChange: handleChangeCheckbox,
onChangeSelectAll: handleChangeSelectAllCheckbox,
setSelectedAction,
};
const canEditInputs = (canUpdate && !isCreating) || (canCreate && isCreating);
const isLoading = !isCreating && !apiToken && status !== 'success';
if (isLoading) {
return <LoadingView apiTokenName={apiToken?.name} />;
}
return (
<ApiTokenPermissionsContextProvider value={providerValue}>
<Main>
<SettingsPageTitle name="API Tokens" />
<Formik
validationSchema={schema}
validateOnChange={false}
initialValues={{
name: apiToken?.name || '',
description: apiToken?.description || '',
type: apiToken?.type,
lifespan: apiToken?.lifespan ? apiToken.lifespan.toString() : apiToken?.lifespan,
}}
enableReinitialize
onSubmit={(body, actions) => handleSubmit(body, actions)}
>
{({ errors, handleChange, isSubmitting, values, setFieldValue }) => {
if (hasChangedPermissions && values?.type !== 'custom') {
setFieldValue('type', 'custom');
}
return (
<Form>
<FormHead
apiToken={apiToken}
setApiToken={setApiToken}
canEditInputs={canEditInputs}
canRegenerate={canRegenerate}
isSubmitting={isSubmitting}
/>
<FormBody
apiToken={apiToken}
errors={errors}
onChange={handleChange}
canEditInputs={canEditInputs}
isCreating={isCreating}
values={values}
onDispatch={dispatch}
setHasChangedPermissions={setHasChangedPermissions}
/>
</Form>
);
}}
</Formik>
</Main>
</ApiTokenPermissionsContextProvider>
);
};
export default ApiTokenCreateView;
| packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js | 1 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.998052716255188,
0.032262079417705536,
0.0001634134241612628,
0.00017519730317872018,
0.17347383499145508
]
|
{
"id": 7,
"code_window": [
"\n",
" try {\n",
" const {\n",
" data: { data: response },\n",
" } = isCreating\n",
" ? await post(`/admin/api-tokens`, {\n",
" ...body,\n",
" lifespan: lifespanVal,\n",
" permissions: body.type === 'custom' ? state.selectedActions : null,\n",
" })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ? await axiosInstance.post(`/admin/api-tokens`, {\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 164
} | import { merge, get, isEmpty, set } from 'lodash';
import findMatchingPermission from './findMatchingPermissions';
/**
* Creates the default condition form: { [conditionId]: false }
* @param {object} conditions.id Id of the condition
* @returns {object}
*/
const createDefaultConditionsForm = (conditions, initialConditions = []) =>
conditions.reduce((acc, current) => {
acc[current.id] = initialConditions.indexOf(current.id) !== -1;
return acc;
}, {});
/**
* Create the default form a property (fields, locales) with all the values
* set to false
* @param {object} property.children ex: {children: [{value: 'foo',}]}
* @param {array<string>} The found property values retrieved from the role associated permissions
* @returns {object} ex: { foo: false }
*
*/
const createDefaultPropertyForms = ({ children }, propertyValues, prefix = '') => {
return children.reduce((acc, current) => {
if (current.children) {
return {
...acc,
[current.value]: createDefaultPropertyForms(
current,
propertyValues,
`${prefix}${current.value}.`
),
};
}
const hasProperty = propertyValues.indexOf(`${prefix}${current.value}`) !== -1;
acc[current.value] = hasProperty;
return acc;
}, {});
};
/**
* Creates the default form for all the properties found in a content type's layout
* @param {array<string>} propertiesArray ex; ['fields', 'locales']
* @param {object} ctLayout layout of the content type ex:
* ctLayout = {
* properties: [{
* value: 'fields',
* children: [{value: 'name'}]
* }
* }
* @returns {object} In this case it will return { fields: { name: false } }
*/
const createDefaultPropertiesForm = (propertiesArray, ctLayout, matchingPermission) => {
return propertiesArray.reduce(
(acc, currentPropertyName) => {
const foundProperty = ctLayout.properties.find(({ value }) => value === currentPropertyName);
if (foundProperty) {
const matchingPermissionPropertyValues = get(
matchingPermission,
['properties', foundProperty.value],
[]
);
const propertyForm = createDefaultPropertyForms(
foundProperty,
matchingPermissionPropertyValues
);
acc.properties[currentPropertyName] = propertyForm;
}
return acc;
},
{ properties: {} }
);
};
/**
* Return an object of content types layout of an action's subject ex: { adress: {uid, label, properties } }
* @param {array<object>} allLayouts All the content types' layout
* @param {object} subjects
*/
const findLayouts = (allLayouts, subjects) => {
return subjects.reduce((acc, current) => {
const foundLayout = allLayouts.find(({ uid }) => uid === current) || null;
if (foundLayout) {
acc[current] = foundLayout;
}
return acc;
}, {});
};
/**
* Creates the default for for a content type
* @param {object} layout.subjects All the content types to display
* @param {array<object>} actionArray An action has the following shape:
* action = {label: 'string', actionId: 'string', subjects: [object], applyToProperties: ['string]}
* @param {array<object>} conditionArray Ex: { id: 'string', category: 'string' }
* @returns {object} Ex:
* {
* ctUId: {
* [actionId]: {
* [propertyName]: { enabled: false, conditions: { [id]: false } }
* }
* }
* }
*/
const createDefaultCTFormFromLayout = (
{ subjects },
actionArray,
conditionArray,
initialPermissions = []
) => {
return actionArray.reduce((defaultForm, current) => {
const actionSubjects = current.subjects;
const subjectLayouts = findLayouts(subjects, actionSubjects);
// This can happen when an action is not related to a content type
// for instance the D&P permission is applied only with the cts that
// have the D&P features enabled
if (isEmpty(subjectLayouts)) {
return defaultForm;
}
// The object has the following shape: { [ctUID]: { [actionId]: { [property]: { enabled: false } } } }
const contentTypesActions = Object.keys(subjectLayouts).reduce((acc, currentCTUID) => {
const { actionId, applyToProperties } = current;
const currentSubjectLayout = subjectLayouts[currentCTUID];
const properties = currentSubjectLayout.properties.map(({ value }) => value);
const doesNothaveProperty = properties.every(
(property) => (applyToProperties || []).indexOf(property) === -1
);
const matchingPermission = findMatchingPermission(initialPermissions, actionId, currentCTUID);
const conditionsForm = createDefaultConditionsForm(
conditionArray,
get(matchingPermission, 'conditions', [])
);
if (isEmpty(applyToProperties) || doesNothaveProperty) {
set(acc, [currentCTUID, actionId], {
properties: {
enabled: matchingPermission !== undefined,
},
conditions: conditionsForm,
});
return acc;
}
const propertiesForm = createDefaultPropertiesForm(
applyToProperties,
subjectLayouts[currentCTUID],
matchingPermission
);
set(acc, [currentCTUID, actionId], { ...propertiesForm, conditions: conditionsForm });
return acc;
}, {});
return merge(defaultForm, contentTypesActions);
}, {});
};
export default createDefaultCTFormFromLayout;
export {
createDefaultConditionsForm,
createDefaultPropertyForms,
createDefaultPropertiesForm,
findLayouts,
};
| packages/core/admin/admin/src/pages/SettingsPage/pages/Roles/EditPage/components/Permissions/utils/createDefaultCTFormFromLayout.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00019594749028328806,
0.00017055048374459147,
0.00016307426267303526,
0.00017065102292690426,
0.000007135367013688665
]
|
{
"id": 7,
"code_window": [
"\n",
" try {\n",
" const {\n",
" data: { data: response },\n",
" } = isCreating\n",
" ? await post(`/admin/api-tokens`, {\n",
" ...body,\n",
" lifespan: lifespanVal,\n",
" permissions: body.type === 'custom' ? state.selectedActions : null,\n",
" })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ? await axiosInstance.post(`/admin/api-tokens`, {\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 164
} | import reducer, { initialState } from '../reducer';
describe('ApplicationsInfosPage | LogoModalStepper | reducer', () => {
describe('DEFAULT_ACTION', () => {
it('should return initialState', () => {
const state = { ...initialState };
expect(reducer(state, {})).toEqual(state);
});
});
describe('GO_TO', () => {
it('should update current step', () => {
const state = { ...initialState };
const action = {
type: 'GO_TO',
to: 'pending',
};
const expected = { ...initialState, currentStep: action.to };
const actual = reducer(state, action);
expect(actual).toEqual(expected);
});
});
});
| packages/core/admin/admin/src/pages/SettingsPage/pages/ApplicationInfosPage/components/LogoInput/tests/reducer.test.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.0001718164567137137,
0.00016966999100986868,
0.00016798829892650247,
0.00016920524649322033,
0.0000015970171034496161
]
|
{
"id": 7,
"code_window": [
"\n",
" try {\n",
" const {\n",
" data: { data: response },\n",
" } = isCreating\n",
" ? await post(`/admin/api-tokens`, {\n",
" ...body,\n",
" lifespan: lifespanVal,\n",
" permissions: body.type === 'custom' ? state.selectedActions : null,\n",
" })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ? await axiosInstance.post(`/admin/api-tokens`, {\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 164
} | 'use strict';
const isUsingTypeScript = require('./is-using-typescript');
const isUsingTypeScriptSync = require('./is-using-typescript-sync');
const getConfigPath = require('./get-config-path');
const reportDiagnostics = require('./report-diagnostics');
const resolveConfigOptions = require('./resolve-config-options');
const formatHost = require('./format-host');
const resolveOutDir = require('./resolve-outdir');
module.exports = {
isUsingTypeScript,
isUsingTypeScriptSync,
getConfigPath,
reportDiagnostics,
resolveConfigOptions,
formatHost,
resolveOutDir,
};
| packages/utils/typescript/lib/utils/index.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017014180775731802,
0.0001690090139163658,
0.00016787622007541358,
0.0001690090139163658,
0.0000011327938409522176
]
|
{
"id": 8,
"code_window": [
" ...body,\n",
" lifespan: lifespanVal,\n",
" permissions: body.type === 'custom' ? state.selectedActions : null,\n",
" })\n",
" : await put(`/admin/api-tokens/${id}`, {\n",
" name: body.name,\n",
" description: body.description,\n",
" type: body.type,\n",
" permissions: body.type === 'custom' ? state.selectedActions : null,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" : await axiosInstance.put(`/admin/api-tokens/${id}`, {\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 169
} | import React, { useEffect, useState, useRef, useReducer } from 'react';
import { useIntl } from 'react-intl';
import {
SettingsPageTitle,
useFocusWhenNavigate,
Form,
useOverlayBlocker,
useNotification,
useTracking,
useGuidedTour,
useRBAC,
} from '@strapi/helper-plugin';
import { Main } from '@strapi/design-system/Main';
import { Formik } from 'formik';
import { get as getProperty } from 'lodash';
import { useRouteMatch, useHistory } from 'react-router-dom';
import { useQuery } from 'react-query';
import { useFetchClient } from '../../../../../hooks';
import { formatAPIErrors } from '../../../../../utils';
import { schema } from './utils';
import LoadingView from './components/LoadingView';
import FormHead from './components/FormHead';
import FormBody from './components/FormBody';
import adminPermissions from '../../../../../permissions';
import { ApiTokenPermissionsContextProvider } from '../../../../../contexts/ApiTokenPermissions';
import init from './init';
import reducer, { initialState } from './reducer';
const MSG_ERROR_NAME_TAKEN = 'Name already taken';
const ApiTokenCreateView = () => {
const { get, post, put } = useFetchClient();
useFocusWhenNavigate();
const { formatMessage } = useIntl();
const { lockApp, unlockApp } = useOverlayBlocker();
const toggleNotification = useNotification();
const history = useHistory();
const [apiToken, setApiToken] = useState(
history.location.state?.apiToken.accessKey
? {
...history.location.state.apiToken,
}
: null
);
const { trackUsage } = useTracking();
const trackUsageRef = useRef(trackUsage);
const { setCurrentStep } = useGuidedTour();
const {
allowedActions: { canCreate, canUpdate, canRegenerate },
} = useRBAC(adminPermissions.settings['api-tokens']);
const [state, dispatch] = useReducer(reducer, initialState, (state) => init(state, {}));
const {
params: { id },
} = useRouteMatch('/settings/api-tokens/:id');
const isCreating = id === 'create';
useQuery(
'content-api-permissions',
async () => {
const [permissions, routes] = await Promise.all(
['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => {
const { data } = await get(url);
return data.data;
})
);
dispatch({
type: 'UPDATE_PERMISSIONS_LAYOUT',
value: permissions,
});
dispatch({
type: 'UPDATE_ROUTES',
value: routes,
});
if (apiToken) {
if (apiToken?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (apiToken?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (apiToken?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: apiToken?.permissions,
});
}
}
},
{
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
useEffect(() => {
trackUsageRef.current(isCreating ? 'didAddTokenFromList' : 'didEditTokenFromList');
}, [isCreating]);
const { status } = useQuery(
['api-token', id],
async () => {
const {
data: { data },
} = await get(`/admin/api-tokens/${id}`);
setApiToken({
...data,
});
if (data?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (data?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (data?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: data?.permissions,
});
}
return data;
},
{
enabled: !isCreating && !apiToken,
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
const handleSubmit = async (body, actions) => {
trackUsageRef.current(isCreating ? 'willCreateToken' : 'willEditToken');
lockApp();
const lifespanVal =
body.lifespan && parseInt(body.lifespan, 10) && body.lifespan !== '0'
? parseInt(body.lifespan, 10)
: null;
try {
const {
data: { data: response },
} = isCreating
? await post(`/admin/api-tokens`, {
...body,
lifespan: lifespanVal,
permissions: body.type === 'custom' ? state.selectedActions : null,
})
: await put(`/admin/api-tokens/${id}`, {
name: body.name,
description: body.description,
type: body.type,
permissions: body.type === 'custom' ? state.selectedActions : null,
});
if (isCreating) {
history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });
setCurrentStep('apiTokens.success');
}
unlockApp();
setApiToken({
...response,
});
toggleNotification({
type: 'success',
message: isCreating
? formatMessage({
id: 'notification.success.tokencreated',
defaultMessage: 'API Token successfully created',
})
: formatMessage({
id: 'notification.success.tokenedited',
defaultMessage: 'API Token successfully edited',
}),
});
trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {
type: apiToken.type,
});
} catch (err) {
const errors = formatAPIErrors(err.response.data);
actions.setErrors(errors);
if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) {
toggleNotification({
type: 'warning',
message: getProperty(
err,
'response.data.message',
'notification.error.tokennamenotunique'
),
});
} else {
toggleNotification({
type: 'warning',
message: getProperty(err, 'response.data.message', 'notification.error'),
});
}
unlockApp();
}
};
const [hasChangedPermissions, setHasChangedPermissions] = useState(false);
const handleChangeCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'ON_CHANGE',
value,
});
};
const handleChangeSelectAllCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'SELECT_ALL_IN_PERMISSION',
value,
});
};
const setSelectedAction = ({ target: { value } }) => {
dispatch({
type: 'SET_SELECTED_ACTION',
value,
});
};
const providerValue = {
...state,
onChange: handleChangeCheckbox,
onChangeSelectAll: handleChangeSelectAllCheckbox,
setSelectedAction,
};
const canEditInputs = (canUpdate && !isCreating) || (canCreate && isCreating);
const isLoading = !isCreating && !apiToken && status !== 'success';
if (isLoading) {
return <LoadingView apiTokenName={apiToken?.name} />;
}
return (
<ApiTokenPermissionsContextProvider value={providerValue}>
<Main>
<SettingsPageTitle name="API Tokens" />
<Formik
validationSchema={schema}
validateOnChange={false}
initialValues={{
name: apiToken?.name || '',
description: apiToken?.description || '',
type: apiToken?.type,
lifespan: apiToken?.lifespan ? apiToken.lifespan.toString() : apiToken?.lifespan,
}}
enableReinitialize
onSubmit={(body, actions) => handleSubmit(body, actions)}
>
{({ errors, handleChange, isSubmitting, values, setFieldValue }) => {
if (hasChangedPermissions && values?.type !== 'custom') {
setFieldValue('type', 'custom');
}
return (
<Form>
<FormHead
apiToken={apiToken}
setApiToken={setApiToken}
canEditInputs={canEditInputs}
canRegenerate={canRegenerate}
isSubmitting={isSubmitting}
/>
<FormBody
apiToken={apiToken}
errors={errors}
onChange={handleChange}
canEditInputs={canEditInputs}
isCreating={isCreating}
values={values}
onDispatch={dispatch}
setHasChangedPermissions={setHasChangedPermissions}
/>
</Form>
);
}}
</Formik>
</Main>
</ApiTokenPermissionsContextProvider>
);
};
export default ApiTokenCreateView;
| packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js | 1 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.9879833459854126,
0.0316275879740715,
0.00016180849343072623,
0.00017122650751844049,
0.1717820167541504
]
|
{
"id": 8,
"code_window": [
" ...body,\n",
" lifespan: lifespanVal,\n",
" permissions: body.type === 'custom' ? state.selectedActions : null,\n",
" })\n",
" : await put(`/admin/api-tokens/${id}`, {\n",
" name: body.name,\n",
" description: body.description,\n",
" type: body.type,\n",
" permissions: body.type === 'custom' ? state.selectedActions : null,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" : await axiosInstance.put(`/admin/api-tokens/${id}`, {\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 169
} | 'use strict';
const { get, map, mapValues } = require('lodash/fp');
module.exports = ({ strapi }) => ({
graphqlScalarToOperators(graphqlScalar) {
const { GRAPHQL_SCALAR_OPERATORS } = strapi.plugin('graphql').service('constants');
const { operators } = strapi.plugin('graphql').service('builders').filters;
const associations = mapValues(
map((operatorName) => operators[operatorName]),
GRAPHQL_SCALAR_OPERATORS
);
return get(graphqlScalar, associations);
},
});
| packages/plugins/graphql/server/services/utils/mappers/graphql-scalar-to-operators.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017070163448806852,
0.00016960292123258114,
0.00016850422252900898,
0.00016960292123258114,
0.0000010987059795297682
]
|
{
"id": 8,
"code_window": [
" ...body,\n",
" lifespan: lifespanVal,\n",
" permissions: body.type === 'custom' ? state.selectedActions : null,\n",
" })\n",
" : await put(`/admin/api-tokens/${id}`, {\n",
" name: body.name,\n",
" description: body.description,\n",
" type: body.type,\n",
" permissions: body.type === 'custom' ? state.selectedActions : null,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" : await axiosInstance.put(`/admin/api-tokens/${id}`, {\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 169
} | import React, { useEffect, useMemo, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { AutoReloadOverlayBockerContext } from '@strapi/helper-plugin';
import Blocker from './Blocker';
const ELAPSED = 30;
const AutoReloadOverlayBlockerProvider = ({ children }) => {
const [isOpen, setIsOpen] = useState(false);
const [{ elapsed }, setState] = useState({ elapsed: 0, start: 0 });
const [config, setConfig] = useState(undefined);
const lockAppWithAutoreload = (config = undefined) => {
setIsOpen(true);
setConfig(config);
setState((prev) => ({ ...prev, start: Date.now() }));
};
const unlockAppWithAutoreload = () => {
setIsOpen(false);
setState({ start: 0, elapsed: 0 });
setConfig(undefined);
};
const lockApp = useRef(lockAppWithAutoreload);
const unlockApp = useRef(unlockAppWithAutoreload);
useEffect(() => {
let timer = null;
if (isOpen) {
timer = setInterval(() => {
if (elapsed > ELAPSED) {
clearInterval(timer);
return null;
}
setState((prev) => ({ ...prev, elapsed: Math.round(Date.now() - prev.start) / 1000 }));
return null;
}, 1000);
} else {
clearInterval(timer);
}
return () => {
clearInterval(timer);
};
}, [isOpen, elapsed]);
let displayedIcon = config?.icon || 'reload';
let description = {
id: config?.description || 'components.OverlayBlocker.description',
defaultMessage:
"You're using a feature that needs the server to restart. Please wait until the server is up.",
};
let title = {
id: config?.title || 'components.OverlayBlocker.title',
defaultMessage: 'Waiting for restart',
};
if (elapsed > ELAPSED) {
displayedIcon = 'time';
description = {
id: 'components.OverlayBlocker.description.serverError',
defaultMessage: 'The server should have restarted, please check your logs in the terminal.',
};
title = {
id: 'components.OverlayBlocker.title.serverError',
defaultMessage: 'The restart is taking longer than expected',
};
}
const autoReloadValue = useMemo(() => {
return { lockApp: lockApp.current, unlockApp: unlockApp.current };
}, [lockApp, unlockApp]);
return (
<AutoReloadOverlayBockerContext.Provider value={autoReloadValue}>
<Blocker
displayedIcon={displayedIcon}
isOpen={isOpen}
description={description}
title={title}
/>
{children}
</AutoReloadOverlayBockerContext.Provider>
);
};
AutoReloadOverlayBlockerProvider.propTypes = {
children: PropTypes.element.isRequired,
};
export default AutoReloadOverlayBlockerProvider;
| packages/core/admin/admin/src/components/AutoReloadOverlayBlockerProvider/index.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017337345343548805,
0.00016940882778726518,
0.00016138999490067363,
0.0001712267694529146,
0.000003500716047710739
]
|
{
"id": 8,
"code_window": [
" ...body,\n",
" lifespan: lifespanVal,\n",
" permissions: body.type === 'custom' ? state.selectedActions : null,\n",
" })\n",
" : await put(`/admin/api-tokens/${id}`, {\n",
" name: body.name,\n",
" description: body.description,\n",
" type: body.type,\n",
" permissions: body.type === 'custom' ? state.selectedActions : null,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" : await axiosInstance.put(`/admin/api-tokens/${id}`, {\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 169
} | #!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx --no lint-staged
| .husky/pre-commit | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00016886387311387807,
0.00016886387311387807,
0.00016886387311387807,
0.00016886387311387807,
0
]
|
{
"id": 9,
"code_window": [
" actions.setErrors(errors);\n",
"\n",
" if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) {\n",
" toggleNotification({\n",
" type: 'warning',\n",
" message: getProperty(\n",
" err,\n",
" 'response.data.message',\n",
" 'notification.error.tokennamenotunique'\n",
" ),\n",
" });\n",
" } else {\n",
" toggleNotification({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" message: get(err, 'response.data.message', 'notification.error.tokennamenotunique'),\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 208
} | import React, { useEffect, useState, useRef, useReducer } from 'react';
import { useIntl } from 'react-intl';
import {
SettingsPageTitle,
useFocusWhenNavigate,
Form,
useOverlayBlocker,
useNotification,
useTracking,
useGuidedTour,
useRBAC,
} from '@strapi/helper-plugin';
import { Main } from '@strapi/design-system/Main';
import { Formik } from 'formik';
import { get as getProperty } from 'lodash';
import { useRouteMatch, useHistory } from 'react-router-dom';
import { useQuery } from 'react-query';
import { useFetchClient } from '../../../../../hooks';
import { formatAPIErrors } from '../../../../../utils';
import { schema } from './utils';
import LoadingView from './components/LoadingView';
import FormHead from './components/FormHead';
import FormBody from './components/FormBody';
import adminPermissions from '../../../../../permissions';
import { ApiTokenPermissionsContextProvider } from '../../../../../contexts/ApiTokenPermissions';
import init from './init';
import reducer, { initialState } from './reducer';
const MSG_ERROR_NAME_TAKEN = 'Name already taken';
const ApiTokenCreateView = () => {
const { get, post, put } = useFetchClient();
useFocusWhenNavigate();
const { formatMessage } = useIntl();
const { lockApp, unlockApp } = useOverlayBlocker();
const toggleNotification = useNotification();
const history = useHistory();
const [apiToken, setApiToken] = useState(
history.location.state?.apiToken.accessKey
? {
...history.location.state.apiToken,
}
: null
);
const { trackUsage } = useTracking();
const trackUsageRef = useRef(trackUsage);
const { setCurrentStep } = useGuidedTour();
const {
allowedActions: { canCreate, canUpdate, canRegenerate },
} = useRBAC(adminPermissions.settings['api-tokens']);
const [state, dispatch] = useReducer(reducer, initialState, (state) => init(state, {}));
const {
params: { id },
} = useRouteMatch('/settings/api-tokens/:id');
const isCreating = id === 'create';
useQuery(
'content-api-permissions',
async () => {
const [permissions, routes] = await Promise.all(
['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => {
const { data } = await get(url);
return data.data;
})
);
dispatch({
type: 'UPDATE_PERMISSIONS_LAYOUT',
value: permissions,
});
dispatch({
type: 'UPDATE_ROUTES',
value: routes,
});
if (apiToken) {
if (apiToken?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (apiToken?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (apiToken?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: apiToken?.permissions,
});
}
}
},
{
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
useEffect(() => {
trackUsageRef.current(isCreating ? 'didAddTokenFromList' : 'didEditTokenFromList');
}, [isCreating]);
const { status } = useQuery(
['api-token', id],
async () => {
const {
data: { data },
} = await get(`/admin/api-tokens/${id}`);
setApiToken({
...data,
});
if (data?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (data?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (data?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: data?.permissions,
});
}
return data;
},
{
enabled: !isCreating && !apiToken,
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
const handleSubmit = async (body, actions) => {
trackUsageRef.current(isCreating ? 'willCreateToken' : 'willEditToken');
lockApp();
const lifespanVal =
body.lifespan && parseInt(body.lifespan, 10) && body.lifespan !== '0'
? parseInt(body.lifespan, 10)
: null;
try {
const {
data: { data: response },
} = isCreating
? await post(`/admin/api-tokens`, {
...body,
lifespan: lifespanVal,
permissions: body.type === 'custom' ? state.selectedActions : null,
})
: await put(`/admin/api-tokens/${id}`, {
name: body.name,
description: body.description,
type: body.type,
permissions: body.type === 'custom' ? state.selectedActions : null,
});
if (isCreating) {
history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });
setCurrentStep('apiTokens.success');
}
unlockApp();
setApiToken({
...response,
});
toggleNotification({
type: 'success',
message: isCreating
? formatMessage({
id: 'notification.success.tokencreated',
defaultMessage: 'API Token successfully created',
})
: formatMessage({
id: 'notification.success.tokenedited',
defaultMessage: 'API Token successfully edited',
}),
});
trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {
type: apiToken.type,
});
} catch (err) {
const errors = formatAPIErrors(err.response.data);
actions.setErrors(errors);
if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) {
toggleNotification({
type: 'warning',
message: getProperty(
err,
'response.data.message',
'notification.error.tokennamenotunique'
),
});
} else {
toggleNotification({
type: 'warning',
message: getProperty(err, 'response.data.message', 'notification.error'),
});
}
unlockApp();
}
};
const [hasChangedPermissions, setHasChangedPermissions] = useState(false);
const handleChangeCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'ON_CHANGE',
value,
});
};
const handleChangeSelectAllCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'SELECT_ALL_IN_PERMISSION',
value,
});
};
const setSelectedAction = ({ target: { value } }) => {
dispatch({
type: 'SET_SELECTED_ACTION',
value,
});
};
const providerValue = {
...state,
onChange: handleChangeCheckbox,
onChangeSelectAll: handleChangeSelectAllCheckbox,
setSelectedAction,
};
const canEditInputs = (canUpdate && !isCreating) || (canCreate && isCreating);
const isLoading = !isCreating && !apiToken && status !== 'success';
if (isLoading) {
return <LoadingView apiTokenName={apiToken?.name} />;
}
return (
<ApiTokenPermissionsContextProvider value={providerValue}>
<Main>
<SettingsPageTitle name="API Tokens" />
<Formik
validationSchema={schema}
validateOnChange={false}
initialValues={{
name: apiToken?.name || '',
description: apiToken?.description || '',
type: apiToken?.type,
lifespan: apiToken?.lifespan ? apiToken.lifespan.toString() : apiToken?.lifespan,
}}
enableReinitialize
onSubmit={(body, actions) => handleSubmit(body, actions)}
>
{({ errors, handleChange, isSubmitting, values, setFieldValue }) => {
if (hasChangedPermissions && values?.type !== 'custom') {
setFieldValue('type', 'custom');
}
return (
<Form>
<FormHead
apiToken={apiToken}
setApiToken={setApiToken}
canEditInputs={canEditInputs}
canRegenerate={canRegenerate}
isSubmitting={isSubmitting}
/>
<FormBody
apiToken={apiToken}
errors={errors}
onChange={handleChange}
canEditInputs={canEditInputs}
isCreating={isCreating}
values={values}
onDispatch={dispatch}
setHasChangedPermissions={setHasChangedPermissions}
/>
</Form>
);
}}
</Formik>
</Main>
</ApiTokenPermissionsContextProvider>
);
};
export default ApiTokenCreateView;
| packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js | 1 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.9971121549606323,
0.06287356466054916,
0.0001636153319850564,
0.00016823210171423852,
0.24109698832035065
]
|
{
"id": 9,
"code_window": [
" actions.setErrors(errors);\n",
"\n",
" if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) {\n",
" toggleNotification({\n",
" type: 'warning',\n",
" message: getProperty(\n",
" err,\n",
" 'response.data.message',\n",
" 'notification.error.tokennamenotunique'\n",
" ),\n",
" });\n",
" } else {\n",
" toggleNotification({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" message: get(err, 'response.data.message', 'notification.error.tokennamenotunique'),\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 208
} | /**
*
* useOverlayBlocker
*
*/
import { useContext, useRef } from 'react';
import OverlayBlockerContext from '../../contexts/OverlayBlockerContext';
const useOverlayBlocker = () => {
const { lockApp, unlockApp } = useContext(OverlayBlockerContext);
// Use a ref so we can safely add the components or the fields
// to a hook dependencies array
const lockAppRef = useRef(lockApp);
const unlockAppRef = useRef(unlockApp);
return { lockApp: lockAppRef.current, unlockApp: unlockAppRef.current };
};
export default useOverlayBlocker;
| packages/core/helper-plugin/lib/src/hooks/useOverlayBlocker/index.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.0001682229631114751,
0.0001669413613853976,
0.00016620478709228337,
0.00016639633395243436,
9.0959690624004e-7
]
|
{
"id": 9,
"code_window": [
" actions.setErrors(errors);\n",
"\n",
" if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) {\n",
" toggleNotification({\n",
" type: 'warning',\n",
" message: getProperty(\n",
" err,\n",
" 'response.data.message',\n",
" 'notification.error.tokennamenotunique'\n",
" ),\n",
" });\n",
" } else {\n",
" toggleNotification({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" message: get(err, 'response.data.message', 'notification.error.tokennamenotunique'),\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 208
} | 'use strict';
module.exports = ({ strapi }) => ({
getWelcomeMessage() {
return 'Welcome to Strapi 🚀';
},
});
| packages/generators/generators/lib/files/js/plugin/server/services/my-service.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00016843884077388793,
0.00016843884077388793,
0.00016843884077388793,
0.00016843884077388793,
0
]
|
{
"id": 9,
"code_window": [
" actions.setErrors(errors);\n",
"\n",
" if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) {\n",
" toggleNotification({\n",
" type: 'warning',\n",
" message: getProperty(\n",
" err,\n",
" 'response.data.message',\n",
" 'notification.error.tokennamenotunique'\n",
" ),\n",
" });\n",
" } else {\n",
" toggleNotification({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" message: get(err, 'response.data.message', 'notification.error.tokennamenotunique'),\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 208
} | const hasPermissionsTestData = {
userPermissions: {
user1: [
// Admin marketplace
{
action: 'admin::marketplace.read',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::marketplace.plugins.install',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::marketplace.plugins.uninstall',
subject: null,
properties: {},
conditions: ['customCondition'],
},
// Admin webhooks
{
action: 'admin::webhooks.create',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::webhooks.read',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::webhooks.update',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::webhooks.delete',
subject: null,
properties: {},
conditions: [],
},
// Admin users
{
action: 'admin::users.create',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::users.read',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::users.update',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::users.delete',
subject: null,
properties: {},
conditions: [],
},
// Admin roles
{
action: 'admin::roles.create',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::roles.read',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::roles.update',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::roles.delete',
subject: null,
properties: {},
conditions: [],
},
// Content type builder
{
action: 'plugin::content-type-builder.read',
subject: null,
properties: {},
conditions: null,
},
// Documentation plugin
{
action: 'plugin::documentation.read',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::documentation.settings.update',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::documentation.settings.regenerate',
subject: null,
properties: {},
conditions: null,
},
// Upload plugin
{
action: 'plugin::upload.read',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::upload.assets.create',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::upload.assets.update',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::upload.assets.dowload',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::upload.assets.copy-link',
subject: null,
properties: {},
conditions: null,
},
// Users-permissions
{
action: 'plugin::users-permissions.roles.create',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::users-permissions.roles.read',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::users-permissions.roles.update',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::users-permissions.roles.delete',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::users-permissions.email-templates.read',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::users-permissions.email-templates.update',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::users-permissions.providers.read',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::users-permissions.providers.update',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::users-permissions.advanced-settings.read',
subject: null,
properties: {},
conditions: null,
},
{
action: 'plugin::users-permissions.advanced-settings.update',
subject: null,
properties: {},
conditions: null,
},
],
user2: [
{
action: 'admin::marketplace.plugins.install',
subject: null,
properties: {},
conditions: ['some condition'],
},
// Admin webhooks
{
action: 'admin::webhooks.create',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::webhooks.read',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::webhooks.update',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::webhooks.delete',
subject: null,
properties: {},
conditions: [],
},
// Admin users
{
action: 'admin::users.create',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::users.read',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::users.update',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::users.delete',
subject: null,
properties: {},
conditions: [],
},
// Admin roles
{
action: 'admin::roles.create',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::roles.read',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::roles.update',
subject: null,
properties: {},
conditions: [],
},
{
action: 'admin::roles.delete',
subject: null,
properties: {},
conditions: [],
},
// Content type builder
{
action: 'plugin::content-type-builder.read',
subject: null,
properties: {},
conditions: [],
},
// Upload plugin
{
action: 'plugin::upload.read',
subject: null,
properties: {},
conditions: [],
},
{
action: 'plugin::upload.assets.create',
subject: null,
properties: {},
conditions: [],
},
{
action: 'plugin::upload.assets.update',
subject: null,
properties: {},
conditions: [],
},
{
action: 'plugin::upload.assets.dowload',
subject: null,
properties: {},
conditions: [],
},
{
action: 'plugin::upload.assets.copy-link',
subject: null,
properties: {},
conditions: [],
},
// Users-permissions
{
action: 'plugin::users-permissions.roles.create',
subject: null,
properties: {},
conditions: [],
},
{
action: 'plugin::users-permissions.roles.read',
subject: null,
properties: {},
conditions: [],
},
{
action: 'plugin::users-permissions.roles.update',
subject: null,
properties: {},
conditions: [],
},
{
action: 'plugin::users-permissions.roles.delete',
subject: null,
properties: {},
conditions: [],
},
{
action: 'plugin::users-permissions.email-templates.read',
subject: null,
properties: {},
conditions: [],
},
{
action: 'plugin::users-permissions.email-templates.update',
subject: null,
properties: {},
conditions: [],
},
{
action: 'plugin::users-permissions.providers.read',
subject: null,
properties: {},
conditions: [],
},
{
action: 'plugin::users-permissions.providers.update',
subject: null,
properties: {},
conditions: [],
},
{
action: 'plugin::users-permissions.advanced-settings.read',
subject: null,
properties: {},
conditions: [],
},
{
action: 'plugin::users-permissions.advanced-settings.update',
subject: null,
properties: {},
conditions: [],
},
],
},
permissionsToCheck: {
listPlugins: [
{ action: 'admin::marketplace.read', subject: null },
{ action: 'admin::marketplace.plugins.uninstall', subject: null },
],
marketplace: [
{ action: 'admin::marketplace.read', subject: null },
{ action: 'admin::marketplace.plugins.install', subject: null },
],
settings: [
// webhooks
{ action: 'admin::webhook.create', subject: null },
{ action: 'admin::webhook.read', subject: null },
{ action: 'admin::webhook.update', subject: null },
{ action: 'admin::webhook.delete', subject: null },
// users
{ action: 'admin::users.create', subject: null },
{ action: 'admin::users.read', subject: null },
{ action: 'admin::users.update', subject: null },
{ action: 'admin::users.delete', subject: null },
// roles
{ action: 'admin::roles.create', subject: null },
{ action: 'admin::roles.update', subject: null },
{ action: 'admin::roles.read', subject: null },
{ action: 'admin::roles.delete', subject: null },
// media library
{ action: 'plugin::upload.read', subject: null },
{ action: 'plugin::upload.assets.create', subject: null },
{ action: 'plugin::upload.assets.update', subject: null },
],
},
};
export default hasPermissionsTestData;
| packages/core/helper-plugin/lib/src/utils/hasPermissions/tests/hasPermissionsTestData.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017316493904218078,
0.00017046878929249942,
0.00016552188026253134,
0.0001704267633613199,
0.0000018034393178822938
]
|
{
"id": 10,
"code_window": [
" });\n",
" } else {\n",
" toggleNotification({\n",
" type: 'warning',\n",
" message: getProperty(err, 'response.data.message', 'notification.error'),\n",
" });\n",
" }\n",
" unlockApp();\n",
" }\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" message: get(err, 'response.data.message', 'notification.error'),\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 217
} | import React, { useEffect, useState, useRef, useReducer } from 'react';
import { useIntl } from 'react-intl';
import {
SettingsPageTitle,
useFocusWhenNavigate,
Form,
useOverlayBlocker,
useNotification,
useTracking,
useGuidedTour,
useRBAC,
} from '@strapi/helper-plugin';
import { Main } from '@strapi/design-system/Main';
import { Formik } from 'formik';
import { get as getProperty } from 'lodash';
import { useRouteMatch, useHistory } from 'react-router-dom';
import { useQuery } from 'react-query';
import { useFetchClient } from '../../../../../hooks';
import { formatAPIErrors } from '../../../../../utils';
import { schema } from './utils';
import LoadingView from './components/LoadingView';
import FormHead from './components/FormHead';
import FormBody from './components/FormBody';
import adminPermissions from '../../../../../permissions';
import { ApiTokenPermissionsContextProvider } from '../../../../../contexts/ApiTokenPermissions';
import init from './init';
import reducer, { initialState } from './reducer';
const MSG_ERROR_NAME_TAKEN = 'Name already taken';
const ApiTokenCreateView = () => {
const { get, post, put } = useFetchClient();
useFocusWhenNavigate();
const { formatMessage } = useIntl();
const { lockApp, unlockApp } = useOverlayBlocker();
const toggleNotification = useNotification();
const history = useHistory();
const [apiToken, setApiToken] = useState(
history.location.state?.apiToken.accessKey
? {
...history.location.state.apiToken,
}
: null
);
const { trackUsage } = useTracking();
const trackUsageRef = useRef(trackUsage);
const { setCurrentStep } = useGuidedTour();
const {
allowedActions: { canCreate, canUpdate, canRegenerate },
} = useRBAC(adminPermissions.settings['api-tokens']);
const [state, dispatch] = useReducer(reducer, initialState, (state) => init(state, {}));
const {
params: { id },
} = useRouteMatch('/settings/api-tokens/:id');
const isCreating = id === 'create';
useQuery(
'content-api-permissions',
async () => {
const [permissions, routes] = await Promise.all(
['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => {
const { data } = await get(url);
return data.data;
})
);
dispatch({
type: 'UPDATE_PERMISSIONS_LAYOUT',
value: permissions,
});
dispatch({
type: 'UPDATE_ROUTES',
value: routes,
});
if (apiToken) {
if (apiToken?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (apiToken?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (apiToken?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: apiToken?.permissions,
});
}
}
},
{
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
useEffect(() => {
trackUsageRef.current(isCreating ? 'didAddTokenFromList' : 'didEditTokenFromList');
}, [isCreating]);
const { status } = useQuery(
['api-token', id],
async () => {
const {
data: { data },
} = await get(`/admin/api-tokens/${id}`);
setApiToken({
...data,
});
if (data?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (data?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (data?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: data?.permissions,
});
}
return data;
},
{
enabled: !isCreating && !apiToken,
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
const handleSubmit = async (body, actions) => {
trackUsageRef.current(isCreating ? 'willCreateToken' : 'willEditToken');
lockApp();
const lifespanVal =
body.lifespan && parseInt(body.lifespan, 10) && body.lifespan !== '0'
? parseInt(body.lifespan, 10)
: null;
try {
const {
data: { data: response },
} = isCreating
? await post(`/admin/api-tokens`, {
...body,
lifespan: lifespanVal,
permissions: body.type === 'custom' ? state.selectedActions : null,
})
: await put(`/admin/api-tokens/${id}`, {
name: body.name,
description: body.description,
type: body.type,
permissions: body.type === 'custom' ? state.selectedActions : null,
});
if (isCreating) {
history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });
setCurrentStep('apiTokens.success');
}
unlockApp();
setApiToken({
...response,
});
toggleNotification({
type: 'success',
message: isCreating
? formatMessage({
id: 'notification.success.tokencreated',
defaultMessage: 'API Token successfully created',
})
: formatMessage({
id: 'notification.success.tokenedited',
defaultMessage: 'API Token successfully edited',
}),
});
trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {
type: apiToken.type,
});
} catch (err) {
const errors = formatAPIErrors(err.response.data);
actions.setErrors(errors);
if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) {
toggleNotification({
type: 'warning',
message: getProperty(
err,
'response.data.message',
'notification.error.tokennamenotunique'
),
});
} else {
toggleNotification({
type: 'warning',
message: getProperty(err, 'response.data.message', 'notification.error'),
});
}
unlockApp();
}
};
const [hasChangedPermissions, setHasChangedPermissions] = useState(false);
const handleChangeCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'ON_CHANGE',
value,
});
};
const handleChangeSelectAllCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'SELECT_ALL_IN_PERMISSION',
value,
});
};
const setSelectedAction = ({ target: { value } }) => {
dispatch({
type: 'SET_SELECTED_ACTION',
value,
});
};
const providerValue = {
...state,
onChange: handleChangeCheckbox,
onChangeSelectAll: handleChangeSelectAllCheckbox,
setSelectedAction,
};
const canEditInputs = (canUpdate && !isCreating) || (canCreate && isCreating);
const isLoading = !isCreating && !apiToken && status !== 'success';
if (isLoading) {
return <LoadingView apiTokenName={apiToken?.name} />;
}
return (
<ApiTokenPermissionsContextProvider value={providerValue}>
<Main>
<SettingsPageTitle name="API Tokens" />
<Formik
validationSchema={schema}
validateOnChange={false}
initialValues={{
name: apiToken?.name || '',
description: apiToken?.description || '',
type: apiToken?.type,
lifespan: apiToken?.lifespan ? apiToken.lifespan.toString() : apiToken?.lifespan,
}}
enableReinitialize
onSubmit={(body, actions) => handleSubmit(body, actions)}
>
{({ errors, handleChange, isSubmitting, values, setFieldValue }) => {
if (hasChangedPermissions && values?.type !== 'custom') {
setFieldValue('type', 'custom');
}
return (
<Form>
<FormHead
apiToken={apiToken}
setApiToken={setApiToken}
canEditInputs={canEditInputs}
canRegenerate={canRegenerate}
isSubmitting={isSubmitting}
/>
<FormBody
apiToken={apiToken}
errors={errors}
onChange={handleChange}
canEditInputs={canEditInputs}
isCreating={isCreating}
values={values}
onDispatch={dispatch}
setHasChangedPermissions={setHasChangedPermissions}
/>
</Form>
);
}}
</Formik>
</Main>
</ApiTokenPermissionsContextProvider>
);
};
export default ApiTokenCreateView;
| packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js | 1 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.9982635378837585,
0.03820957988500595,
0.00016294866509269923,
0.00017237954307347536,
0.1743246167898178
]
|
{
"id": 10,
"code_window": [
" });\n",
" } else {\n",
" toggleNotification({\n",
" type: 'warning',\n",
" message: getProperty(err, 'response.data.message', 'notification.error'),\n",
" });\n",
" }\n",
" unlockApp();\n",
" }\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" message: get(err, 'response.data.message', 'notification.error'),\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 217
} | 'use strict';
const baseConfig = require('../../../jest.base-config');
const pkg = require('./package.json');
module.exports = {
...baseConfig,
displayName: (pkg.strapi && pkg.strapi.name) || pkg.name,
roots: [__dirname],
};
| packages/plugins/sentry/jest.config.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017460575327277184,
0.0001730241347104311,
0.00017144250159617513,
0.0001730241347104311,
0.0000015816258382983506
]
|
{
"id": 10,
"code_window": [
" });\n",
" } else {\n",
" toggleNotification({\n",
" type: 'warning',\n",
" message: getProperty(err, 'response.data.message', 'notification.error'),\n",
" });\n",
" }\n",
" unlockApp();\n",
" }\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" message: get(err, 'response.data.message', 'notification.error'),\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 217
} | import styled from 'styled-components';
const Container = styled.div`
padding: 18px 30px 66px 30px;
`;
export default Container;
| packages/core/admin/admin/src/content-manager/components/Container/index.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017525695147924125,
0.00017525695147924125,
0.00017525695147924125,
0.00017525695147924125,
0
]
|
{
"id": 10,
"code_window": [
" });\n",
" } else {\n",
" toggleNotification({\n",
" type: 'warning',\n",
" message: getProperty(err, 'response.data.message', 'notification.error'),\n",
" });\n",
" }\n",
" unlockApp();\n",
" }\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" message: get(err, 'response.data.message', 'notification.error'),\n"
],
"file_path": "packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js",
"type": "replace",
"edit_start_line_idx": 217
} | 'use strict';
/* eslint-disable no-nested-ternary */
const chalk = require('chalk');
const codeToColor = (code) => {
return code >= 500
? chalk.red(code)
: code >= 400
? chalk.yellow(code)
: code >= 300
? chalk.cyan(code)
: code >= 200
? chalk.green(code)
: code;
};
/**
* @type {import('./').MiddlewareFactory}
*/
module.exports = (_, { strapi }) => {
return async (ctx, next) => {
const start = Date.now();
await next();
const delta = Math.ceil(Date.now() - start);
strapi.log.http(`${ctx.method} ${ctx.url} (${delta} ms) ${codeToColor(ctx.status)}`);
};
};
| packages/core/strapi/lib/middlewares/logger.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017506687436252832,
0.00017395272152498364,
0.00017243338515982032,
0.00017415531328879297,
0.0000010046879879155313
]
|
{
"id": 11,
"code_window": [
" it('should return the 4 HTTP methods to call GET, POST, PUT and DELETE apis', () => {\n",
" const response = getFetchClient();\n",
" expect(response).toHaveProperty('get');\n",
" expect(response).toHaveProperty('post');\n",
" expect(response).toHaveProperty('put');\n",
" expect(response).toHaveProperty('delete');\n",
" });\n",
" it('should contain the headers config values and the data when we try to reach an unknown API', async () => {\n",
" const response = getFetchClient();\n",
" try {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(response).toHaveProperty('del');\n"
],
"file_path": "packages/core/admin/admin/src/utils/tests/getFetchClient.test.js",
"type": "replace",
"edit_start_line_idx": 14
} | import React, { useEffect, useState, useRef, useReducer } from 'react';
import { useIntl } from 'react-intl';
import {
SettingsPageTitle,
useFocusWhenNavigate,
Form,
useOverlayBlocker,
useNotification,
useTracking,
useGuidedTour,
useRBAC,
} from '@strapi/helper-plugin';
import { Main } from '@strapi/design-system/Main';
import { Formik } from 'formik';
import { get as getProperty } from 'lodash';
import { useRouteMatch, useHistory } from 'react-router-dom';
import { useQuery } from 'react-query';
import { useFetchClient } from '../../../../../hooks';
import { formatAPIErrors } from '../../../../../utils';
import { schema } from './utils';
import LoadingView from './components/LoadingView';
import FormHead from './components/FormHead';
import FormBody from './components/FormBody';
import adminPermissions from '../../../../../permissions';
import { ApiTokenPermissionsContextProvider } from '../../../../../contexts/ApiTokenPermissions';
import init from './init';
import reducer, { initialState } from './reducer';
const MSG_ERROR_NAME_TAKEN = 'Name already taken';
const ApiTokenCreateView = () => {
const { get, post, put } = useFetchClient();
useFocusWhenNavigate();
const { formatMessage } = useIntl();
const { lockApp, unlockApp } = useOverlayBlocker();
const toggleNotification = useNotification();
const history = useHistory();
const [apiToken, setApiToken] = useState(
history.location.state?.apiToken.accessKey
? {
...history.location.state.apiToken,
}
: null
);
const { trackUsage } = useTracking();
const trackUsageRef = useRef(trackUsage);
const { setCurrentStep } = useGuidedTour();
const {
allowedActions: { canCreate, canUpdate, canRegenerate },
} = useRBAC(adminPermissions.settings['api-tokens']);
const [state, dispatch] = useReducer(reducer, initialState, (state) => init(state, {}));
const {
params: { id },
} = useRouteMatch('/settings/api-tokens/:id');
const isCreating = id === 'create';
useQuery(
'content-api-permissions',
async () => {
const [permissions, routes] = await Promise.all(
['/admin/content-api/permissions', '/admin/content-api/routes'].map(async (url) => {
const { data } = await get(url);
return data.data;
})
);
dispatch({
type: 'UPDATE_PERMISSIONS_LAYOUT',
value: permissions,
});
dispatch({
type: 'UPDATE_ROUTES',
value: routes,
});
if (apiToken) {
if (apiToken?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (apiToken?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (apiToken?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: apiToken?.permissions,
});
}
}
},
{
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
useEffect(() => {
trackUsageRef.current(isCreating ? 'didAddTokenFromList' : 'didEditTokenFromList');
}, [isCreating]);
const { status } = useQuery(
['api-token', id],
async () => {
const {
data: { data },
} = await get(`/admin/api-tokens/${id}`);
setApiToken({
...data,
});
if (data?.type === 'read-only') {
dispatch({
type: 'ON_CHANGE_READ_ONLY',
});
}
if (data?.type === 'full-access') {
dispatch({
type: 'SELECT_ALL_ACTIONS',
});
}
if (data?.type === 'custom') {
dispatch({
type: 'UPDATE_PERMISSIONS',
value: data?.permissions,
});
}
return data;
},
{
enabled: !isCreating && !apiToken,
onError() {
toggleNotification({
type: 'warning',
message: { id: 'notification.error', defaultMessage: 'An error occured' },
});
},
}
);
const handleSubmit = async (body, actions) => {
trackUsageRef.current(isCreating ? 'willCreateToken' : 'willEditToken');
lockApp();
const lifespanVal =
body.lifespan && parseInt(body.lifespan, 10) && body.lifespan !== '0'
? parseInt(body.lifespan, 10)
: null;
try {
const {
data: { data: response },
} = isCreating
? await post(`/admin/api-tokens`, {
...body,
lifespan: lifespanVal,
permissions: body.type === 'custom' ? state.selectedActions : null,
})
: await put(`/admin/api-tokens/${id}`, {
name: body.name,
description: body.description,
type: body.type,
permissions: body.type === 'custom' ? state.selectedActions : null,
});
if (isCreating) {
history.replace(`/settings/api-tokens/${response.id}`, { apiToken: response });
setCurrentStep('apiTokens.success');
}
unlockApp();
setApiToken({
...response,
});
toggleNotification({
type: 'success',
message: isCreating
? formatMessage({
id: 'notification.success.tokencreated',
defaultMessage: 'API Token successfully created',
})
: formatMessage({
id: 'notification.success.tokenedited',
defaultMessage: 'API Token successfully edited',
}),
});
trackUsageRef.current(isCreating ? 'didCreateToken' : 'didEditToken', {
type: apiToken.type,
});
} catch (err) {
const errors = formatAPIErrors(err.response.data);
actions.setErrors(errors);
if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) {
toggleNotification({
type: 'warning',
message: getProperty(
err,
'response.data.message',
'notification.error.tokennamenotunique'
),
});
} else {
toggleNotification({
type: 'warning',
message: getProperty(err, 'response.data.message', 'notification.error'),
});
}
unlockApp();
}
};
const [hasChangedPermissions, setHasChangedPermissions] = useState(false);
const handleChangeCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'ON_CHANGE',
value,
});
};
const handleChangeSelectAllCheckbox = ({ target: { value } }) => {
setHasChangedPermissions(true);
dispatch({
type: 'SELECT_ALL_IN_PERMISSION',
value,
});
};
const setSelectedAction = ({ target: { value } }) => {
dispatch({
type: 'SET_SELECTED_ACTION',
value,
});
};
const providerValue = {
...state,
onChange: handleChangeCheckbox,
onChangeSelectAll: handleChangeSelectAllCheckbox,
setSelectedAction,
};
const canEditInputs = (canUpdate && !isCreating) || (canCreate && isCreating);
const isLoading = !isCreating && !apiToken && status !== 'success';
if (isLoading) {
return <LoadingView apiTokenName={apiToken?.name} />;
}
return (
<ApiTokenPermissionsContextProvider value={providerValue}>
<Main>
<SettingsPageTitle name="API Tokens" />
<Formik
validationSchema={schema}
validateOnChange={false}
initialValues={{
name: apiToken?.name || '',
description: apiToken?.description || '',
type: apiToken?.type,
lifespan: apiToken?.lifespan ? apiToken.lifespan.toString() : apiToken?.lifespan,
}}
enableReinitialize
onSubmit={(body, actions) => handleSubmit(body, actions)}
>
{({ errors, handleChange, isSubmitting, values, setFieldValue }) => {
if (hasChangedPermissions && values?.type !== 'custom') {
setFieldValue('type', 'custom');
}
return (
<Form>
<FormHead
apiToken={apiToken}
setApiToken={setApiToken}
canEditInputs={canEditInputs}
canRegenerate={canRegenerate}
isSubmitting={isSubmitting}
/>
<FormBody
apiToken={apiToken}
errors={errors}
onChange={handleChange}
canEditInputs={canEditInputs}
isCreating={isCreating}
values={values}
onDispatch={dispatch}
setHasChangedPermissions={setHasChangedPermissions}
/>
</Form>
);
}}
</Formik>
</Main>
</ApiTokenPermissionsContextProvider>
);
};
export default ApiTokenCreateView;
| packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/index.js | 1 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.0015300536761060357,
0.00021653794101439416,
0.00016514935123268515,
0.00017130328342318535,
0.00023656916164327413
]
|
{
"id": 11,
"code_window": [
" it('should return the 4 HTTP methods to call GET, POST, PUT and DELETE apis', () => {\n",
" const response = getFetchClient();\n",
" expect(response).toHaveProperty('get');\n",
" expect(response).toHaveProperty('post');\n",
" expect(response).toHaveProperty('put');\n",
" expect(response).toHaveProperty('delete');\n",
" });\n",
" it('should contain the headers config values and the data when we try to reach an unknown API', async () => {\n",
" const response = getFetchClient();\n",
" try {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(response).toHaveProperty('del');\n"
],
"file_path": "packages/core/admin/admin/src/utils/tests/getFetchClient.test.js",
"type": "replace",
"edit_start_line_idx": 14
} | <!--- useFocusWhenNavigate.stories.mdx --->
import { Meta } from '@storybook/addon-docs';
<Meta title="hooks/useFocusWhenNavigate" />
# useFocusWhenNavigate
This hook is used in order to focus the user on the page in the admin panel.
## Usage
```
import { useFocusWhenNavigate } from '@strapi/helper-plugin';
import { Main } from '@strapi/design-system';
const HomePage = () => {
useFocusWhenNavigate();
return (
<Main>
<h1>This is the homepage</h1>
</Main>
);
};
```
| packages/core/helper-plugin/lib/src/hooks/useFocusWhenNavigate/useFocusWhenNavigate.stories.mdx | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.0001751857780618593,
0.00017432437743991613,
0.0001732531382003799,
0.00017453418695367873,
8.028251272662601e-7
]
|
{
"id": 11,
"code_window": [
" it('should return the 4 HTTP methods to call GET, POST, PUT and DELETE apis', () => {\n",
" const response = getFetchClient();\n",
" expect(response).toHaveProperty('get');\n",
" expect(response).toHaveProperty('post');\n",
" expect(response).toHaveProperty('put');\n",
" expect(response).toHaveProperty('delete');\n",
" });\n",
" it('should contain the headers config values and the data when we try to reach an unknown API', async () => {\n",
" const response = getFetchClient();\n",
" try {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(response).toHaveProperty('del');\n"
],
"file_path": "packages/core/admin/admin/src/utils/tests/getFetchClient.test.js",
"type": "replace",
"edit_start_line_idx": 14
} | const languageNativeNames = {
ar: 'العربية',
ca: 'Català',
cs: 'Čeština',
de: 'Deutsch',
dk: 'Dansk',
en: 'English',
es: 'Español',
fr: 'Français',
gu: 'Gujarati',
he: 'עברית',
hu: 'Magyar',
id: 'Indonesian',
it: 'Italiano',
ja: '日本語',
ko: '한국어',
ml: 'Malayalam',
ms: 'Melayu',
nl: 'Nederlands',
no: 'Norwegian',
pl: 'Polski',
'pt-BR': 'Português (Brasil)',
pt: 'Português (Portugal)',
ru: 'Русский',
sk: 'Slovenčina',
sv: 'Swedish',
th: 'ไทย',
tr: 'Türkçe',
uk: 'Українська',
vi: 'Tiếng Việt',
'zh-Hans': '中文 (简体)',
zh: '中文 (繁體)',
sa: 'संस्कृत',
hi: 'हिन्दी',
};
export default languageNativeNames;
| packages/core/admin/admin/src/translations/languageNativeNames.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017588170885574073,
0.00017330862465314567,
0.00017124514852184802,
0.00017305384972132742,
0.0000020400095763761783
]
|
{
"id": 11,
"code_window": [
" it('should return the 4 HTTP methods to call GET, POST, PUT and DELETE apis', () => {\n",
" const response = getFetchClient();\n",
" expect(response).toHaveProperty('get');\n",
" expect(response).toHaveProperty('post');\n",
" expect(response).toHaveProperty('put');\n",
" expect(response).toHaveProperty('delete');\n",
" });\n",
" it('should contain the headers config values and the data when we try to reach an unknown API', async () => {\n",
" const response = getFetchClient();\n",
" try {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(response).toHaveProperty('del');\n"
],
"file_path": "packages/core/admin/admin/src/utils/tests/getFetchClient.test.js",
"type": "replace",
"edit_start_line_idx": 14
} | 'use strict';
class ResizeObserverMock {
constructor() {
this.disconnect = () => null;
this.observe = () => null;
this.unobserve = () => null;
}
}
global.ResizeObserver = ResizeObserverMock;
| packages/admin-test-utils/lib/mocks/ResizeObserver.js | 0 | https://github.com/strapi/strapi/commit/32c323892fb5a85a5ba014a4b99ba5d8a0cca688 | [
0.00017514701175969094,
0.0001746788329910487,
0.00017421063967049122,
0.0001746788329910487,
4.681860445998609e-7
]
|
{
"id": 0,
"code_window": [
"import classNames from 'classnames';\n",
"import { createStyleSheet } from 'jss-theme-reactor';\n",
"import customPropTypes from 'material-ui/utils/customPropTypes';\n",
"\n",
"export const styleSheet = createStyleSheet('AppContent', (theme) => {\n",
" return {\n",
" content: theme.mixins.gutters({\n",
" paddingTop: 80,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import MarkdownElement from 'docs/src/components/MarkdownElement';\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "add",
"edit_start_line_idx": 7
} | // @flow weak
import React from 'react';
import {
applyRouterMiddleware,
browserHistory,
Router,
Route,
IndexRoute,
IndexRedirect,
} from 'react-router';
import { useScroll } from 'react-router-scroll';
import { kebabCase, titleize } from 'docs/src/utils/helpers';
import AppFrame from 'docs/src/components/AppFrame';
import AppContent from 'docs/src/components/AppContent';
import MarkdownDocs from 'docs/src/components/MarkdownDocs';
import Home from 'docs/src/pages/Home';
import { componentAPIs, requireMarkdown, demos, requireDemo } from 'docs/src/components/files';
export default function AppRouter() {
return (
<Router
history={browserHistory}
render={applyRouterMiddleware(useScroll())}
>
<Route title="Material UI" path="/" component={AppFrame}>
<IndexRoute dockDrawer component={Home} title={null} />
<Route
title="Getting Started"
path="/getting-started"
nav
component={AppContent}
>
<IndexRedirect to="installation" />
<Route
title="Installation"
path="/getting-started/installation"
content={requireMarkdown('./getting-started/installation.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Usage"
path="/getting-started/usage"
content={requireMarkdown('./getting-started/usage.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Server Rendering"
path="/getting-started/server-rendering"
content={requireMarkdown('./getting-started/server-rendering.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Examples"
path="/getting-started/examples"
content={requireMarkdown('./getting-started/examples.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Supported Components"
path="/getting-started/supported-components"
content={requireMarkdown('./getting-started/supported-components.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Customization"
path="/customization"
nav
component={AppContent}
>
<IndexRedirect to="themes" />
<Route
title="Themes"
path="/customization/themes"
content={requireMarkdown('./customization/themes.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Composition"
path="/customization/composition"
content={requireMarkdown('./customization/composition.md')}
component={MarkdownDocs}
nav
/>
<Route
title="API"
path="/customization/api"
content={requireMarkdown('./customization/api.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Style"
path="/style"
nav
component={AppContent}
>
<Route
title="Color"
path="/style/color"
content={requireMarkdown('./style/color.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Icons"
path="/style/icons"
content={requireMarkdown('./style/icons.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Typography"
path="/style/typography"
content={requireMarkdown('./style/typography.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Layout"
path="/layout"
nav
component={AppContent}
>
<Route
title="Responsive UI"
path="/layout/responsive-ui"
content={requireMarkdown('./layout/responsive-ui.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Component Demos"
path="/component-demos"
nav
component={AppContent}
>
{demos.map(((demo) => {
return (
<Route
key={demo.name}
title={titleize(demo.name)}
path={`/component-demos/${demo.name}`}
content={requireDemo(demo.path)}
component={MarkdownDocs}
demo={demo}
nav
/>
);
}))}
</Route>
<Route
title="Component API"
path="/component-api"
nav
component={AppContent}
>
{componentAPIs.map(((componentAPI) => {
return (
<Route
key={componentAPI.name}
title={componentAPI.name}
path={`/component-api/${kebabCase(componentAPI.name)}`}
content={requireMarkdown(componentAPI.path)}
component={MarkdownDocs}
componentAPI={componentAPI}
nav
/>
);
}))}
</Route>
<Route
title="Discover More"
path="/discover-more"
nav
component={AppContent}
>
<IndexRedirect to="community" />
<Route
title="Community"
path="/discover-more/community"
content={requireMarkdown('./discover-more/community.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Showcase"
path="/discover-more/showcase"
content={requireMarkdown('./discover-more/showcase.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Related Projects"
path="/discover-more/related-projects"
content={requireMarkdown('./discover-more/related-projects.md')}
component={MarkdownDocs}
nav
/>
</Route>
</Route>
</Router>
);
}
| docs/src/components/AppRouter.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0001766928908182308,
0.00017040842794813216,
0.0001661965507082641,
0.0001694702950771898,
0.000003025527576028253
]
|
{
"id": 0,
"code_window": [
"import classNames from 'classnames';\n",
"import { createStyleSheet } from 'jss-theme-reactor';\n",
"import customPropTypes from 'material-ui/utils/customPropTypes';\n",
"\n",
"export const styleSheet = createStyleSheet('AppContent', (theme) => {\n",
" return {\n",
" content: theme.mixins.gutters({\n",
" paddingTop: 80,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import MarkdownElement from 'docs/src/components/MarkdownElement';\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "add",
"edit_start_line_idx": 7
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let CallMade = (props) => (
<SvgIcon {...props}>
<path d="M9 5v2h6.59L4 18.59 5.41 20 17 8.41V15h2V5z"/>
</SvgIcon>
);
CallMade = pure(CallMade);
CallMade.muiName = 'SvgIcon';
export default CallMade;
| packages/material-ui-icons/src/CallMade.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017580641724634916,
0.00017470127204433084,
0.00017359611229039729,
0.00017470127204433084,
0.0000011051524779759347
]
|
{
"id": 0,
"code_window": [
"import classNames from 'classnames';\n",
"import { createStyleSheet } from 'jss-theme-reactor';\n",
"import customPropTypes from 'material-ui/utils/customPropTypes';\n",
"\n",
"export const styleSheet = createStyleSheet('AppContent', (theme) => {\n",
" return {\n",
" content: theme.mixins.gutters({\n",
" paddingTop: 80,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import MarkdownElement from 'docs/src/components/MarkdownElement';\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "add",
"edit_start_line_idx": 7
} | // flow-typed signature: 62a56ebee5d69ec5be1185b6446ba4f1
// flow-typed version: <<STUB>>/babel-preset-stage-1_v^6.24.1/flow_v0.44.2
/**
* This is an autogenerated libdef stub for:
*
* 'babel-preset-stage-1'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'babel-preset-stage-1' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'babel-preset-stage-1/lib/index' {
declare module.exports: any;
}
// Filename aliases
declare module 'babel-preset-stage-1/lib/index.js' {
declare module.exports: $Exports<'babel-preset-stage-1/lib/index'>;
}
| flow-typed/npm/babel-preset-stage-1_vx.x.x.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017093942733481526,
0.00016868161037564278,
0.00016340985894203186,
0.000170188577612862,
0.000003062355744987144
]
|
{
"id": 0,
"code_window": [
"import classNames from 'classnames';\n",
"import { createStyleSheet } from 'jss-theme-reactor';\n",
"import customPropTypes from 'material-ui/utils/customPropTypes';\n",
"\n",
"export const styleSheet = createStyleSheet('AppContent', (theme) => {\n",
" return {\n",
" content: theme.mixins.gutters({\n",
" paddingTop: 80,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import MarkdownElement from 'docs/src/components/MarkdownElement';\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "add",
"edit_start_line_idx": 7
} | // @flow
import Switch from './Switch';
import withSwitchLabel from '../internal/withSwitchLabel';
const LabelSwitch = withSwitchLabel(Switch);
export default Switch;
export { LabelSwitch };
| src/Switch/index.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017381954239681363,
0.00017381954239681363,
0.00017381954239681363,
0.00017381954239681363,
0
]
|
{
"id": 1,
"code_window": [
" },\n",
" };\n",
"});\n",
"\n",
"export default function AppContent(props, context) {\n",
" const { className, children } = props;\n",
" const classes = context.styleManager.render(styleSheet);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" const {\n",
" className,\n",
" children: childrenProp,\n",
" route,\n",
" } = props;\n",
"\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "replace",
"edit_start_line_idx": 25
} | // @flow weak
import React from 'react';
import {
applyRouterMiddleware,
browserHistory,
Router,
Route,
IndexRoute,
IndexRedirect,
} from 'react-router';
import { useScroll } from 'react-router-scroll';
import { kebabCase, titleize } from 'docs/src/utils/helpers';
import AppFrame from 'docs/src/components/AppFrame';
import AppContent from 'docs/src/components/AppContent';
import MarkdownDocs from 'docs/src/components/MarkdownDocs';
import Home from 'docs/src/pages/Home';
import { componentAPIs, requireMarkdown, demos, requireDemo } from 'docs/src/components/files';
export default function AppRouter() {
return (
<Router
history={browserHistory}
render={applyRouterMiddleware(useScroll())}
>
<Route title="Material UI" path="/" component={AppFrame}>
<IndexRoute dockDrawer component={Home} title={null} />
<Route
title="Getting Started"
path="/getting-started"
nav
component={AppContent}
>
<IndexRedirect to="installation" />
<Route
title="Installation"
path="/getting-started/installation"
content={requireMarkdown('./getting-started/installation.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Usage"
path="/getting-started/usage"
content={requireMarkdown('./getting-started/usage.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Server Rendering"
path="/getting-started/server-rendering"
content={requireMarkdown('./getting-started/server-rendering.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Examples"
path="/getting-started/examples"
content={requireMarkdown('./getting-started/examples.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Supported Components"
path="/getting-started/supported-components"
content={requireMarkdown('./getting-started/supported-components.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Customization"
path="/customization"
nav
component={AppContent}
>
<IndexRedirect to="themes" />
<Route
title="Themes"
path="/customization/themes"
content={requireMarkdown('./customization/themes.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Composition"
path="/customization/composition"
content={requireMarkdown('./customization/composition.md')}
component={MarkdownDocs}
nav
/>
<Route
title="API"
path="/customization/api"
content={requireMarkdown('./customization/api.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Style"
path="/style"
nav
component={AppContent}
>
<Route
title="Color"
path="/style/color"
content={requireMarkdown('./style/color.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Icons"
path="/style/icons"
content={requireMarkdown('./style/icons.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Typography"
path="/style/typography"
content={requireMarkdown('./style/typography.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Layout"
path="/layout"
nav
component={AppContent}
>
<Route
title="Responsive UI"
path="/layout/responsive-ui"
content={requireMarkdown('./layout/responsive-ui.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Component Demos"
path="/component-demos"
nav
component={AppContent}
>
{demos.map(((demo) => {
return (
<Route
key={demo.name}
title={titleize(demo.name)}
path={`/component-demos/${demo.name}`}
content={requireDemo(demo.path)}
component={MarkdownDocs}
demo={demo}
nav
/>
);
}))}
</Route>
<Route
title="Component API"
path="/component-api"
nav
component={AppContent}
>
{componentAPIs.map(((componentAPI) => {
return (
<Route
key={componentAPI.name}
title={componentAPI.name}
path={`/component-api/${kebabCase(componentAPI.name)}`}
content={requireMarkdown(componentAPI.path)}
component={MarkdownDocs}
componentAPI={componentAPI}
nav
/>
);
}))}
</Route>
<Route
title="Discover More"
path="/discover-more"
nav
component={AppContent}
>
<IndexRedirect to="community" />
<Route
title="Community"
path="/discover-more/community"
content={requireMarkdown('./discover-more/community.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Showcase"
path="/discover-more/showcase"
content={requireMarkdown('./discover-more/showcase.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Related Projects"
path="/discover-more/related-projects"
content={requireMarkdown('./discover-more/related-projects.md')}
component={MarkdownDocs}
nav
/>
</Route>
</Route>
</Router>
);
}
| docs/src/components/AppRouter.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.9974350333213806,
0.3614247739315033,
0.000166094207088463,
0.00017036989447660744,
0.4779239594936371
]
|
{
"id": 1,
"code_window": [
" },\n",
" };\n",
"});\n",
"\n",
"export default function AppContent(props, context) {\n",
" const { className, children } = props;\n",
" const classes = context.styleManager.render(styleSheet);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" const {\n",
" className,\n",
" children: childrenProp,\n",
" route,\n",
" } = props;\n",
"\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "replace",
"edit_start_line_idx": 25
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Replay5 = (props) => (
<SvgIcon {...props}>
<path d="M12 5V1L7 6l5 5V7c3.3 0 6 2.7 6 6s-2.7 6-6 6-6-2.7-6-6H4c0 4.4 3.6 8 8 8s8-3.6 8-8-3.6-8-8-8zm-1.3 8.9l.2-2.2h2.4v.7h-1.7l-.1.9s.1 0 .1-.1.1 0 .1-.1.1 0 .2 0h.2c.2 0 .4 0 .5.1s.3.2.4.3.2.3.3.5.1.4.1.6c0 .2 0 .4-.1.5s-.1.3-.3.5-.3.2-.4.3-.4.1-.6.1c-.2 0-.4 0-.5-.1s-.3-.1-.5-.2-.2-.2-.3-.4-.1-.3-.1-.5h.8c0 .2.1.3.2.4s.2.1.4.1c.1 0 .2 0 .3-.1l.2-.2s.1-.2.1-.3v-.6l-.1-.2-.2-.2s-.2-.1-.3-.1h-.2s-.1 0-.2.1-.1 0-.1.1-.1.1-.1.1h-.7z"/>
</SvgIcon>
);
Replay5 = pure(Replay5);
Replay5.muiName = 'SvgIcon';
export default Replay5;
| packages/material-ui-icons/src/Replay5.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.002945699030533433,
0.0015595478471368551,
0.00017339659098070115,
0.0015595478471368551,
0.0013861512998118997
]
|
{
"id": 1,
"code_window": [
" },\n",
" };\n",
"});\n",
"\n",
"export default function AppContent(props, context) {\n",
" const { className, children } = props;\n",
" const classes = context.styleManager.render(styleSheet);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" const {\n",
" className,\n",
" children: childrenProp,\n",
" route,\n",
" } = props;\n",
"\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "replace",
"edit_start_line_idx": 25
} | // @flow weak
import React from 'react';
import { assert } from 'chai';
import { createShallow } from 'src/test-utils';
import { createStyleSheet } from 'jss-theme-reactor';
import withStyles from './withStyles';
const Empty = () => <div />;
Empty.propTypes = {}; // Breaks the referential transparency for testing purposes.
describe('withStyles', () => {
let shallow;
before(() => {
shallow = createShallow();
});
it('should provide a classes property', () => {
const styleSheet = createStyleSheet('MuiTextField', () => ({
root: {
display: 'flex',
},
}));
const classes = shallow.context.styleManager.render(styleSheet);
const StyledComponent = withStyles(styleSheet)(Empty);
const wrapper = shallow(<StyledComponent />);
assert.strictEqual(wrapper.props().classes, classes,
'Should provide the classes property');
});
});
| src/styles/withStyles.spec.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.7312672734260559,
0.18345528841018677,
0.000168411381309852,
0.0011927341111004353,
0.3162803053855896
]
|
{
"id": 1,
"code_window": [
" },\n",
" };\n",
"});\n",
"\n",
"export default function AppContent(props, context) {\n",
" const { className, children } = props;\n",
" const classes = context.styleManager.render(styleSheet);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" const {\n",
" className,\n",
" children: childrenProp,\n",
" route,\n",
" } = props;\n",
"\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "replace",
"edit_start_line_idx": 25
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let PanoramaFishEye = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/>
</SvgIcon>
);
PanoramaFishEye = pure(PanoramaFishEye);
PanoramaFishEye.muiName = 'SvgIcon';
export default PanoramaFishEye;
| packages/material-ui-icons/src/PanoramaFishEye.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0002082906139548868,
0.00020702621259260923,
0.00020576181123033166,
0.00020702621259260923,
0.0000012644013622775674
]
|
{
"id": 2,
"code_window": [
" const classes = context.styleManager.render(styleSheet);\n",
" return (\n",
" <div className={classNames(classes.content, className)}>\n",
" {children}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" let children = childrenProp;\n",
"\n",
" if (!children) {\n",
" const text = `\n",
"# Summary\n",
"\n",
"${route.childRoutes.map((childRoute) => (`- [${childRoute.title}](${childRoute.path})`)).join('\\n')}\n",
"`;\n",
" children = <MarkdownElement text={text} />;\n",
" }\n",
"\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "add",
"edit_start_line_idx": 27
} | // @flow weak
import React from 'react';
import {
applyRouterMiddleware,
browserHistory,
Router,
Route,
IndexRoute,
IndexRedirect,
} from 'react-router';
import { useScroll } from 'react-router-scroll';
import { kebabCase, titleize } from 'docs/src/utils/helpers';
import AppFrame from 'docs/src/components/AppFrame';
import AppContent from 'docs/src/components/AppContent';
import MarkdownDocs from 'docs/src/components/MarkdownDocs';
import Home from 'docs/src/pages/Home';
import { componentAPIs, requireMarkdown, demos, requireDemo } from 'docs/src/components/files';
export default function AppRouter() {
return (
<Router
history={browserHistory}
render={applyRouterMiddleware(useScroll())}
>
<Route title="Material UI" path="/" component={AppFrame}>
<IndexRoute dockDrawer component={Home} title={null} />
<Route
title="Getting Started"
path="/getting-started"
nav
component={AppContent}
>
<IndexRedirect to="installation" />
<Route
title="Installation"
path="/getting-started/installation"
content={requireMarkdown('./getting-started/installation.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Usage"
path="/getting-started/usage"
content={requireMarkdown('./getting-started/usage.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Server Rendering"
path="/getting-started/server-rendering"
content={requireMarkdown('./getting-started/server-rendering.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Examples"
path="/getting-started/examples"
content={requireMarkdown('./getting-started/examples.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Supported Components"
path="/getting-started/supported-components"
content={requireMarkdown('./getting-started/supported-components.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Customization"
path="/customization"
nav
component={AppContent}
>
<IndexRedirect to="themes" />
<Route
title="Themes"
path="/customization/themes"
content={requireMarkdown('./customization/themes.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Composition"
path="/customization/composition"
content={requireMarkdown('./customization/composition.md')}
component={MarkdownDocs}
nav
/>
<Route
title="API"
path="/customization/api"
content={requireMarkdown('./customization/api.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Style"
path="/style"
nav
component={AppContent}
>
<Route
title="Color"
path="/style/color"
content={requireMarkdown('./style/color.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Icons"
path="/style/icons"
content={requireMarkdown('./style/icons.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Typography"
path="/style/typography"
content={requireMarkdown('./style/typography.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Layout"
path="/layout"
nav
component={AppContent}
>
<Route
title="Responsive UI"
path="/layout/responsive-ui"
content={requireMarkdown('./layout/responsive-ui.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Component Demos"
path="/component-demos"
nav
component={AppContent}
>
{demos.map(((demo) => {
return (
<Route
key={demo.name}
title={titleize(demo.name)}
path={`/component-demos/${demo.name}`}
content={requireDemo(demo.path)}
component={MarkdownDocs}
demo={demo}
nav
/>
);
}))}
</Route>
<Route
title="Component API"
path="/component-api"
nav
component={AppContent}
>
{componentAPIs.map(((componentAPI) => {
return (
<Route
key={componentAPI.name}
title={componentAPI.name}
path={`/component-api/${kebabCase(componentAPI.name)}`}
content={requireMarkdown(componentAPI.path)}
component={MarkdownDocs}
componentAPI={componentAPI}
nav
/>
);
}))}
</Route>
<Route
title="Discover More"
path="/discover-more"
nav
component={AppContent}
>
<IndexRedirect to="community" />
<Route
title="Community"
path="/discover-more/community"
content={requireMarkdown('./discover-more/community.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Showcase"
path="/discover-more/showcase"
content={requireMarkdown('./discover-more/showcase.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Related Projects"
path="/discover-more/related-projects"
content={requireMarkdown('./discover-more/related-projects.md')}
component={MarkdownDocs}
nav
/>
</Route>
</Route>
</Router>
);
}
| docs/src/components/AppRouter.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017523436690680683,
0.00017171406943816692,
0.00016158400103449821,
0.00017246906645596027,
0.0000027768173822551034
]
|
{
"id": 2,
"code_window": [
" const classes = context.styleManager.render(styleSheet);\n",
" return (\n",
" <div className={classNames(classes.content, className)}>\n",
" {children}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" let children = childrenProp;\n",
"\n",
" if (!children) {\n",
" const text = `\n",
"# Summary\n",
"\n",
"${route.childRoutes.map((childRoute) => (`- [${childRoute.title}](${childRoute.path})`)).join('\\n')}\n",
"`;\n",
" children = <MarkdownElement text={text} />;\n",
" }\n",
"\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "add",
"edit_start_line_idx": 27
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let AirlineSeatReclineNormal = (props) => (
<SvgIcon {...props}>
<path d="M7.59 5.41c-.78-.78-.78-2.05 0-2.83.78-.78 2.05-.78 2.83 0 .78.78.78 2.05 0 2.83-.79.79-2.05.79-2.83 0zM6 16V7H4v9c0 2.76 2.24 5 5 5h6v-2H9c-1.66 0-3-1.34-3-3zm14 4.07L14.93 15H11.5v-3.68c1.4 1.15 3.6 2.16 5.5 2.16v-2.16c-1.66.02-3.61-.87-4.67-2.04l-1.4-1.55c-.19-.21-.43-.38-.69-.5-.29-.14-.62-.23-.96-.23h-.03C8.01 7 7 8.01 7 9.25V15c0 1.66 1.34 3 3 3h5.07l3.5 3.5L20 20.07z"/>
</SvgIcon>
);
AirlineSeatReclineNormal = pure(AirlineSeatReclineNormal);
AirlineSeatReclineNormal.muiName = 'SvgIcon';
export default AirlineSeatReclineNormal;
| packages/material-ui-icons/src/AirlineSeatReclineNormal.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00016956849140115082,
0.00016778099234215915,
0.00016599349328316748,
0.00016778099234215915,
0.0000017874990589916706
]
|
{
"id": 2,
"code_window": [
" const classes = context.styleManager.render(styleSheet);\n",
" return (\n",
" <div className={classNames(classes.content, className)}>\n",
" {children}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" let children = childrenProp;\n",
"\n",
" if (!children) {\n",
" const text = `\n",
"# Summary\n",
"\n",
"${route.childRoutes.map((childRoute) => (`- [${childRoute.title}](${childRoute.path})`)).join('\\n')}\n",
"`;\n",
" children = <MarkdownElement text={text} />;\n",
" }\n",
"\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "add",
"edit_start_line_idx": 27
} | // @flow weak
import React from 'react';
import Typography from 'material-ui/Typography';
const style = {
width: '100%',
maxWidth: 500,
};
export default function Types() {
return (
<div style={style}>
<Typography type="display4" gutterBottom>
Display 4
</Typography>
<Typography type="display3" gutterBottom>
Display 3
</Typography>
<Typography type="display2" gutterBottom>
Display 2
</Typography>
<Typography type="display1" gutterBottom>
Display 1
</Typography>
<Typography type="headline" gutterBottom>
Headline
</Typography>
<Typography type="title" gutterBottom>
Title
</Typography>
<Typography type="subheading" gutterBottom>
Subheading
</Typography>
<Typography type="body2" gutterBottom>
Body 2
</Typography>
<Typography type="body1" gutterBottom align="right">
Body 1
</Typography>
<Typography type="caption" gutterBottom align="center">
Caption
</Typography>
<Typography gutterBottom noWrap>
{`
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
`}
</Typography>
</div>
);
}
| docs/src/pages/style/Types.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017939654935617,
0.00017329024558421224,
0.00016580906230956316,
0.00017342486535198987,
0.000004037678991153371
]
|
{
"id": 2,
"code_window": [
" const classes = context.styleManager.render(styleSheet);\n",
" return (\n",
" <div className={classNames(classes.content, className)}>\n",
" {children}\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" let children = childrenProp;\n",
"\n",
" if (!children) {\n",
" const text = `\n",
"# Summary\n",
"\n",
"${route.childRoutes.map((childRoute) => (`- [${childRoute.title}](${childRoute.path})`)).join('\\n')}\n",
"`;\n",
" children = <MarkdownElement text={text} />;\n",
" }\n",
"\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "add",
"edit_start_line_idx": 27
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let EuroSymbol = (props) => (
<SvgIcon {...props}>
<path d="M15 18.5c-2.51 0-4.68-1.42-5.76-3.5H15v-2H8.58c-.05-.33-.08-.66-.08-1s.03-.67.08-1H15V9H9.24C10.32 6.92 12.5 5.5 15 5.5c1.61 0 3.09.59 4.23 1.57L21 5.3C19.41 3.87 17.3 3 15 3c-3.92 0-7.24 2.51-8.48 6H3v2h3.06c-.04.33-.06.66-.06 1 0 .34.02.67.06 1H3v2h3.52c1.24 3.49 4.56 6 8.48 6 2.31 0 4.41-.87 6-2.3l-1.78-1.77c-1.13.98-2.6 1.57-4.22 1.57z"/>
</SvgIcon>
);
EuroSymbol = pure(EuroSymbol);
EuroSymbol.muiName = 'SvgIcon';
export default EuroSymbol;
| packages/material-ui-icons/src/EuroSymbol.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017871671298053116,
0.00017267536895815283,
0.0001666340249357745,
0.00017267536895815283,
0.0000060413440223783255
]
|
{
"id": 3,
"code_window": [
"AppContent.propTypes = {\n",
" children: PropTypes.node,\n",
" className: PropTypes.string,\n",
"};\n",
"\n",
"AppContent.contextTypes = {\n",
" styleManager: customPropTypes.muiRequired,\n",
"};"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" route: PropTypes.object.isRequired,\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "add",
"edit_start_line_idx": 37
} | // @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { createStyleSheet } from 'jss-theme-reactor';
import marked from 'marked';
import customPropTypes from 'material-ui/utils/customPropTypes';
import prism from 'docs/src/utils/prism';
const renderer = new marked.Renderer();
renderer.heading = (text, level) => {
const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
return `
<h${level}>
<a class="anchor-link" id="${escapedText}"></a>${
text
}<a class="anchor-link-style" href="#${escapedText}">${
'#'
}</a>
</h${level}>
`;
};
marked.setOptions({
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false,
highlight(code) {
return prism.highlight(code, prism.languages.jsx);
},
renderer,
});
const anchorLinkStyle = (theme) => ({
'& .anchor-link-style': {
display: 'none',
},
'&:hover .anchor-link-style': {
display: 'inline',
fontSize: '0.8em',
lineHeight: '1',
paddingLeft: theme.spacing.unit,
color: theme.palette.text.hint,
},
});
const styleSheet = createStyleSheet('MarkdownElement', (theme) => ({
root: {
fontFamily: theme.typography.fontFamily,
marginTop: theme.spacing.unit * 2,
marginBottom: theme.spacing.unit * 2,
padding: '0 10px',
'& .anchor-link': {
marginTop: -theme.spacing.unit * 12, // Offset for the anchor.
position: 'absolute',
},
'& pre': {
margin: '25px 0',
padding: '12px 18px',
backgroundColor: theme.palette.background.paper,
borderRadius: 3,
overflow: 'auto',
},
'& code': {
display: 'inline-block',
lineHeight: 1.6,
fontFamily: 'Consolas, "Liberation Mono", Menlo, Courier, monospace',
padding: '3px 6px',
color: theme.palette.text.primary,
backgroundColor: theme.palette.background.paper,
fontSize: 14,
},
'& h1': {
...theme.typography.display2,
color: theme.palette.text.secondary,
margin: '0.7em 0',
...anchorLinkStyle(theme),
},
'& h2': {
...theme.typography.display1,
color: theme.palette.text.secondary,
margin: '1em 0 0.7em',
...anchorLinkStyle(theme),
},
'& h3': {
...theme.typography.headline,
color: theme.palette.text.secondary,
margin: '1em 0 0.7em',
...anchorLinkStyle(theme),
},
'& p, & ul, & ol': {
lineHeight: 1.6,
},
'& p code, & ul code': {
fontSize: 14,
},
'& table': {
width: '100%',
borderCollapse: 'collapse',
borderSpacing: 0,
overflow: 'hidden',
},
'& thead': {
fontSize: 12,
fontWeight: theme.typography.fontWeightMedium,
color: theme.palette.text.secondary,
},
'& tbody': {
fontSize: 13,
lineHeight: 1.5,
color: theme.palette.text.primary,
},
'& td': {
borderBottom: `1px solid ${theme.palette.text.lightDivider}`,
padding: `${theme.spacing.unit}px ${theme.spacing.unit * 8}px ${
theme.spacing.unit}px ${theme.spacing.unit * 3}px`,
textAlign: 'left',
},
'& td:last-child': {
paddingRight: theme.spacing.unit * 3,
},
'& td compact': {
paddingRight: theme.spacing.unit * 3,
},
'& td code': {
fontSize: 13,
},
'& th': {
whiteSpace: 'pre',
borderBottom: `1px solid ${theme.palette.text.lightDivider}`,
padding: '0 56px 0 24px',
textAlign: 'left',
},
'& th:last-child': {
paddingRight: theme.spacing.unit * 3,
},
'& tr': {
height: 48,
},
'& thead tr': {
height: 64,
},
'& strong': {
fontWeight: theme.typography.fontWeightMedium,
},
'& blockquote': {
borderLeft: `5px solid ${theme.palette.text.hint}`,
background: theme.palette.background.paper,
padding: `${theme.spacing.unit / 2}px ${theme.spacing.unit * 3}px`,
margin: `${theme.spacing.unit * 3}px 0`,
},
'& a': {
color: theme.palette.accent.A400,
textDecoration: 'none',
'&:hover': {
textDecoration: 'underline',
},
},
},
}));
function MarkdownElement(props, context) {
const {
className,
text,
} = props;
const classes = context.styleManager.render(styleSheet);
/* eslint-disable react/no-danger */
return (
<div
className={classNames(classes.root, 'markdown-body', className)}
dangerouslySetInnerHTML={{ __html: marked(text) }}
/>
);
/* eslint-enable */
}
MarkdownElement.propTypes = {
className: PropTypes.string,
text: PropTypes.string.isRequired,
};
MarkdownElement.contextTypes = {
styleManager: customPropTypes.muiRequired,
};
export default MarkdownElement;
| docs/src/components/MarkdownElement.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.002333651063963771,
0.00048559828428551555,
0.00016579229850322008,
0.00017458597721997648,
0.0007024636142887175
]
|
{
"id": 3,
"code_window": [
"AppContent.propTypes = {\n",
" children: PropTypes.node,\n",
" className: PropTypes.string,\n",
"};\n",
"\n",
"AppContent.contextTypes = {\n",
" styleManager: customPropTypes.muiRequired,\n",
"};"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" route: PropTypes.object.isRequired,\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "add",
"edit_start_line_idx": 37
} | // @flow weak
import React from 'react';
import { assert } from 'chai';
import { createShallow } from 'src/test-utils';
import DialogActions, { styleSheet } from './DialogActions';
describe('<DialogActions />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallow();
classes = shallow.context.styleManager.render(styleSheet);
});
it('should render a div', () => {
const wrapper = shallow(
<DialogActions />,
);
assert.strictEqual(wrapper.name(), 'div');
});
it('should spread custom props on the root node', () => {
const wrapper = shallow(<DialogActions data-my-prop="woof" />);
assert.strictEqual(wrapper.prop('data-my-prop'), 'woof', 'custom prop should be woof');
});
it('should render with the user and root classes', () => {
const wrapper = shallow(<DialogActions className="woof" />);
assert.strictEqual(wrapper.hasClass('woof'), true, 'should have the "woof" class');
assert.strictEqual(wrapper.hasClass(classes.root), true, 'should have the root class');
});
it('should render children with the button class wrapped in a div with the action class', () => {
const wrapper = shallow(
<DialogActions>
<button className="woof">Hello</button>
</DialogActions>,
);
const container = wrapper.childAt(0);
assert.strictEqual(container.hasClass(classes.action), true, 'should have the action wrapper');
assert.strictEqual(container.is('div'), true, 'should be a div');
const button = container.childAt(0);
assert.strictEqual(button.is('button'), true, 'should be a button');
assert.strictEqual(button.hasClass('woof'), true, 'should have the user class');
assert.strictEqual(button.hasClass(classes.button), true, 'should have the button class');
});
});
| src/Dialog/DialogActions.spec.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0001743528846418485,
0.0001699936983641237,
0.00016640601097606122,
0.0001686450414126739,
0.000003186582944181282
]
|
{
"id": 3,
"code_window": [
"AppContent.propTypes = {\n",
" children: PropTypes.node,\n",
" className: PropTypes.string,\n",
"};\n",
"\n",
"AppContent.contextTypes = {\n",
" styleManager: customPropTypes.muiRequired,\n",
"};"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" route: PropTypes.object.isRequired,\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "add",
"edit_start_line_idx": 37
} | // @flow weak
/* eslint-disable react/no-multi-comp */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { createStyleSheet } from 'jss-theme-reactor';
import SwipeableViews from 'react-swipeable-views';
import customPropTypes from 'material-ui/utils/customPropTypes';
import Paper from 'material-ui/Paper';
import Tabs, { Tab } from 'material-ui/Tabs';
const TabContainer = (props) => (
<div style={{ padding: 20 }}>
{props.children}
</div>
);
TabContainer.propTypes = {
children: PropTypes.node.isRequired,
};
const styleSheet = createStyleSheet('FullWidthTabs', (theme) => ({
root: {
flexGrow: 1,
marginTop: 30,
},
appBar: {
backgroundColor: theme.palette.background.appBar,
},
}));
export default class FullWidthTabs extends Component {
static contextTypes = {
styleManager: customPropTypes.muiRequired,
};
state = {
index: 0,
};
handleChange = (event, index) => {
this.setState({ index });
};
handleChangeIndex = (index) => {
this.setState({ index });
};
render() {
const classes = this.context.styleManager.render(styleSheet);
return (
<Paper style={{ width: 500 }}>
<div className={classes.appBar}>
<Tabs
index={this.state.index}
onChange={this.handleChange}
textColor="accent"
fullWidth
>
<Tab label="Item One" />
<Tab label="Item Two" />
<Tab label="Item Three" />
</Tabs>
</div>
<SwipeableViews index={this.state.index} onChangeIndex={this.handleChangeIndex}>
<TabContainer>{'Item One'}</TabContainer>
<TabContainer>{'Item Two'}</TabContainer>
<TabContainer>{'Item Three'}</TabContainer>
</SwipeableViews>
</Paper>
);
}
}
| docs/src/pages/component-demos/tabs/FullWidthTabs.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.07583190500736237,
0.01020764745771885,
0.0001682629226706922,
0.0002028463495662436,
0.0248281117528677
]
|
{
"id": 3,
"code_window": [
"AppContent.propTypes = {\n",
" children: PropTypes.node,\n",
" className: PropTypes.string,\n",
"};\n",
"\n",
"AppContent.contextTypes = {\n",
" styleManager: customPropTypes.muiRequired,\n",
"};"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" route: PropTypes.object.isRequired,\n"
],
"file_path": "docs/src/components/AppContent.js",
"type": "add",
"edit_start_line_idx": 37
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Folder = (props) => (
<SvgIcon {...props}>
<path d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/>
</SvgIcon>
);
Folder = pure(Folder);
Folder.muiName = 'SvgIcon';
export default Folder;
| packages/material-ui-icons/src/Folder.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017441822274122387,
0.00017430685693398118,
0.00017419550567865372,
0.00017430685693398118,
1.1135853128507733e-7
]
|
{
"id": 4,
"code_window": [
" Router,\n",
" Route,\n",
" IndexRoute,\n",
" IndexRedirect,\n",
"} from 'react-router';\n",
"import { useScroll } from 'react-router-scroll';\n",
"import { kebabCase, titleize } from 'docs/src/utils/helpers';\n",
"import AppFrame from 'docs/src/components/AppFrame';\n",
"import AppContent from 'docs/src/components/AppContent';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 9
} | // @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { createStyleSheet } from 'jss-theme-reactor';
import marked from 'marked';
import customPropTypes from 'material-ui/utils/customPropTypes';
import prism from 'docs/src/utils/prism';
const renderer = new marked.Renderer();
renderer.heading = (text, level) => {
const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
return `
<h${level}>
<a class="anchor-link" id="${escapedText}"></a>${
text
}<a class="anchor-link-style" href="#${escapedText}">${
'#'
}</a>
</h${level}>
`;
};
marked.setOptions({
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false,
highlight(code) {
return prism.highlight(code, prism.languages.jsx);
},
renderer,
});
const anchorLinkStyle = (theme) => ({
'& .anchor-link-style': {
display: 'none',
},
'&:hover .anchor-link-style': {
display: 'inline',
fontSize: '0.8em',
lineHeight: '1',
paddingLeft: theme.spacing.unit,
color: theme.palette.text.hint,
},
});
const styleSheet = createStyleSheet('MarkdownElement', (theme) => ({
root: {
fontFamily: theme.typography.fontFamily,
marginTop: theme.spacing.unit * 2,
marginBottom: theme.spacing.unit * 2,
padding: '0 10px',
'& .anchor-link': {
marginTop: -theme.spacing.unit * 12, // Offset for the anchor.
position: 'absolute',
},
'& pre': {
margin: '25px 0',
padding: '12px 18px',
backgroundColor: theme.palette.background.paper,
borderRadius: 3,
overflow: 'auto',
},
'& code': {
display: 'inline-block',
lineHeight: 1.6,
fontFamily: 'Consolas, "Liberation Mono", Menlo, Courier, monospace',
padding: '3px 6px',
color: theme.palette.text.primary,
backgroundColor: theme.palette.background.paper,
fontSize: 14,
},
'& h1': {
...theme.typography.display2,
color: theme.palette.text.secondary,
margin: '0.7em 0',
...anchorLinkStyle(theme),
},
'& h2': {
...theme.typography.display1,
color: theme.palette.text.secondary,
margin: '1em 0 0.7em',
...anchorLinkStyle(theme),
},
'& h3': {
...theme.typography.headline,
color: theme.palette.text.secondary,
margin: '1em 0 0.7em',
...anchorLinkStyle(theme),
},
'& p, & ul, & ol': {
lineHeight: 1.6,
},
'& p code, & ul code': {
fontSize: 14,
},
'& table': {
width: '100%',
borderCollapse: 'collapse',
borderSpacing: 0,
overflow: 'hidden',
},
'& thead': {
fontSize: 12,
fontWeight: theme.typography.fontWeightMedium,
color: theme.palette.text.secondary,
},
'& tbody': {
fontSize: 13,
lineHeight: 1.5,
color: theme.palette.text.primary,
},
'& td': {
borderBottom: `1px solid ${theme.palette.text.lightDivider}`,
padding: `${theme.spacing.unit}px ${theme.spacing.unit * 8}px ${
theme.spacing.unit}px ${theme.spacing.unit * 3}px`,
textAlign: 'left',
},
'& td:last-child': {
paddingRight: theme.spacing.unit * 3,
},
'& td compact': {
paddingRight: theme.spacing.unit * 3,
},
'& td code': {
fontSize: 13,
},
'& th': {
whiteSpace: 'pre',
borderBottom: `1px solid ${theme.palette.text.lightDivider}`,
padding: '0 56px 0 24px',
textAlign: 'left',
},
'& th:last-child': {
paddingRight: theme.spacing.unit * 3,
},
'& tr': {
height: 48,
},
'& thead tr': {
height: 64,
},
'& strong': {
fontWeight: theme.typography.fontWeightMedium,
},
'& blockquote': {
borderLeft: `5px solid ${theme.palette.text.hint}`,
background: theme.palette.background.paper,
padding: `${theme.spacing.unit / 2}px ${theme.spacing.unit * 3}px`,
margin: `${theme.spacing.unit * 3}px 0`,
},
'& a': {
color: theme.palette.accent.A400,
textDecoration: 'none',
'&:hover': {
textDecoration: 'underline',
},
},
},
}));
function MarkdownElement(props, context) {
const {
className,
text,
} = props;
const classes = context.styleManager.render(styleSheet);
/* eslint-disable react/no-danger */
return (
<div
className={classNames(classes.root, 'markdown-body', className)}
dangerouslySetInnerHTML={{ __html: marked(text) }}
/>
);
/* eslint-enable */
}
MarkdownElement.propTypes = {
className: PropTypes.string,
text: PropTypes.string.isRequired,
};
MarkdownElement.contextTypes = {
styleManager: customPropTypes.muiRequired,
};
export default MarkdownElement;
| docs/src/components/MarkdownElement.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0001778442965587601,
0.00017416586342733353,
0.00016927107935771346,
0.0001754065160639584,
0.000002736772103162366
]
|
{
"id": 4,
"code_window": [
" Router,\n",
" Route,\n",
" IndexRoute,\n",
" IndexRedirect,\n",
"} from 'react-router';\n",
"import { useScroll } from 'react-router-scroll';\n",
"import { kebabCase, titleize } from 'docs/src/utils/helpers';\n",
"import AppFrame from 'docs/src/components/AppFrame';\n",
"import AppContent from 'docs/src/components/AppContent';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 9
} | // @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from '../utils/customPropTypes';
export const styleSheet = createStyleSheet('MuiDialogContent', () => {
const gutter = 24;
return {
root: {
flex: '1 1 auto',
overflowY: 'auto',
padding: `0 ${gutter}px ${gutter}px ${gutter}px`,
'&:first-child': {
paddingTop: gutter,
},
},
};
});
export default function DialogContent(props, context) {
const {
children,
className,
...other
} = props;
const classes = context.styleManager.render(styleSheet);
return (
<div className={classNames(classes.root, className)} {...other}>
{children}
</div>
);
}
DialogContent.propTypes = {
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
};
DialogContent.contextTypes = {
styleManager: customPropTypes.muiRequired,
};
| src/Dialog/DialogContent.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0001731791562633589,
0.00016875914297997952,
0.00016427689115516841,
0.00016860917094163597,
0.0000030433830033871345
]
|
{
"id": 4,
"code_window": [
" Router,\n",
" Route,\n",
" IndexRoute,\n",
" IndexRedirect,\n",
"} from 'react-router';\n",
"import { useScroll } from 'react-router-scroll';\n",
"import { kebabCase, titleize } from 'docs/src/utils/helpers';\n",
"import AppFrame from 'docs/src/components/AppFrame';\n",
"import AppContent from 'docs/src/components/AppContent';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 9
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let List = (props) => (
<SvgIcon {...props}>
<path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"/>
</SvgIcon>
);
List = pure(List);
List.muiName = 'SvgIcon';
export default List;
| packages/material-ui-icons/src/List.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017628632485866547,
0.00017311685951426625,
0.00016994740872178227,
0.00017311685951426625,
0.0000031694580684415996
]
|
{
"id": 4,
"code_window": [
" Router,\n",
" Route,\n",
" IndexRoute,\n",
" IndexRedirect,\n",
"} from 'react-router';\n",
"import { useScroll } from 'react-router-scroll';\n",
"import { kebabCase, titleize } from 'docs/src/utils/helpers';\n",
"import AppFrame from 'docs/src/components/AppFrame';\n",
"import AppContent from 'docs/src/components/AppContent';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 9
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let SubdirectoryArrowRight = (props) => (
<SvgIcon {...props}>
<path d="M19 15l-6 6-1.42-1.42L15.17 16H4V4h2v10h9.17l-3.59-3.58L13 9l6 6z"/>
</SvgIcon>
);
SubdirectoryArrowRight = pure(SubdirectoryArrowRight);
SubdirectoryArrowRight.muiName = 'SvgIcon';
export default SubdirectoryArrowRight;
| packages/material-ui-icons/src/SubdirectoryArrowRight.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0001736005797283724,
0.00017236711573787034,
0.0001711336662992835,
0.00017236711573787034,
0.0000012334567145444453
]
|
{
"id": 5,
"code_window": [
" title=\"Getting Started\"\n",
" path=\"/getting-started\"\n",
" nav\n",
" component={AppContent}\n",
" >\n",
" <IndexRedirect to=\"installation\" />\n",
" <Route\n",
" title=\"Installation\"\n",
" path=\"/getting-started/installation\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 33
} | // @flow weak
import React from 'react';
import {
applyRouterMiddleware,
browserHistory,
Router,
Route,
IndexRoute,
IndexRedirect,
} from 'react-router';
import { useScroll } from 'react-router-scroll';
import { kebabCase, titleize } from 'docs/src/utils/helpers';
import AppFrame from 'docs/src/components/AppFrame';
import AppContent from 'docs/src/components/AppContent';
import MarkdownDocs from 'docs/src/components/MarkdownDocs';
import Home from 'docs/src/pages/Home';
import { componentAPIs, requireMarkdown, demos, requireDemo } from 'docs/src/components/files';
export default function AppRouter() {
return (
<Router
history={browserHistory}
render={applyRouterMiddleware(useScroll())}
>
<Route title="Material UI" path="/" component={AppFrame}>
<IndexRoute dockDrawer component={Home} title={null} />
<Route
title="Getting Started"
path="/getting-started"
nav
component={AppContent}
>
<IndexRedirect to="installation" />
<Route
title="Installation"
path="/getting-started/installation"
content={requireMarkdown('./getting-started/installation.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Usage"
path="/getting-started/usage"
content={requireMarkdown('./getting-started/usage.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Server Rendering"
path="/getting-started/server-rendering"
content={requireMarkdown('./getting-started/server-rendering.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Examples"
path="/getting-started/examples"
content={requireMarkdown('./getting-started/examples.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Supported Components"
path="/getting-started/supported-components"
content={requireMarkdown('./getting-started/supported-components.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Customization"
path="/customization"
nav
component={AppContent}
>
<IndexRedirect to="themes" />
<Route
title="Themes"
path="/customization/themes"
content={requireMarkdown('./customization/themes.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Composition"
path="/customization/composition"
content={requireMarkdown('./customization/composition.md')}
component={MarkdownDocs}
nav
/>
<Route
title="API"
path="/customization/api"
content={requireMarkdown('./customization/api.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Style"
path="/style"
nav
component={AppContent}
>
<Route
title="Color"
path="/style/color"
content={requireMarkdown('./style/color.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Icons"
path="/style/icons"
content={requireMarkdown('./style/icons.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Typography"
path="/style/typography"
content={requireMarkdown('./style/typography.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Layout"
path="/layout"
nav
component={AppContent}
>
<Route
title="Responsive UI"
path="/layout/responsive-ui"
content={requireMarkdown('./layout/responsive-ui.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Component Demos"
path="/component-demos"
nav
component={AppContent}
>
{demos.map(((demo) => {
return (
<Route
key={demo.name}
title={titleize(demo.name)}
path={`/component-demos/${demo.name}`}
content={requireDemo(demo.path)}
component={MarkdownDocs}
demo={demo}
nav
/>
);
}))}
</Route>
<Route
title="Component API"
path="/component-api"
nav
component={AppContent}
>
{componentAPIs.map(((componentAPI) => {
return (
<Route
key={componentAPI.name}
title={componentAPI.name}
path={`/component-api/${kebabCase(componentAPI.name)}`}
content={requireMarkdown(componentAPI.path)}
component={MarkdownDocs}
componentAPI={componentAPI}
nav
/>
);
}))}
</Route>
<Route
title="Discover More"
path="/discover-more"
nav
component={AppContent}
>
<IndexRedirect to="community" />
<Route
title="Community"
path="/discover-more/community"
content={requireMarkdown('./discover-more/community.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Showcase"
path="/discover-more/showcase"
content={requireMarkdown('./discover-more/showcase.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Related Projects"
path="/discover-more/related-projects"
content={requireMarkdown('./discover-more/related-projects.md')}
component={MarkdownDocs}
nav
/>
</Route>
</Route>
</Router>
);
}
| docs/src/components/AppRouter.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.9735859036445618,
0.05235262215137482,
0.00016362844326067716,
0.004333698656409979,
0.20134711265563965
]
|
{
"id": 5,
"code_window": [
" title=\"Getting Started\"\n",
" path=\"/getting-started\"\n",
" nav\n",
" component={AppContent}\n",
" >\n",
" <IndexRedirect to=\"installation\" />\n",
" <Route\n",
" title=\"Installation\"\n",
" path=\"/getting-started/installation\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 33
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Audiotrack = (props) => (
<SvgIcon {...props}>
<path d="M12 3v9.28c-.47-.17-.97-.28-1.5-.28C8.01 12 6 14.01 6 16.5S8.01 21 10.5 21c2.31 0 4.2-1.75 4.45-4H15V6h4V3h-7z"/>
</SvgIcon>
);
Audiotrack = pure(Audiotrack);
Audiotrack.muiName = 'SvgIcon';
export default Audiotrack;
| packages/material-ui-icons/src/Audiotrack.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017316527373623103,
0.00017313580610789359,
0.00017310633847955614,
0.00017313580610789359,
2.9467628337442875e-8
]
|
{
"id": 5,
"code_window": [
" title=\"Getting Started\"\n",
" path=\"/getting-started\"\n",
" nav\n",
" component={AppContent}\n",
" >\n",
" <IndexRedirect to=\"installation\" />\n",
" <Route\n",
" title=\"Installation\"\n",
" path=\"/getting-started/installation\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 33
} | List
====
A material list root element.
```jsx
<List>
<ListItem>....</ListItem>
</List>
```
Props
-----
| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| children | node | | The content of the component. |
| className | string | | The CSS class name of the root element. |
| component | union: string<br> func<br> | 'div' | The component used for the root node. Either a string to use a DOM element or a component. |
| dense | bool | false | If `true`, compact vertical padding designed for keyboard and mouse input will be used for the list and list items. The property is available to descendant components as the `dense` context. |
| disablePadding | bool | false | If `true`, vertical padding will be removed from the list. |
| subheader | node | | The content of the component, normally `ListItem`. |
Any other properties supplied will be spread to the root element.
| docs/src/pages/component-api/List/List.md | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0001689393975539133,
0.00016772764502093196,
0.00016665071598254144,
0.00016759279242251068,
9.392027777721523e-7
]
|
{
"id": 5,
"code_window": [
" title=\"Getting Started\"\n",
" path=\"/getting-started\"\n",
" nav\n",
" component={AppContent}\n",
" >\n",
" <IndexRedirect to=\"installation\" />\n",
" <Route\n",
" title=\"Installation\"\n",
" path=\"/getting-started/installation\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 33
} | // @flow weak
import React from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from 'material-ui/utils/customPropTypes';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import IconButton from 'material-ui/IconButton';
import MenuIcon from 'material-ui-icons/Menu';
const styleSheet = createStyleSheet('ButtonAppBar', () => ({
root: {
position: 'relative',
marginTop: 30,
width: '100%',
},
appBar: {
position: 'relative',
},
flex: {
flex: 1,
},
}));
export default function ButtonAppBar(props, context) {
const classes = context.styleManager.render(styleSheet);
return (
<div className={classes.root}>
<AppBar className={classes.appBar}>
<Toolbar>
<IconButton contrast>
<MenuIcon />
</IconButton>
<Typography type="title" colorInherit className={classes.flex}>Title</Typography>
<Button contrast>Login</Button>
</Toolbar>
</AppBar>
</div>
);
}
ButtonAppBar.contextTypes = {
styleManager: customPropTypes.muiRequired,
};
| docs/src/pages/component-demos/app-bar/ButtonAppBar.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017394355381838977,
0.00017169550119433552,
0.0001697404368314892,
0.00017129200568888336,
0.000001513049483037321
]
|
{
"id": 6,
"code_window": [
" nav\n",
" component={AppContent}\n",
" >\n",
" <IndexRedirect to=\"themes\" />\n",
" <Route\n",
" title=\"Themes\"\n",
" path=\"/customization/themes\"\n",
" content={requireMarkdown('./customization/themes.md')}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 76
} | // @flow weak
import React from 'react';
import {
applyRouterMiddleware,
browserHistory,
Router,
Route,
IndexRoute,
IndexRedirect,
} from 'react-router';
import { useScroll } from 'react-router-scroll';
import { kebabCase, titleize } from 'docs/src/utils/helpers';
import AppFrame from 'docs/src/components/AppFrame';
import AppContent from 'docs/src/components/AppContent';
import MarkdownDocs from 'docs/src/components/MarkdownDocs';
import Home from 'docs/src/pages/Home';
import { componentAPIs, requireMarkdown, demos, requireDemo } from 'docs/src/components/files';
export default function AppRouter() {
return (
<Router
history={browserHistory}
render={applyRouterMiddleware(useScroll())}
>
<Route title="Material UI" path="/" component={AppFrame}>
<IndexRoute dockDrawer component={Home} title={null} />
<Route
title="Getting Started"
path="/getting-started"
nav
component={AppContent}
>
<IndexRedirect to="installation" />
<Route
title="Installation"
path="/getting-started/installation"
content={requireMarkdown('./getting-started/installation.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Usage"
path="/getting-started/usage"
content={requireMarkdown('./getting-started/usage.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Server Rendering"
path="/getting-started/server-rendering"
content={requireMarkdown('./getting-started/server-rendering.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Examples"
path="/getting-started/examples"
content={requireMarkdown('./getting-started/examples.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Supported Components"
path="/getting-started/supported-components"
content={requireMarkdown('./getting-started/supported-components.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Customization"
path="/customization"
nav
component={AppContent}
>
<IndexRedirect to="themes" />
<Route
title="Themes"
path="/customization/themes"
content={requireMarkdown('./customization/themes.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Composition"
path="/customization/composition"
content={requireMarkdown('./customization/composition.md')}
component={MarkdownDocs}
nav
/>
<Route
title="API"
path="/customization/api"
content={requireMarkdown('./customization/api.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Style"
path="/style"
nav
component={AppContent}
>
<Route
title="Color"
path="/style/color"
content={requireMarkdown('./style/color.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Icons"
path="/style/icons"
content={requireMarkdown('./style/icons.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Typography"
path="/style/typography"
content={requireMarkdown('./style/typography.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Layout"
path="/layout"
nav
component={AppContent}
>
<Route
title="Responsive UI"
path="/layout/responsive-ui"
content={requireMarkdown('./layout/responsive-ui.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Component Demos"
path="/component-demos"
nav
component={AppContent}
>
{demos.map(((demo) => {
return (
<Route
key={demo.name}
title={titleize(demo.name)}
path={`/component-demos/${demo.name}`}
content={requireDemo(demo.path)}
component={MarkdownDocs}
demo={demo}
nav
/>
);
}))}
</Route>
<Route
title="Component API"
path="/component-api"
nav
component={AppContent}
>
{componentAPIs.map(((componentAPI) => {
return (
<Route
key={componentAPI.name}
title={componentAPI.name}
path={`/component-api/${kebabCase(componentAPI.name)}`}
content={requireMarkdown(componentAPI.path)}
component={MarkdownDocs}
componentAPI={componentAPI}
nav
/>
);
}))}
</Route>
<Route
title="Discover More"
path="/discover-more"
nav
component={AppContent}
>
<IndexRedirect to="community" />
<Route
title="Community"
path="/discover-more/community"
content={requireMarkdown('./discover-more/community.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Showcase"
path="/discover-more/showcase"
content={requireMarkdown('./discover-more/showcase.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Related Projects"
path="/discover-more/related-projects"
content={requireMarkdown('./discover-more/related-projects.md')}
component={MarkdownDocs}
nav
/>
</Route>
</Route>
</Router>
);
}
| docs/src/components/AppRouter.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.9904819130897522,
0.07899399846792221,
0.00016830270760692656,
0.002907024696469307,
0.24281401932239532
]
|
{
"id": 6,
"code_window": [
" nav\n",
" component={AppContent}\n",
" >\n",
" <IndexRedirect to=\"themes\" />\n",
" <Route\n",
" title=\"Themes\"\n",
" path=\"/customization/themes\"\n",
" content={requireMarkdown('./customization/themes.md')}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 76
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Gif = (props) => (
<SvgIcon {...props}>
<path d="M11.5 9H13v6h-1.5zM9 9H6c-.6 0-1 .5-1 1v4c0 .5.4 1 1 1h3c.6 0 1-.5 1-1v-2H8.5v1.5h-2v-3H10V10c0-.5-.4-1-1-1zm10 1.5V9h-4.5v6H16v-2h2v-1.5h-2v-1z"/>
</SvgIcon>
);
Gif = pure(Gif);
Gif.muiName = 'SvgIcon';
export default Gif;
| packages/material-ui-icons/src/Gif.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017712017870508134,
0.0001767519279383123,
0.00017638367717154324,
0.0001767519279383123,
3.6825076676905155e-7
]
|
{
"id": 6,
"code_window": [
" nav\n",
" component={AppContent}\n",
" >\n",
" <IndexRedirect to=\"themes\" />\n",
" <Route\n",
" title=\"Themes\"\n",
" path=\"/customization/themes\"\n",
" content={requireMarkdown('./customization/themes.md')}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 76
} | // @flow weak
import addEventListener from 'dom-helpers/events/on';
import removeEventListener from 'dom-helpers/events/off';
export default function (node, event, handler, options) {
addEventListener(node, event, handler, options);
return {
remove() {
removeEventListener(node, event, handler, options);
},
};
}
| src/utils/addEventListener.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017369494889862835,
0.00017235917039215565,
0.00017102339188568294,
0.00017235917039215565,
0.0000013357785064727068
]
|
{
"id": 6,
"code_window": [
" nav\n",
" component={AppContent}\n",
" >\n",
" <IndexRedirect to=\"themes\" />\n",
" <Route\n",
" title=\"Themes\"\n",
" path=\"/customization/themes\"\n",
" content={requireMarkdown('./customization/themes.md')}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 76
} | <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M8 20v14h6V20H8zm12 0v14h6V20h-6zM4 44h38v-6H4v6zm28-24v14h6V20h-6zM23 2L4 12v4h38v-4L23 2z"/></svg> | packages/material-ui-icons/test/fixtures/material-design-icons/svg/action/svg/production/ic_account_balance_48px.svg | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017083775310311466,
0.00017083775310311466,
0.00017083775310311466,
0.00017083775310311466,
0
]
|
{
"id": 7,
"code_window": [
" title=\"Discover More\"\n",
" path=\"/discover-more\"\n",
" nav\n",
" component={AppContent}\n",
" >\n",
" <IndexRedirect to=\"community\" />\n",
" <Route\n",
" title=\"Community\"\n",
" path=\"/discover-more/community\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 187
} | // @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Link as LinkRouter } from 'react-router';
import { withStyles, createStyleSheet } from 'material-ui/styles';
const styleSheet = createStyleSheet('Link', (theme) => ({
root: {
color: 'inherit',
textDecoration: 'inherit',
'&:hover': {
textDecoration: 'underline',
},
},
primary: {
color: theme.palette.primary[500],
},
}));
function Link(props) {
const {
component: ComponentProp,
classes,
className,
variant,
to,
...other
} = props;
let Component;
if (ComponentProp) {
Component = ComponentProp;
} else if (to) {
Component = LinkRouter;
} else {
Component = 'a';
}
return (
<Component
to={to}
className={classNames(classes.root, {
[classes.primary]: variant === 'primary',
}, className)}
{...other}
/>
);
}
Link.propTypes = {
classes: PropTypes.object.isRequired,
className: PropTypes.string,
component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
to: PropTypes.string,
variant: PropTypes.oneOf(['primary']),
};
export default withStyles(styleSheet)(Link);
| docs/src/components/Link.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017644524632487446,
0.00016919885820243508,
0.00016237354429904372,
0.0001708696800051257,
0.000005416759449872188
]
|
{
"id": 7,
"code_window": [
" title=\"Discover More\"\n",
" path=\"/discover-more\"\n",
" nav\n",
" component={AppContent}\n",
" >\n",
" <IndexRedirect to=\"community\" />\n",
" <Route\n",
" title=\"Community\"\n",
" path=\"/discover-more/community\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 187
} | // flow-typed signature: 9dd848e8027a6162f0d617747e34a623
// flow-typed version: <<STUB>>/warning_v^3.0.0/flow_v0.44.2
/**
* This is an autogenerated libdef stub for:
*
* 'warning'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'warning' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'warning/browser' {
declare module.exports: any;
}
declare module 'warning/warning' {
declare module.exports: any;
}
// Filename aliases
declare module 'warning/browser.js' {
declare module.exports: $Exports<'warning/browser'>;
}
declare module 'warning/warning.js' {
declare module.exports: $Exports<'warning/warning'>;
}
| flow-typed/npm/warning_vx.x.x.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017527198360767215,
0.00016861443873494864,
0.0001641040580580011,
0.00016754085663706064,
0.0000047512826313322876
]
|
{
"id": 7,
"code_window": [
" title=\"Discover More\"\n",
" path=\"/discover-more\"\n",
" nav\n",
" component={AppContent}\n",
" >\n",
" <IndexRedirect to=\"community\" />\n",
" <Route\n",
" title=\"Community\"\n",
" path=\"/discover-more/community\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 187
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let BatteryChargingFull = (props) => (
<SvgIcon {...props}>
<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM11 20v-5.5H9L13 7v5.5h2L11 20z"/>
</SvgIcon>
);
BatteryChargingFull = pure(BatteryChargingFull);
BatteryChargingFull.muiName = 'SvgIcon';
export default BatteryChargingFull;
| packages/material-ui-icons/src/BatteryChargingFull.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017457862850278616,
0.00017281429609283805,
0.00017104996368288994,
0.00017281429609283805,
0.0000017643324099481106
]
|
{
"id": 7,
"code_window": [
" title=\"Discover More\"\n",
" path=\"/discover-more\"\n",
" nav\n",
" component={AppContent}\n",
" >\n",
" <IndexRedirect to=\"community\" />\n",
" <Route\n",
" title=\"Community\"\n",
" path=\"/discover-more/community\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "docs/src/components/AppRouter.js",
"type": "replace",
"edit_start_line_idx": 187
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let BorderInner = (props) => (
<SvgIcon {...props}>
<path d="M3 21h2v-2H3v2zm4 0h2v-2H7v2zM5 7H3v2h2V7zM3 17h2v-2H3v2zM9 3H7v2h2V3zM5 3H3v2h2V3zm12 0h-2v2h2V3zm2 6h2V7h-2v2zm0-6v2h2V3h-2zm-4 18h2v-2h-2v2zM13 3h-2v8H3v2h8v8h2v-8h8v-2h-8V3zm6 18h2v-2h-2v2zm0-4h2v-2h-2v2z"/>
</SvgIcon>
);
BorderInner = pure(BorderInner);
BorderInner.muiName = 'SvgIcon';
export default BorderInner;
| packages/material-ui-icons/src/BorderInner.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017360322817694396,
0.00017075380310416222,
0.00016790437803138047,
0.00017075380310416222,
0.0000028494250727817416
]
|
{
"id": 8,
"code_window": [
"import { withStyles, createStyleSheet } from 'material-ui/styles';\n",
"\n",
"const styleSheet = createStyleSheet('Link', (theme) => ({\n",
" root: {\n",
" color: 'inherit',\n",
" textDecoration: 'inherit',\n",
" '&:hover': {\n",
" textDecoration: 'underline',\n",
" },\n",
" },\n",
" primary: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" textDecoration: 'none',\n"
],
"file_path": "docs/src/components/Link.js",
"type": "replace",
"edit_start_line_idx": 11
} | // @flow weak
import React from 'react';
import {
applyRouterMiddleware,
browserHistory,
Router,
Route,
IndexRoute,
IndexRedirect,
} from 'react-router';
import { useScroll } from 'react-router-scroll';
import { kebabCase, titleize } from 'docs/src/utils/helpers';
import AppFrame from 'docs/src/components/AppFrame';
import AppContent from 'docs/src/components/AppContent';
import MarkdownDocs from 'docs/src/components/MarkdownDocs';
import Home from 'docs/src/pages/Home';
import { componentAPIs, requireMarkdown, demos, requireDemo } from 'docs/src/components/files';
export default function AppRouter() {
return (
<Router
history={browserHistory}
render={applyRouterMiddleware(useScroll())}
>
<Route title="Material UI" path="/" component={AppFrame}>
<IndexRoute dockDrawer component={Home} title={null} />
<Route
title="Getting Started"
path="/getting-started"
nav
component={AppContent}
>
<IndexRedirect to="installation" />
<Route
title="Installation"
path="/getting-started/installation"
content={requireMarkdown('./getting-started/installation.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Usage"
path="/getting-started/usage"
content={requireMarkdown('./getting-started/usage.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Server Rendering"
path="/getting-started/server-rendering"
content={requireMarkdown('./getting-started/server-rendering.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Examples"
path="/getting-started/examples"
content={requireMarkdown('./getting-started/examples.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Supported Components"
path="/getting-started/supported-components"
content={requireMarkdown('./getting-started/supported-components.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Customization"
path="/customization"
nav
component={AppContent}
>
<IndexRedirect to="themes" />
<Route
title="Themes"
path="/customization/themes"
content={requireMarkdown('./customization/themes.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Composition"
path="/customization/composition"
content={requireMarkdown('./customization/composition.md')}
component={MarkdownDocs}
nav
/>
<Route
title="API"
path="/customization/api"
content={requireMarkdown('./customization/api.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Style"
path="/style"
nav
component={AppContent}
>
<Route
title="Color"
path="/style/color"
content={requireMarkdown('./style/color.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Icons"
path="/style/icons"
content={requireMarkdown('./style/icons.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Typography"
path="/style/typography"
content={requireMarkdown('./style/typography.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Layout"
path="/layout"
nav
component={AppContent}
>
<Route
title="Responsive UI"
path="/layout/responsive-ui"
content={requireMarkdown('./layout/responsive-ui.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Component Demos"
path="/component-demos"
nav
component={AppContent}
>
{demos.map(((demo) => {
return (
<Route
key={demo.name}
title={titleize(demo.name)}
path={`/component-demos/${demo.name}`}
content={requireDemo(demo.path)}
component={MarkdownDocs}
demo={demo}
nav
/>
);
}))}
</Route>
<Route
title="Component API"
path="/component-api"
nav
component={AppContent}
>
{componentAPIs.map(((componentAPI) => {
return (
<Route
key={componentAPI.name}
title={componentAPI.name}
path={`/component-api/${kebabCase(componentAPI.name)}`}
content={requireMarkdown(componentAPI.path)}
component={MarkdownDocs}
componentAPI={componentAPI}
nav
/>
);
}))}
</Route>
<Route
title="Discover More"
path="/discover-more"
nav
component={AppContent}
>
<IndexRedirect to="community" />
<Route
title="Community"
path="/discover-more/community"
content={requireMarkdown('./discover-more/community.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Showcase"
path="/discover-more/showcase"
content={requireMarkdown('./discover-more/showcase.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Related Projects"
path="/discover-more/related-projects"
content={requireMarkdown('./discover-more/related-projects.md')}
component={MarkdownDocs}
nav
/>
</Route>
</Route>
</Router>
);
}
| docs/src/components/AppRouter.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017732549167703837,
0.00017458548245485872,
0.00017106335144490004,
0.00017456687055528164,
0.000001530631493551482
]
|
{
"id": 8,
"code_window": [
"import { withStyles, createStyleSheet } from 'material-ui/styles';\n",
"\n",
"const styleSheet = createStyleSheet('Link', (theme) => ({\n",
" root: {\n",
" color: 'inherit',\n",
" textDecoration: 'inherit',\n",
" '&:hover': {\n",
" textDecoration: 'underline',\n",
" },\n",
" },\n",
" primary: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" textDecoration: 'none',\n"
],
"file_path": "docs/src/components/Link.js",
"type": "replace",
"edit_start_line_idx": 11
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let RssFeed = (props) => (
<SvgIcon {...props}>
<circle cx="6.18" cy="17.82" r="2.18"/><path d="M4 4.44v2.83c7.03 0 12.73 5.7 12.73 12.73h2.83c0-8.59-6.97-15.56-15.56-15.56zm0 5.66v2.83c3.9 0 7.07 3.17 7.07 7.07h2.83c0-5.47-4.43-9.9-9.9-9.9z"/>
</SvgIcon>
);
RssFeed = pure(RssFeed);
RssFeed.muiName = 'SvgIcon';
export default RssFeed;
| packages/material-ui-icons/src/RssFeed.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017526828742120415,
0.0001716144324745983,
0.00016796057752799243,
0.0001716144324745983,
0.000003653854946605861
]
|
{
"id": 8,
"code_window": [
"import { withStyles, createStyleSheet } from 'material-ui/styles';\n",
"\n",
"const styleSheet = createStyleSheet('Link', (theme) => ({\n",
" root: {\n",
" color: 'inherit',\n",
" textDecoration: 'inherit',\n",
" '&:hover': {\n",
" textDecoration: 'underline',\n",
" },\n",
" },\n",
" primary: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" textDecoration: 'none',\n"
],
"file_path": "docs/src/components/Link.js",
"type": "replace",
"edit_start_line_idx": 11
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Flare = (props) => (
<SvgIcon {...props}>
<path d="M7 11H1v2h6v-2zm2.17-3.24L7.05 5.64 5.64 7.05l2.12 2.12 1.41-1.41zM13 1h-2v6h2V1zm5.36 6.05l-1.41-1.41-2.12 2.12 1.41 1.41 2.12-2.12zM17 11v2h6v-2h-6zm-5-2c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3zm2.83 7.24l2.12 2.12 1.41-1.41-2.12-2.12-1.41 1.41zm-9.19.71l1.41 1.41 2.12-2.12-1.41-1.41-2.12 2.12zM11 23h2v-6h-2v6z"/>
</SvgIcon>
);
Flare = pure(Flare);
Flare.muiName = 'SvgIcon';
export default Flare;
| packages/material-ui-icons/src/Flare.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0001739607978379354,
0.00016976328333839774,
0.0001655657688388601,
0.00016976328333839774,
0.000004197514499537647
]
|
{
"id": 8,
"code_window": [
"import { withStyles, createStyleSheet } from 'material-ui/styles';\n",
"\n",
"const styleSheet = createStyleSheet('Link', (theme) => ({\n",
" root: {\n",
" color: 'inherit',\n",
" textDecoration: 'inherit',\n",
" '&:hover': {\n",
" textDecoration: 'underline',\n",
" },\n",
" },\n",
" primary: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" textDecoration: 'none',\n"
],
"file_path": "docs/src/components/Link.js",
"type": "replace",
"edit_start_line_idx": 11
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Traffic = (props) => (
<SvgIcon {...props}>
<path d="M20 10h-3V8.86c1.72-.45 3-2 3-3.86h-3V4c0-.55-.45-1-1-1H8c-.55 0-1 .45-1 1v1H4c0 1.86 1.28 3.41 3 3.86V10H4c0 1.86 1.28 3.41 3 3.86V15H4c0 1.86 1.28 3.41 3 3.86V20c0 .55.45 1 1 1h8c.55 0 1-.45 1-1v-1.14c1.72-.45 3-2 3-3.86h-3v-1.14c1.72-.45 3-2 3-3.86zm-8 9c-1.11 0-2-.9-2-2s.89-2 2-2c1.1 0 2 .9 2 2s-.89 2-2 2zm0-5c-1.11 0-2-.9-2-2s.89-2 2-2c1.1 0 2 .9 2 2s-.89 2-2 2zm0-5c-1.11 0-2-.9-2-2 0-1.11.89-2 2-2 1.1 0 2 .89 2 2 0 1.1-.89 2-2 2z"/>
</SvgIcon>
);
Traffic = pure(Traffic);
Traffic.muiName = 'SvgIcon';
export default Traffic;
| packages/material-ui-icons/src/Traffic.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0010416385484859347,
0.0006053909892216325,
0.00016914345906116068,
0.0006053909892216325,
0.00043624755926430225
]
|
{
"id": 9,
"code_window": [
" },\n",
" },\n",
" primary: {\n",
" color: theme.palette.primary[500],\n",
" },\n",
"}));\n",
"\n",
"function Link(props) {\n",
" const {\n",
" component: ComponentProp,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" accent: {\n",
" color: theme.palette.accent.A400,\n",
" },\n"
],
"file_path": "docs/src/components/Link.js",
"type": "add",
"edit_start_line_idx": 19
} | // @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from 'material-ui/utils/customPropTypes';
export const styleSheet = createStyleSheet('AppContent', (theme) => {
return {
content: theme.mixins.gutters({
paddingTop: 80,
flex: '1 1 100%',
maxWidth: '100%',
margin: '0 auto',
}),
[theme.breakpoints.up(948)]: {
content: {
maxWidth: 900,
},
},
};
});
export default function AppContent(props, context) {
const { className, children } = props;
const classes = context.styleManager.render(styleSheet);
return (
<div className={classNames(classes.content, className)}>
{children}
</div>
);
}
AppContent.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
};
AppContent.contextTypes = {
styleManager: customPropTypes.muiRequired,
};
| docs/src/components/AppContent.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0011096542002633214,
0.0004595025966409594,
0.00017075501091312617,
0.00025119708152487874,
0.000360857171472162
]
|
{
"id": 9,
"code_window": [
" },\n",
" },\n",
" primary: {\n",
" color: theme.palette.primary[500],\n",
" },\n",
"}));\n",
"\n",
"function Link(props) {\n",
" const {\n",
" component: ComponentProp,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" accent: {\n",
" color: theme.palette.accent.A400,\n",
" },\n"
],
"file_path": "docs/src/components/Link.js",
"type": "add",
"edit_start_line_idx": 19
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let DriveEta = (props) => (
<SvgIcon {...props}>
<path d="M18.92 5.01C18.72 4.42 18.16 4 17.5 4h-11c-.66 0-1.21.42-1.42 1.01L3 11v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 15c-.83 0-1.5-.67-1.5-1.5S5.67 12 6.5 12s1.5.67 1.5 1.5S7.33 15 6.5 15zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 10l1.5-4.5h11L19 10H5z"/>
</SvgIcon>
);
DriveEta = pure(DriveEta);
DriveEta.muiName = 'SvgIcon';
export default DriveEta;
| packages/material-ui-icons/src/DriveEta.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00016990318545140326,
0.00016910367412492633,
0.00016830414824653417,
0.00016910367412492633,
7.995186024345458e-7
]
|
{
"id": 9,
"code_window": [
" },\n",
" },\n",
" primary: {\n",
" color: theme.palette.primary[500],\n",
" },\n",
"}));\n",
"\n",
"function Link(props) {\n",
" const {\n",
" component: ComponentProp,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" accent: {\n",
" color: theme.palette.accent.A400,\n",
" },\n"
],
"file_path": "docs/src/components/Link.js",
"type": "add",
"edit_start_line_idx": 19
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let LocalPharmacy = (props) => (
<SvgIcon {...props}>
<path d="M21 5h-2.64l1.14-3.14L17.15 1l-1.46 4H3v2l2 6-2 6v2h18v-2l-2-6 2-6V5zm-5 9h-3v3h-2v-3H8v-2h3V9h2v3h3v2z"/>
</SvgIcon>
);
LocalPharmacy = pure(LocalPharmacy);
LocalPharmacy.muiName = 'SvgIcon';
export default LocalPharmacy;
| packages/material-ui-icons/src/LocalPharmacy.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00018112805264536291,
0.00017636909615248442,
0.00017161015421152115,
0.00017636909615248442,
0.0000047589492169208825
]
|
{
"id": 9,
"code_window": [
" },\n",
" },\n",
" primary: {\n",
" color: theme.palette.primary[500],\n",
" },\n",
"}));\n",
"\n",
"function Link(props) {\n",
" const {\n",
" component: ComponentProp,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" accent: {\n",
" color: theme.palette.accent.A400,\n",
" },\n"
],
"file_path": "docs/src/components/Link.js",
"type": "add",
"edit_start_line_idx": 19
} | /* eslint-disable flowtype/require-valid-file-annotation, no-console */
import { assert } from 'chai';
import consoleErrorMock from './consoleErrorMock';
describe('consoleErrorMock()', () => {
it('should throw error when calling callCount() before spy()', () => {
let errorCalledFlag = false;
try {
consoleErrorMock.callCount();
} catch (error) {
errorCalledFlag = true;
}
assert.strictEqual(errorCalledFlag, true);
});
describe('spy()', () => {
it('should place a spy in console.error', () => {
consoleErrorMock.spy();
assert.ok(console.error.hasOwnProperty('isSinonProxy'));
consoleErrorMock.reset();
assert.notOk(console.error.hasOwnProperty('isSinonProxy'));
});
it('should keep the call count', () => {
consoleErrorMock.spy();
console.error();
assert.strictEqual(consoleErrorMock.callCount(), 1);
consoleErrorMock.reset();
});
});
});
| src/test-utils/consoleErrorMock.spec.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017307366942986846,
0.0001715155376587063,
0.00016962749941740185,
0.00017168049816973507,
0.0000013772954616797506
]
|
{
"id": 10,
"code_window": [
" to={to}\n",
" className={classNames(classes.root, {\n",
" [classes.primary]: variant === 'primary',\n",
" }, className)}\n",
" {...other}\n",
" />\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" [classes.accent]: variant === 'accent',\n"
],
"file_path": "docs/src/components/Link.js",
"type": "add",
"edit_start_line_idx": 46
} | // @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from 'material-ui/utils/customPropTypes';
export const styleSheet = createStyleSheet('AppContent', (theme) => {
return {
content: theme.mixins.gutters({
paddingTop: 80,
flex: '1 1 100%',
maxWidth: '100%',
margin: '0 auto',
}),
[theme.breakpoints.up(948)]: {
content: {
maxWidth: 900,
},
},
};
});
export default function AppContent(props, context) {
const { className, children } = props;
const classes = context.styleManager.render(styleSheet);
return (
<div className={classNames(classes.content, className)}>
{children}
</div>
);
}
AppContent.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
};
AppContent.contextTypes = {
styleManager: customPropTypes.muiRequired,
};
| docs/src/components/AppContent.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.13981418311595917,
0.028138786554336548,
0.0001685055176494643,
0.000176348868990317,
0.05583774670958519
]
|
{
"id": 10,
"code_window": [
" to={to}\n",
" className={classNames(classes.root, {\n",
" [classes.primary]: variant === 'primary',\n",
" }, className)}\n",
" {...other}\n",
" />\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" [classes.accent]: variant === 'accent',\n"
],
"file_path": "docs/src/components/Link.js",
"type": "add",
"edit_start_line_idx": 46
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Colorize = (props) => (
<SvgIcon {...props}>
<path d="M20.71 5.63l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-3.12 3.12-1.93-1.91-1.41 1.41 1.42 1.42L3 16.25V21h4.75l8.92-8.92 1.42 1.42 1.41-1.41-1.92-1.92 3.12-3.12c.4-.4.4-1.03.01-1.42zM6.92 19L5 17.08l8.06-8.06 1.92 1.92L6.92 19z"/>
</SvgIcon>
);
Colorize = pure(Colorize);
Colorize.muiName = 'SvgIcon';
export default Colorize;
| packages/material-ui-icons/src/Colorize.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0001779712038114667,
0.00017291177937295288,
0.00016785235493443906,
0.00017291177937295288,
0.000005059424438513815
]
|
{
"id": 10,
"code_window": [
" to={to}\n",
" className={classNames(classes.root, {\n",
" [classes.primary]: variant === 'primary',\n",
" }, className)}\n",
" {...other}\n",
" />\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" [classes.accent]: variant === 'accent',\n"
],
"file_path": "docs/src/components/Link.js",
"type": "add",
"edit_start_line_idx": 46
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let QueueMusic = (props) => (
<SvgIcon {...props}>
<path d="M15 6H3v2h12V6zm0 4H3v2h12v-2zM3 16h8v-2H3v2zM17 6v8.18c-.31-.11-.65-.18-1-.18-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3V8h3V6h-5z"/>
</SvgIcon>
);
QueueMusic = pure(QueueMusic);
QueueMusic.muiName = 'SvgIcon';
export default QueueMusic;
| packages/material-ui-icons/src/QueueMusic.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017488084267824888,
0.00017357536125928164,
0.0001722698798403144,
0.00017357536125928164,
0.000001305481418967247
]
|
{
"id": 10,
"code_window": [
" to={to}\n",
" className={classNames(classes.root, {\n",
" [classes.primary]: variant === 'primary',\n",
" }, className)}\n",
" {...other}\n",
" />\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" [classes.accent]: variant === 'accent',\n"
],
"file_path": "docs/src/components/Link.js",
"type": "add",
"edit_start_line_idx": 46
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let ContentCut = (props) => (
<SvgIcon {...props}>
<path d="M9.64 7.64c.23-.5.36-1.05.36-1.64 0-2.21-1.79-4-4-4S2 3.79 2 6s1.79 4 4 4c.59 0 1.14-.13 1.64-.36L10 12l-2.36 2.36C7.14 14.13 6.59 14 6 14c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4c0-.59-.13-1.14-.36-1.64L12 14l7 7h3v-1L9.64 7.64zM6 8c-1.1 0-2-.89-2-2s.9-2 2-2 2 .89 2 2-.9 2-2 2zm0 12c-1.1 0-2-.89-2-2s.9-2 2-2 2 .89 2 2-.9 2-2 2zm6-7.5c-.28 0-.5-.22-.5-.5s.22-.5.5-.5.5.22.5.5-.22.5-.5.5zM19 3l-6 6 2 2 7-7V3z"/>
</SvgIcon>
);
ContentCut = pure(ContentCut);
ContentCut.muiName = 'SvgIcon';
export default ContentCut;
| packages/material-ui-icons/src/ContentCut.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017639763245824724,
0.00017243943875655532,
0.0001684812450548634,
0.00017243943875655532,
0.0000039581937016919255
]
|
{
"id": 11,
"code_window": [
" className: PropTypes.string,\n",
" component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),\n",
" to: PropTypes.string,\n",
" variant: PropTypes.oneOf(['primary']),\n",
"};\n",
"\n",
"export default withStyles(styleSheet)(Link);"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" variant: PropTypes.oneOf(['primary', 'accent']),\n"
],
"file_path": "docs/src/components/Link.js",
"type": "replace",
"edit_start_line_idx": 57
} | // @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { createStyleSheet } from 'jss-theme-reactor';
import marked from 'marked';
import customPropTypes from 'material-ui/utils/customPropTypes';
import prism from 'docs/src/utils/prism';
const renderer = new marked.Renderer();
renderer.heading = (text, level) => {
const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
return `
<h${level}>
<a class="anchor-link" id="${escapedText}"></a>${
text
}<a class="anchor-link-style" href="#${escapedText}">${
'#'
}</a>
</h${level}>
`;
};
marked.setOptions({
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false,
highlight(code) {
return prism.highlight(code, prism.languages.jsx);
},
renderer,
});
const anchorLinkStyle = (theme) => ({
'& .anchor-link-style': {
display: 'none',
},
'&:hover .anchor-link-style': {
display: 'inline',
fontSize: '0.8em',
lineHeight: '1',
paddingLeft: theme.spacing.unit,
color: theme.palette.text.hint,
},
});
const styleSheet = createStyleSheet('MarkdownElement', (theme) => ({
root: {
fontFamily: theme.typography.fontFamily,
marginTop: theme.spacing.unit * 2,
marginBottom: theme.spacing.unit * 2,
padding: '0 10px',
'& .anchor-link': {
marginTop: -theme.spacing.unit * 12, // Offset for the anchor.
position: 'absolute',
},
'& pre': {
margin: '25px 0',
padding: '12px 18px',
backgroundColor: theme.palette.background.paper,
borderRadius: 3,
overflow: 'auto',
},
'& code': {
display: 'inline-block',
lineHeight: 1.6,
fontFamily: 'Consolas, "Liberation Mono", Menlo, Courier, monospace',
padding: '3px 6px',
color: theme.palette.text.primary,
backgroundColor: theme.palette.background.paper,
fontSize: 14,
},
'& h1': {
...theme.typography.display2,
color: theme.palette.text.secondary,
margin: '0.7em 0',
...anchorLinkStyle(theme),
},
'& h2': {
...theme.typography.display1,
color: theme.palette.text.secondary,
margin: '1em 0 0.7em',
...anchorLinkStyle(theme),
},
'& h3': {
...theme.typography.headline,
color: theme.palette.text.secondary,
margin: '1em 0 0.7em',
...anchorLinkStyle(theme),
},
'& p, & ul, & ol': {
lineHeight: 1.6,
},
'& p code, & ul code': {
fontSize: 14,
},
'& table': {
width: '100%',
borderCollapse: 'collapse',
borderSpacing: 0,
overflow: 'hidden',
},
'& thead': {
fontSize: 12,
fontWeight: theme.typography.fontWeightMedium,
color: theme.palette.text.secondary,
},
'& tbody': {
fontSize: 13,
lineHeight: 1.5,
color: theme.palette.text.primary,
},
'& td': {
borderBottom: `1px solid ${theme.palette.text.lightDivider}`,
padding: `${theme.spacing.unit}px ${theme.spacing.unit * 8}px ${
theme.spacing.unit}px ${theme.spacing.unit * 3}px`,
textAlign: 'left',
},
'& td:last-child': {
paddingRight: theme.spacing.unit * 3,
},
'& td compact': {
paddingRight: theme.spacing.unit * 3,
},
'& td code': {
fontSize: 13,
},
'& th': {
whiteSpace: 'pre',
borderBottom: `1px solid ${theme.palette.text.lightDivider}`,
padding: '0 56px 0 24px',
textAlign: 'left',
},
'& th:last-child': {
paddingRight: theme.spacing.unit * 3,
},
'& tr': {
height: 48,
},
'& thead tr': {
height: 64,
},
'& strong': {
fontWeight: theme.typography.fontWeightMedium,
},
'& blockquote': {
borderLeft: `5px solid ${theme.palette.text.hint}`,
background: theme.palette.background.paper,
padding: `${theme.spacing.unit / 2}px ${theme.spacing.unit * 3}px`,
margin: `${theme.spacing.unit * 3}px 0`,
},
'& a': {
color: theme.palette.accent.A400,
textDecoration: 'none',
'&:hover': {
textDecoration: 'underline',
},
},
},
}));
function MarkdownElement(props, context) {
const {
className,
text,
} = props;
const classes = context.styleManager.render(styleSheet);
/* eslint-disable react/no-danger */
return (
<div
className={classNames(classes.root, 'markdown-body', className)}
dangerouslySetInnerHTML={{ __html: marked(text) }}
/>
);
/* eslint-enable */
}
MarkdownElement.propTypes = {
className: PropTypes.string,
text: PropTypes.string.isRequired,
};
MarkdownElement.contextTypes = {
styleManager: customPropTypes.muiRequired,
};
export default MarkdownElement;
| docs/src/components/MarkdownElement.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.003673288971185684,
0.0004890792770311236,
0.0001670414349064231,
0.00017541191482450813,
0.0008289509569294751
]
|
{
"id": 11,
"code_window": [
" className: PropTypes.string,\n",
" component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),\n",
" to: PropTypes.string,\n",
" variant: PropTypes.oneOf(['primary']),\n",
"};\n",
"\n",
"export default withStyles(styleSheet)(Link);"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" variant: PropTypes.oneOf(['primary', 'accent']),\n"
],
"file_path": "docs/src/components/Link.js",
"type": "replace",
"edit_start_line_idx": 57
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let SwapVert = (props) => (
<SvgIcon {...props}>
<path d="M16 17.01V10h-2v7.01h-3L15 21l4-3.99h-3zM9 3L5 6.99h3V14h2V6.99h3L9 3z"/>
</SvgIcon>
);
SwapVert = pure(SwapVert);
SwapVert.muiName = 'SvgIcon';
export default SwapVert;
| packages/material-ui-icons/src/SwapVert.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017172096704598516,
0.00017144216690212488,
0.0001711633667582646,
0.00017144216690212488,
2.788001438602805e-7
]
|
{
"id": 11,
"code_window": [
" className: PropTypes.string,\n",
" component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),\n",
" to: PropTypes.string,\n",
" variant: PropTypes.oneOf(['primary']),\n",
"};\n",
"\n",
"export default withStyles(styleSheet)(Link);"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" variant: PropTypes.oneOf(['primary', 'accent']),\n"
],
"file_path": "docs/src/components/Link.js",
"type": "replace",
"edit_start_line_idx": 57
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let LocalAtm = (props) => (
<SvgIcon {...props}>
<path d="M11 17h2v-1h1c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1h-3v-1h4V8h-2V7h-2v1h-1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1h3v1H9v2h2v1zm9-13H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4V6h16v12z"/>
</SvgIcon>
);
LocalAtm = pure(LocalAtm);
LocalAtm.muiName = 'SvgIcon';
export default LocalAtm;
| packages/material-ui-icons/src/LocalAtm.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0001707221381366253,
0.00017038971418514848,
0.0001700573047855869,
0.00017038971418514848,
3.324166755191982e-7
]
|
{
"id": 11,
"code_window": [
" className: PropTypes.string,\n",
" component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),\n",
" to: PropTypes.string,\n",
" variant: PropTypes.oneOf(['primary']),\n",
"};\n",
"\n",
"export default withStyles(styleSheet)(Link);"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" variant: PropTypes.oneOf(['primary', 'accent']),\n"
],
"file_path": "docs/src/components/Link.js",
"type": "replace",
"edit_start_line_idx": 57
} | // @flow
/**
* Responsively hides children by omission.
*/
import React, { Element } from 'react';
import { keys as breakpoints } from '../styles/breakpoints';
import withWidth, { isWidthDown, isWidthUp } from '../utils/withWidth';
import type { HiddenProps } from './Hidden';
import { defaultProps } from './Hidden';
type Props = HiddenProps & {
/**
* @ignore
* width prop provided by withWidth decorator
*/
width: string,
};
function HiddenJs(props: Props): ?Element<any> {
const {
children,
component,
only,
xsUp, // eslint-disable-line no-unused-vars
smUp, // eslint-disable-line no-unused-vars
mdUp, // eslint-disable-line no-unused-vars
lgUp, // eslint-disable-line no-unused-vars
xlUp, // eslint-disable-line no-unused-vars
xsDown, // eslint-disable-line no-unused-vars
smDown, // eslint-disable-line no-unused-vars
mdDown, // eslint-disable-line no-unused-vars
lgDown, // eslint-disable-line no-unused-vars
xlDown, // eslint-disable-line no-unused-vars
width,
...other
} = props;
// workaround: see https://github.com/facebook/flow/issues/1660#issuecomment-297775427
const ComponentProp = component || defaultProps.component;
let visible = true;
// `only` takes priority.
if (only && width === only) {
visible = false;
} else {
// determine visibility based on the smallest size up
for (let i = 0; i < breakpoints.length; i += 1) {
const breakpoint = breakpoints[i];
const breakpointUp = props[`${breakpoint}Up`];
const breakpointDown = props[`${breakpoint}Down`];
if (
(breakpointUp && isWidthUp(width, breakpoint)) ||
(breakpointDown && (isWidthDown(width, breakpoint, true)))
) {
visible = false;
break;
}
}
}
if (!visible) {
return null;
}
return (
<ComponentProp {...other}>
{children}
</ComponentProp>
);
}
HiddenJs.defaultProps = defaultProps;
export default withWidth()(HiddenJs);
| src/Hidden/HiddenJs.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0002989826025441289,
0.0001875717716757208,
0.00016737368423491716,
0.00017247685173060745,
0.000042187413782812655
]
|
{
"id": 12,
"code_window": [
" marginTop: -theme.spacing.unit * 12, // Offset for the anchor.\n",
" position: 'absolute',\n",
" },\n",
" '& pre': {\n",
" margin: '25px 0',\n",
" padding: '12px 18px',\n",
" backgroundColor: theme.palette.background.paper,\n",
" borderRadius: 3,\n",
" overflow: 'auto',\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin: `${theme.spacing.unit * 3}px 0`,\n"
],
"file_path": "docs/src/components/MarkdownElement.js",
"type": "replace",
"edit_start_line_idx": 64
} | // @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from 'material-ui/utils/customPropTypes';
export const styleSheet = createStyleSheet('AppContent', (theme) => {
return {
content: theme.mixins.gutters({
paddingTop: 80,
flex: '1 1 100%',
maxWidth: '100%',
margin: '0 auto',
}),
[theme.breakpoints.up(948)]: {
content: {
maxWidth: 900,
},
},
};
});
export default function AppContent(props, context) {
const { className, children } = props;
const classes = context.styleManager.render(styleSheet);
return (
<div className={classNames(classes.content, className)}>
{children}
</div>
);
}
AppContent.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
};
AppContent.contextTypes = {
styleManager: customPropTypes.muiRequired,
};
| docs/src/components/AppContent.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.0010862579802051187,
0.00036004549474455416,
0.00016383091860916466,
0.00017171933723147959,
0.0003634189779404551
]
|
{
"id": 12,
"code_window": [
" marginTop: -theme.spacing.unit * 12, // Offset for the anchor.\n",
" position: 'absolute',\n",
" },\n",
" '& pre': {\n",
" margin: '25px 0',\n",
" padding: '12px 18px',\n",
" backgroundColor: theme.palette.background.paper,\n",
" borderRadius: 3,\n",
" overflow: 'auto',\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin: `${theme.spacing.unit * 3}px 0`,\n"
],
"file_path": "docs/src/components/MarkdownElement.js",
"type": "replace",
"edit_start_line_idx": 64
} | // @flow weak
import React, { Component } from 'react';
import { findDOMNode } from 'react-dom';
import { assert } from 'chai';
import { spy } from 'sinon';
import { createMount } from 'src/test-utils';
import Transition, { UNMOUNTED, EXITED, ENTERING, ENTERED, EXITING } from './Transition';
describe('<Transition />', () => {
let mount;
before(() => {
mount = createMount();
});
after(() => {
mount.cleanUp();
});
it('should not transition on mount', () => {
const wrapper = mount(
<Transition in timeout={0} onEnter={() => assert.fail()}>
<div />
</Transition>,
);
assert.strictEqual(wrapper.state('status'), ENTERED);
});
it('should start exited with transitionAppear', () => {
const wrapper = mount(
<Transition transitionAppear>
<div />
</Transition>,
);
assert.strictEqual(wrapper.state('status'), EXITED);
});
it('should transition on mount with transitionAppear', () => {
const wrapper = mount(
<Transition in transitionAppear timeout={0}>
<div />
</Transition>,
);
assert.strictEqual(wrapper.state('status'), ENTERING);
});
it('should flush new props to the DOM before initiating a transition', (done) => {
const wrapper = mount(
<Transition
in={false}
timeout={0}
enteringClassName="test-entering"
onEnter={(node) => {
assert.strictEqual(
node.classList.contains('test-class'),
true,
'should have the test-class',
);
assert.strictEqual(
node.classList.contains('test-entering'),
false,
'should not have the test-entering class',
);
done();
}}
>
<div />
</Transition>,
);
assert.strictEqual(wrapper.hasClass('test-class'), false, 'should not have the test-class yet');
wrapper.setProps({ in: true, className: 'test-class' });
});
describe('entering', () => {
let wrapper;
beforeEach(() => {
wrapper = mount(
<Transition
timeout={10}
enteredClassName="test-enter"
enteringClassName="test-entering"
>
<div />
</Transition>,
);
});
it('should fire callbacks', (done) => {
const onEnter = spy();
const onEntering = spy();
assert.strictEqual(wrapper.state('status'), EXITED);
wrapper = wrapper.setProps({
in: true,
onEnter,
onEntering,
onEntered() {
assert.strictEqual(onEnter.callCount, 1);
assert.strictEqual(onEntering.callCount, 1);
assert.strictEqual(onEnter.calledBefore(onEntering), true);
done();
},
});
});
it('should move to each transition state', (done) => {
let count = 0;
assert.strictEqual(wrapper.state('status'), EXITED);
wrapper = wrapper.setProps({
in: true,
onEnter() {
count += 1;
assert.strictEqual(wrapper.state('status'), EXITED);
},
onEntering() {
count += 1;
assert.strictEqual(wrapper.state('status'), ENTERING);
},
onEntered() {
assert.strictEqual(wrapper.state('status'), ENTERED);
assert.strictEqual(count, 2);
done();
},
});
});
it('should apply classes at each transition state', (done) => {
let count = 0;
assert.strictEqual(wrapper.state('status'), EXITED);
wrapper = wrapper.setProps({
in: true,
onEnter(node) {
count += 1;
assert.strictEqual(node.className, '');
},
onEntering(node) {
count += 1;
assert.strictEqual(node.className, 'test-entering');
},
onEntered(node) {
assert.strictEqual(node.className, 'test-enter');
assert.strictEqual(count, 2);
done();
},
});
});
});
describe('exiting', () => {
let wrapper;
beforeEach(() => {
wrapper = mount(
<Transition
in
timeout={10}
exitedClassName="test-exit"
exitingClassName="test-exiting"
>
<div />
</Transition>,
);
});
it('should fire callbacks', (done) => {
const onExit = spy();
const onExiting = spy();
assert.strictEqual(wrapper.state('status'), ENTERED);
wrapper = wrapper.setProps({
in: false,
onExit,
onExiting,
onExited() {
assert.strictEqual(onExit.callCount, 1);
assert.strictEqual(onExiting.callCount, 1);
assert.strictEqual(onExit.calledBefore(onExiting), true);
done();
},
});
});
it('should move to each transition state', (done) => {
let count = 0;
assert.strictEqual(wrapper.state('status'), ENTERED);
wrapper = wrapper.setProps({
in: false,
onExit() {
count += 1;
assert.strictEqual(wrapper.state('status'), ENTERED);
},
onExiting() {
count += 1;
assert.strictEqual(wrapper.state('status'), EXITING);
},
onExited() {
assert.strictEqual(wrapper.state('status'), EXITED);
assert.strictEqual(count, 2);
done();
},
});
});
it('should apply classes at each transition state', (done) => {
let count = 0;
assert.strictEqual(wrapper.state('status'), ENTERED);
wrapper = wrapper.setProps({
in: false,
onExit(node) {
count += 1;
assert.strictEqual(node.className, '');
},
onExiting(node) {
count += 1;
assert.strictEqual(node.className, 'test-exiting');
},
onExited(node) {
assert.strictEqual(node.className, 'test-exit');
assert.strictEqual(count, 2);
done();
},
});
});
});
describe('unmountOnExit', () => {
class UnmountTransition extends Component {
state = {};
componentWillMount() {
this.setState({
in: this.props.initialIn, // eslint-disable-line react/prop-types
});
}
transition = null;
getStatus() {
return this.transition.state.status;
}
render() {
const {
initialIn, // eslint-disable-line no-unused-vars, react/prop-types
...other
} = this.props;
return (
<Transition
ref={(c) => {
if (c !== null) {
this.transition = c;
}
}}
unmountOnExit
in={this.state.in}
timeout={10}
{...other}
>
<div />
</Transition>
);
}
}
it('should mount when entering', (done) => {
const wrapper = mount(
<UnmountTransition
initialIn={false}
onEnter={() => {
assert.strictEqual(wrapper.instance().getStatus(), EXITED);
assert.ok(findDOMNode(wrapper.instance()));
done();
}}
/>,
);
assert.strictEqual(wrapper.instance().getStatus(), UNMOUNTED);
assert.isNotOk(findDOMNode(wrapper.instance()));
wrapper.setState({ in: true });
});
it('should unmount after exiting', (done) => {
const wrapper = mount(
<UnmountTransition
initialIn
onExited={() => {
assert.strictEqual(wrapper.instance().getStatus(), UNMOUNTED);
assert.isNotOk(findDOMNode(wrapper.instance()));
done();
}}
/>,
);
assert.strictEqual(wrapper.instance().getStatus(), ENTERED);
assert.ok(findDOMNode(wrapper.instance()));
wrapper.setState({ in: false });
});
});
describe('shouldComponentUpdate', () => {
let wrapper;
let instance;
let currentState;
let nextState;
let result;
const nextProps = {};
before(() => {
wrapper = mount(<Transition><div /></Transition>);
});
it('should update', () => {
currentState = { status: EXITED };
wrapper.setProps({ in: true });
nextState = currentState;
wrapper.setState(currentState);
instance = wrapper.instance();
result = instance.shouldComponentUpdate(nextProps, nextState);
assert.strictEqual(result, false);
});
it('shouldn\'t update due to prop:in being false', () => {
currentState = { status: EXITED };
nextState = currentState;
wrapper.setState({ status: EXITED });
wrapper.setProps({ in: false });
instance = wrapper.instance();
result = instance.shouldComponentUpdate(nextProps, nextState);
assert.strictEqual(result, true);
});
it('shouldn\'t update due to currentState.status != EXITED', () => {
currentState = { status: UNMOUNTED };
wrapper.setState(currentState);
nextState = currentState;
wrapper.setProps({ in: true });
instance = wrapper.instance();
result = instance.shouldComponentUpdate(nextProps, nextState);
assert.strictEqual(result, true);
});
it('shouldn\'t update due to currentState.status != nextState.status', () => {
currentState = { status: EXITED };
wrapper.setState(currentState);
nextState = currentState;
nextState.status = UNMOUNTED;
wrapper.setProps({ in: true });
instance = wrapper.instance();
result = instance.shouldComponentUpdate(nextProps, nextState);
assert.strictEqual(result, true);
});
});
});
| src/internal/Transition.spec.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017458928050473332,
0.00017072746413759887,
0.0001643430150579661,
0.0001709839270915836,
0.0000022169901967572514
]
|
{
"id": 12,
"code_window": [
" marginTop: -theme.spacing.unit * 12, // Offset for the anchor.\n",
" position: 'absolute',\n",
" },\n",
" '& pre': {\n",
" margin: '25px 0',\n",
" padding: '12px 18px',\n",
" backgroundColor: theme.palette.background.paper,\n",
" borderRadius: 3,\n",
" overflow: 'auto',\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin: `${theme.spacing.unit * 3}px 0`,\n"
],
"file_path": "docs/src/components/MarkdownElement.js",
"type": "replace",
"edit_start_line_idx": 64
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let PlayCircleOutline = (props) => (
<SvgIcon {...props}>
<path d="M10 16.5l6-4.5-6-4.5v9zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/>
</SvgIcon>
);
PlayCircleOutline = pure(PlayCircleOutline);
PlayCircleOutline.muiName = 'SvgIcon';
export default PlayCircleOutline;
| packages/material-ui-icons/src/PlayCircleOutline.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017032003961503506,
0.00016979467181954533,
0.0001692693040240556,
0.00016979467181954533,
5.253677954897285e-7
]
|
{
"id": 12,
"code_window": [
" marginTop: -theme.spacing.unit * 12, // Offset for the anchor.\n",
" position: 'absolute',\n",
" },\n",
" '& pre': {\n",
" margin: '25px 0',\n",
" padding: '12px 18px',\n",
" backgroundColor: theme.palette.background.paper,\n",
" borderRadius: 3,\n",
" overflow: 'auto',\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin: `${theme.spacing.unit * 3}px 0`,\n"
],
"file_path": "docs/src/components/MarkdownElement.js",
"type": "replace",
"edit_start_line_idx": 64
} | // @flow weak
import React from 'react';
import Paper from 'material-ui/Paper';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from 'material-ui/utils/customPropTypes';
import Layout from 'material-ui/Layout';
const styleSheet = createStyleSheet('StressLayout', (theme) => ({
root: {
width: 400,
backgroundColor: theme.palette.primary.A400,
},
paper: {
padding: 16,
textAlign: 'center',
},
}));
export default function StressLayout(props, context) {
const classes = context.styleManager.render(styleSheet);
return (
<div className={classes.root}>
<Layout container gutter={24} direction="column">
<Layout container item gutter={8}>
<Layout item xs={3}>
<Paper className={classes.paper}>
xs=3
</Paper>
</Layout>
<Layout item xs={9}>
<Paper className={classes.paper}>
xs=9
</Paper>
</Layout>
</Layout>
<Layout
container
item
gutter={8}
direction="row-reverse"
>
<Layout item xs={3}>
<Paper className={classes.paper}>
first
</Paper>
</Layout>
<Layout item xs={3}>
<Paper className={classes.paper}>
last
</Paper>
</Layout>
</Layout>
<Layout
container
item
gutter={8}
justify="space-between"
>
<Layout item xs={3}>
<Paper className={classes.paper}>
space
</Paper>
</Layout>
<Layout item xs={3}>
<Paper className={classes.paper}>
between
</Paper>
</Layout>
</Layout>
<Layout
container
item
gutter={8}
align="stretch"
direction="column-reverse"
>
<Layout item>
<Paper className={classes.paper}>
reverse
</Paper>
</Layout>
<Layout item>
<Paper className={classes.paper}>
column
</Paper>
</Layout>
</Layout>
</Layout>
</div>
);
}
StressLayout.contextTypes = {
styleManager: customPropTypes.muiRequired,
};
| test/regressions/tests/Layout/StressLayout.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.002598789054900408,
0.0004108299035578966,
0.00016283619333989918,
0.0001673221995588392,
0.0007293277885764837
]
|
{
"id": 13,
"code_window": [
" margin: `${theme.spacing.unit * 3}px 0`,\n",
" },\n",
" '& a': {\n",
" color: theme.palette.accent.A400,\n",
" textDecoration: 'none',\n",
" '&:hover': {\n",
" textDecoration: 'underline',\n",
" },\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // Style taken from the Link component\n"
],
"file_path": "docs/src/components/MarkdownElement.js",
"type": "add",
"edit_start_line_idx": 159
} | // @flow weak
import React from 'react';
import {
applyRouterMiddleware,
browserHistory,
Router,
Route,
IndexRoute,
IndexRedirect,
} from 'react-router';
import { useScroll } from 'react-router-scroll';
import { kebabCase, titleize } from 'docs/src/utils/helpers';
import AppFrame from 'docs/src/components/AppFrame';
import AppContent from 'docs/src/components/AppContent';
import MarkdownDocs from 'docs/src/components/MarkdownDocs';
import Home from 'docs/src/pages/Home';
import { componentAPIs, requireMarkdown, demos, requireDemo } from 'docs/src/components/files';
export default function AppRouter() {
return (
<Router
history={browserHistory}
render={applyRouterMiddleware(useScroll())}
>
<Route title="Material UI" path="/" component={AppFrame}>
<IndexRoute dockDrawer component={Home} title={null} />
<Route
title="Getting Started"
path="/getting-started"
nav
component={AppContent}
>
<IndexRedirect to="installation" />
<Route
title="Installation"
path="/getting-started/installation"
content={requireMarkdown('./getting-started/installation.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Usage"
path="/getting-started/usage"
content={requireMarkdown('./getting-started/usage.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Server Rendering"
path="/getting-started/server-rendering"
content={requireMarkdown('./getting-started/server-rendering.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Examples"
path="/getting-started/examples"
content={requireMarkdown('./getting-started/examples.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Supported Components"
path="/getting-started/supported-components"
content={requireMarkdown('./getting-started/supported-components.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Customization"
path="/customization"
nav
component={AppContent}
>
<IndexRedirect to="themes" />
<Route
title="Themes"
path="/customization/themes"
content={requireMarkdown('./customization/themes.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Composition"
path="/customization/composition"
content={requireMarkdown('./customization/composition.md')}
component={MarkdownDocs}
nav
/>
<Route
title="API"
path="/customization/api"
content={requireMarkdown('./customization/api.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Style"
path="/style"
nav
component={AppContent}
>
<Route
title="Color"
path="/style/color"
content={requireMarkdown('./style/color.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Icons"
path="/style/icons"
content={requireMarkdown('./style/icons.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Typography"
path="/style/typography"
content={requireMarkdown('./style/typography.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Layout"
path="/layout"
nav
component={AppContent}
>
<Route
title="Responsive UI"
path="/layout/responsive-ui"
content={requireMarkdown('./layout/responsive-ui.md')}
component={MarkdownDocs}
nav
/>
</Route>
<Route
title="Component Demos"
path="/component-demos"
nav
component={AppContent}
>
{demos.map(((demo) => {
return (
<Route
key={demo.name}
title={titleize(demo.name)}
path={`/component-demos/${demo.name}`}
content={requireDemo(demo.path)}
component={MarkdownDocs}
demo={demo}
nav
/>
);
}))}
</Route>
<Route
title="Component API"
path="/component-api"
nav
component={AppContent}
>
{componentAPIs.map(((componentAPI) => {
return (
<Route
key={componentAPI.name}
title={componentAPI.name}
path={`/component-api/${kebabCase(componentAPI.name)}`}
content={requireMarkdown(componentAPI.path)}
component={MarkdownDocs}
componentAPI={componentAPI}
nav
/>
);
}))}
</Route>
<Route
title="Discover More"
path="/discover-more"
nav
component={AppContent}
>
<IndexRedirect to="community" />
<Route
title="Community"
path="/discover-more/community"
content={requireMarkdown('./discover-more/community.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Showcase"
path="/discover-more/showcase"
content={requireMarkdown('./discover-more/showcase.md')}
component={MarkdownDocs}
nav
/>
<Route
title="Related Projects"
path="/discover-more/related-projects"
content={requireMarkdown('./discover-more/related-projects.md')}
component={MarkdownDocs}
nav
/>
</Route>
</Route>
</Router>
);
}
| docs/src/components/AppRouter.js | 1 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017786244279704988,
0.0001752362004481256,
0.00016991775191854686,
0.00017559525440447032,
0.000002030460564128589
]
|
{
"id": 13,
"code_window": [
" margin: `${theme.spacing.unit * 3}px 0`,\n",
" },\n",
" '& a': {\n",
" color: theme.palette.accent.A400,\n",
" textDecoration: 'none',\n",
" '&:hover': {\n",
" textDecoration: 'underline',\n",
" },\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // Style taken from the Link component\n"
],
"file_path": "docs/src/components/MarkdownElement.js",
"type": "add",
"edit_start_line_idx": 159
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let MusicNote = (props) => (
<SvgIcon {...props}>
<path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/>
</SvgIcon>
);
MusicNote = pure(MusicNote);
MusicNote.muiName = 'SvgIcon';
export default MusicNote;
| packages/material-ui-icons/src/MusicNote.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017459776427131146,
0.00017296735313721,
0.00017133694200310856,
0.00017296735313721,
0.0000016304111341014504
]
|
{
"id": 13,
"code_window": [
" margin: `${theme.spacing.unit * 3}px 0`,\n",
" },\n",
" '& a': {\n",
" color: theme.palette.accent.A400,\n",
" textDecoration: 'none',\n",
" '&:hover': {\n",
" textDecoration: 'underline',\n",
" },\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // Style taken from the Link component\n"
],
"file_path": "docs/src/components/MarkdownElement.js",
"type": "add",
"edit_start_line_idx": 159
} | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let ChildCare = (props) => (
<SvgIcon {...props}>
<circle cx="14.5" cy="10.5" r="1.25"/><circle cx="9.5" cy="10.5" r="1.25"/><path d="M22.94 12.66c.04-.21.06-.43.06-.66s-.02-.45-.06-.66c-.25-1.51-1.36-2.74-2.81-3.17-.53-1.12-1.28-2.1-2.19-2.91C16.36 3.85 14.28 3 12 3s-4.36.85-5.94 2.26c-.92.81-1.67 1.8-2.19 2.91-1.45.43-2.56 1.65-2.81 3.17-.04.21-.06.43-.06.66s.02.45.06.66c.25 1.51 1.36 2.74 2.81 3.17.52 1.11 1.27 2.09 2.17 2.89C7.62 20.14 9.71 21 12 21s4.38-.86 5.97-2.28c.9-.8 1.65-1.79 2.17-2.89 1.44-.43 2.55-1.65 2.8-3.17zM19 14c-.1 0-.19-.02-.29-.03-.2.67-.49 1.29-.86 1.86C16.6 17.74 14.45 19 12 19s-4.6-1.26-5.85-3.17c-.37-.57-.66-1.19-.86-1.86-.1.01-.19.03-.29.03-1.1 0-2-.9-2-2s.9-2 2-2c.1 0 .19.02.29.03.2-.67.49-1.29.86-1.86C7.4 6.26 9.55 5 12 5s4.6 1.26 5.85 3.17c.37.57.66 1.19.86 1.86.1-.01.19-.03.29-.03 1.1 0 2 .9 2 2s-.9 2-2 2zM7.5 14c.76 1.77 2.49 3 4.5 3s3.74-1.23 4.5-3h-9z"/>
</SvgIcon>
);
ChildCare = pure(ChildCare);
ChildCare.muiName = 'SvgIcon';
export default ChildCare;
| packages/material-ui-icons/src/ChildCare.js | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00035975550417788327,
0.0002686519001144916,
0.00017754831060301512,
0.0002686519001144916,
0.00009110359678743407
]
|
{
"id": 13,
"code_window": [
" margin: `${theme.spacing.unit * 3}px 0`,\n",
" },\n",
" '& a': {\n",
" color: theme.palette.accent.A400,\n",
" textDecoration: 'none',\n",
" '&:hover': {\n",
" textDecoration: 'underline',\n",
" },\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // Style taken from the Link component\n"
],
"file_path": "docs/src/components/MarkdownElement.js",
"type": "add",
"edit_start_line_idx": 159
} | {
"name": "eslint-plugin-material-ui",
"version": "1.0.0",
"private": "true",
"description": "Custom eslint rules for Material-UI",
"repository": "https://github.com/callemall/material-ui/packages/eslint-plugin-material-ui",
"main": "lib/index.js",
"scripts": {
"test": "../../node_modules/mocha/bin/_mocha -- tests/lib/**/*.js",
"lint": "../../node_modules/eslint/bin/eslint.js --rulesdir ../.. --ext .js lib tests && echo \"eslint: no lint errors\""
},
"engines": {
"node": ">=0.10.0"
},
"license": "MIT"
}
| packages/eslint-plugin-material-ui/package.json | 0 | https://github.com/mui/material-ui/commit/eca04cd49955899f7c4c62e080d7b32e42fbce5e | [
0.00017463955737184733,
0.00017369017587043345,
0.00017274079436901957,
0.00017369017587043345,
9.493815014138818e-7
]
|
{
"id": 0,
"code_window": [
"\n",
" export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] {\n",
" const declarationDiagnostics = createDiagnosticCollection();\n",
" forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile);\n",
" return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName);\n",
"\n",
" function getDeclarationDiagnosticsFromFile({ declarationFilePath }, sources: SourceFile[], isBundledEmit: boolean) {\n",
" emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);\n"
],
"file_path": "src/compiler/declarationEmitter.ts",
"type": "replace",
"edit_start_line_idx": 35
} | /// <reference path="sys.ts" />
/// <reference path="emitter.ts" />
/// <reference path="core.ts" />
namespace ts {
/* @internal */ export let programTime = 0;
/* @internal */ export let emitTime = 0;
/* @internal */ export let ioReadTime = 0;
/* @internal */ export let ioWriteTime = 0;
/** The version of the TypeScript compiler release */
const emptyArray: any[] = [];
export const version = "1.9.0";
export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string {
let fileName = "tsconfig.json";
while (true) {
if (fileExists(fileName)) {
return fileName;
}
const parentPath = getDirectoryPath(searchPath);
if (parentPath === searchPath) {
break;
}
searchPath = parentPath;
fileName = "../" + fileName;
}
return undefined;
}
export function resolveTripleslashReference(moduleName: string, containingFile: string): string {
const basePath = getDirectoryPath(containingFile);
const referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName);
return normalizePath(referencedFileName);
}
function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void;
function trace(host: ModuleResolutionHost, message: DiagnosticMessage): void {
host.trace(formatMessage.apply(undefined, arguments));
}
function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean {
return compilerOptions.traceModuleResolution && host.trace !== undefined;
}
function startsWith(str: string, prefix: string): boolean {
return str.lastIndexOf(prefix, 0) === 0;
}
function endsWith(str: string, suffix: string): boolean {
const expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
function hasZeroOrOneAsteriskCharacter(str: string): boolean {
let seenAsterisk = false;
for (let i = 0; i < str.length; i++) {
if (str.charCodeAt(i) === CharacterCodes.asterisk) {
if (!seenAsterisk) {
seenAsterisk = true;
}
else {
// have already seen asterisk
return false;
}
}
}
return true;
}
function createResolvedModule(resolvedFileName: string, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations {
return { resolvedModule: resolvedFileName ? { resolvedFileName, isExternalLibraryImport } : undefined, failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName: string): boolean {
if (isRootedDiskPath(moduleName)) {
return false;
}
const i = moduleName.lastIndexOf("./", 1);
const startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === CharacterCodes.dot);
return !startsWithDotSlashOrDotDotSlash;
}
interface ModuleResolutionState {
host: ModuleResolutionHost;
compilerOptions: CompilerOptions;
traceEnabled: boolean;
// skip .tsx files if jsx is not enabled
skipTsx: boolean;
}
export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
const traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
trace(host, Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
}
let moduleResolution = compilerOptions.moduleResolution;
if (moduleResolution === undefined) {
moduleResolution = getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic;
if (traceEnabled) {
trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]);
}
}
else {
if (traceEnabled) {
trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]);
}
}
let result: ResolvedModuleWithFailedLookupLocations;
switch (moduleResolution) {
case ModuleResolutionKind.NodeJs:
result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
break;
case ModuleResolutionKind.Classic:
result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
break;
}
if (traceEnabled) {
if (result.resolvedModule) {
trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
}
else {
trace(host, Diagnostics.Module_name_0_was_not_resolved, moduleName);
}
}
return result;
}
/*
* Every module resolution kind can has its specific understanding how to load module from a specific path on disk
* I.e. for path '/a/b/c':
* - Node loader will first to try to check if '/a/b/c' points to a file with some supported extension and if this fails
* it will try to load module from directory: directory '/a/b/c' should exist and it should have either 'package.json' with
* 'typings' entry or file 'index' with some supported extension
* - Classic loader will only try to interpret '/a/b/c' as file.
*/
type ResolutionKindSpecificLoader = (candidate: string, extensions: string[], failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState) => string;
/**
* Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
* mitigate differences between design time structure of the project and its runtime counterpart so the same import name
* can be resolved successfully by TypeScript compiler and runtime module loader.
* If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
* fallback to standard resolution routine.
*
* - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
* names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
* be '/a/b/c/d'
* - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
* will be resolved based on the content of the module name.
* Structure of 'paths' compiler options
* 'paths': {
* pattern-1: [...substitutions],
* pattern-2: [...substitutions],
* ...
* pattern-n: [...substitutions]
* }
* Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
* all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
* If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
* <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
* If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
* After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
* from the candidate location.
* Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
* substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
* will be converted to absolute using baseUrl.
* For example:
* baseUrl: /a/b/c
* "paths": {
* // match all module names
* "*": [
* "*", // use matched name as is,
* // <matched name> will be looked as /a/b/c/<matched name>
*
* "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
* // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
* ],
* // match module names that start with 'components/'
* "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
* // it is rooted so it will be final candidate location
* }
*
* 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
* they were in the same location. For example lets say there are two files
* '/local/src/content/file1.ts'
* '/shared/components/contracts/src/content/protocols/file2.ts'
* After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
* if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
* 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
* root dirs were merged together.
* I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
* Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
* '/local/src/content/protocols/file2' and try to load it - failure.
* Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
* be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
* entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
*/
function tryLoadModuleUsingOptionalResolutionSettings(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader,
failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string {
if (moduleHasNonRelativeName(moduleName)) {
return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state);
}
else {
return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state);
}
}
function tryLoadModuleUsingRootDirs(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader,
failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string {
if (!state.compilerOptions.rootDirs) {
return undefined;
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
}
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
let matchedRootDir: string;
let matchedNormalizedPrefix: string;
for (const rootDir of state.compilerOptions.rootDirs) {
// rootDirs are expected to be absolute
// in case of tsconfig.json this will happen automatically - compiler will expand relative names
// using location of tsconfig.json as base location
let normalizedRoot = normalizePath(rootDir);
if (!endsWith(normalizedRoot, directorySeparator)) {
normalizedRoot += directorySeparator;
}
const isLongestMatchingPrefix =
startsWith(candidate, normalizedRoot) &&
(matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
if (state.traceEnabled) {
trace(state.host, Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
}
if (isLongestMatchingPrefix) {
matchedNormalizedPrefix = normalizedRoot;
matchedRootDir = rootDir;
}
}
if (matchedNormalizedPrefix) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
}
const suffix = candidate.substr(matchedNormalizedPrefix.length);
// first - try to load from a initial location
if (state.traceEnabled) {
trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
}
const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
if (resolvedFileName) {
return resolvedFileName;
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.Trying_other_entries_in_rootDirs);
}
// then try to resolve using remaining entries in rootDirs
for (const rootDir of state.compilerOptions.rootDirs) {
if (rootDir === matchedRootDir) {
// skip the initially matched entry
continue;
}
const candidate = combinePaths(normalizePath(rootDir), suffix);
if (state.traceEnabled) {
trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate);
}
const baseDirectory = getDirectoryPath(candidate);
const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
if (resolvedFileName) {
return resolvedFileName;
}
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.Module_resolution_using_rootDirs_has_failed);
}
}
return undefined;
}
function tryLoadModuleUsingBaseUrl(moduleName: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[],
supportedExtensions: string[], state: ModuleResolutionState): string {
if (!state.compilerOptions.baseUrl) {
return undefined;
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
}
let longestMatchPrefixLength = -1;
let matchedPattern: string;
let matchedStar: string;
if (state.compilerOptions.paths) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
}
for (const key in state.compilerOptions.paths) {
const pattern: string = key;
const indexOfStar = pattern.indexOf("*");
if (indexOfStar !== -1) {
const prefix = pattern.substr(0, indexOfStar);
const suffix = pattern.substr(indexOfStar + 1);
if (moduleName.length >= prefix.length + suffix.length &&
startsWith(moduleName, prefix) &&
endsWith(moduleName, suffix)) {
// use length of prefix as betterness criteria
if (prefix.length > longestMatchPrefixLength) {
longestMatchPrefixLength = prefix.length;
matchedPattern = pattern;
matchedStar = moduleName.substr(prefix.length, moduleName.length - suffix.length);
}
}
}
else if (pattern === moduleName) {
// pattern was matched as is - no need to search further
matchedPattern = pattern;
matchedStar = undefined;
break;
}
}
}
if (matchedPattern) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPattern);
}
for (const subst of state.compilerOptions.paths[matchedPattern]) {
const path = matchedStar ? subst.replace("\*", matchedStar) : subst;
const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, path));
if (state.traceEnabled) {
trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
}
const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
if (resolvedFileName) {
return resolvedFileName;
}
}
return undefined;
}
else {
const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, moduleName));
if (state.traceEnabled) {
trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate);
}
return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
}
}
export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
const containingDirectory = getDirectoryPath(containingFile);
const supportedExtensions = getSupportedExtensions(compilerOptions);
const traceEnabled = isTraceEnabled(compilerOptions, host);
const failedLookupLocations: string[] = [];
const state = {compilerOptions, host, traceEnabled, skipTsx: false};
let resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName,
failedLookupLocations, supportedExtensions, state);
if (resolvedFileName) {
return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations);
}
let isExternalLibraryImport = false;
if (moduleHasNonRelativeName(moduleName)) {
if (traceEnabled) {
trace(host, Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
}
resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state);
isExternalLibraryImport = resolvedFileName !== undefined;
}
else {
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
}
return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
}
function nodeLoadModuleByRelativeName(candidate: string, supportedExtensions: string[], failedLookupLocations: string[],
onlyRecordFailures: boolean, state: ModuleResolutionState): string {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
}
const resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state);
return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state);
}
/* @internal */
export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean } ): boolean {
// if host does not support 'directoryExists' assume that directory will exist
return !host.directoryExists || host.directoryExists(directoryName);
}
/**
* @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
* in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
*/
function loadModuleFromFile(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
return forEach(extensions, tryLoad);
function tryLoad(ext: string): string {
if (ext === ".tsx" && state.skipTsx) {
return undefined;
}
const fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext;
if (!onlyRecordFailures && state.host.fileExists(fileName)) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_exist_use_it_as_a_module_resolution_result, fileName);
}
return fileName;
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_does_not_exist, fileName);
}
failedLookupLocation.push(fileName);
return undefined;
}
}
}
function loadNodeModuleFromDirectory(extensions: string[], candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
const packageJsonPath = combinePaths(candidate, "package.json");
const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
if (directoryExists && state.host.fileExists(packageJsonPath)) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Found_package_json_at_0, packageJsonPath);
}
let jsonContent: { typings?: string };
try {
const jsonText = state.host.readFile(packageJsonPath);
jsonContent = jsonText ? <{ typings?: string }>JSON.parse(jsonText) : { typings: undefined };
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
jsonContent = { typings: undefined };
}
if (jsonContent.typings) {
if (typeof jsonContent.typings === "string") {
const typingsFile = normalizePath(combinePaths(candidate, jsonContent.typings));
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_typings_field_0_that_references_1, jsonContent.typings, typingsFile);
}
const result = loadModuleFromFile(typingsFile, extensions, failedLookupLocation, !directoryProbablyExists(getDirectoryPath(typingsFile), state.host), state);
if (result) {
return result;
}
}
else if (state.traceEnabled) {
trace(state.host, Diagnostics.Expected_type_of_typings_field_in_package_json_to_be_string_got_0, typeof jsonContent.typings);
}
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_does_not_have_typings_field);
}
}
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_does_not_exist, packageJsonPath);
}
// record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
failedLookupLocation.push(packageJsonPath);
}
return loadModuleFromFile(combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
}
function loadModuleFromNodeModules(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string {
directory = normalizeSlashes(directory);
while (true) {
const baseName = getBaseFileName(directory);
if (baseName !== "node_modules") {
const nodeModulesFolder = combinePaths(directory, "node_modules");
const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName));
// Load only typescript files irrespective of allowJs option if loading from node modules
let result = loadModuleFromFile(candidate, supportedTypeScriptExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
if (result) {
return result;
}
result = loadNodeModuleFromDirectory(supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
if (result) {
return result;
}
}
const parentPath = getDirectoryPath(directory);
if (parentPath === directory) {
break;
}
directory = parentPath;
}
return undefined;
}
export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
const traceEnabled = isTraceEnabled(compilerOptions, host);
const state = { compilerOptions, host, traceEnabled, skipTsx: !compilerOptions.jsx };
const failedLookupLocations: string[] = [];
const supportedExtensions = getSupportedExtensions(compilerOptions);
let containingDirectory = getDirectoryPath(containingFile);
const resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
if (resolvedFileName) {
return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations);
}
let referencedSourceFile: string;
if (moduleHasNonRelativeName(moduleName)) {
while (true) {
const searchName = normalizePath(combinePaths(containingDirectory, moduleName));
referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
if (referencedSourceFile) {
break;
}
const parentPath = getDirectoryPath(containingDirectory);
if (parentPath === containingDirectory) {
break;
}
containingDirectory = parentPath;
}
}
else {
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
}
return referencedSourceFile
? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations }
: { resolvedModule: undefined, failedLookupLocations };
}
/* @internal */
export const defaultInitCompilerOptions: CompilerOptions = {
module: ModuleKind.CommonJS,
target: ScriptTarget.ES5,
noImplicitAny: false,
sourceMap: false,
};
export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost {
const existingDirectories: Map<boolean> = {};
function getCanonicalFileName(fileName: string): string {
// if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
// otherwise use toLowerCase as a canonical form.
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
// returned by CScript sys environment
const unsupportedFileEncodingErrorCode = -2147024809;
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile {
let text: string;
try {
const start = new Date().getTime();
text = sys.readFile(fileName, options.charset);
ioReadTime += new Date().getTime() - start;
}
catch (e) {
if (onError) {
onError(e.number === unsupportedFileEncodingErrorCode
? createCompilerDiagnostic(Diagnostics.Unsupported_file_encoding).messageText
: e.message);
}
text = "";
}
return text !== undefined ? createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
}
function directoryExists(directoryPath: string): boolean {
if (hasProperty(existingDirectories, directoryPath)) {
return true;
}
if (sys.directoryExists(directoryPath)) {
existingDirectories[directoryPath] = true;
return true;
}
return false;
}
function ensureDirectoriesExist(directoryPath: string) {
if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) {
const parentDirectory = getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
sys.createDirectory(directoryPath);
}
}
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) {
try {
const start = new Date().getTime();
ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName)));
sys.writeFile(fileName, data, writeByteOrderMark);
ioWriteTime += new Date().getTime() - start;
}
catch (e) {
if (onError) {
onError(e.message);
}
}
}
const newLine = getNewLineCharacter(options);
return {
getSourceFile,
getDefaultLibFileName: options => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options)),
writeFile,
getCurrentDirectory: memoize(() => sys.getCurrentDirectory()),
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
getCanonicalFileName,
getNewLine: () => newLine,
fileExists: fileName => sys.fileExists(fileName),
readFile: fileName => sys.readFile(fileName),
trace: (s: string) => sys.write(s + newLine),
directoryExists: directoryName => sys.directoryExists(directoryName)
};
}
export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[] {
let diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(
program.getSyntacticDiagnostics(sourceFile, cancellationToken),
program.getGlobalDiagnostics(cancellationToken),
program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (program.getCompilerOptions().declaration) {
diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken));
}
return sortAndDeduplicateDiagnostics(diagnostics);
}
export function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string {
if (typeof messageText === "string") {
return messageText;
}
else {
let diagnosticChain = messageText;
let result = "";
let indent = 0;
while (diagnosticChain) {
if (indent) {
result += newLine;
for (let i = 0; i < indent; i++) {
result += " ";
}
}
result += diagnosticChain.messageText;
indent++;
diagnosticChain = diagnosticChain.next;
}
return result;
}
}
export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program {
let program: Program;
let files: SourceFile[] = [];
let fileProcessingDiagnostics = createDiagnosticCollection();
const programDiagnostics = createDiagnosticCollection();
let commonSourceDirectory: string;
let diagnosticsProducingTypeChecker: TypeChecker;
let noDiagnosticsTypeChecker: TypeChecker;
let classifiableNames: Map<string>;
let skipDefaultLib = options.noLib;
const supportedExtensions = getSupportedExtensions(options);
const start = new Date().getTime();
host = host || createCompilerHost(options);
// Map storing if there is emit blocking diagnostics for given input
const hasEmitBlockingDiagnostics = createFileMap<boolean>(getCanonicalFileName);
const currentDirectory = host.getCurrentDirectory();
const resolveModuleNamesWorker = host.resolveModuleNames
? ((moduleNames: string[], containingFile: string) => host.resolveModuleNames(moduleNames, containingFile))
: ((moduleNames: string[], containingFile: string) => {
const resolvedModuleNames: ResolvedModule[] = [];
// resolveModuleName does not store any results between calls.
// lookup is a local cache to avoid resolving the same module name several times
const lookup: Map<ResolvedModule> = {};
for (const moduleName of moduleNames) {
let resolvedName: ResolvedModule;
if (hasProperty(lookup, moduleName)) {
resolvedName = lookup[moduleName];
}
else {
resolvedName = resolveModuleName(moduleName, containingFile, options, host).resolvedModule;
lookup[moduleName] = resolvedName;
}
resolvedModuleNames.push(resolvedName);
}
return resolvedModuleNames;
});
const filesByName = createFileMap<SourceFile>();
// stores 'filename -> file association' ignoring case
// used to track cases when two file names differ only in casing
const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createFileMap<SourceFile>(fileName => fileName.toLowerCase()) : undefined;
if (oldProgram) {
// check properties that can affect structure of the program or module resolution strategy
// if any of these properties has changed - structure cannot be reused
const oldOptions = oldProgram.getCompilerOptions();
if ((oldOptions.module !== options.module) ||
(oldOptions.noResolve !== options.noResolve) ||
(oldOptions.target !== options.target) ||
(oldOptions.noLib !== options.noLib) ||
(oldOptions.jsx !== options.jsx) ||
(oldOptions.allowJs !== options.allowJs)) {
oldProgram = undefined;
}
}
if (!tryReuseStructureFromOldProgram()) {
forEach(rootNames, name => processRootFile(name, /*isDefaultLib*/ false));
// Do not process the default library if:
// - The '--noLib' flag is used.
// - A 'no-default-lib' reference comment is encountered in
// processing the root files.
if (!skipDefaultLib) {
processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ true);
}
}
// unconditionally set oldProgram to undefined to prevent it from being captured in closure
oldProgram = undefined;
program = {
getRootFileNames: () => rootNames,
getSourceFile,
getSourceFiles: () => files,
getCompilerOptions: () => options,
getSyntacticDiagnostics,
getOptionsDiagnostics,
getGlobalDiagnostics,
getSemanticDiagnostics,
getDeclarationDiagnostics,
getTypeChecker,
getClassifiableNames,
getDiagnosticsProducingTypeChecker,
getCommonSourceDirectory,
emit,
getCurrentDirectory: () => currentDirectory,
getNodeCount: () => getDiagnosticsProducingTypeChecker().getNodeCount(),
getIdentifierCount: () => getDiagnosticsProducingTypeChecker().getIdentifierCount(),
getSymbolCount: () => getDiagnosticsProducingTypeChecker().getSymbolCount(),
getTypeCount: () => getDiagnosticsProducingTypeChecker().getTypeCount(),
getFileProcessingDiagnostics: () => fileProcessingDiagnostics
};
verifyCompilerOptions();
programTime += new Date().getTime() - start;
return program;
function getCommonSourceDirectory() {
if (typeof commonSourceDirectory === "undefined") {
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
// If a rootDir is specified and is valid use it as the commonSourceDirectory
commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
else {
commonSourceDirectory = computeCommonSourceDirectory(files);
}
if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) {
// Make sure directory path ends with directory separator so this string can directly
// used to replace with "" to get the relative path of the source file and the relative path doesn't
// start with / making it rooted path
commonSourceDirectory += directorySeparator;
}
}
return commonSourceDirectory;
}
function getClassifiableNames() {
if (!classifiableNames) {
// Initialize a checker so that all our files are bound.
getTypeChecker();
classifiableNames = {};
for (const sourceFile of files) {
copyMap(sourceFile.classifiableNames, classifiableNames);
}
}
return classifiableNames;
}
function tryReuseStructureFromOldProgram(): boolean {
if (!oldProgram) {
return false;
}
Debug.assert(!oldProgram.structureIsReused);
// there is an old program, check if we can reuse its structure
const oldRootNames = oldProgram.getRootFileNames();
if (!arrayIsEqualTo(oldRootNames, rootNames)) {
return false;
}
// check if program source files has changed in the way that can affect structure of the program
const newSourceFiles: SourceFile[] = [];
const filePaths: Path[] = [];
const modifiedSourceFiles: SourceFile[] = [];
for (const oldSourceFile of oldProgram.getSourceFiles()) {
let newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target);
if (!newSourceFile) {
return false;
}
newSourceFile.path = oldSourceFile.path;
filePaths.push(newSourceFile.path);
if (oldSourceFile !== newSourceFile) {
if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
// value of no-default-lib has changed
// this will affect if default library is injected into the list of files
return false;
}
// check tripleslash references
if (!arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
// tripleslash references has changed
return false;
}
// check imports and module augmentations
collectExternalModuleReferences(newSourceFile);
if (!arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
// imports has changed
return false;
}
if (!arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
// moduleAugmentations has changed
return false;
}
if (resolveModuleNamesWorker) {
const moduleNames = map(concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral);
const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory));
// ensure that module resolution results are still correct
for (let i = 0; i < moduleNames.length; i++) {
const newResolution = resolutions[i];
const oldResolution = getResolvedModule(oldSourceFile, moduleNames[i]);
const resolutionChanged = oldResolution
? !newResolution ||
oldResolution.resolvedFileName !== newResolution.resolvedFileName ||
!!oldResolution.isExternalLibraryImport !== !!newResolution.isExternalLibraryImport
: newResolution;
if (resolutionChanged) {
return false;
}
}
}
// pass the cache of module resolutions from the old source file
newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
modifiedSourceFiles.push(newSourceFile);
}
else {
// file has no changes - use it as is
newSourceFile = oldSourceFile;
}
// if file has passed all checks it should be safe to reuse it
newSourceFiles.push(newSourceFile);
}
// update fileName -> file mapping
for (let i = 0, len = newSourceFiles.length; i < len; i++) {
filesByName.set(filePaths[i], newSourceFiles[i]);
}
files = newSourceFiles;
fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
for (const modifiedFile of modifiedSourceFiles) {
fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile);
}
oldProgram.structureIsReused = true;
return true;
}
function getEmitHost(writeFileCallback?: WriteFileCallback): EmitHost {
return {
getCanonicalFileName,
getCommonSourceDirectory: program.getCommonSourceDirectory,
getCompilerOptions: program.getCompilerOptions,
getCurrentDirectory: () => currentDirectory,
getNewLine: () => host.getNewLine(),
getSourceFile: program.getSourceFile,
getSourceFiles: program.getSourceFiles,
writeFile: writeFileCallback || (
(fileName, data, writeByteOrderMark, onError) => host.writeFile(fileName, data, writeByteOrderMark, onError)),
isEmitBlocked,
};
}
function getDiagnosticsProducingTypeChecker() {
return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ true));
}
function getTypeChecker() {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ false));
}
function emit(sourceFile?: SourceFile, writeFileCallback?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult {
return runWithCancellationToken(() => emitWorker(this, sourceFile, writeFileCallback, cancellationToken));
}
function isEmitBlocked(emitFileName: string): boolean {
return hasEmitBlockingDiagnostics.contains(toPath(emitFileName, currentDirectory, getCanonicalFileName));
}
function emitWorker(program: Program, sourceFile: SourceFile, writeFileCallback: WriteFileCallback, cancellationToken: CancellationToken): EmitResult {
let declarationDiagnostics: Diagnostic[] = [];
if (options.noEmit) {
return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emitSkipped: true };
}
// If the noEmitOnError flag is set, then check if we have any errors so far. If so,
// immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we
// get any preEmit diagnostics, not just the ones
if (options.noEmitOnError) {
const diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(
program.getSyntacticDiagnostics(sourceFile, cancellationToken),
program.getGlobalDiagnostics(cancellationToken),
program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (diagnostics.length === 0 && program.getCompilerOptions().declaration) {
declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
}
if (diagnostics.length > 0 || declarationDiagnostics.length > 0) {
return { diagnostics, sourceMaps: undefined, emitSkipped: true };
}
}
// Create the emit resolver outside of the "emitTime" tracking code below. That way
// any cost associated with it (like type checking) are appropriate associated with
// the type-checking counter.
//
// If the -out option is specified, we should not pass the source file to getEmitResolver.
// This is because in the -out scenario all files need to be emitted, and therefore all
// files need to be type checked. And the way to specify that all files need to be type
// checked is to not pass the file to getEmitResolver.
const emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
const start = new Date().getTime();
const emitResult = emitFiles(
emitResolver,
getEmitHost(writeFileCallback),
sourceFile);
emitTime += new Date().getTime() - start;
return emitResult;
}
function getSourceFile(fileName: string): SourceFile {
return filesByName.get(toPath(fileName, currentDirectory, getCanonicalFileName));
}
function getDiagnosticsHelper(
sourceFile: SourceFile,
getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => Diagnostic[],
cancellationToken: CancellationToken): Diagnostic[] {
if (sourceFile) {
return getDiagnostics(sourceFile, cancellationToken);
}
const allDiagnostics: Diagnostic[] = [];
forEach(program.getSourceFiles(), sourceFile => {
if (cancellationToken) {
cancellationToken.throwIfCancellationRequested();
}
addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken));
});
return sortAndDeduplicateDiagnostics(allDiagnostics);
}
function getSyntacticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
}
function getSemanticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
}
function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
}
function getSyntacticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return sourceFile.parseDiagnostics;
}
function runWithCancellationToken<T>(func: () => T): T {
try {
return func();
}
catch (e) {
if (e instanceof OperationCanceledException) {
// We were canceled while performing the operation. Because our type checker
// might be a bad state, we need to throw it away.
//
// Note: we are overly aggressive here. We do not actually *have* to throw away
// the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep
// the lifetimes of these two TypeCheckers the same. Also, we generally only
// cancel when the user has made a change anyways. And, in that case, we (the
// program instance) will get thrown away anyways. So trying to keep one of
// these type checkers alive doesn't serve much purpose.
noDiagnosticsTypeChecker = undefined;
diagnosticsProducingTypeChecker = undefined;
}
throw e;
}
}
function getSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return runWithCancellationToken(() => {
const typeChecker = getDiagnosticsProducingTypeChecker();
Debug.assert(!!sourceFile.bindDiagnostics);
const bindDiagnostics = sourceFile.bindDiagnostics;
// For JavaScript files, we don't want to report the normal typescript semantic errors.
// Instead, we just report errors for using TypeScript-only constructs from within a
// JavaScript file.
const checkDiagnostics = isSourceFileJavaScript(sourceFile) ?
getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) :
typeChecker.getDiagnostics(sourceFile, cancellationToken);
const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile);
});
}
function getJavaScriptSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return runWithCancellationToken(() => {
const diagnostics: Diagnostic[] = [];
walk(sourceFile);
return diagnostics;
function walk(node: Node): boolean {
if (!node) {
return false;
}
switch (node.kind) {
case SyntaxKind.ImportEqualsDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.ExportAssignment:
if ((<ExportAssignment>node).isExportEquals) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_a_ts_file));
return true;
}
break;
case SyntaxKind.ClassDeclaration:
let classDeclaration = <ClassDeclaration>node;
if (checkModifiers(classDeclaration.modifiers) ||
checkTypeParameters(classDeclaration.typeParameters)) {
return true;
}
break;
case SyntaxKind.HeritageClause:
let heritageClause = <HeritageClause>node;
if (heritageClause.token === SyntaxKind.ImplementsKeyword) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file));
return true;
}
break;
case SyntaxKind.InterfaceDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.ModuleDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.module_declarations_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.TypeAliasDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.type_aliases_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ArrowFunction:
case SyntaxKind.FunctionDeclaration:
const functionDeclaration = <FunctionLikeDeclaration>node;
if (checkModifiers(functionDeclaration.modifiers) ||
checkTypeParameters(functionDeclaration.typeParameters) ||
checkTypeAnnotation(functionDeclaration.type)) {
return true;
}
break;
case SyntaxKind.VariableStatement:
const variableStatement = <VariableStatement>node;
if (checkModifiers(variableStatement.modifiers)) {
return true;
}
break;
case SyntaxKind.VariableDeclaration:
const variableDeclaration = <VariableDeclaration>node;
if (checkTypeAnnotation(variableDeclaration.type)) {
return true;
}
break;
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
const expression = <CallExpression>node;
if (expression.typeArguments && expression.typeArguments.length > 0) {
const start = expression.typeArguments.pos;
diagnostics.push(createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start,
Diagnostics.type_arguments_can_only_be_used_in_a_ts_file));
return true;
}
break;
case SyntaxKind.Parameter:
const parameter = <ParameterDeclaration>node;
if (parameter.modifiers) {
const start = parameter.modifiers.pos;
diagnostics.push(createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start,
Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file));
return true;
}
if (parameter.questionToken) {
diagnostics.push(createDiagnosticForNode(parameter.questionToken, Diagnostics._0_can_only_be_used_in_a_ts_file, "?"));
return true;
}
if (parameter.type) {
diagnostics.push(createDiagnosticForNode(parameter.type, Diagnostics.types_can_only_be_used_in_a_ts_file));
return true;
}
break;
case SyntaxKind.PropertyDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.property_declarations_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.EnumDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.TypeAssertionExpression:
let typeAssertionExpression = <TypeAssertion>node;
diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.Decorator:
if (!options.experimentalDecorators) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning));
}
return true;
}
return forEachChild(node, walk);
}
function checkTypeParameters(typeParameters: NodeArray<TypeParameterDeclaration>): boolean {
if (typeParameters) {
const start = typeParameters.pos;
diagnostics.push(createFileDiagnostic(sourceFile, start, typeParameters.end - start, Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file));
return true;
}
return false;
}
function checkTypeAnnotation(type: TypeNode): boolean {
if (type) {
diagnostics.push(createDiagnosticForNode(type, Diagnostics.types_can_only_be_used_in_a_ts_file));
return true;
}
return false;
}
function checkModifiers(modifiers: ModifiersArray): boolean {
if (modifiers) {
for (const modifier of modifiers) {
switch (modifier.kind) {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.ReadonlyKeyword:
case SyntaxKind.DeclareKeyword:
diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind)));
return true;
// These are all legal modifiers.
case SyntaxKind.StaticKeyword:
case SyntaxKind.ExportKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.DefaultKeyword:
case SyntaxKind.AbstractKeyword:
}
}
}
return false;
}
});
}
function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return runWithCancellationToken(() => {
if (!isDeclarationFile(sourceFile)) {
const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
// Don't actually write any files since we're just getting diagnostics.
const writeFile: WriteFileCallback = () => { };
return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);
}
});
}
function getOptionsDiagnostics(): Diagnostic[] {
const allDiagnostics: Diagnostic[] = [];
addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics());
addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics());
return sortAndDeduplicateDiagnostics(allDiagnostics);
}
function getGlobalDiagnostics(): Diagnostic[] {
const allDiagnostics: Diagnostic[] = [];
addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics());
return sortAndDeduplicateDiagnostics(allDiagnostics);
}
function hasExtension(fileName: string): boolean {
return getBaseFileName(fileName).indexOf(".") >= 0;
}
function processRootFile(fileName: string, isDefaultLib: boolean) {
processSourceFile(normalizePath(fileName), isDefaultLib);
}
function fileReferenceIsEqualTo(a: FileReference, b: FileReference): boolean {
return a.fileName === b.fileName;
}
function moduleNameIsEqualTo(a: LiteralExpression, b: LiteralExpression): boolean {
return a.text === b.text;
}
function getTextOfLiteral(literal: LiteralExpression): string {
return literal.text;
}
function collectExternalModuleReferences(file: SourceFile): void {
if (file.imports) {
return;
}
const isJavaScriptFile = isSourceFileJavaScript(file);
const isExternalModuleFile = isExternalModule(file);
let imports: LiteralExpression[];
let moduleAugmentations: LiteralExpression[];
for (const node of file.statements) {
collectModuleReferences(node, /*inAmbientModule*/ false);
if (isJavaScriptFile) {
collectRequireCalls(node);
}
}
file.imports = imports || emptyArray;
file.moduleAugmentations = moduleAugmentations || emptyArray;
return;
function collectModuleReferences(node: Node, inAmbientModule: boolean): void {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.ExportDeclaration:
let moduleNameExpr = getExternalModuleName(node);
if (!moduleNameExpr || moduleNameExpr.kind !== SyntaxKind.StringLiteral) {
break;
}
if (!(<LiteralExpression>moduleNameExpr).text) {
break;
}
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
if (!inAmbientModule || !isExternalModuleNameRelative((<LiteralExpression>moduleNameExpr).text)) {
(imports || (imports = [])).push(<LiteralExpression>moduleNameExpr);
}
break;
case SyntaxKind.ModuleDeclaration:
if (isAmbientModule(<ModuleDeclaration>node) && (inAmbientModule || node.flags & NodeFlags.Ambient || isDeclarationFile(file))) {
const moduleName = <LiteralExpression>(<ModuleDeclaration>node).name;
// Ambient module declarations can be interpreted as augmentations for some existing external modules.
// This will happen in two cases:
// - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
// - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
// immediately nested in top level ambient module declaration .
if (isExternalModuleFile || (inAmbientModule && !isExternalModuleNameRelative(moduleName.text))) {
(moduleAugmentations || (moduleAugmentations = [])).push(moduleName);
}
else if (!inAmbientModule) {
// An AmbientExternalModuleDeclaration declares an external module.
// This type of declaration is permitted only in the global module.
// The StringLiteral must specify a top - level external module name.
// Relative external module names are not permitted
// NOTE: body of ambient module is always a module block
for (const statement of (<ModuleBlock>(<ModuleDeclaration>node).body).statements) {
collectModuleReferences(statement, /*inAmbientModule*/ true);
}
}
}
}
}
function collectRequireCalls(node: Node): void {
if (isRequireCall(node, /*checkArgumentIsStringLiteral*/true)) {
(imports || (imports = [])).push(<StringLiteral>(<CallExpression>node).arguments[0]);
}
else {
forEachChild(node, collectRequireCalls);
}
}
}
function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) {
let diagnosticArgument: string[];
let diagnostic: DiagnosticMessage;
if (hasExtension(fileName)) {
if (!options.allowNonTsExtensions && !forEach(supportedExtensions, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) {
diagnostic = Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1;
diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"];
}
else if (!findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) {
diagnostic = Diagnostics.File_0_not_found;
diagnosticArgument = [fileName];
}
else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) {
diagnostic = Diagnostics.A_file_cannot_have_a_reference_to_itself;
diagnosticArgument = [fileName];
}
}
else {
const nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd);
if (!nonTsFile) {
if (options.allowNonTsExtensions) {
diagnostic = Diagnostics.File_0_not_found;
diagnosticArgument = [fileName];
}
else if (!forEach(supportedExtensions, extension => findSourceFile(fileName + extension, toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd))) {
diagnostic = Diagnostics.File_0_not_found;
fileName += ".ts";
diagnosticArgument = [fileName];
}
}
}
if (diagnostic) {
if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) {
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...diagnosticArgument));
}
else {
fileProcessingDiagnostics.add(createCompilerDiagnostic(diagnostic, ...diagnosticArgument));
}
}
}
function reportFileNamesDifferOnlyInCasingError(fileName: string, existingFileName: string, refFile: SourceFile, refPos: number, refEnd: number): void {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName));
}
else {
fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName));
}
}
// Get source file from normalized fileName
function findSourceFile(fileName: string, path: Path, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): SourceFile {
if (filesByName.contains(path)) {
const file = filesByName.get(path);
// try to check if we've already seen this file but with a different casing in path
// NOTE: this only makes sense for case-insensitive file systems
if (file && options.forceConsistentCasingInFileNames && getNormalizedAbsolutePath(file.fileName, currentDirectory) !== getNormalizedAbsolutePath(fileName, currentDirectory)) {
reportFileNamesDifferOnlyInCasingError(fileName, file.fileName, refFile, refPos, refEnd);
}
return file;
}
// We haven't looked for this file, do so now and cache result
const file = host.getSourceFile(fileName, options.target, hostErrorMessage => {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
else {
fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
});
filesByName.set(path, file);
if (file) {
file.path = path;
if (host.useCaseSensitiveFileNames()) {
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
const existingFile = filesByNameIgnoreCase.get(path);
if (existingFile) {
reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd);
}
else {
filesByNameIgnoreCase.set(path, file);
}
}
skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib;
const basePath = getDirectoryPath(fileName);
if (!options.noResolve) {
processReferencedFiles(file, basePath);
}
// always process imported modules to record module name resolutions
processImportedModules(file, basePath);
if (isDefaultLib) {
files.unshift(file);
}
else {
files.push(file);
}
}
return file;
}
function processReferencedFiles(file: SourceFile, basePath: string) {
forEach(file.referencedFiles, ref => {
const referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
processSourceFile(referencedFileName, /*isDefaultLib*/ false, file, ref.pos, ref.end);
});
}
function getCanonicalFileName(fileName: string): string {
return host.getCanonicalFileName(fileName);
}
function processImportedModules(file: SourceFile, basePath: string) {
collectExternalModuleReferences(file);
if (file.imports.length || file.moduleAugmentations.length) {
file.resolvedModules = {};
const moduleNames = map(concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral);
const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory));
for (let i = 0; i < moduleNames.length; i++) {
const resolution = resolutions[i];
setResolvedModule(file, moduleNames[i], resolution);
// add file to program only if:
// - resolution was successful
// - noResolve is falsy
// - module name come from the list fo imports
const shouldAddFile = resolution &&
!options.noResolve &&
i < file.imports.length;
if (shouldAddFile) {
const importedFile = findSourceFile(resolution.resolvedFileName, toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, file, skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
if (importedFile && resolution.isExternalLibraryImport) {
// Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files,
// this check is ok. Otherwise this would be never true for javascript file
if (!isExternalModule(importedFile) && importedFile.statements.length) {
const start = getTokenPosOfNode(file.imports[i], file);
fileProcessingDiagnostics.add(createFileDiagnostic(file, start, file.imports[i].end - start, Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName));
}
else if (importedFile.referencedFiles.length) {
const firstRef = importedFile.referencedFiles[0];
fileProcessingDiagnostics.add(createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition));
}
}
}
}
}
else {
// no imports - drop cached module resolutions
file.resolvedModules = undefined;
}
return;
}
function computeCommonSourceDirectory(sourceFiles: SourceFile[]): string {
let commonPathComponents: string[];
const failed = forEach(files, sourceFile => {
// Each file contributes into common source file path
if (isDeclarationFile(sourceFile)) {
return;
}
const sourcePathComponents = getNormalizedPathComponents(sourceFile.fileName, currentDirectory);
sourcePathComponents.pop(); // The base file name is not part of the common directory path
if (!commonPathComponents) {
// first file
commonPathComponents = sourcePathComponents;
return;
}
for (let i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) {
if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
if (i === 0) {
// Failed to find any common path component
return true;
}
// New common path found that is 0 -> i-1
commonPathComponents.length = i;
break;
}
}
// If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
if (sourcePathComponents.length < commonPathComponents.length) {
commonPathComponents.length = sourcePathComponents.length;
}
});
// A common path can not be found when paths span multiple drives on windows, for example
if (failed) {
return "";
}
if (!commonPathComponents) { // Can happen when all input files are .d.ts files
return currentDirectory;
}
return getNormalizedPathFromPathComponents(commonPathComponents);
}
function checkSourceFilesBelongToPath(sourceFiles: SourceFile[], rootDirectory: string): boolean {
let allFilesBelongToPath = true;
if (sourceFiles) {
const absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory));
for (const sourceFile of sourceFiles) {
if (!isDeclarationFile(sourceFile)) {
const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir));
allFilesBelongToPath = false;
}
}
}
}
return allFilesBelongToPath;
}
function verifyCompilerOptions() {
if (options.isolatedModules) {
if (options.declaration) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"));
}
if (options.noEmitOnError) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"));
}
if (options.out) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"));
}
if (options.outFile) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"));
}
}
if (options.inlineSourceMap) {
if (options.sourceMap) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"));
}
if (options.mapRoot) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"));
}
}
if (options.paths && options.baseUrl === undefined) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option));
}
if (options.paths) {
for (const key in options.paths) {
if (!hasProperty(options.paths, key)) {
continue;
}
if (!hasZeroOrOneAsteriskCharacter(key)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key));
}
for (const subst of options.paths[key]) {
if (!hasZeroOrOneAsteriskCharacter(subst)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key));
}
}
}
}
if (options.inlineSources) {
if (!options.sourceMap && !options.inlineSourceMap) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided));
}
if (options.sourceRoot) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources"));
}
}
if (options.out && options.outFile) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"));
}
if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) {
// Error to specify --mapRoot or --sourceRoot without mapSourceFiles
if (options.mapRoot) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"));
}
if (options.sourceRoot && !options.inlineSourceMap) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap"));
}
}
if (options.declarationDir) {
if (!options.declaration) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"));
}
if (options.out || options.outFile) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"));
}
}
const languageVersion = options.target || ScriptTarget.ES3;
const outFile = options.outFile || options.out;
const firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined);
if (options.isolatedModules) {
if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES6) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher));
}
const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined);
if (firstNonExternalModuleSourceFile) {
const span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
}
}
else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file));
}
// Cannot specify module gen target of es6 when below es6
if (options.module === ModuleKind.ES6 && languageVersion < ScriptTarget.ES6) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower));
}
// Cannot specify module gen that isn't amd or system with --out
if (outFile && options.module && !(options.module === ModuleKind.AMD || options.module === ModuleKind.System)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
}
// there has to be common source directory if user specified --outdir || --sourceRoot
// if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
if (options.outDir || // there is --outDir specified
options.sourceRoot || // there is --sourceRoot specified
options.mapRoot) { // there is --mapRoot specified
// Precalculate and cache the common source directory
const dir = getCommonSourceDirectory();
// If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure
if (options.outDir && dir === "" && forEach(files, file => getRootLength(file.fileName) > 1)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files));
}
}
if (options.noEmit) {
if (options.out) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "out"));
}
if (options.outFile) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outFile"));
}
if (options.outDir) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outDir"));
}
if (options.declaration) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration"));
}
}
else if (options.allowJs && options.declaration) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"));
}
if (options.emitDecoratorMetadata &&
!options.experimentalDecorators) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
}
if (options.reactNamespace && !isIdentifier(options.reactNamespace, languageVersion)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace));
}
// If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
if (!options.noEmit && !options.suppressOutputPathCheck) {
const emitHost = getEmitHost();
const emitFilesSeen = createFileMap<boolean>(!host.useCaseSensitiveFileNames() ? key => key.toLocaleLowerCase() : undefined);
forEachExpectedEmitFile(emitHost, (emitFileNames, sourceFiles, isBundledEmit) => {
verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen);
verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen);
});
}
// Verify that all the emit files are unique and don't overwrite input files
function verifyEmitFilePath(emitFileName: string, emitFilesSeen: FileMap<boolean>) {
if (emitFileName) {
const emitFilePath = toPath(emitFileName, currentDirectory, getCanonicalFileName);
// Report error if the output overwrites input file
if (filesByName.contains(emitFilePath)) {
createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file);
}
// Report error if multiple files write into same file
if (emitFilesSeen.contains(emitFilePath)) {
// Already seen the same emit file - report error
createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files);
}
else {
emitFilesSeen.set(emitFilePath, true);
}
}
}
}
function createEmitBlockingDiagnostics(emitFileName: string, emitFilePath: Path, message: DiagnosticMessage) {
hasEmitBlockingDiagnostics.set(toPath(emitFileName, currentDirectory, getCanonicalFileName), true);
programDiagnostics.add(createCompilerDiagnostic(message, emitFileName));
}
}
}
| src/compiler/program.ts | 1 | https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843 | [
0.9990159273147583,
0.07135928422212601,
0.00016142323147505522,
0.00032566653680987656,
0.23891380429267883
]
|
{
"id": 0,
"code_window": [
"\n",
" export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] {\n",
" const declarationDiagnostics = createDiagnosticCollection();\n",
" forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile);\n",
" return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName);\n",
"\n",
" function getDeclarationDiagnosticsFromFile({ declarationFilePath }, sources: SourceFile[], isBundledEmit: boolean) {\n",
" emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);\n"
],
"file_path": "src/compiler/declarationEmitter.ts",
"type": "replace",
"edit_start_line_idx": 35
} | //// [EnumAndModuleWithSameNameAndCommonRoot.ts]
enum enumdule {
Red, Blue
}
module enumdule {
export class Point {
constructor(public x: number, public y: number) { }
}
}
var x: enumdule;
var x = enumdule.Red;
var y: { x: number; y: number };
var y = new enumdule.Point(0, 0);
//// [EnumAndModuleWithSameNameAndCommonRoot.js]
var enumdule;
(function (enumdule) {
enumdule[enumdule["Red"] = 0] = "Red";
enumdule[enumdule["Blue"] = 1] = "Blue";
})(enumdule || (enumdule = {}));
var enumdule;
(function (enumdule) {
var Point = (function () {
function Point(x, y) {
this.x = x;
this.y = y;
}
return Point;
}());
enumdule.Point = Point;
})(enumdule || (enumdule = {}));
var x;
var x = enumdule.Red;
var y;
var y = new enumdule.Point(0, 0);
| tests/baselines/reference/EnumAndModuleWithSameNameAndCommonRoot.js | 0 | https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843 | [
0.0001748435024637729,
0.0001740149746183306,
0.0001719001738820225,
0.00017465814016759396,
0.0000012301854894758435
]
|
{
"id": 0,
"code_window": [
"\n",
" export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] {\n",
" const declarationDiagnostics = createDiagnosticCollection();\n",
" forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile);\n",
" return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName);\n",
"\n",
" function getDeclarationDiagnosticsFromFile({ declarationFilePath }, sources: SourceFile[], isBundledEmit: boolean) {\n",
" emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);\n"
],
"file_path": "src/compiler/declarationEmitter.ts",
"type": "replace",
"edit_start_line_idx": 35
} | //// [file.tsx]
declare var vdom: any;
declare var ctrl: any;
declare var model: any;
// A simple render function with nesting and control statements
let render = (ctrl, model) =>
<section class="todoapp">
<header class="header">
<h1>todos <x></h1>
<input class="new-todo" autofocus autocomplete="off" placeholder="What needs to be done?" value={model.newTodo} onKeyup={ctrl.addTodo.bind(ctrl, model)} />
</header>
<section class="main" style={{display:(model.todos && model.todos.length) ? "block" : "none"}}>
<input class="toggle-all" type="checkbox" onChange={ctrl.toggleAll.bind(ctrl)}/>
<ul class="todo-list">
{model.filteredTodos.map((todo) =>
<li class={{todo: true, completed: todo.completed, editing: todo == model.editedTodo}}>
<div class="view">
{(!todo.editable) ?
<input class="toggle" type="checkbox"></input>
: null
}
<label onDoubleClick={()=>{ctrl.editTodo(todo)}}>{todo.title}</label>
<button class="destroy" onClick={ctrl.removeTodo.bind(ctrl,todo)}></button>
<div class="iconBorder">
<div class="icon"/>
</div>
</div>
</li>
)}
</ul>
</section>
</section>
//// [file.js]
// A simple render function with nesting and control statements
var render = function (ctrl, model) {
return vdom.createElement("section", {class: "todoapp"},
vdom.createElement("header", {class: "header"},
vdom.createElement("h1", null, "todos <x>"),
vdom.createElement("input", {class: "new-todo", autofocus: true, autocomplete: "off", placeholder: "What needs to be done?", value: model.newTodo, onKeyup: ctrl.addTodo.bind(ctrl, model)})),
vdom.createElement("section", {class: "main", style: { display: (model.todos && model.todos.length) ? "block" : "none" }},
vdom.createElement("input", {class: "toggle-all", type: "checkbox", onChange: ctrl.toggleAll.bind(ctrl)}),
vdom.createElement("ul", {class: "todo-list"}, model.filteredTodos.map(function (todo) {
return vdom.createElement("li", {class: { todo: true, completed: todo.completed, editing: todo == model.editedTodo }},
vdom.createElement("div", {class: "view"},
(!todo.editable) ?
vdom.createElement("input", {class: "toggle", type: "checkbox"})
: null,
vdom.createElement("label", {onDoubleClick: function () { ctrl.editTodo(todo); }}, todo.title),
vdom.createElement("button", {class: "destroy", onClick: ctrl.removeTodo.bind(ctrl, todo)}),
vdom.createElement("div", {class: "iconBorder"},
vdom.createElement("div", {class: "icon"})
))
);
}))));
};
| tests/baselines/reference/tsxReactEmitNesting.js | 0 | https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843 | [
0.00017547348397783935,
0.00017011335876304656,
0.000161962685524486,
0.00017107916937675327,
0.000004196042937110178
]
|
{
"id": 0,
"code_window": [
"\n",
" export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] {\n",
" const declarationDiagnostics = createDiagnosticCollection();\n",
" forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile);\n",
" return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName);\n",
"\n",
" function getDeclarationDiagnosticsFromFile({ declarationFilePath }, sources: SourceFile[], isBundledEmit: boolean) {\n",
" emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);\n"
],
"file_path": "src/compiler/declarationEmitter.ts",
"type": "replace",
"edit_start_line_idx": 35
} | //@target: ES5
function asReversedTuple(a: number, b: string, c: boolean): [boolean, string, number] {
let [x, y, z] = arguments;
return [z, y, x];
}
| tests/cases/compiler/argumentsObjectIterator03_ES5.ts | 0 | https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843 | [
0.00017127174942288548,
0.00017127174942288548,
0.00017127174942288548,
0.00017127174942288548,
0
]
|
{
"id": 1,
"code_window": [
" function getSemanticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n",
" return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);\n",
" }\n",
"\n",
" function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n",
" return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);\n",
" }\n",
"\n",
" function getSyntacticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const options = program.getCompilerOptions();\n",
" if (!sourceFile || options.out || options.outFile) {\n",
" return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);\n",
" }\n",
" else {\n",
" return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);\n",
" }\n"
],
"file_path": "src/compiler/program.ts",
"type": "replace",
"edit_start_line_idx": 1000
} | /// <reference path="sys.ts" />
/// <reference path="emitter.ts" />
/// <reference path="core.ts" />
namespace ts {
/* @internal */ export let programTime = 0;
/* @internal */ export let emitTime = 0;
/* @internal */ export let ioReadTime = 0;
/* @internal */ export let ioWriteTime = 0;
/** The version of the TypeScript compiler release */
const emptyArray: any[] = [];
export const version = "1.9.0";
export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string {
let fileName = "tsconfig.json";
while (true) {
if (fileExists(fileName)) {
return fileName;
}
const parentPath = getDirectoryPath(searchPath);
if (parentPath === searchPath) {
break;
}
searchPath = parentPath;
fileName = "../" + fileName;
}
return undefined;
}
export function resolveTripleslashReference(moduleName: string, containingFile: string): string {
const basePath = getDirectoryPath(containingFile);
const referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName);
return normalizePath(referencedFileName);
}
function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void;
function trace(host: ModuleResolutionHost, message: DiagnosticMessage): void {
host.trace(formatMessage.apply(undefined, arguments));
}
function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean {
return compilerOptions.traceModuleResolution && host.trace !== undefined;
}
function startsWith(str: string, prefix: string): boolean {
return str.lastIndexOf(prefix, 0) === 0;
}
function endsWith(str: string, suffix: string): boolean {
const expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
function hasZeroOrOneAsteriskCharacter(str: string): boolean {
let seenAsterisk = false;
for (let i = 0; i < str.length; i++) {
if (str.charCodeAt(i) === CharacterCodes.asterisk) {
if (!seenAsterisk) {
seenAsterisk = true;
}
else {
// have already seen asterisk
return false;
}
}
}
return true;
}
function createResolvedModule(resolvedFileName: string, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations {
return { resolvedModule: resolvedFileName ? { resolvedFileName, isExternalLibraryImport } : undefined, failedLookupLocations };
}
function moduleHasNonRelativeName(moduleName: string): boolean {
if (isRootedDiskPath(moduleName)) {
return false;
}
const i = moduleName.lastIndexOf("./", 1);
const startsWithDotSlashOrDotDotSlash = i === 0 || (i === 1 && moduleName.charCodeAt(0) === CharacterCodes.dot);
return !startsWithDotSlashOrDotDotSlash;
}
interface ModuleResolutionState {
host: ModuleResolutionHost;
compilerOptions: CompilerOptions;
traceEnabled: boolean;
// skip .tsx files if jsx is not enabled
skipTsx: boolean;
}
export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
const traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
trace(host, Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
}
let moduleResolution = compilerOptions.moduleResolution;
if (moduleResolution === undefined) {
moduleResolution = getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic;
if (traceEnabled) {
trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]);
}
}
else {
if (traceEnabled) {
trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]);
}
}
let result: ResolvedModuleWithFailedLookupLocations;
switch (moduleResolution) {
case ModuleResolutionKind.NodeJs:
result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host);
break;
case ModuleResolutionKind.Classic:
result = classicNameResolver(moduleName, containingFile, compilerOptions, host);
break;
}
if (traceEnabled) {
if (result.resolvedModule) {
trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
}
else {
trace(host, Diagnostics.Module_name_0_was_not_resolved, moduleName);
}
}
return result;
}
/*
* Every module resolution kind can has its specific understanding how to load module from a specific path on disk
* I.e. for path '/a/b/c':
* - Node loader will first to try to check if '/a/b/c' points to a file with some supported extension and if this fails
* it will try to load module from directory: directory '/a/b/c' should exist and it should have either 'package.json' with
* 'typings' entry or file 'index' with some supported extension
* - Classic loader will only try to interpret '/a/b/c' as file.
*/
type ResolutionKindSpecificLoader = (candidate: string, extensions: string[], failedLookupLocations: string[], onlyRecordFailures: boolean, state: ModuleResolutionState) => string;
/**
* Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
* mitigate differences between design time structure of the project and its runtime counterpart so the same import name
* can be resolved successfully by TypeScript compiler and runtime module loader.
* If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
* fallback to standard resolution routine.
*
* - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
* names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
* be '/a/b/c/d'
* - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
* will be resolved based on the content of the module name.
* Structure of 'paths' compiler options
* 'paths': {
* pattern-1: [...substitutions],
* pattern-2: [...substitutions],
* ...
* pattern-n: [...substitutions]
* }
* Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
* all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
* If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
* <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
* If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
* After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
* from the candidate location.
* Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
* substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
* will be converted to absolute using baseUrl.
* For example:
* baseUrl: /a/b/c
* "paths": {
* // match all module names
* "*": [
* "*", // use matched name as is,
* // <matched name> will be looked as /a/b/c/<matched name>
*
* "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
* // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
* ],
* // match module names that start with 'components/'
* "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
* // it is rooted so it will be final candidate location
* }
*
* 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
* they were in the same location. For example lets say there are two files
* '/local/src/content/file1.ts'
* '/shared/components/contracts/src/content/protocols/file2.ts'
* After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
* if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
* 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
* root dirs were merged together.
* I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
* Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
* '/local/src/content/protocols/file2' and try to load it - failure.
* Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
* be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
* entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
*/
function tryLoadModuleUsingOptionalResolutionSettings(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader,
failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string {
if (moduleHasNonRelativeName(moduleName)) {
return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state);
}
else {
return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state);
}
}
function tryLoadModuleUsingRootDirs(moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader,
failedLookupLocations: string[], supportedExtensions: string[], state: ModuleResolutionState): string {
if (!state.compilerOptions.rootDirs) {
return undefined;
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
}
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
let matchedRootDir: string;
let matchedNormalizedPrefix: string;
for (const rootDir of state.compilerOptions.rootDirs) {
// rootDirs are expected to be absolute
// in case of tsconfig.json this will happen automatically - compiler will expand relative names
// using location of tsconfig.json as base location
let normalizedRoot = normalizePath(rootDir);
if (!endsWith(normalizedRoot, directorySeparator)) {
normalizedRoot += directorySeparator;
}
const isLongestMatchingPrefix =
startsWith(candidate, normalizedRoot) &&
(matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
if (state.traceEnabled) {
trace(state.host, Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
}
if (isLongestMatchingPrefix) {
matchedNormalizedPrefix = normalizedRoot;
matchedRootDir = rootDir;
}
}
if (matchedNormalizedPrefix) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
}
const suffix = candidate.substr(matchedNormalizedPrefix.length);
// first - try to load from a initial location
if (state.traceEnabled) {
trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
}
const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state);
if (resolvedFileName) {
return resolvedFileName;
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.Trying_other_entries_in_rootDirs);
}
// then try to resolve using remaining entries in rootDirs
for (const rootDir of state.compilerOptions.rootDirs) {
if (rootDir === matchedRootDir) {
// skip the initially matched entry
continue;
}
const candidate = combinePaths(normalizePath(rootDir), suffix);
if (state.traceEnabled) {
trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate);
}
const baseDirectory = getDirectoryPath(candidate);
const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state);
if (resolvedFileName) {
return resolvedFileName;
}
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.Module_resolution_using_rootDirs_has_failed);
}
}
return undefined;
}
function tryLoadModuleUsingBaseUrl(moduleName: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: string[],
supportedExtensions: string[], state: ModuleResolutionState): string {
if (!state.compilerOptions.baseUrl) {
return undefined;
}
if (state.traceEnabled) {
trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName);
}
let longestMatchPrefixLength = -1;
let matchedPattern: string;
let matchedStar: string;
if (state.compilerOptions.paths) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
}
for (const key in state.compilerOptions.paths) {
const pattern: string = key;
const indexOfStar = pattern.indexOf("*");
if (indexOfStar !== -1) {
const prefix = pattern.substr(0, indexOfStar);
const suffix = pattern.substr(indexOfStar + 1);
if (moduleName.length >= prefix.length + suffix.length &&
startsWith(moduleName, prefix) &&
endsWith(moduleName, suffix)) {
// use length of prefix as betterness criteria
if (prefix.length > longestMatchPrefixLength) {
longestMatchPrefixLength = prefix.length;
matchedPattern = pattern;
matchedStar = moduleName.substr(prefix.length, moduleName.length - suffix.length);
}
}
}
else if (pattern === moduleName) {
// pattern was matched as is - no need to search further
matchedPattern = pattern;
matchedStar = undefined;
break;
}
}
}
if (matchedPattern) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPattern);
}
for (const subst of state.compilerOptions.paths[matchedPattern]) {
const path = matchedStar ? subst.replace("\*", matchedStar) : subst;
const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, path));
if (state.traceEnabled) {
trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
}
const resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
if (resolvedFileName) {
return resolvedFileName;
}
}
return undefined;
}
else {
const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, moduleName));
if (state.traceEnabled) {
trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate);
}
return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
}
}
export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
const containingDirectory = getDirectoryPath(containingFile);
const supportedExtensions = getSupportedExtensions(compilerOptions);
const traceEnabled = isTraceEnabled(compilerOptions, host);
const failedLookupLocations: string[] = [];
const state = {compilerOptions, host, traceEnabled, skipTsx: false};
let resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName,
failedLookupLocations, supportedExtensions, state);
if (resolvedFileName) {
return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations);
}
let isExternalLibraryImport = false;
if (moduleHasNonRelativeName(moduleName)) {
if (traceEnabled) {
trace(host, Diagnostics.Loading_module_0_from_node_modules_folder, moduleName);
}
resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state);
isExternalLibraryImport = resolvedFileName !== undefined;
}
else {
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
}
return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations);
}
function nodeLoadModuleByRelativeName(candidate: string, supportedExtensions: string[], failedLookupLocations: string[],
onlyRecordFailures: boolean, state: ModuleResolutionState): string {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate);
}
const resolvedFileName = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state);
return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state);
}
/* @internal */
export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean } ): boolean {
// if host does not support 'directoryExists' assume that directory will exist
return !host.directoryExists || host.directoryExists(directoryName);
}
/**
* @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
* in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
*/
function loadModuleFromFile(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
return forEach(extensions, tryLoad);
function tryLoad(ext: string): string {
if (ext === ".tsx" && state.skipTsx) {
return undefined;
}
const fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext;
if (!onlyRecordFailures && state.host.fileExists(fileName)) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_exist_use_it_as_a_module_resolution_result, fileName);
}
return fileName;
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_does_not_exist, fileName);
}
failedLookupLocation.push(fileName);
return undefined;
}
}
}
function loadNodeModuleFromDirectory(extensions: string[], candidate: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
const packageJsonPath = combinePaths(candidate, "package.json");
const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host);
if (directoryExists && state.host.fileExists(packageJsonPath)) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Found_package_json_at_0, packageJsonPath);
}
let jsonContent: { typings?: string };
try {
const jsonText = state.host.readFile(packageJsonPath);
jsonContent = jsonText ? <{ typings?: string }>JSON.parse(jsonText) : { typings: undefined };
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
jsonContent = { typings: undefined };
}
if (jsonContent.typings) {
if (typeof jsonContent.typings === "string") {
const typingsFile = normalizePath(combinePaths(candidate, jsonContent.typings));
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_typings_field_0_that_references_1, jsonContent.typings, typingsFile);
}
const result = loadModuleFromFile(typingsFile, extensions, failedLookupLocation, !directoryProbablyExists(getDirectoryPath(typingsFile), state.host), state);
if (result) {
return result;
}
}
else if (state.traceEnabled) {
trace(state.host, Diagnostics.Expected_type_of_typings_field_in_package_json_to_be_string_got_0, typeof jsonContent.typings);
}
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_does_not_have_typings_field);
}
}
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_does_not_exist, packageJsonPath);
}
// record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
failedLookupLocation.push(packageJsonPath);
}
return loadModuleFromFile(combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
}
function loadModuleFromNodeModules(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string {
directory = normalizeSlashes(directory);
while (true) {
const baseName = getBaseFileName(directory);
if (baseName !== "node_modules") {
const nodeModulesFolder = combinePaths(directory, "node_modules");
const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName));
// Load only typescript files irrespective of allowJs option if loading from node modules
let result = loadModuleFromFile(candidate, supportedTypeScriptExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
if (result) {
return result;
}
result = loadNodeModuleFromDirectory(supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
if (result) {
return result;
}
}
const parentPath = getDirectoryPath(directory);
if (parentPath === directory) {
break;
}
directory = parentPath;
}
return undefined;
}
export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
const traceEnabled = isTraceEnabled(compilerOptions, host);
const state = { compilerOptions, host, traceEnabled, skipTsx: !compilerOptions.jsx };
const failedLookupLocations: string[] = [];
const supportedExtensions = getSupportedExtensions(compilerOptions);
let containingDirectory = getDirectoryPath(containingFile);
const resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state);
if (resolvedFileName) {
return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/false, failedLookupLocations);
}
let referencedSourceFile: string;
if (moduleHasNonRelativeName(moduleName)) {
while (true) {
const searchName = normalizePath(combinePaths(containingDirectory, moduleName));
referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
if (referencedSourceFile) {
break;
}
const parentPath = getDirectoryPath(containingDirectory);
if (parentPath === containingDirectory) {
break;
}
containingDirectory = parentPath;
}
}
else {
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state);
}
return referencedSourceFile
? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations }
: { resolvedModule: undefined, failedLookupLocations };
}
/* @internal */
export const defaultInitCompilerOptions: CompilerOptions = {
module: ModuleKind.CommonJS,
target: ScriptTarget.ES5,
noImplicitAny: false,
sourceMap: false,
};
export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost {
const existingDirectories: Map<boolean> = {};
function getCanonicalFileName(fileName: string): string {
// if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
// otherwise use toLowerCase as a canonical form.
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
// returned by CScript sys environment
const unsupportedFileEncodingErrorCode = -2147024809;
function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile {
let text: string;
try {
const start = new Date().getTime();
text = sys.readFile(fileName, options.charset);
ioReadTime += new Date().getTime() - start;
}
catch (e) {
if (onError) {
onError(e.number === unsupportedFileEncodingErrorCode
? createCompilerDiagnostic(Diagnostics.Unsupported_file_encoding).messageText
: e.message);
}
text = "";
}
return text !== undefined ? createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
}
function directoryExists(directoryPath: string): boolean {
if (hasProperty(existingDirectories, directoryPath)) {
return true;
}
if (sys.directoryExists(directoryPath)) {
existingDirectories[directoryPath] = true;
return true;
}
return false;
}
function ensureDirectoriesExist(directoryPath: string) {
if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) {
const parentDirectory = getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
sys.createDirectory(directoryPath);
}
}
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) {
try {
const start = new Date().getTime();
ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName)));
sys.writeFile(fileName, data, writeByteOrderMark);
ioWriteTime += new Date().getTime() - start;
}
catch (e) {
if (onError) {
onError(e.message);
}
}
}
const newLine = getNewLineCharacter(options);
return {
getSourceFile,
getDefaultLibFileName: options => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options)),
writeFile,
getCurrentDirectory: memoize(() => sys.getCurrentDirectory()),
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
getCanonicalFileName,
getNewLine: () => newLine,
fileExists: fileName => sys.fileExists(fileName),
readFile: fileName => sys.readFile(fileName),
trace: (s: string) => sys.write(s + newLine),
directoryExists: directoryName => sys.directoryExists(directoryName)
};
}
export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[] {
let diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(
program.getSyntacticDiagnostics(sourceFile, cancellationToken),
program.getGlobalDiagnostics(cancellationToken),
program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (program.getCompilerOptions().declaration) {
diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken));
}
return sortAndDeduplicateDiagnostics(diagnostics);
}
export function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string {
if (typeof messageText === "string") {
return messageText;
}
else {
let diagnosticChain = messageText;
let result = "";
let indent = 0;
while (diagnosticChain) {
if (indent) {
result += newLine;
for (let i = 0; i < indent; i++) {
result += " ";
}
}
result += diagnosticChain.messageText;
indent++;
diagnosticChain = diagnosticChain.next;
}
return result;
}
}
export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program {
let program: Program;
let files: SourceFile[] = [];
let fileProcessingDiagnostics = createDiagnosticCollection();
const programDiagnostics = createDiagnosticCollection();
let commonSourceDirectory: string;
let diagnosticsProducingTypeChecker: TypeChecker;
let noDiagnosticsTypeChecker: TypeChecker;
let classifiableNames: Map<string>;
let skipDefaultLib = options.noLib;
const supportedExtensions = getSupportedExtensions(options);
const start = new Date().getTime();
host = host || createCompilerHost(options);
// Map storing if there is emit blocking diagnostics for given input
const hasEmitBlockingDiagnostics = createFileMap<boolean>(getCanonicalFileName);
const currentDirectory = host.getCurrentDirectory();
const resolveModuleNamesWorker = host.resolveModuleNames
? ((moduleNames: string[], containingFile: string) => host.resolveModuleNames(moduleNames, containingFile))
: ((moduleNames: string[], containingFile: string) => {
const resolvedModuleNames: ResolvedModule[] = [];
// resolveModuleName does not store any results between calls.
// lookup is a local cache to avoid resolving the same module name several times
const lookup: Map<ResolvedModule> = {};
for (const moduleName of moduleNames) {
let resolvedName: ResolvedModule;
if (hasProperty(lookup, moduleName)) {
resolvedName = lookup[moduleName];
}
else {
resolvedName = resolveModuleName(moduleName, containingFile, options, host).resolvedModule;
lookup[moduleName] = resolvedName;
}
resolvedModuleNames.push(resolvedName);
}
return resolvedModuleNames;
});
const filesByName = createFileMap<SourceFile>();
// stores 'filename -> file association' ignoring case
// used to track cases when two file names differ only in casing
const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createFileMap<SourceFile>(fileName => fileName.toLowerCase()) : undefined;
if (oldProgram) {
// check properties that can affect structure of the program or module resolution strategy
// if any of these properties has changed - structure cannot be reused
const oldOptions = oldProgram.getCompilerOptions();
if ((oldOptions.module !== options.module) ||
(oldOptions.noResolve !== options.noResolve) ||
(oldOptions.target !== options.target) ||
(oldOptions.noLib !== options.noLib) ||
(oldOptions.jsx !== options.jsx) ||
(oldOptions.allowJs !== options.allowJs)) {
oldProgram = undefined;
}
}
if (!tryReuseStructureFromOldProgram()) {
forEach(rootNames, name => processRootFile(name, /*isDefaultLib*/ false));
// Do not process the default library if:
// - The '--noLib' flag is used.
// - A 'no-default-lib' reference comment is encountered in
// processing the root files.
if (!skipDefaultLib) {
processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ true);
}
}
// unconditionally set oldProgram to undefined to prevent it from being captured in closure
oldProgram = undefined;
program = {
getRootFileNames: () => rootNames,
getSourceFile,
getSourceFiles: () => files,
getCompilerOptions: () => options,
getSyntacticDiagnostics,
getOptionsDiagnostics,
getGlobalDiagnostics,
getSemanticDiagnostics,
getDeclarationDiagnostics,
getTypeChecker,
getClassifiableNames,
getDiagnosticsProducingTypeChecker,
getCommonSourceDirectory,
emit,
getCurrentDirectory: () => currentDirectory,
getNodeCount: () => getDiagnosticsProducingTypeChecker().getNodeCount(),
getIdentifierCount: () => getDiagnosticsProducingTypeChecker().getIdentifierCount(),
getSymbolCount: () => getDiagnosticsProducingTypeChecker().getSymbolCount(),
getTypeCount: () => getDiagnosticsProducingTypeChecker().getTypeCount(),
getFileProcessingDiagnostics: () => fileProcessingDiagnostics
};
verifyCompilerOptions();
programTime += new Date().getTime() - start;
return program;
function getCommonSourceDirectory() {
if (typeof commonSourceDirectory === "undefined") {
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
// If a rootDir is specified and is valid use it as the commonSourceDirectory
commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
else {
commonSourceDirectory = computeCommonSourceDirectory(files);
}
if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== directorySeparator) {
// Make sure directory path ends with directory separator so this string can directly
// used to replace with "" to get the relative path of the source file and the relative path doesn't
// start with / making it rooted path
commonSourceDirectory += directorySeparator;
}
}
return commonSourceDirectory;
}
function getClassifiableNames() {
if (!classifiableNames) {
// Initialize a checker so that all our files are bound.
getTypeChecker();
classifiableNames = {};
for (const sourceFile of files) {
copyMap(sourceFile.classifiableNames, classifiableNames);
}
}
return classifiableNames;
}
function tryReuseStructureFromOldProgram(): boolean {
if (!oldProgram) {
return false;
}
Debug.assert(!oldProgram.structureIsReused);
// there is an old program, check if we can reuse its structure
const oldRootNames = oldProgram.getRootFileNames();
if (!arrayIsEqualTo(oldRootNames, rootNames)) {
return false;
}
// check if program source files has changed in the way that can affect structure of the program
const newSourceFiles: SourceFile[] = [];
const filePaths: Path[] = [];
const modifiedSourceFiles: SourceFile[] = [];
for (const oldSourceFile of oldProgram.getSourceFiles()) {
let newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target);
if (!newSourceFile) {
return false;
}
newSourceFile.path = oldSourceFile.path;
filePaths.push(newSourceFile.path);
if (oldSourceFile !== newSourceFile) {
if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
// value of no-default-lib has changed
// this will affect if default library is injected into the list of files
return false;
}
// check tripleslash references
if (!arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
// tripleslash references has changed
return false;
}
// check imports and module augmentations
collectExternalModuleReferences(newSourceFile);
if (!arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
// imports has changed
return false;
}
if (!arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
// moduleAugmentations has changed
return false;
}
if (resolveModuleNamesWorker) {
const moduleNames = map(concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral);
const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory));
// ensure that module resolution results are still correct
for (let i = 0; i < moduleNames.length; i++) {
const newResolution = resolutions[i];
const oldResolution = getResolvedModule(oldSourceFile, moduleNames[i]);
const resolutionChanged = oldResolution
? !newResolution ||
oldResolution.resolvedFileName !== newResolution.resolvedFileName ||
!!oldResolution.isExternalLibraryImport !== !!newResolution.isExternalLibraryImport
: newResolution;
if (resolutionChanged) {
return false;
}
}
}
// pass the cache of module resolutions from the old source file
newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
modifiedSourceFiles.push(newSourceFile);
}
else {
// file has no changes - use it as is
newSourceFile = oldSourceFile;
}
// if file has passed all checks it should be safe to reuse it
newSourceFiles.push(newSourceFile);
}
// update fileName -> file mapping
for (let i = 0, len = newSourceFiles.length; i < len; i++) {
filesByName.set(filePaths[i], newSourceFiles[i]);
}
files = newSourceFiles;
fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
for (const modifiedFile of modifiedSourceFiles) {
fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile);
}
oldProgram.structureIsReused = true;
return true;
}
function getEmitHost(writeFileCallback?: WriteFileCallback): EmitHost {
return {
getCanonicalFileName,
getCommonSourceDirectory: program.getCommonSourceDirectory,
getCompilerOptions: program.getCompilerOptions,
getCurrentDirectory: () => currentDirectory,
getNewLine: () => host.getNewLine(),
getSourceFile: program.getSourceFile,
getSourceFiles: program.getSourceFiles,
writeFile: writeFileCallback || (
(fileName, data, writeByteOrderMark, onError) => host.writeFile(fileName, data, writeByteOrderMark, onError)),
isEmitBlocked,
};
}
function getDiagnosticsProducingTypeChecker() {
return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ true));
}
function getTypeChecker() {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ false));
}
function emit(sourceFile?: SourceFile, writeFileCallback?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult {
return runWithCancellationToken(() => emitWorker(this, sourceFile, writeFileCallback, cancellationToken));
}
function isEmitBlocked(emitFileName: string): boolean {
return hasEmitBlockingDiagnostics.contains(toPath(emitFileName, currentDirectory, getCanonicalFileName));
}
function emitWorker(program: Program, sourceFile: SourceFile, writeFileCallback: WriteFileCallback, cancellationToken: CancellationToken): EmitResult {
let declarationDiagnostics: Diagnostic[] = [];
if (options.noEmit) {
return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emitSkipped: true };
}
// If the noEmitOnError flag is set, then check if we have any errors so far. If so,
// immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we
// get any preEmit diagnostics, not just the ones
if (options.noEmitOnError) {
const diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(
program.getSyntacticDiagnostics(sourceFile, cancellationToken),
program.getGlobalDiagnostics(cancellationToken),
program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (diagnostics.length === 0 && program.getCompilerOptions().declaration) {
declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
}
if (diagnostics.length > 0 || declarationDiagnostics.length > 0) {
return { diagnostics, sourceMaps: undefined, emitSkipped: true };
}
}
// Create the emit resolver outside of the "emitTime" tracking code below. That way
// any cost associated with it (like type checking) are appropriate associated with
// the type-checking counter.
//
// If the -out option is specified, we should not pass the source file to getEmitResolver.
// This is because in the -out scenario all files need to be emitted, and therefore all
// files need to be type checked. And the way to specify that all files need to be type
// checked is to not pass the file to getEmitResolver.
const emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile);
const start = new Date().getTime();
const emitResult = emitFiles(
emitResolver,
getEmitHost(writeFileCallback),
sourceFile);
emitTime += new Date().getTime() - start;
return emitResult;
}
function getSourceFile(fileName: string): SourceFile {
return filesByName.get(toPath(fileName, currentDirectory, getCanonicalFileName));
}
function getDiagnosticsHelper(
sourceFile: SourceFile,
getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => Diagnostic[],
cancellationToken: CancellationToken): Diagnostic[] {
if (sourceFile) {
return getDiagnostics(sourceFile, cancellationToken);
}
const allDiagnostics: Diagnostic[] = [];
forEach(program.getSourceFiles(), sourceFile => {
if (cancellationToken) {
cancellationToken.throwIfCancellationRequested();
}
addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken));
});
return sortAndDeduplicateDiagnostics(allDiagnostics);
}
function getSyntacticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
}
function getSemanticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
}
function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
}
function getSyntacticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return sourceFile.parseDiagnostics;
}
function runWithCancellationToken<T>(func: () => T): T {
try {
return func();
}
catch (e) {
if (e instanceof OperationCanceledException) {
// We were canceled while performing the operation. Because our type checker
// might be a bad state, we need to throw it away.
//
// Note: we are overly aggressive here. We do not actually *have* to throw away
// the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep
// the lifetimes of these two TypeCheckers the same. Also, we generally only
// cancel when the user has made a change anyways. And, in that case, we (the
// program instance) will get thrown away anyways. So trying to keep one of
// these type checkers alive doesn't serve much purpose.
noDiagnosticsTypeChecker = undefined;
diagnosticsProducingTypeChecker = undefined;
}
throw e;
}
}
function getSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return runWithCancellationToken(() => {
const typeChecker = getDiagnosticsProducingTypeChecker();
Debug.assert(!!sourceFile.bindDiagnostics);
const bindDiagnostics = sourceFile.bindDiagnostics;
// For JavaScript files, we don't want to report the normal typescript semantic errors.
// Instead, we just report errors for using TypeScript-only constructs from within a
// JavaScript file.
const checkDiagnostics = isSourceFileJavaScript(sourceFile) ?
getJavaScriptSemanticDiagnosticsForFile(sourceFile, cancellationToken) :
typeChecker.getDiagnostics(sourceFile, cancellationToken);
const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile);
});
}
function getJavaScriptSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return runWithCancellationToken(() => {
const diagnostics: Diagnostic[] = [];
walk(sourceFile);
return diagnostics;
function walk(node: Node): boolean {
if (!node) {
return false;
}
switch (node.kind) {
case SyntaxKind.ImportEqualsDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.ExportAssignment:
if ((<ExportAssignment>node).isExportEquals) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_a_ts_file));
return true;
}
break;
case SyntaxKind.ClassDeclaration:
let classDeclaration = <ClassDeclaration>node;
if (checkModifiers(classDeclaration.modifiers) ||
checkTypeParameters(classDeclaration.typeParameters)) {
return true;
}
break;
case SyntaxKind.HeritageClause:
let heritageClause = <HeritageClause>node;
if (heritageClause.token === SyntaxKind.ImplementsKeyword) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file));
return true;
}
break;
case SyntaxKind.InterfaceDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.ModuleDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.module_declarations_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.TypeAliasDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.type_aliases_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ArrowFunction:
case SyntaxKind.FunctionDeclaration:
const functionDeclaration = <FunctionLikeDeclaration>node;
if (checkModifiers(functionDeclaration.modifiers) ||
checkTypeParameters(functionDeclaration.typeParameters) ||
checkTypeAnnotation(functionDeclaration.type)) {
return true;
}
break;
case SyntaxKind.VariableStatement:
const variableStatement = <VariableStatement>node;
if (checkModifiers(variableStatement.modifiers)) {
return true;
}
break;
case SyntaxKind.VariableDeclaration:
const variableDeclaration = <VariableDeclaration>node;
if (checkTypeAnnotation(variableDeclaration.type)) {
return true;
}
break;
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
const expression = <CallExpression>node;
if (expression.typeArguments && expression.typeArguments.length > 0) {
const start = expression.typeArguments.pos;
diagnostics.push(createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start,
Diagnostics.type_arguments_can_only_be_used_in_a_ts_file));
return true;
}
break;
case SyntaxKind.Parameter:
const parameter = <ParameterDeclaration>node;
if (parameter.modifiers) {
const start = parameter.modifiers.pos;
diagnostics.push(createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start,
Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file));
return true;
}
if (parameter.questionToken) {
diagnostics.push(createDiagnosticForNode(parameter.questionToken, Diagnostics._0_can_only_be_used_in_a_ts_file, "?"));
return true;
}
if (parameter.type) {
diagnostics.push(createDiagnosticForNode(parameter.type, Diagnostics.types_can_only_be_used_in_a_ts_file));
return true;
}
break;
case SyntaxKind.PropertyDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.property_declarations_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.EnumDeclaration:
diagnostics.push(createDiagnosticForNode(node, Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.TypeAssertionExpression:
let typeAssertionExpression = <TypeAssertion>node;
diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file));
return true;
case SyntaxKind.Decorator:
if (!options.experimentalDecorators) {
diagnostics.push(createDiagnosticForNode(node, Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning));
}
return true;
}
return forEachChild(node, walk);
}
function checkTypeParameters(typeParameters: NodeArray<TypeParameterDeclaration>): boolean {
if (typeParameters) {
const start = typeParameters.pos;
diagnostics.push(createFileDiagnostic(sourceFile, start, typeParameters.end - start, Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file));
return true;
}
return false;
}
function checkTypeAnnotation(type: TypeNode): boolean {
if (type) {
diagnostics.push(createDiagnosticForNode(type, Diagnostics.types_can_only_be_used_in_a_ts_file));
return true;
}
return false;
}
function checkModifiers(modifiers: ModifiersArray): boolean {
if (modifiers) {
for (const modifier of modifiers) {
switch (modifier.kind) {
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
case SyntaxKind.ReadonlyKeyword:
case SyntaxKind.DeclareKeyword:
diagnostics.push(createDiagnosticForNode(modifier, Diagnostics._0_can_only_be_used_in_a_ts_file, tokenToString(modifier.kind)));
return true;
// These are all legal modifiers.
case SyntaxKind.StaticKeyword:
case SyntaxKind.ExportKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.DefaultKeyword:
case SyntaxKind.AbstractKeyword:
}
}
}
return false;
}
});
}
function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {
return runWithCancellationToken(() => {
if (!isDeclarationFile(sourceFile)) {
const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
// Don't actually write any files since we're just getting diagnostics.
const writeFile: WriteFileCallback = () => { };
return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);
}
});
}
function getOptionsDiagnostics(): Diagnostic[] {
const allDiagnostics: Diagnostic[] = [];
addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics());
addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics());
return sortAndDeduplicateDiagnostics(allDiagnostics);
}
function getGlobalDiagnostics(): Diagnostic[] {
const allDiagnostics: Diagnostic[] = [];
addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics());
return sortAndDeduplicateDiagnostics(allDiagnostics);
}
function hasExtension(fileName: string): boolean {
return getBaseFileName(fileName).indexOf(".") >= 0;
}
function processRootFile(fileName: string, isDefaultLib: boolean) {
processSourceFile(normalizePath(fileName), isDefaultLib);
}
function fileReferenceIsEqualTo(a: FileReference, b: FileReference): boolean {
return a.fileName === b.fileName;
}
function moduleNameIsEqualTo(a: LiteralExpression, b: LiteralExpression): boolean {
return a.text === b.text;
}
function getTextOfLiteral(literal: LiteralExpression): string {
return literal.text;
}
function collectExternalModuleReferences(file: SourceFile): void {
if (file.imports) {
return;
}
const isJavaScriptFile = isSourceFileJavaScript(file);
const isExternalModuleFile = isExternalModule(file);
let imports: LiteralExpression[];
let moduleAugmentations: LiteralExpression[];
for (const node of file.statements) {
collectModuleReferences(node, /*inAmbientModule*/ false);
if (isJavaScriptFile) {
collectRequireCalls(node);
}
}
file.imports = imports || emptyArray;
file.moduleAugmentations = moduleAugmentations || emptyArray;
return;
function collectModuleReferences(node: Node, inAmbientModule: boolean): void {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ImportEqualsDeclaration:
case SyntaxKind.ExportDeclaration:
let moduleNameExpr = getExternalModuleName(node);
if (!moduleNameExpr || moduleNameExpr.kind !== SyntaxKind.StringLiteral) {
break;
}
if (!(<LiteralExpression>moduleNameExpr).text) {
break;
}
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
if (!inAmbientModule || !isExternalModuleNameRelative((<LiteralExpression>moduleNameExpr).text)) {
(imports || (imports = [])).push(<LiteralExpression>moduleNameExpr);
}
break;
case SyntaxKind.ModuleDeclaration:
if (isAmbientModule(<ModuleDeclaration>node) && (inAmbientModule || node.flags & NodeFlags.Ambient || isDeclarationFile(file))) {
const moduleName = <LiteralExpression>(<ModuleDeclaration>node).name;
// Ambient module declarations can be interpreted as augmentations for some existing external modules.
// This will happen in two cases:
// - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
// - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
// immediately nested in top level ambient module declaration .
if (isExternalModuleFile || (inAmbientModule && !isExternalModuleNameRelative(moduleName.text))) {
(moduleAugmentations || (moduleAugmentations = [])).push(moduleName);
}
else if (!inAmbientModule) {
// An AmbientExternalModuleDeclaration declares an external module.
// This type of declaration is permitted only in the global module.
// The StringLiteral must specify a top - level external module name.
// Relative external module names are not permitted
// NOTE: body of ambient module is always a module block
for (const statement of (<ModuleBlock>(<ModuleDeclaration>node).body).statements) {
collectModuleReferences(statement, /*inAmbientModule*/ true);
}
}
}
}
}
function collectRequireCalls(node: Node): void {
if (isRequireCall(node, /*checkArgumentIsStringLiteral*/true)) {
(imports || (imports = [])).push(<StringLiteral>(<CallExpression>node).arguments[0]);
}
else {
forEachChild(node, collectRequireCalls);
}
}
}
function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) {
let diagnosticArgument: string[];
let diagnostic: DiagnosticMessage;
if (hasExtension(fileName)) {
if (!options.allowNonTsExtensions && !forEach(supportedExtensions, extension => fileExtensionIs(host.getCanonicalFileName(fileName), extension))) {
diagnostic = Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1;
diagnosticArgument = [fileName, "'" + supportedExtensions.join("', '") + "'"];
}
else if (!findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) {
diagnostic = Diagnostics.File_0_not_found;
diagnosticArgument = [fileName];
}
else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) {
diagnostic = Diagnostics.A_file_cannot_have_a_reference_to_itself;
diagnosticArgument = [fileName];
}
}
else {
const nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd);
if (!nonTsFile) {
if (options.allowNonTsExtensions) {
diagnostic = Diagnostics.File_0_not_found;
diagnosticArgument = [fileName];
}
else if (!forEach(supportedExtensions, extension => findSourceFile(fileName + extension, toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd))) {
diagnostic = Diagnostics.File_0_not_found;
fileName += ".ts";
diagnosticArgument = [fileName];
}
}
}
if (diagnostic) {
if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) {
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...diagnosticArgument));
}
else {
fileProcessingDiagnostics.add(createCompilerDiagnostic(diagnostic, ...diagnosticArgument));
}
}
}
function reportFileNamesDifferOnlyInCasingError(fileName: string, existingFileName: string, refFile: SourceFile, refPos: number, refEnd: number): void {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName));
}
else {
fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName));
}
}
// Get source file from normalized fileName
function findSourceFile(fileName: string, path: Path, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number): SourceFile {
if (filesByName.contains(path)) {
const file = filesByName.get(path);
// try to check if we've already seen this file but with a different casing in path
// NOTE: this only makes sense for case-insensitive file systems
if (file && options.forceConsistentCasingInFileNames && getNormalizedAbsolutePath(file.fileName, currentDirectory) !== getNormalizedAbsolutePath(fileName, currentDirectory)) {
reportFileNamesDifferOnlyInCasingError(fileName, file.fileName, refFile, refPos, refEnd);
}
return file;
}
// We haven't looked for this file, do so now and cache result
const file = host.getSourceFile(fileName, options.target, hostErrorMessage => {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
else {
fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
});
filesByName.set(path, file);
if (file) {
file.path = path;
if (host.useCaseSensitiveFileNames()) {
// for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
const existingFile = filesByNameIgnoreCase.get(path);
if (existingFile) {
reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd);
}
else {
filesByNameIgnoreCase.set(path, file);
}
}
skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib;
const basePath = getDirectoryPath(fileName);
if (!options.noResolve) {
processReferencedFiles(file, basePath);
}
// always process imported modules to record module name resolutions
processImportedModules(file, basePath);
if (isDefaultLib) {
files.unshift(file);
}
else {
files.push(file);
}
}
return file;
}
function processReferencedFiles(file: SourceFile, basePath: string) {
forEach(file.referencedFiles, ref => {
const referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
processSourceFile(referencedFileName, /*isDefaultLib*/ false, file, ref.pos, ref.end);
});
}
function getCanonicalFileName(fileName: string): string {
return host.getCanonicalFileName(fileName);
}
function processImportedModules(file: SourceFile, basePath: string) {
collectExternalModuleReferences(file);
if (file.imports.length || file.moduleAugmentations.length) {
file.resolvedModules = {};
const moduleNames = map(concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral);
const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory));
for (let i = 0; i < moduleNames.length; i++) {
const resolution = resolutions[i];
setResolvedModule(file, moduleNames[i], resolution);
// add file to program only if:
// - resolution was successful
// - noResolve is falsy
// - module name come from the list fo imports
const shouldAddFile = resolution &&
!options.noResolve &&
i < file.imports.length;
if (shouldAddFile) {
const importedFile = findSourceFile(resolution.resolvedFileName, toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, file, skipTrivia(file.text, file.imports[i].pos), file.imports[i].end);
if (importedFile && resolution.isExternalLibraryImport) {
// Since currently irrespective of allowJs, we only look for supportedTypeScript extension external module files,
// this check is ok. Otherwise this would be never true for javascript file
if (!isExternalModule(importedFile) && importedFile.statements.length) {
const start = getTokenPosOfNode(file.imports[i], file);
fileProcessingDiagnostics.add(createFileDiagnostic(file, start, file.imports[i].end - start, Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName));
}
else if (importedFile.referencedFiles.length) {
const firstRef = importedFile.referencedFiles[0];
fileProcessingDiagnostics.add(createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition));
}
}
}
}
}
else {
// no imports - drop cached module resolutions
file.resolvedModules = undefined;
}
return;
}
function computeCommonSourceDirectory(sourceFiles: SourceFile[]): string {
let commonPathComponents: string[];
const failed = forEach(files, sourceFile => {
// Each file contributes into common source file path
if (isDeclarationFile(sourceFile)) {
return;
}
const sourcePathComponents = getNormalizedPathComponents(sourceFile.fileName, currentDirectory);
sourcePathComponents.pop(); // The base file name is not part of the common directory path
if (!commonPathComponents) {
// first file
commonPathComponents = sourcePathComponents;
return;
}
for (let i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) {
if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
if (i === 0) {
// Failed to find any common path component
return true;
}
// New common path found that is 0 -> i-1
commonPathComponents.length = i;
break;
}
}
// If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
if (sourcePathComponents.length < commonPathComponents.length) {
commonPathComponents.length = sourcePathComponents.length;
}
});
// A common path can not be found when paths span multiple drives on windows, for example
if (failed) {
return "";
}
if (!commonPathComponents) { // Can happen when all input files are .d.ts files
return currentDirectory;
}
return getNormalizedPathFromPathComponents(commonPathComponents);
}
function checkSourceFilesBelongToPath(sourceFiles: SourceFile[], rootDirectory: string): boolean {
let allFilesBelongToPath = true;
if (sourceFiles) {
const absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory));
for (const sourceFile of sourceFiles) {
if (!isDeclarationFile(sourceFile)) {
const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir));
allFilesBelongToPath = false;
}
}
}
}
return allFilesBelongToPath;
}
function verifyCompilerOptions() {
if (options.isolatedModules) {
if (options.declaration) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"));
}
if (options.noEmitOnError) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"));
}
if (options.out) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"));
}
if (options.outFile) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"));
}
}
if (options.inlineSourceMap) {
if (options.sourceMap) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"));
}
if (options.mapRoot) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"));
}
}
if (options.paths && options.baseUrl === undefined) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option));
}
if (options.paths) {
for (const key in options.paths) {
if (!hasProperty(options.paths, key)) {
continue;
}
if (!hasZeroOrOneAsteriskCharacter(key)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key));
}
for (const subst of options.paths[key]) {
if (!hasZeroOrOneAsteriskCharacter(subst)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key));
}
}
}
}
if (options.inlineSources) {
if (!options.sourceMap && !options.inlineSourceMap) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided));
}
if (options.sourceRoot) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSources"));
}
}
if (options.out && options.outFile) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"));
}
if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) {
// Error to specify --mapRoot or --sourceRoot without mapSourceFiles
if (options.mapRoot) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"));
}
if (options.sourceRoot && !options.inlineSourceMap) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap"));
}
}
if (options.declarationDir) {
if (!options.declaration) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"));
}
if (options.out || options.outFile) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"));
}
}
const languageVersion = options.target || ScriptTarget.ES3;
const outFile = options.outFile || options.out;
const firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined);
if (options.isolatedModules) {
if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES6) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher));
}
const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined);
if (firstNonExternalModuleSourceFile) {
const span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
}
}
else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided_with_a_valid_module_type_Consider_setting_the_module_compiler_option_in_a_tsconfig_json_file));
}
// Cannot specify module gen target of es6 when below es6
if (options.module === ModuleKind.ES6 && languageVersion < ScriptTarget.ES6) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower));
}
// Cannot specify module gen that isn't amd or system with --out
if (outFile && options.module && !(options.module === ModuleKind.AMD || options.module === ModuleKind.System)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
}
// there has to be common source directory if user specified --outdir || --sourceRoot
// if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
if (options.outDir || // there is --outDir specified
options.sourceRoot || // there is --sourceRoot specified
options.mapRoot) { // there is --mapRoot specified
// Precalculate and cache the common source directory
const dir = getCommonSourceDirectory();
// If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure
if (options.outDir && dir === "" && forEach(files, file => getRootLength(file.fileName) > 1)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files));
}
}
if (options.noEmit) {
if (options.out) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "out"));
}
if (options.outFile) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outFile"));
}
if (options.outDir) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outDir"));
}
if (options.declaration) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration"));
}
}
else if (options.allowJs && options.declaration) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"));
}
if (options.emitDecoratorMetadata &&
!options.experimentalDecorators) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
}
if (options.reactNamespace && !isIdentifier(options.reactNamespace, languageVersion)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace));
}
// If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
if (!options.noEmit && !options.suppressOutputPathCheck) {
const emitHost = getEmitHost();
const emitFilesSeen = createFileMap<boolean>(!host.useCaseSensitiveFileNames() ? key => key.toLocaleLowerCase() : undefined);
forEachExpectedEmitFile(emitHost, (emitFileNames, sourceFiles, isBundledEmit) => {
verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen);
verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen);
});
}
// Verify that all the emit files are unique and don't overwrite input files
function verifyEmitFilePath(emitFileName: string, emitFilesSeen: FileMap<boolean>) {
if (emitFileName) {
const emitFilePath = toPath(emitFileName, currentDirectory, getCanonicalFileName);
// Report error if the output overwrites input file
if (filesByName.contains(emitFilePath)) {
createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file);
}
// Report error if multiple files write into same file
if (emitFilesSeen.contains(emitFilePath)) {
// Already seen the same emit file - report error
createEmitBlockingDiagnostics(emitFileName, emitFilePath, Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files);
}
else {
emitFilesSeen.set(emitFilePath, true);
}
}
}
}
function createEmitBlockingDiagnostics(emitFileName: string, emitFilePath: Path, message: DiagnosticMessage) {
hasEmitBlockingDiagnostics.set(toPath(emitFileName, currentDirectory, getCanonicalFileName), true);
programDiagnostics.add(createCompilerDiagnostic(message, emitFileName));
}
}
}
| src/compiler/program.ts | 1 | https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843 | [
0.99921715259552,
0.08724183589220047,
0.00016053357103373855,
0.00018156510486733168,
0.2691134214401245
]
|
{
"id": 1,
"code_window": [
" function getSemanticDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n",
" return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);\n",
" }\n",
"\n",
" function getDeclarationDiagnostics(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n",
" return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);\n",
" }\n",
"\n",
" function getSyntacticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const options = program.getCompilerOptions();\n",
" if (!sourceFile || options.out || options.outFile) {\n",
" return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);\n",
" }\n",
" else {\n",
" return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);\n",
" }\n"
],
"file_path": "src/compiler/program.ts",
"type": "replace",
"edit_start_line_idx": 1000
} | tests/cases/compiler/functionCall12.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target.
tests/cases/compiler/functionCall12.ts(5,5): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
tests/cases/compiler/functionCall12.ts(7,15): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
==== tests/cases/compiler/functionCall12.ts (3 errors) ====
function foo(a:string, b?:number, c?:string){}
foo('foo', 1);
foo('foo');
foo();
~~~~~
!!! error TS2346: Supplied parameters do not match any signature of call target.
foo(1, 'bar');
~
!!! error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
foo('foo', 1, 'bar');
foo('foo', 1, 3);
~
!!! error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
| tests/baselines/reference/functionCall12.errors.txt | 0 | https://github.com/microsoft/TypeScript/commit/8e77f40ace2155b16bb0ac5a417467edbec86843 | [
0.00037400805740617216,
0.00024101506278384477,
0.00017172686057165265,
0.00017731025582179427,
0.0000940678728511557
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.