hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 3, "code_window": [ " if (!targetSchema) {\n", " return acc;\n", " }\n", "\n", " return {\n", " ...acc,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const populateObject = convertNestedPopulate(subPopulate, targetSchema);\n", "\n", " if (!populateObject) {\n", " return acc;\n", " }\n", "\n" ], "file_path": "packages/core/utils/lib/convert-query-params.js", "type": "add", "edit_start_line_idx": 205 }
'use strict'; module.exports = { default: { provider: 'sendmail', providerOptions: {}, settings: { defaultFrom: 'Strapi <[email protected]>', }, }, validator() {}, };
packages/core/email/server/config.js
0
https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d
[ 0.00017400576325599104, 0.00017257370927836746, 0.00017114165530074388, 0.00017257370927836746, 0.0000014320539776235819 ]
{ "id": 3, "code_window": [ " if (!targetSchema) {\n", " return acc;\n", " }\n", "\n", " return {\n", " ...acc,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const populateObject = convertNestedPopulate(subPopulate, targetSchema);\n", "\n", " if (!populateObject) {\n", " return acc;\n", " }\n", "\n" ], "file_path": "packages/core/utils/lib/convert-query-params.js", "type": "add", "edit_start_line_idx": 205 }
import formatLayouts, { formatEditRelationsLayoutWithMetas, formatLayoutWithMetas, formatListLayoutWithMetas, generateRelationQueryInfos, generateRelationQueryInfosForComponents, getDisplayedModels, } from '../formatLayouts'; const addressSchema = { uid: 'api::address.address', attributes: { categories: { targetModel: 'api::category.category', }, }, layouts: { editRelations: ['categories'], }, metadatas: { categories: { edit: { mainField: { name: 'name', type: 'string', }, }, }, }, }; const simpleModels = [ { uid: 'api::category.category', isDisplayed: true, attributes: { name: { type: 'string', }, }, }, ]; describe('Content Manager | hooks | useFetchContentTypeLayout | utils ', () => { describe('formatEditRelationsLayoutWithMetas', () => { it('should format editRelations layout correctly', () => { const expectedLayout = [ { name: 'categories', size: 6, fieldSchema: { targetModel: 'api::category.category', }, metadatas: { mainField: { name: 'name', type: 'string', }, }, queryInfos: { endPoint: '/content-manager/relations/api::address.address/categories', containsKey: 'name', defaultParams: {}, shouldDisplayRelationLink: true, }, targetModelPluginOptions: {}, }, ]; expect(formatEditRelationsLayoutWithMetas(addressSchema, simpleModels)).toEqual( expectedLayout ); }); }); describe('formatLayouts', () => { it('should format the content type and components layouts', () => { const models = [ { uid: 'compo', attributes: { full_name: { type: 'string', required: true, }, city: { type: 'string', maxLength: 100, }, compo: { type: 'component', repeatable: true, }, }, settings: { test: 'test' }, options: { timestamps: false }, }, { attributes: { full_name: { type: 'string', required: true, }, city: { type: 'string', maxLength: 100, }, dz: { type: 'dynamiczone', }, compo: { type: 'component', repeatable: true, }, }, uid: 'contentType', }, ]; const data = { components: { compo: { uid: 'compo', layouts: { edit: [ [ { name: 'full_name', size: 6 }, { name: 'city', size: 6 }, ], [{ name: 'compo', size: 12 }], ], }, metadatas: { full_name: { edit: { description: 'test', editable: true, label: 'Full_name', placeholder: '', visible: true, }, }, city: { edit: { description: '', editable: false, label: 'City', placeholder: '', visible: true, }, }, compo: { edit: { description: '', editable: true, label: 'compo', placeholder: '', visible: true, }, }, }, }, }, contentType: { uid: 'contentType', layouts: { list: [], editRelations: [], edit: [ [{ name: 'dz', size: 12 }], [ { name: 'full_name', size: 6 }, { name: 'city', size: 6 }, ], [{ name: 'compo', size: 12 }], ], }, metadatas: { full_name: { edit: { description: 'test', editable: true, label: 'Full_name', placeholder: '', visible: true, }, }, city: { edit: { description: '', editable: false, label: 'City', placeholder: '', visible: true, }, }, dz: { edit: { description: '', editable: true, label: 'Dz', placeholder: '', visible: true, }, }, compo: { edit: { description: '', editable: true, label: 'compo', placeholder: '', visible: true, }, }, }, }, }; const result = formatLayouts(data, models); expect(result.components.compo).toHaveProperty('attributes'); expect(result.components.compo).toHaveProperty('layouts'); expect(result.components.compo).toHaveProperty('metadatas'); expect(result.contentType).toHaveProperty('attributes'); expect(result.contentType).toHaveProperty('layouts'); expect(result.contentType).toHaveProperty('metadatas'); expect(result.contentType.layouts.edit).toEqual([ [ { name: 'dz', size: 12, fieldSchema: { type: 'dynamiczone', }, metadatas: { description: '', editable: true, label: 'Dz', placeholder: '', visible: true, }, }, ], [ { name: 'full_name', size: 6, fieldSchema: { type: 'string', required: true, }, metadatas: { description: 'test', editable: true, label: 'Full_name', placeholder: '', visible: true, }, }, { name: 'city', size: 6, fieldSchema: { type: 'string', maxLength: 100, }, metadatas: { description: '', editable: false, label: 'City', placeholder: '', visible: true, }, }, ], [ { name: 'compo', size: 12, fieldSchema: { type: 'component', repeatable: true, }, metadatas: { description: '', editable: true, label: 'compo', placeholder: '', visible: true, }, }, ], ]); expect(result.components.compo.layouts.edit).toEqual([ [ { name: 'full_name', size: 6, fieldSchema: { type: 'string', required: true, }, metadatas: { description: 'test', editable: true, label: 'Full_name', placeholder: '', visible: true, }, }, { name: 'city', size: 6, fieldSchema: { type: 'string', maxLength: 100, }, metadatas: { description: '', editable: false, label: 'City', placeholder: '', visible: true, }, }, ], [ { name: 'compo', size: 12, fieldSchema: { type: 'component', repeatable: true, }, metadatas: { description: '', editable: true, label: 'compo', placeholder: '', visible: true, }, }, ], ]); }); }); describe('formatLayoutWithMetas', () => { it('should return a layout with the metadas for each input', () => { const data = { attributes: { full_name: { type: 'string', required: true, }, city: { type: 'string', maxLength: 100, }, dz: { type: 'dynamiczone', }, compo: { type: 'component', repeatable: true, }, }, layouts: { edit: [ [{ name: 'dz', size: 12 }], [ { name: 'full_name', size: 6 }, { name: 'city', size: 6 }, ], [{ name: 'compo', size: 12 }], ], }, metadatas: { full_name: { edit: { description: 'test', editable: true, label: 'Full_name', placeholder: '', visible: true, }, }, city: { edit: { description: '', editable: false, label: 'City', placeholder: '', visible: true, }, }, dz: { edit: { description: '', editable: true, label: 'Dz', placeholder: '', visible: true, }, }, compo: { edit: { description: '', editable: true, label: 'compo', placeholder: '', visible: true, }, }, }, }; const expected = [ [ { name: 'dz', size: 12, fieldSchema: { type: 'dynamiczone', }, metadatas: { description: '', editable: true, label: 'Dz', placeholder: '', visible: true, }, }, ], [ { name: 'full_name', size: 6, fieldSchema: { type: 'string', required: true, }, metadatas: { description: 'test', editable: true, label: 'Full_name', placeholder: '', visible: true, }, }, { name: 'city', size: 6, fieldSchema: { type: 'string', maxLength: 100, }, metadatas: { description: '', editable: false, label: 'City', placeholder: '', visible: true, }, }, ], [ { name: 'compo', size: 12, fieldSchema: { type: 'component', repeatable: true, }, metadatas: { description: '', editable: true, label: 'compo', placeholder: '', visible: true, }, }, ], ]; expect(formatLayoutWithMetas(data)).toEqual(expected); }); }); describe('formatListLayoutWithMetas', () => { it('should format the list layout correctly', () => { const data = { uid: 'address', layouts: { list: ['test', 'categories', 'component'], }, metadatas: { test: { list: { ok: true }, }, component: { list: { mainField: { name: 'name', schema: { type: 'string', }, }, }, }, categories: { list: { ok: true, mainField: { name: 'name', schema: { type: 'string', }, }, }, }, }, attributes: { test: { type: 'string' }, categories: { type: 'relation', targetModel: 'category', }, component: { type: 'component', component: 'some.component', repeatable: false, }, }, }; const components = { 'some.component': { settings: { mainField: 'name', }, attributes: { type: 'string', }, }, }; const expected = [ { name: 'test', key: '__test_key__', metadatas: { ok: true }, fieldSchema: { type: 'string' }, }, { name: 'categories', key: '__categories_key__', metadatas: { ok: true, mainField: { name: 'name', schema: { type: 'string', }, }, }, fieldSchema: { type: 'relation', targetModel: 'category' }, queryInfos: { defaultParams: {}, endPoint: 'collection-types/address' }, }, { name: 'component', key: '__component_key__', metadatas: { mainField: { name: 'name', }, }, fieldSchema: { type: 'component', component: 'some.component', repeatable: false, }, }, ]; expect(formatListLayoutWithMetas(data, components)).toEqual(expected); }); }); describe('generateRelationQueryInfos', () => { it('should return an object with the correct keys', () => { expect(generateRelationQueryInfos(addressSchema, 'categories', simpleModels)).toEqual({ endPoint: '/content-manager/relations/api::address.address/categories', containsKey: 'name', defaultParams: {}, shouldDisplayRelationLink: true, }); }); }); describe('generateRelationQueryInfosForComponents', () => { it('should return an object with the correct keys', () => { expect( generateRelationQueryInfosForComponents( addressSchema, 'categories', 'api::address.address', simpleModels ) ).toEqual({ endPoint: '/content-manager/relations/api::address.address/categories', containsKey: 'name', defaultParams: { _component: 'api::address.address', }, shouldDisplayRelationLink: true, }); }); }); describe('getDisplayedModels', () => { it('should return an array containing only the displayable models', () => { const models = [ { uid: 'test', isDisplayed: false }, { uid: 'testtest', isDisplayed: true }, ]; expect(getDisplayedModels([])).toHaveLength(0); expect(getDisplayedModels(models)).toHaveLength(1); expect(getDisplayedModels(models)[0]).toEqual('testtest'); }); }); });
packages/core/admin/admin/src/content-manager/hooks/useFetchContentTypeLayout/utils/tests/formatLayouts.test.js
0
https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d
[ 0.00039449817268177867, 0.00017724244389683008, 0.00016488310939166695, 0.00017125715385191143, 0.00003137732346658595 ]
{ "id": 4, "code_window": [ " return {\n", " ...acc,\n", " [key]: convertNestedPopulate(subPopulate, targetSchema),\n", " };\n", " }, {});\n", "};\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " [key]: populateObject,\n" ], "file_path": "packages/core/utils/lib/convert-query-params.js", "type": "replace", "edit_start_line_idx": 207 }
/* eslint-disable max-classes-per-file */ 'use strict'; /** * Converts the standard Strapi REST query params to a more usable format for querying * You can read more here: https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest-api.html#filters */ const { has, isEmpty, isObject, isPlainObject, cloneDeep, get, mergeAll } = require('lodash/fp'); const _ = require('lodash'); const parseType = require('./parse-type'); const contentTypesUtils = require('./content-types'); const { PUBLISHED_AT_ATTRIBUTE } = contentTypesUtils.constants; class InvalidOrderError extends Error { constructor() { super(); this.message = 'Invalid order. order can only be one of asc|desc|ASC|DESC'; } } class InvalidSortError extends Error { constructor() { super(); this.message = 'Invalid sort parameter. Expected a string, an array of strings, a sort object or an array of sort objects'; } } const validateOrder = (order) => { if (!['asc', 'desc'].includes(order.toLocaleLowerCase())) { throw new InvalidOrderError(); } }; const convertCountQueryParams = (countQuery) => { return parseType({ type: 'boolean', value: countQuery }); }; /** * Sort query parser * @param {string} sortQuery - ex: id:asc,price:desc */ const convertSortQueryParams = (sortQuery) => { if (typeof sortQuery === 'string') { return sortQuery.split(',').map((value) => convertSingleSortQueryParam(value)); } if (Array.isArray(sortQuery)) { return sortQuery.flatMap((sortValue) => convertSortQueryParams(sortValue)); } if (_.isPlainObject(sortQuery)) { return convertNestedSortQueryParam(sortQuery); } throw new InvalidSortError(); }; const convertSingleSortQueryParam = (sortQuery) => { // split field and order param with default order to ascending const [field, order = 'asc'] = sortQuery.split(':'); if (field.length === 0) { throw new Error('Field cannot be empty'); } validateOrder(order); return _.set({}, field, order); }; const convertNestedSortQueryParam = (sortQuery) => { const transformedSort = {}; for (const field of Object.keys(sortQuery)) { const order = sortQuery[field]; // this is a deep sort if (_.isPlainObject(order)) { transformedSort[field] = convertNestedSortQueryParam(order); } else { validateOrder(order); transformedSort[field] = order; } } return transformedSort; }; /** * Start query parser * @param {string} startQuery */ const convertStartQueryParams = (startQuery) => { const startAsANumber = _.toNumber(startQuery); if (!_.isInteger(startAsANumber) || startAsANumber < 0) { throw new Error(`convertStartQueryParams expected a positive integer got ${startAsANumber}`); } return startAsANumber; }; /** * Limit query parser * @param {string} limitQuery */ const convertLimitQueryParams = (limitQuery) => { const limitAsANumber = _.toNumber(limitQuery); if (!_.isInteger(limitAsANumber) || (limitAsANumber !== -1 && limitAsANumber < 0)) { throw new Error(`convertLimitQueryParams expected a positive integer got ${limitAsANumber}`); } if (limitAsANumber === -1) return null; return limitAsANumber; }; class InvalidPopulateError extends Error { constructor() { super(); this.message = 'Invalid populate parameter. Expected a string, an array of strings, a populate object'; } } // NOTE: we could support foo.* or foo.bar.* etc later on const convertPopulateQueryParams = (populate, schema, depth = 0) => { if (depth === 0 && populate === '*') { return true; } if (typeof populate === 'string') { return populate.split(',').map((value) => _.trim(value)); } if (Array.isArray(populate)) { // map convert return _.uniq( populate.flatMap((value) => { if (typeof value !== 'string') { throw new InvalidPopulateError(); } return value.split(',').map((value) => _.trim(value)); }) ); } if (_.isPlainObject(populate)) { return convertPopulateObject(populate, schema); } throw new InvalidPopulateError(); }; const convertPopulateObject = (populate, schema) => { if (!schema) { return {}; } const { attributes } = schema; return Object.entries(populate).reduce((acc, [key, subPopulate]) => { const attribute = attributes[key]; if (!attribute) { return acc; } // FIXME: This is a temporary solution for dynamic zones that should be // fixed when we'll implement a more accurate way to query them if (attribute.type === 'dynamiczone') { const populates = attribute.components .map((uid) => strapi.getModel(uid)) .map((schema) => convertNestedPopulate(subPopulate, schema)); return { ...acc, [key]: mergeAll(populates), }; } // NOTE: Retrieve the target schema UID. // Only handles basic relations, medias and component since it's not possible // to populate with options for a dynamic zone or a polymorphic relation let targetSchemaUID; if (attribute.type === 'relation') { targetSchemaUID = attribute.target; } else if (attribute.type === 'component') { targetSchemaUID = attribute.component; } else if (attribute.type === 'media') { targetSchemaUID = 'plugin::upload.file'; } else { return acc; } const targetSchema = strapi.getModel(targetSchemaUID); if (!targetSchema) { return acc; } return { ...acc, [key]: convertNestedPopulate(subPopulate, targetSchema), }; }, {}); }; const convertNestedPopulate = (subPopulate, schema) => { if (subPopulate === '*') { return true; } if (_.isString(subPopulate)) { return parseType({ type: 'boolean', value: subPopulate, forceCast: true }); } if (_.isBoolean(subPopulate)) { return subPopulate; } if (!_.isPlainObject(subPopulate)) { throw new Error(`Invalid nested populate. Expected '*' or an object`); } // TODO: We will need to consider a way to add limitation / pagination const { sort, filters, fields, populate, count } = subPopulate; const query = {}; if (sort) { query.orderBy = convertSortQueryParams(sort); } if (filters) { query.where = convertFiltersQueryParams(filters, schema); } if (fields) { query.select = convertFieldsQueryParams(fields); } if (populate) { query.populate = convertPopulateQueryParams(populate, schema); } if (count) { query.count = convertCountQueryParams(count); } return query; }; const convertFieldsQueryParams = (fields, depth = 0) => { if (depth === 0 && fields === '*') { return undefined; } if (typeof fields === 'string') { const fieldsValues = fields.split(',').map((value) => _.trim(value)); return _.uniq(['id', ...fieldsValues]); } if (Array.isArray(fields)) { // map convert const fieldsValues = fields.flatMap((value) => convertFieldsQueryParams(value, depth + 1)); return _.uniq(['id', ...fieldsValues]); } throw new Error('Invalid fields parameter. Expected a string or an array of strings'); }; const convertFiltersQueryParams = (filters, schema) => { // Filters need to be either an array or an object // Here we're only checking for 'object' type since typeof [] => object and typeof {} => object if (!isObject(filters)) { throw new Error('The filters parameter must be an object or an array'); } // Don't mutate the original object const filtersCopy = cloneDeep(filters); return convertAndSanitizeFilters(filtersCopy, schema); }; const convertAndSanitizeFilters = (filters, schema) => { if (!isPlainObject(filters)) { return filters; } if (Array.isArray(filters)) { return ( filters // Sanitize each filter .map((filter) => convertAndSanitizeFilters(filter, schema)) // Filter out empty filters .filter((filter) => !isObject(filter) || !isEmpty(filter)) ); } const removeOperator = (operator) => delete filters[operator]; // Here, `key` can either be an operator or an attribute name for (const [key, value] of Object.entries(filters)) { const attribute = get(key, schema.attributes); // Handle attributes if (attribute) { // Relations if (attribute.type === 'relation') { filters[key] = convertAndSanitizeFilters(value, strapi.getModel(attribute.target)); } // Components else if (attribute.type === 'component') { filters[key] = convertAndSanitizeFilters(value, strapi.getModel(attribute.component)); } // Media else if (attribute.type === 'media') { filters[key] = convertAndSanitizeFilters(value, strapi.getModel('plugin::upload.file')); } // Dynamic Zones else if (attribute.type === 'dynamiczone') { removeOperator(key); } // Password attributes else if (attribute.type === 'password') { // Always remove password attributes from filters object removeOperator(key); } // Scalar attributes else { filters[key] = convertAndSanitizeFilters(value, schema); } } // Handle operators else if (['$null', '$notNull'].includes(key)) { filters[key] = parseType({ type: 'boolean', value: filters[key], forceCast: true }); } else if (isObject(value)) { filters[key] = convertAndSanitizeFilters(value, schema); } // Remove empty objects & arrays if (isPlainObject(filters[key]) && isEmpty(filters[key])) { removeOperator(key); } } return filters; }; const convertPublicationStateParams = (type, params = {}, query = {}) => { if (!type) { return; } const { publicationState } = params; if (!_.isNil(publicationState)) { if (!contentTypesUtils.constants.DP_PUB_STATES.includes(publicationState)) { throw new Error( `Invalid publicationState. Expected one of 'preview','live' received: ${publicationState}.` ); } // NOTE: this is the query layer filters not the entity service filters query.filters = ({ meta }) => { if (publicationState === 'live' && has(PUBLISHED_AT_ATTRIBUTE, meta.attributes)) { return { [PUBLISHED_AT_ATTRIBUTE]: { $notNull: true } }; } }; } }; module.exports = { convertSortQueryParams, convertStartQueryParams, convertLimitQueryParams, convertPopulateQueryParams, convertFiltersQueryParams, convertFieldsQueryParams, convertPublicationStateParams, };
packages/core/utils/lib/convert-query-params.js
1
https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d
[ 0.9930220246315002, 0.029254134744405746, 0.00016534095630049706, 0.0002159091818612069, 0.15523289144039154 ]
{ "id": 4, "code_window": [ " return {\n", " ...acc,\n", " [key]: convertNestedPopulate(subPopulate, targetSchema),\n", " };\n", " }, {});\n", "};\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " [key]: populateObject,\n" ], "file_path": "packages/core/utils/lib/convert-query-params.js", "type": "replace", "edit_start_line_idx": 207 }
'use strict'; const yup = require('yup'); const _ = require('lodash'); const { defaults } = require('lodash/fp'); const utils = require('./string-formatting'); const { YupValidationError } = require('./errors'); const printValue = require('./print-value'); const MixedSchemaType = yup.MixedSchema; const isNotNilTest = (value) => !_.isNil(value); function isNotNill(msg = '${path} must be defined.') { return this.test('defined', msg, isNotNilTest); } const isNotNullTest = (value) => !_.isNull(value); function isNotNull(msg = '${path} cannot be null.') { return this.test('defined', msg, isNotNullTest); } function isFunction(message = '${path} is not a function') { return this.test( 'is a function', message, (value) => _.isUndefined(value) || _.isFunction(value) ); } function isCamelCase(message = '${path} is not in camel case (anExampleOfCamelCase)') { return this.test('is in camelCase', message, (value) => utils.isCamelCase(value)); } function isKebabCase(message = '${path} is not in kebab case (an-example-of-kebab-case)') { return this.test('is in kebab-case', message, (value) => utils.isKebabCase(value)); } function onlyContainsFunctions(message = '${path} contains values that are not functions') { return this.test( 'only contains functions', message, (value) => _.isUndefined(value) || (value && Object.values(value).every(_.isFunction)) ); } yup.addMethod(yup.mixed, 'notNil', isNotNill); yup.addMethod(yup.mixed, 'notNull', isNotNull); yup.addMethod(yup.mixed, 'isFunction', isFunction); yup.addMethod(yup.string, 'isCamelCase', isCamelCase); yup.addMethod(yup.string, 'isKebabCase', isKebabCase); yup.addMethod(yup.object, 'onlyContainsFunctions', onlyContainsFunctions); class StrapiIDSchema extends MixedSchemaType { constructor() { super({ type: 'strapiID' }); } _typeCheck(value) { return typeof value === 'string' || (Number.isInteger(value) && value >= 0); } } yup.strapiID = () => new StrapiIDSchema(); const handleYupError = (error, errorMessage) => { throw new YupValidationError(error, errorMessage); }; const defaultValidationParam = { strict: true, abortEarly: false }; const validateYupSchema = (schema, options = {}) => async (body, errorMessage) => { try { const optionsWithDefaults = defaults(defaultValidationParam, options); return await schema.validate(body, optionsWithDefaults); } catch (e) { handleYupError(e, errorMessage); } }; const validateYupSchemaSync = (schema, options = {}) => (body, errorMessage) => { try { const optionsWithDefaults = defaults(defaultValidationParam, options); return schema.validateSync(body, optionsWithDefaults); } catch (e) { handleYupError(e, errorMessage); } }; // Temporary fix of this issue : https://github.com/jquense/yup/issues/616 yup.setLocale({ mixed: { notType({ path, type, value, originalValue }) { const isCast = originalValue != null && originalValue !== value; const msg = `${path} must be a \`${type}\` type, ` + `but the final value was: \`${printValue(value, true)}\`${ isCast ? ` (cast from the value \`${printValue(originalValue, true)}\`).` : '.' }`; /* Remove comment that is not supposed to be seen by the enduser if (value === null) { msg += `\n If "null" is intended as an empty value be sure to mark the schema as \`.nullable()\``; } */ return msg; }, }, }); module.exports = { yup, handleYupError, validateYupSchema, validateYupSchemaSync, };
packages/core/utils/lib/validators.js
0
https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d
[ 0.00020355288870632648, 0.00017189406207762659, 0.0001643387950025499, 0.00016970402793958783, 0.000009604337719792966 ]
{ "id": 4, "code_window": [ " return {\n", " ...acc,\n", " [key]: convertNestedPopulate(subPopulate, targetSchema),\n", " };\n", " }, {});\n", "};\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " [key]: populateObject,\n" ], "file_path": "packages/core/utils/lib/convert-query-params.js", "type": "replace", "edit_start_line_idx": 207 }
'use strict'; const { arg } = require('nexus'); module.exports = ({ strapi }) => { const { PUBLICATION_STATE_TYPE_NAME } = strapi.plugin('graphql').service('constants'); return arg({ type: PUBLICATION_STATE_TYPE_NAME, default: 'live', }); };
packages/plugins/graphql/server/services/internals/args/publication-state.js
0
https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d
[ 0.00017167054465971887, 0.00017154932720586658, 0.0001714281243039295, 0.00017154932720586658, 1.212101778946817e-7 ]
{ "id": 4, "code_window": [ " return {\n", " ...acc,\n", " [key]: convertNestedPopulate(subPopulate, targetSchema),\n", " };\n", " }, {});\n", "};\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " [key]: populateObject,\n" ], "file_path": "packages/core/utils/lib/convert-query-params.js", "type": "replace", "edit_start_line_idx": 207 }
'use strict'; module.exports = { passport: require('./passport'), role: require('./role'), };
packages/core/admin/ee/server/services/index.js
0
https://github.com/strapi/strapi/commit/3327196cce01c0ec98fa48ed233183473dee028d
[ 0.00017083447892218828, 0.00017083447892218828, 0.00017083447892218828, 0.00017083447892218828, 0 ]
{ "id": 0, "code_window": [ " \"@testing-library/react\": \"^10.0.4\",\n", " \"@types/webpack-env\": \"^1.15.2\"\n", " },\n", " \"peerDependencies\": {\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n", " },\n", " \"gitHead\": \"4a4c98997fe9b0f791f30fd168d867423ffcf730\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\"\n" ], "file_path": "addons/a11y/package.json", "type": "replace", "edit_start_line_idx": 57 }
{ "name": "@storybook/addon-storysource", "version": "6.1.0-alpha.35", "description": "Stories addon for storybook", "keywords": [ "addon", "storybook" ], "homepage": "https://github.com/storybookjs/storybook/tree/master/addons/storysource", "bugs": { "url": "https://github.com/storybookjs/storybook/issues" }, "repository": { "type": "git", "url": "https://github.com/storybookjs/storybook.git", "directory": "addons/storysource" }, "license": "MIT", "main": "dist/index.js", "types": "dist/index.d.ts", "files": [ "dist/**/*", "README.md", "*.js", "*.d.ts", "ts3.4/**/*" ], "scripts": { "prepare": "node ../../scripts/prepare.js" }, "dependencies": { "@storybook/addons": "6.1.0-alpha.35", "@storybook/api": "6.1.0-alpha.35", "@storybook/client-logger": "6.1.0-alpha.35", "@storybook/components": "6.1.0-alpha.35", "@storybook/router": "6.1.0-alpha.35", "@storybook/source-loader": "6.1.0-alpha.35", "@storybook/theming": "6.1.0-alpha.35", "core-js": "^3.0.1", "estraverse": "^4.2.0", "loader-utils": "^2.0.0", "prettier": "~2.0.5", "prop-types": "^15.7.2", "react-syntax-highlighter": "^13.5.0", "regenerator-runtime": "^0.13.7" }, "devDependencies": { "@types/react": "^16.9.27", "@types/react-syntax-highlighter": "^11.0.4" }, "peerDependencies": { "react": "15 || 16 || ^17.0.0", "react-dom": "15 || 16 || ^17.0.0" }, "publishConfig": { "access": "public" }, "gitHead": "4a4c98997fe9b0f791f30fd168d867423ffcf730", "typesVersions": { "<3.8": { "*": [ "ts3.4/*" ] } } }
addons/storysource/package.json
1
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.9902085065841675, 0.14160262048244476, 0.00016430133837275207, 0.00016960971697699279, 0.3464418947696686 ]
{ "id": 0, "code_window": [ " \"@testing-library/react\": \"^10.0.4\",\n", " \"@types/webpack-env\": \"^1.15.2\"\n", " },\n", " \"peerDependencies\": {\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n", " },\n", " \"gitHead\": \"4a4c98997fe9b0f791f30fd168d867423ffcf730\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\"\n" ], "file_path": "addons/a11y/package.json", "type": "replace", "edit_start_line_idx": 57 }
```js // ProfilePage.stories.js import React from 'react'; import ProfilePage from './ProfilePage'; import UserPosts from './UserPosts'; import { normal as UserFriendsNormal } from './UserFriends.stories'; export default { title: 'ProfilePage', }; const ProfilePageProps = { name: 'Jimi Hendrix', userId: '1', }; const context = { // We can access the `userId` prop here if required: UserPostsContainer({ userId }) { return <UserPosts {...UserPostsProps} />; }, // Most of the time we can simply pass in a story. // In this case we're passing in the `normal` story export // from the `UserFriends` component stories. UserFriendsContainer: UserFriendsNormal, }; export const normal = () => { return ( <ProfilePageContext.Provider value={context}> <ProfilePage {...ProfilePageProps} /> </ProfilePageContext.Provider> ); }; ```
docs/snippets/react/mock-context-container.js.mdx
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.00017129088519141078, 0.00016962650988716632, 0.00016814454284030944, 0.00016953531303443015, 0.0000011571534059839905 ]
{ "id": 0, "code_window": [ " \"@testing-library/react\": \"^10.0.4\",\n", " \"@types/webpack-env\": \"^1.15.2\"\n", " },\n", " \"peerDependencies\": {\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n", " },\n", " \"gitHead\": \"4a4c98997fe9b0f791f30fd168d867423ffcf730\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\"\n" ], "file_path": "addons/a11y/package.json", "type": "replace", "edit_start_line_idx": 57 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`storiesof-to-csf transforms correctly using "export-names.input.js" data 1`] = ` "/* eslint-disable import/no-extraneous-dependencies */ import React from 'react'; import FlexCenter from './FlexCenter'; import { specs, urls } from './LiveView.stories'; import { ignoredRegions } from './IgnoredRegions.stories'; export { specs, urls, ignoredRegions }; export default { title: 'FlexCenter', excludeStories: ['specs', 'urls', 'ignoredRegions'], }; export const _21 = () => ( <FlexCenter width={200} height={100} style={{ background: 'papayawhip' }}> <div style={{ padding: 30, background: 'hotpink' }}>2:1</div> </FlexCenter> ); _21.story = { name: '2:1', };" `;
lib/codemod/src/transforms/__testfixtures__/storiesof-to-csf/export-names.output.snapshot
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.00017285333888139576, 0.00017078254313673824, 0.00016952352598309517, 0.00016997073544189334, 0.0000014756186601516674 ]
{ "id": 0, "code_window": [ " \"@testing-library/react\": \"^10.0.4\",\n", " \"@types/webpack-env\": \"^1.15.2\"\n", " },\n", " \"peerDependencies\": {\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n", " },\n", " \"gitHead\": \"4a4c98997fe9b0f791f30fd168d867423ffcf730\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\"\n" ], "file_path": "addons/a11y/package.json", "type": "replace", "edit_start_line_idx": 57 }
import chalk from 'chalk'; import { gt, satisfies } from '@storybook/semver'; import { sync as spawnSync } from 'cross-spawn'; import { commandLog } from '../helpers'; import { PackageJson, PackageJsonWithDepsAndDevDeps } from './PackageJson'; import { readPackageJson, writePackageJson } from './PackageJsonHelper'; const logger = console; // Cannot be `import` as it's not under TS root dir const storybookPackagesVersions = require('../../versions.json'); export abstract class JsPackageManager { public abstract readonly type: 'npm' | 'yarn1' | 'yarn2'; public abstract initPackageJson(): void; public abstract getRunStorybookCommand(): string; public abstract getRunCommand(command: string): string; /** * Install dependencies listed in `package.json` */ public installDependencies(): void { let done = commandLog('Preparing to install dependencies'); done(); logger.log(); logger.log(); done = commandLog('Installing dependencies'); try { this.runInstall(); } catch (e) { done('An error occurred while installing dependencies.'); process.exit(1); } done(); } public retrievePackageJson(): PackageJsonWithDepsAndDevDeps { let packageJson = readPackageJson(); if (!packageJson) { // It will create a new package.json file this.initPackageJson(); // read the newly created package.json file packageJson = readPackageJson() || {}; } return { ...packageJson, dependencies: { ...packageJson.dependencies }, devDependencies: { ...packageJson.devDependencies }, }; } /** * Add dependencies to a project using `yarn add` or `npm install`. * * @param {Object} options contains `skipInstall`, `packageJson` and `installAsDevDependencies` which we use to determine how we install packages. * @param {Array} dependencies contains a list of packages to add. * @example * addDependencies(options, [ * `@storybook/react@${storybookVersion}`, * `@storybook/addon-actions@${actionsVersion}`, * `@storybook/addon-links@${linksVersion}`, * `@storybook/addons@${addonsVersion}`, * ]); */ public addDependencies( options: { skipInstall?: boolean; installAsDevDependencies?: boolean; packageJson?: PackageJson; }, dependencies: string[] ): void { const { skipInstall } = options; if (skipInstall) { const { packageJson } = options; const dependenciesMap = dependencies.reduce((acc, dep) => { const idx = dep.lastIndexOf('@'); const packageName = dep.slice(0, idx); const packageVersion = dep.slice(idx + 1); return { ...acc, [packageName]: packageVersion }; }, {}); if (options.installAsDevDependencies) { packageJson.devDependencies = { ...packageJson.devDependencies, ...dependenciesMap, }; } else { packageJson.dependencies = { ...packageJson.dependencies, ...dependenciesMap, }; } writePackageJson(packageJson); } else { try { this.runAddDeps(dependencies, options.installAsDevDependencies); } catch (e) { logger.error('An error occurred while installing dependencies.'); logger.log(e.message); process.exit(1); } } } /** * Return an array of strings matching following format: `<package_name>@<package_latest_version>` * * @param packageNames */ public getVersionedPackages(...packageNames: string[]): Promise<string[]> { return Promise.all( packageNames.map( async (packageName) => `${packageName}@${await this.getVersion(packageName)}` ) ); } /** * Return an array of string standing for the latest version of the input packages. * To be able to identify which version goes with which package the order of the input array is keep. * * @param packageNames */ public getVersions(...packageNames: string[]): Promise<string[]> { return Promise.all(packageNames.map((packageName) => this.getVersion(packageName))); } public async getVersion(packageName: string, constraint?: string): Promise<string> { let current; if (/@storybook/.test(packageName)) { current = storybookPackagesVersions[packageName]; } let latest; try { latest = await this.latestVersion(packageName, constraint); } catch (e) { if (current) { logger.warn(`\n ${chalk.yellow(e.message)}`); return current; } logger.error(`\n ${chalk.red(e.message)}`); process.exit(1); } const versionToUse = current && (!constraint || satisfies(current, constraint)) && gt(current, latest) ? current : latest; return `^${versionToUse}`; } /** * Get the latest version of the package available on npmjs.com. * If constraint is set then it returns a version satisfying it, otherwise the latest version available is returned. * * @param packageName Name of the package * @param constraint Version range to use to constraint the returned version */ public async latestVersion(packageName: string, constraint?: string): Promise<string> { if (!constraint) { return this.runGetVersions(packageName, false); } const versions = await this.runGetVersions(packageName, true); // Get the latest version satisfying the constraint return versions.reverse().find((version) => satisfies(version, constraint)); } public addStorybookCommandInScripts(options?: { port: number; staticFolder?: string; preCommand?: string; }) { const sbPort = options?.port ?? 6006; const noDll = '--no-dll'; const storybookCmd = options?.staticFolder ? `start-storybook -p ${sbPort} -s ${options.staticFolder} ${noDll}` : `start-storybook -p ${sbPort} ${noDll}`; const buildStorybookCmd = options?.staticFolder ? `build-storybook -s ${options.staticFolder} ${noDll}` : `build-storybook ${noDll}`; const preCommand = options.preCommand ? this.getRunCommand(options.preCommand) : undefined; this.addScripts({ storybook: [preCommand, storybookCmd].filter(Boolean).join(' && '), 'build-storybook': [preCommand, buildStorybookCmd].filter(Boolean).join(' && '), }); } public addScripts(scripts: Record<string, string>) { const packageJson = this.retrievePackageJson(); writePackageJson({ ...packageJson, scripts: { ...packageJson.scripts, ...scripts, }, }); } protected abstract runInstall(): void; protected abstract runAddDeps(dependencies: string[], installAsDevDependencies: boolean): void; /** * Get the latest or all versions of the input package available on npmjs.com * * @param packageName Name of the package * @param fetchAllVersions Should return */ protected abstract runGetVersions<T extends boolean>( packageName: string, fetchAllVersions: T ): // Use generic and conditional type to force `string[]` if fetchAllVersions is true and `string` if false Promise<T extends true ? string[] : string>; public executeCommand(command: string, args: string[], stdio?: 'pipe' | 'inherit'): string { const commandResult = spawnSync(command, args, { stdio: stdio ?? 'pipe', encoding: 'utf-8', }); if (commandResult.status !== 0) { throw new Error(commandResult.stderr ?? ''); } return commandResult.stdout ?? ''; } }
lib/cli/src/js-package-manager/JsPackageManager.ts
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.00017392696463502944, 0.00016904686344787478, 0.00016421894542872906, 0.0001699059212114662, 0.000003114705350526492 ]
{ "id": 1, "code_window": [ " \"@babel/core\": \"^7.11.5\",\n", " \"@storybook/vue\": \"6.1.0-alpha.35\",\n", " \"babel-loader\": \"^8.0.0\",\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\",\n", " \"sveltedoc-parser\": \"^3.0.4\",\n", " \"vue\": \"^2.6.10\",\n", " \"webpack\": \">=4\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\",\n" ], "file_path": "addons/docs/package.json", "type": "replace", "edit_start_line_idx": 119 }
{ "name": "@storybook/addon-docs", "version": "6.1.0-alpha.35", "description": "Superior documentation for your components", "keywords": [ "addon", "notes", "storybook" ], "homepage": "https://github.com/storybookjs/storybook/tree/master/addons/docs", "bugs": { "url": "https://github.com/storybookjs/storybook/issues" }, "repository": { "type": "git", "url": "https://github.com/storybookjs/storybook.git", "directory": "addons/docs" }, "license": "MIT", "main": "dist/public_api.js", "types": "dist/public_api.d.ts", "files": [ "dist/**/*", "angular/**/*", "common/**/*", "ember/**/*", "html/**/*", "postinstall/**/*", "react/**/*", "vue/**/*", "web-components/**/*", "README.md", "*.js", "*.d.ts", "ts3.4/**/*" ], "scripts": { "prepare": "node ../../scripts/prepare.js" }, "dependencies": { "@babel/core": "^7.12.1", "@babel/generator": "^7.12.1", "@babel/parser": "^7.12.3", "@babel/plugin-transform-react-jsx": "^7.12.1", "@babel/preset-env": "^7.12.1", "@jest/transform": "^26.0.0", "@mdx-js/loader": "^1.5.1", "@mdx-js/mdx": "^1.5.1", "@mdx-js/react": "^1.5.1", "@storybook/addons": "6.1.0-alpha.35", "@storybook/api": "6.1.0-alpha.35", "@storybook/client-api": "6.1.0-alpha.35", "@storybook/client-logger": "6.1.0-alpha.35", "@storybook/components": "6.1.0-alpha.35", "@storybook/core": "6.1.0-alpha.35", "@storybook/core-events": "6.1.0-alpha.35", "@storybook/csf": "0.0.1", "@storybook/node-logger": "6.1.0-alpha.35", "@storybook/postinstall": "6.1.0-alpha.35", "@storybook/source-loader": "6.1.0-alpha.35", "@storybook/theming": "6.1.0-alpha.35", "acorn": "^7.1.0", "acorn-jsx": "^5.1.0", "acorn-walk": "^7.0.0", "core-js": "^3.0.1", "doctrine": "^3.0.0", "escodegen": "^1.12.0", "fast-deep-equal": "^3.1.1", "global": "^4.3.2", "html-tags": "^3.1.0", "js-string-escape": "^1.0.1", "lodash": "^4.17.15", "prettier": "~2.0.5", "prop-types": "^15.7.2", "react-element-to-jsx-string": "^14.3.1", "regenerator-runtime": "^0.13.7", "remark-external-links": "^6.0.0", "remark-slug": "^6.0.0", "ts-dedent": "^2.0.0", "util-deprecate": "^1.0.2" }, "devDependencies": { "@angular/core": "^9.1.0", "@babel/core": "^7.12.3", "@emotion/core": "^10.0.20", "@emotion/styled": "^10.0.17", "@storybook/react": "6.1.0-alpha.35", "@storybook/vue": "6.1.0-alpha.35", "@storybook/web-components": "6.1.0-alpha.35", "@types/cross-spawn": "^6.0.1", "@types/doctrine": "^0.0.3", "@types/enzyme": "^3.10.3", "@types/estree": "^0.0.44", "@types/jest": "^25.1.1", "@types/prop-types": "^15.5.9", "@types/tmp": "^0.1.0", "@types/util-deprecate": "^1.0.0", "babel-loader": "^8.0.6", "babel-plugin-react-docgen": "^4.2.1", "cross-spawn": "^7.0.1", "fs-extra": "^9.0.0", "jest": "^26.0.0", "jest-specific-snapshot": "^4.0.0", "lit-element": "^2.2.1", "lit-html": "^1.0.0", "require-from-string": "^2.0.2", "rxjs": "^6.5.4", "styled-components": "^5.0.1", "terser-webpack-plugin": "^3.0.0", "tmp": "^0.2.1", "tslib": "^2.0.0", "web-component-analyzer": "^1.0.3", "webpack": "^4.33.0", "zone.js": "^0.10.2" }, "peerDependencies": { "@babel/core": "^7.11.5", "@storybook/vue": "6.1.0-alpha.35", "babel-loader": "^8.0.0", "react": "15 || 16 || ^17.0.0", "react-dom": "15 || 16 || ^17.0.0", "sveltedoc-parser": "^3.0.4", "vue": "^2.6.10", "webpack": ">=4" }, "peerDependenciesMeta": { "@storybook/vue": { "optional": true }, "sveltedoc-parser": { "optional": true }, "vue": { "optional": true }, "webpack": { "optional": true } }, "publishConfig": { "access": "public" }, "gitHead": "4a4c98997fe9b0f791f30fd168d867423ffcf730", "typesVersions": { "<3.8": { "*": [ "ts3.4/*" ] } } }
addons/docs/package.json
1
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.8997288942337036, 0.06677171587944031, 0.0001641104754526168, 0.00019752154184971005, 0.2186088263988495 ]
{ "id": 1, "code_window": [ " \"@babel/core\": \"^7.11.5\",\n", " \"@storybook/vue\": \"6.1.0-alpha.35\",\n", " \"babel-loader\": \"^8.0.0\",\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\",\n", " \"sveltedoc-parser\": \"^3.0.4\",\n", " \"vue\": \"^2.6.10\",\n", " \"webpack\": \">=4\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\",\n" ], "file_path": "addons/docs/package.json", "type": "replace", "edit_start_line_idx": 119 }
import m from 'mithril'; import { linkTo } from '@storybook/addon-links'; import Welcome from '../Welcome'; export default { title: 'Welcome', component: Welcome, }; export const Story1 = () => ({ view: () => m(Welcome, { showApp: linkTo('Button') }), }); Story1.storyName = 'to Storybook';
examples/mithril-kitchen-sink/src/stories/welcome.stories.js
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.00017174570530187339, 0.00016787287313491106, 0.00016400004096794873, 0.00016787287313491106, 0.0000038728321669623256 ]
{ "id": 1, "code_window": [ " \"@babel/core\": \"^7.11.5\",\n", " \"@storybook/vue\": \"6.1.0-alpha.35\",\n", " \"babel-loader\": \"^8.0.0\",\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\",\n", " \"sveltedoc-parser\": \"^3.0.4\",\n", " \"vue\": \"^2.6.10\",\n", " \"webpack\": \">=4\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\",\n" ], "file_path": "addons/docs/package.json", "type": "replace", "edit_start_line_idx": 119 }
<h1>Storybook Docs FAQs</h1> You've read the [Storybook Docs README](../README.md). You're already familiar with both [DocsPage](./docspage.md) and [MDX](./mdx.md). You've even browsed our [Docs recipes](/./recipes.md). But Docs is a big project and you've still got questions! Maybe you'll find your answer here: - [Does Docs support framework X?](#does-docs-support-framework-x) - [How does Docs interact with existing addons?](#how-does-docs-interact-with-existing-addons) - [How do I debug my MDX story?](#how-do-i-debug-my-mdx-story) - [More resources](#more-resources) ## Does Docs support framework X? Docs does not currently support [React Native](https://github.com/storybooks/storybook/tree/next/app/react-native). Otherwise, [it supports all frameworks that Storybook supports](../README.md#framework-support), including React, Vue, Angular, Ember, Svelte, and others. ## How does Docs interact with existing addons? Currently we hide the addons panel when docs is visible. It's tricky because all the addons assume that there is only one story currently visible, and in docs there are potentially many. We have a proposal for "knobs v2" to address this for knobs, but nothing planned to address it in general. How we deal with it generally is [open for discussion](https://github.com/storybooks/storybook/issues/6700)! ## How do I debug my MDX story? <center> <img src="https://raw.githubusercontent.com/storybookjs/storybook/master/addons/docs/docs/media/faq-debug.png" width="100%" /> </center> > "My story renders in docs, but doesn’t show up the way I’d expect in the Canvas” The original MDX gets compiled to Javascript, and the easiest way to debug your MDX stories in the Canvas is to inspect that Javascript. To do this, open your browser dev tools and view the source that’s being served by the webpack dev server. You may need to hunt for it a little bit under the `webpack > > . > path/to/your/stories` folder, but it’s there. For example, the following MDX story: ```jsx <Story name="solo story"> <Button onClick={action('clicked')}>solo</Button> </Story> ``` Shows up in the dev tools as follows: <center> <img src="https://raw.githubusercontent.com/storybookjs/storybook/master/addons/docs/docs/media/faq-devtools.png" width="100%" /> </center> This is [Component Story Format (CSF)](https://medium.com/storybookjs/component-story-format-66f4c32366df), so there are ways to debug. You can copy and paste this code into a new `.stories.js` file and play around with it at a lower level to understand what's going wrong. ## More resources - References: [README](../README.md) / [DocsPage](docspage.md) / [MDX](mdx.md) / [FAQ](faq.md) / [Recipes](recipes.md) / [Theming](theming.md) / [Props](props-tables.md) - Framework-specific docs: [React](../react/README.md) / [Vue](../vue/README.md) / [Angular](../angular/README.md) / [Web components](../web-components/README.md) / [Ember](../ember/README.md) - Announcements: [Vision](https://medium.com/storybookjs/storybook-docs-sneak-peak-5be78445094a) / [DocsPage](https://medium.com/storybookjs/storybook-docspage-e185bc3622bf) / [MDX](https://medium.com/storybookjs/rich-docs-with-storybook-mdx-61bc145ae7bc) / [Framework support](https://medium.com/storybookjs/storybook-docs-for-new-frameworks-b1f6090ee0ea) - Example: [Storybook Design System](https://github.com/storybookjs/design-system)
addons/docs/docs/faq.md
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.00027527438942342997, 0.00018775030912365764, 0.00015838515537325293, 0.00016846100334078074, 0.00004395484575070441 ]
{ "id": 1, "code_window": [ " \"@babel/core\": \"^7.11.5\",\n", " \"@storybook/vue\": \"6.1.0-alpha.35\",\n", " \"babel-loader\": \"^8.0.0\",\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\",\n", " \"sveltedoc-parser\": \"^3.0.4\",\n", " \"vue\": \"^2.6.10\",\n", " \"webpack\": \">=4\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\",\n" ], "file_path": "addons/docs/package.json", "type": "replace", "edit_start_line_idx": 119 }
import { document, Node } from 'global'; import dedent from 'ts-dedent'; import { simulatePageLoad, simulateDOMContentLoaded } from '@storybook/client-api'; import { RenderContext } from './types'; const rootElement = document.getElementById('root'); export default function renderMain({ storyFn, kind, name, showMain, showError, forceRender, }: RenderContext) { const element = storyFn(); showMain(); if (typeof element === 'string') { rootElement.innerHTML = element; simulatePageLoad(rootElement); } else if (element instanceof Node) { // Don't re-mount the element if it didn't change and neither did the story if (rootElement.firstChild === element && forceRender === true) { return; } rootElement.innerHTML = ''; rootElement.appendChild(element); simulateDOMContentLoaded(); } else { showError({ title: `Expecting an HTML snippet or DOM node from the story: "${name}" of "${kind}".`, description: dedent` Did you forget to return the HTML snippet from the story? Use "() => <your snippet or node>" or when defining the story. `, }); } }
app/html/src/client/preview/render.ts
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.00017244162154383957, 0.0001704369205981493, 0.0001682165457168594, 0.00017054473573807627, 0.0000016779923726062407 ]
{ "id": 2, "code_window": [ " },\n", " \"peerDependencies\": {\n", " \"@babel/core\": \"^7.9.6\",\n", " \"@storybook/vue\": \"6.1.0-alpha.35\",\n", " \"babel-loader\": \"^8.0.0\",\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\",\n", " \"webpack\": \">=4\"\n", " },\n", " \"peerDependenciesMeta\": {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\",\n" ], "file_path": "addons/essentials/package.json", "type": "replace", "edit_start_line_idx": 53 }
{ "name": "@storybook/addon-a11y", "version": "6.1.0-alpha.35", "description": "a11y addon for storybook", "keywords": [ "a11y", "accessibility", "addon", "storybook", "valid", "verify" ], "homepage": "https://github.com/storybookjs/storybook#readme", "bugs": { "url": "https://github.com/storybookjs/storybook/issues" }, "repository": { "type": "git", "url": "git+https://github.com/storybookjs/storybook.git", "directory": "addons/a11y" }, "license": "MIT", "main": "dist/index.js", "types": "dist/index.d.ts", "files": [ "dist/**/*", "README.md", "*.js", "*.d.ts", "ts3.4/**/*" ], "scripts": { "prepare": "node ../../scripts/prepare.js" }, "dependencies": { "@storybook/addons": "6.1.0-alpha.35", "@storybook/api": "6.1.0-alpha.35", "@storybook/channels": "6.1.0-alpha.35", "@storybook/client-api": "6.1.0-alpha.35", "@storybook/client-logger": "6.1.0-alpha.35", "@storybook/components": "6.1.0-alpha.35", "@storybook/core-events": "6.1.0-alpha.35", "@storybook/theming": "6.1.0-alpha.35", "axe-core": "^4.0.1", "core-js": "^3.0.1", "global": "^4.3.2", "lodash": "^4.17.15", "react-sizeme": "^2.5.2", "regenerator-runtime": "^0.13.7", "ts-dedent": "^2.0.0", "util-deprecate": "^1.0.2" }, "devDependencies": { "@testing-library/react": "^10.0.4", "@types/webpack-env": "^1.15.2" }, "peerDependencies": { "react": "15 || 16 || ^17.0.0", "react-dom": "15 || 16 || ^17.0.0" }, "publishConfig": { "access": "public" }, "gitHead": "4a4c98997fe9b0f791f30fd168d867423ffcf730", "typesVersions": { "<3.8": { "*": [ "ts3.4/*" ] } } }
addons/a11y/package.json
1
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.00351688708178699, 0.0005887754959985614, 0.00016464715008623898, 0.00016942276852205396, 0.0011067379964515567 ]
{ "id": 2, "code_window": [ " },\n", " \"peerDependencies\": {\n", " \"@babel/core\": \"^7.9.6\",\n", " \"@storybook/vue\": \"6.1.0-alpha.35\",\n", " \"babel-loader\": \"^8.0.0\",\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\",\n", " \"webpack\": \">=4\"\n", " },\n", " \"peerDependenciesMeta\": {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\",\n" ], "file_path": "addons/essentials/package.json", "type": "replace", "edit_start_line_idx": 53 }
import { includePaths } from '../config/utils'; import { useBaseTsSupport } from '../config/useBaseTsSupport'; export const createBabelLoader = (options, framework) => ({ test: useBaseTsSupport(framework) ? /\.(mjs|tsx?|jsx?)$/ : /\.(mjs|jsx?)$/, use: [ { loader: require.resolve('babel-loader'), options, }, ], include: includePaths, exclude: /node_modules/, });
lib/core/src/server/preview/babel-loader-preview.js
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.00025272610946558416, 0.0002121053112205118, 0.00017148451297543943, 0.0002121053112205118, 0.000040620798245072365 ]
{ "id": 2, "code_window": [ " },\n", " \"peerDependencies\": {\n", " \"@babel/core\": \"^7.9.6\",\n", " \"@storybook/vue\": \"6.1.0-alpha.35\",\n", " \"babel-loader\": \"^8.0.0\",\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\",\n", " \"webpack\": \">=4\"\n", " },\n", " \"peerDependenciesMeta\": {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\",\n" ], "file_path": "addons/essentials/package.json", "type": "replace", "edit_start_line_idx": 53 }
import React, { useMemo, FunctionComponent } from 'react'; import { Badge } from '@storybook/components'; import { API } from '@storybook/api'; import { styled, useTheme, Theme } from '@storybook/theming'; import { shortcutToHumanString } from '@storybook/api/shortcut'; import { MenuItemIcon } from '../components/sidebar/Menu'; const focusableUIElements = { storySearchField: 'storybook-explorer-searchfield', storyListMenu: 'storybook-explorer-menu', storyPanelRoot: 'storybook-panel-root', }; const Key = styled.code(({ theme }) => ({ width: 16, height: 16, lineHeight: '17px', textAlign: 'center', fontSize: '11px', background: 'rgba(0,0,0,0.07)', color: theme.color.defaultText, borderRadius: 2, userSelect: 'none', pointerEvents: 'none', '& + &': { marginLeft: 2, }, })); const Shortcut: FunctionComponent<{ keys: string[] }> = ({ keys }) => ( <> {keys.map((key, index) => ( // eslint-disable-next-line react/no-array-index-key <Key key={index}>{shortcutToHumanString([key])}</Key> ))} </> ); export const useMenu = ( api: API, isFullscreen: boolean, showPanel: boolean, showNav: boolean, enableShortcuts: boolean ) => { const theme = useTheme<Theme>(); const shortcutKeys = api.getShortcutKeys(); const about = useMemo( () => ({ id: 'about', title: 'About your Storybook', onClick: () => api.navigateToSettingsPage('/settings/about'), right: api.versionUpdateAvailable() && <Badge status="positive">Update</Badge>, left: <MenuItemIcon />, }), [api, enableShortcuts, shortcutKeys] ); const releaseNotes = useMemo( () => ({ id: 'release-notes', title: 'Release notes', onClick: () => api.navigateToSettingsPage('/settings/release-notes'), left: <MenuItemIcon />, }), [api, enableShortcuts, shortcutKeys] ); const shortcuts = useMemo( () => ({ id: 'shortcuts', title: 'Keyboard shortcuts', onClick: () => api.navigateToSettingsPage('/settings/shortcuts'), right: enableShortcuts ? <Shortcut keys={shortcutKeys.shortcutsPage} /> : null, left: <MenuItemIcon />, style: { borderBottom: `4px solid ${theme.appBorderColor}`, }, }), [api, enableShortcuts, shortcutKeys] ); const sidebarToggle = useMemo( () => ({ id: 'S', title: 'Show sidebar', onClick: () => api.toggleNav(), right: enableShortcuts ? <Shortcut keys={shortcutKeys.toggleNav} /> : null, left: showNav ? <MenuItemIcon icon="check" /> : <MenuItemIcon />, }), [api, enableShortcuts, shortcutKeys, showNav] ); const addonsToggle = useMemo( () => ({ id: 'A', title: 'Show addons', onClick: () => api.togglePanel(), right: enableShortcuts ? <Shortcut keys={shortcutKeys.togglePanel} /> : null, left: showPanel ? <MenuItemIcon icon="check" /> : <MenuItemIcon />, }), [api, enableShortcuts, shortcutKeys, showPanel] ); const addonsOrientationToggle = useMemo( () => ({ id: 'D', title: 'Change addons orientation', onClick: () => api.togglePanelPosition(), right: enableShortcuts ? <Shortcut keys={shortcutKeys.panelPosition} /> : null, left: <MenuItemIcon />, }), [api, enableShortcuts, shortcutKeys] ); const fullscreenToggle = useMemo( () => ({ id: 'F', title: 'Go full screen', onClick: () => api.toggleFullscreen(), right: enableShortcuts ? <Shortcut keys={shortcutKeys.fullScreen} /> : null, left: isFullscreen ? 'check' : <MenuItemIcon />, }), [api, enableShortcuts, shortcutKeys, isFullscreen] ); const searchToggle = useMemo( () => ({ id: '/', title: 'Search', onClick: () => api.focusOnUIElement(focusableUIElements.storySearchField), right: enableShortcuts ? <Shortcut keys={shortcutKeys.search} /> : null, left: <MenuItemIcon />, }), [api, enableShortcuts, shortcutKeys] ); const up = useMemo( () => ({ id: 'up', title: 'Previous component', onClick: () => api.jumpToComponent(-1), right: enableShortcuts ? <Shortcut keys={shortcutKeys.prevComponent} /> : null, left: <MenuItemIcon />, }), [api, enableShortcuts, shortcutKeys] ); const down = useMemo( () => ({ id: 'down', title: 'Next component', onClick: () => api.jumpToComponent(1), right: enableShortcuts ? <Shortcut keys={shortcutKeys.nextComponent} /> : null, left: <MenuItemIcon />, }), [api, enableShortcuts, shortcutKeys] ); const prev = useMemo( () => ({ id: 'prev', title: 'Previous story', onClick: () => api.jumpToStory(-1), right: enableShortcuts ? <Shortcut keys={shortcutKeys.prevStory} /> : null, left: <MenuItemIcon />, }), [api, enableShortcuts, shortcutKeys] ); const next = useMemo( () => ({ id: 'next', title: 'Next story', onClick: () => api.jumpToStory(1), right: enableShortcuts ? <Shortcut keys={shortcutKeys.nextStory} /> : null, left: <MenuItemIcon />, }), [api, enableShortcuts, shortcutKeys] ); const collapse = useMemo( () => ({ id: 'collapse', title: 'Collapse all', onClick: () => api.collapseAll(), right: enableShortcuts ? <Shortcut keys={shortcutKeys.collapseAll} /> : null, left: <MenuItemIcon />, }), [api, enableShortcuts, shortcutKeys] ); return useMemo( () => [ about, ...(api.releaseNotesVersion() ? [releaseNotes] : []), shortcuts, sidebarToggle, addonsToggle, addonsOrientationToggle, fullscreenToggle, searchToggle, up, down, prev, next, collapse, ], [ about, ...(api.releaseNotesVersion() ? [releaseNotes] : []), shortcuts, sidebarToggle, addonsToggle, addonsOrientationToggle, fullscreenToggle, searchToggle, up, down, prev, next, collapse, ] ); };
lib/ui/src/containers/menu.tsx
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.00017485367425251752, 0.0001711728109512478, 0.00016090995632112026, 0.0001721982698654756, 0.0000030839137252769433 ]
{ "id": 2, "code_window": [ " },\n", " \"peerDependencies\": {\n", " \"@babel/core\": \"^7.9.6\",\n", " \"@storybook/vue\": \"6.1.0-alpha.35\",\n", " \"babel-loader\": \"^8.0.0\",\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\",\n", " \"webpack\": \">=4\"\n", " },\n", " \"peerDependenciesMeta\": {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\",\n" ], "file_path": "addons/essentials/package.json", "type": "replace", "edit_start_line_idx": 53 }
import { statSync } from 'fs'; import { join } from 'path'; const p = (l) => join(__dirname, '..', '..', ...l); export const getDeployables = (files, extraFilter) => { return files.filter((f) => { const packageJsonLocation = p(['examples', f, 'package.json']); let stats = null; try { stats = statSync(packageJsonLocation); } catch (e) { // the folder had no package.json, we'll ignore } return stats && stats.isFile() && extraFilter(packageJsonLocation); }); };
scripts/utils/list-examples.js
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.00017466286954004318, 0.00017346563981845975, 0.00017226841009687632, 0.00017346563981845975, 0.000001197229721583426 ]
{ "id": 3, "code_window": [ " \"@types/react-syntax-highlighter\": \"^11.0.4\"\n", " },\n", " \"peerDependencies\": {\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\"\n" ], "file_path": "addons/storysource/package.json", "type": "replace", "edit_start_line_idx": 51 }
{ "name": "@storybook/addon-a11y", "version": "6.1.0-alpha.35", "description": "a11y addon for storybook", "keywords": [ "a11y", "accessibility", "addon", "storybook", "valid", "verify" ], "homepage": "https://github.com/storybookjs/storybook#readme", "bugs": { "url": "https://github.com/storybookjs/storybook/issues" }, "repository": { "type": "git", "url": "git+https://github.com/storybookjs/storybook.git", "directory": "addons/a11y" }, "license": "MIT", "main": "dist/index.js", "types": "dist/index.d.ts", "files": [ "dist/**/*", "README.md", "*.js", "*.d.ts", "ts3.4/**/*" ], "scripts": { "prepare": "node ../../scripts/prepare.js" }, "dependencies": { "@storybook/addons": "6.1.0-alpha.35", "@storybook/api": "6.1.0-alpha.35", "@storybook/channels": "6.1.0-alpha.35", "@storybook/client-api": "6.1.0-alpha.35", "@storybook/client-logger": "6.1.0-alpha.35", "@storybook/components": "6.1.0-alpha.35", "@storybook/core-events": "6.1.0-alpha.35", "@storybook/theming": "6.1.0-alpha.35", "axe-core": "^4.0.1", "core-js": "^3.0.1", "global": "^4.3.2", "lodash": "^4.17.15", "react-sizeme": "^2.5.2", "regenerator-runtime": "^0.13.7", "ts-dedent": "^2.0.0", "util-deprecate": "^1.0.2" }, "devDependencies": { "@testing-library/react": "^10.0.4", "@types/webpack-env": "^1.15.2" }, "peerDependencies": { "react": "15 || 16 || ^17.0.0", "react-dom": "15 || 16 || ^17.0.0" }, "publishConfig": { "access": "public" }, "gitHead": "4a4c98997fe9b0f791f30fd168d867423ffcf730", "typesVersions": { "<3.8": { "*": [ "ts3.4/*" ] } } }
addons/a11y/package.json
1
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.7099942564964294, 0.08914345502853394, 0.0001648200850468129, 0.00017081614350900054, 0.23466043174266815 ]
{ "id": 3, "code_window": [ " \"@types/react-syntax-highlighter\": \"^11.0.4\"\n", " },\n", " \"peerDependencies\": {\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\"\n" ], "file_path": "addons/storysource/package.json", "type": "replace", "edit_start_line_idx": 51 }
// eslint-disable-next-line import/no-unresolved import raxTestRenderer from 'rax-test-renderer'; function getRenderedTree(story: any, context: any, { renderer, ...rendererOptions }: any) { const storyElement = story.render(); const currentRenderer = renderer || raxTestRenderer.create; const tree = currentRenderer(storyElement, rendererOptions); return tree; } export default getRenderedTree;
addons/storyshots/storyshots-core/src/frameworks/rax/renderTree.ts
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.000174118293216452, 0.00017163281154353172, 0.00016914732987061143, 0.00017163281154353172, 0.0000024854816729202867 ]
{ "id": 3, "code_window": [ " \"@types/react-syntax-highlighter\": \"^11.0.4\"\n", " },\n", " \"peerDependencies\": {\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\"\n" ], "file_path": "addons/storysource/package.json", "type": "replace", "edit_start_line_idx": 51 }
import m from 'mithril'; import { Page } from './Page'; import * as HeaderStories from './Header.stories'; export default { title: 'Example/Page', component: Page, }; const Template = ({ children, ...args }) => ({ view: () => m(Page, args, children), }); export const LoggedIn = Template.bind({}); LoggedIn.args = { ...HeaderStories.LoggedIn.args, }; export const LoggedOut = Template.bind({}); LoggedOut.args = { ...HeaderStories.LoggedOut.args, };
lib/cli/src/frameworks/mithril/Page.stories.js
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.0001725235051708296, 0.0001688440825091675, 0.00016688111645635217, 0.0001671276259003207, 0.0000026036902909254422 ]
{ "id": 3, "code_window": [ " \"@types/react-syntax-highlighter\": \"^11.0.4\"\n", " },\n", " \"peerDependencies\": {\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\"\n" ], "file_path": "addons/storysource/package.json", "type": "replace", "edit_start_line_idx": 51 }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="logo192.png" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>React App</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <!-- This HTML file is a template. If you open it directly in the browser, you will see an empty page. You can add webfonts, meta tags, or analytics to this file. The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> </body> </html>
examples/cra-ts-essentials/public/index.html
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.0001689986966084689, 0.00016664354188833386, 0.0001632203347980976, 0.0001686845935182646, 0.0000026945465378958033 ]
{ "id": 4, "code_window": [ " \"regenerator-runtime\": \"^0.13.7\"\n", " },\n", " \"peerDependencies\": {\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n", " },\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\"\n" ], "file_path": "addons/viewport/package.json", "type": "replace", "edit_start_line_idx": 44 }
{ "name": "@storybook/addon-docs", "version": "6.1.0-alpha.35", "description": "Superior documentation for your components", "keywords": [ "addon", "notes", "storybook" ], "homepage": "https://github.com/storybookjs/storybook/tree/master/addons/docs", "bugs": { "url": "https://github.com/storybookjs/storybook/issues" }, "repository": { "type": "git", "url": "https://github.com/storybookjs/storybook.git", "directory": "addons/docs" }, "license": "MIT", "main": "dist/public_api.js", "types": "dist/public_api.d.ts", "files": [ "dist/**/*", "angular/**/*", "common/**/*", "ember/**/*", "html/**/*", "postinstall/**/*", "react/**/*", "vue/**/*", "web-components/**/*", "README.md", "*.js", "*.d.ts", "ts3.4/**/*" ], "scripts": { "prepare": "node ../../scripts/prepare.js" }, "dependencies": { "@babel/core": "^7.12.1", "@babel/generator": "^7.12.1", "@babel/parser": "^7.12.3", "@babel/plugin-transform-react-jsx": "^7.12.1", "@babel/preset-env": "^7.12.1", "@jest/transform": "^26.0.0", "@mdx-js/loader": "^1.5.1", "@mdx-js/mdx": "^1.5.1", "@mdx-js/react": "^1.5.1", "@storybook/addons": "6.1.0-alpha.35", "@storybook/api": "6.1.0-alpha.35", "@storybook/client-api": "6.1.0-alpha.35", "@storybook/client-logger": "6.1.0-alpha.35", "@storybook/components": "6.1.0-alpha.35", "@storybook/core": "6.1.0-alpha.35", "@storybook/core-events": "6.1.0-alpha.35", "@storybook/csf": "0.0.1", "@storybook/node-logger": "6.1.0-alpha.35", "@storybook/postinstall": "6.1.0-alpha.35", "@storybook/source-loader": "6.1.0-alpha.35", "@storybook/theming": "6.1.0-alpha.35", "acorn": "^7.1.0", "acorn-jsx": "^5.1.0", "acorn-walk": "^7.0.0", "core-js": "^3.0.1", "doctrine": "^3.0.0", "escodegen": "^1.12.0", "fast-deep-equal": "^3.1.1", "global": "^4.3.2", "html-tags": "^3.1.0", "js-string-escape": "^1.0.1", "lodash": "^4.17.15", "prettier": "~2.0.5", "prop-types": "^15.7.2", "react-element-to-jsx-string": "^14.3.1", "regenerator-runtime": "^0.13.7", "remark-external-links": "^6.0.0", "remark-slug": "^6.0.0", "ts-dedent": "^2.0.0", "util-deprecate": "^1.0.2" }, "devDependencies": { "@angular/core": "^9.1.0", "@babel/core": "^7.12.3", "@emotion/core": "^10.0.20", "@emotion/styled": "^10.0.17", "@storybook/react": "6.1.0-alpha.35", "@storybook/vue": "6.1.0-alpha.35", "@storybook/web-components": "6.1.0-alpha.35", "@types/cross-spawn": "^6.0.1", "@types/doctrine": "^0.0.3", "@types/enzyme": "^3.10.3", "@types/estree": "^0.0.44", "@types/jest": "^25.1.1", "@types/prop-types": "^15.5.9", "@types/tmp": "^0.1.0", "@types/util-deprecate": "^1.0.0", "babel-loader": "^8.0.6", "babel-plugin-react-docgen": "^4.2.1", "cross-spawn": "^7.0.1", "fs-extra": "^9.0.0", "jest": "^26.0.0", "jest-specific-snapshot": "^4.0.0", "lit-element": "^2.2.1", "lit-html": "^1.0.0", "require-from-string": "^2.0.2", "rxjs": "^6.5.4", "styled-components": "^5.0.1", "terser-webpack-plugin": "^3.0.0", "tmp": "^0.2.1", "tslib": "^2.0.0", "web-component-analyzer": "^1.0.3", "webpack": "^4.33.0", "zone.js": "^0.10.2" }, "peerDependencies": { "@babel/core": "^7.11.5", "@storybook/vue": "6.1.0-alpha.35", "babel-loader": "^8.0.0", "react": "15 || 16 || ^17.0.0", "react-dom": "15 || 16 || ^17.0.0", "sveltedoc-parser": "^3.0.4", "vue": "^2.6.10", "webpack": ">=4" }, "peerDependenciesMeta": { "@storybook/vue": { "optional": true }, "sveltedoc-parser": { "optional": true }, "vue": { "optional": true }, "webpack": { "optional": true } }, "publishConfig": { "access": "public" }, "gitHead": "4a4c98997fe9b0f791f30fd168d867423ffcf730", "typesVersions": { "<3.8": { "*": [ "ts3.4/*" ] } } }
addons/docs/package.json
1
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.024436306208372116, 0.0024408164899796247, 0.00016386108472943306, 0.00016944421804510057, 0.0063651190139353275 ]
{ "id": 4, "code_window": [ " \"regenerator-runtime\": \"^0.13.7\"\n", " },\n", " \"peerDependencies\": {\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n", " },\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\"\n" ], "file_path": "addons/viewport/package.json", "type": "replace", "edit_start_line_idx": 44 }
# markdown-spellcheck spelling configuration file # Format - lines beginning # are comments # global dictionary is at the start, file overrides afterwards # one word per line, to define a file override use ' - filename' # where filename is relative to this configuration file addon 1 vue svelte webcomponents aurelia iframe webpack addons styleguide-type styleguides angularjs api github config cra PRs cleanup 2 ES2016 prerelease rc npm apollo codemod storyshots graphql lerna eslint js CommonJS IO reflow Node.js. dialog 10 unisolated 3 13 Browserify bundlers 2013 centered center GraphiQL graphiql url javascript storyshots' storybook.js.org CRNA postmessage websocket EventEmitter codemods jscodeshift npm3 HMR Redux storybook-ui react-komposer serializable params README.md storybook.js.org YuzuJS setImmediate Malte Katić Domenic Kowal Zakas Gruber julian juliangruber.com Schlueter linkTo setOptions setStories onStory
.spelling
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.0001711462391540408, 0.0001679666165728122, 0.0001649100158829242, 0.0001679886190686375, 0.000001861152895799023 ]
{ "id": 4, "code_window": [ " \"regenerator-runtime\": \"^0.13.7\"\n", " },\n", " \"peerDependencies\": {\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n", " },\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\"\n" ], "file_path": "addons/viewport/package.json", "type": "replace", "edit_start_line_idx": 44 }
```js // .storybook/preview.js export const globalTypes = { locale: { name: 'Locale', description: 'Internationalization locale', defaultValue: 'en', toolbar: { icon: 'globe', items: [ { value: 'en', right: '🇺🇸', title: 'English' }, { value: 'fr', right: '🇫🇷', title: 'Français' }, { value: 'es', right: '🇪🇸', title: 'Español' }, { value: 'zh', right: '🇨🇳', title: '中文' }, { value: 'kr', right: '🇰🇷', title: '한국어' }, ], }, }, }; ```
docs/snippets/common/storybook-preview-locales-globaltype.js.mdx
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.00017361331265419722, 0.00017298127932008356, 0.00017192248196806759, 0.0001734079996822402, 7.533499228884466e-7 ]
{ "id": 4, "code_window": [ " \"regenerator-runtime\": \"^0.13.7\"\n", " },\n", " \"peerDependencies\": {\n", " \"react\": \"15 || 16 || ^17.0.0\",\n", " \"react-dom\": \"15 || 16 || ^17.0.0\"\n", " },\n", " \"publishConfig\": {\n", " \"access\": \"public\"\n", " },\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"react\": \"^16.8.3 || ^17.0.0\",\n", " \"react-dom\": \"^16.8.3 || ^17.0.0\"\n" ], "file_path": "addons/viewport/package.json", "type": "replace", "edit_start_line_idx": 44 }
<template> <div class="app"> <hello></hello> </div> <script> riot.mount('hello', {}); </script> <style> body { display: flex; align-items: center; justify-content: center; height: 100%; margin: 0; } .app { color: #444; margin-top: 100px; max-width: 600px; font-family: Helvetica, sans-serif; text-align: center; display: flex; align-items: center; } </style> </template>
lib/cli/test/fixtures/riot/src/App.tag
0
https://github.com/storybookjs/storybook/commit/c8ce61732dc8dc1f2c596de6d08625765c1a3155
[ 0.0001752773387124762, 0.00017383370141033083, 0.00017097969248425215, 0.00017453887267038226, 0.0000016772054323155317 ]
{ "id": 0, "code_window": [ " if (\n", " !context.ssr &&\n", " getConstantType(child) === ConstantTypes.NOT_CONSTANT\n", " ) {\n", " callArgs.push(\n", " `${PatchFlags.TEXT} /* ${PatchFlagNames[PatchFlags.TEXT]} */`\n", " )\n", " }\n", " children[i] = {\n", " type: NodeTypes.TEXT_CALL,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " PatchFlags.TEXT +\n", " (__DEV__ ? ` /* ${PatchFlagNames[PatchFlags.TEXT]} */` : ``)\n" ], "file_path": "packages/compiler-core/src/transforms/transformText.ts", "type": "replace", "edit_start_line_idx": 87 }
import { createStructuralDirectiveTransform, TransformContext } from '../transform' import { NodeTypes, ExpressionNode, createSimpleExpression, SourceLocation, SimpleExpressionNode, createCallExpression, createFunctionExpression, createObjectExpression, createObjectProperty, ForCodegenNode, RenderSlotCall, SlotOutletNode, ElementNode, DirectiveNode, ForNode, PlainElementNode, createVNodeCall, VNodeCall, ForRenderListExpression, BlockCodegenNode, ForIteratorExpression } from '../ast' import { createCompilerError, ErrorCodes } from '../errors' import { getInnerRange, findProp, isTemplateNode, isSlotOutlet, injectProp } from '../utils' import { RENDER_LIST, OPEN_BLOCK, CREATE_BLOCK, FRAGMENT } from '../runtimeHelpers' import { processExpression } from './transformExpression' import { validateBrowserExpression } from '../validateExpression' import { PatchFlags, PatchFlagNames } from '@vue/shared' export const transformFor = createStructuralDirectiveTransform( 'for', (node, dir, context) => { const { helper } = context return processFor(node, dir, context, forNode => { // create the loop render function expression now, and add the // iterator on exit after all children have been traversed const renderExp = createCallExpression(helper(RENDER_LIST), [ forNode.source ]) as ForRenderListExpression const keyProp = findProp(node, `key`) const keyProperty = keyProp ? createObjectProperty( `key`, keyProp.type === NodeTypes.ATTRIBUTE ? createSimpleExpression(keyProp.value!.content, true) : keyProp.exp! ) : null if (!__BROWSER__ && context.prefixIdentifiers && keyProperty) { // #2085 process :key expression needs to be processed in order for it // to behave consistently for <template v-for> and <div v-for>. // In the case of `<template v-for>`, the node is discarded and never // traversed so its key expression won't be processed by the normal // transforms. keyProperty.value = processExpression( keyProperty.value as SimpleExpressionNode, context ) } const isStableFragment = forNode.source.type === NodeTypes.SIMPLE_EXPRESSION && forNode.source.constType > 0 const fragmentFlag = isStableFragment ? PatchFlags.STABLE_FRAGMENT : keyProp ? PatchFlags.KEYED_FRAGMENT : PatchFlags.UNKEYED_FRAGMENT forNode.codegenNode = createVNodeCall( context, helper(FRAGMENT), undefined, renderExp, `${fragmentFlag} /* ${PatchFlagNames[fragmentFlag]} */`, undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc ) as ForCodegenNode return () => { // finish the codegen now that all children have been traversed let childBlock: BlockCodegenNode const isTemplate = isTemplateNode(node) const { children } = forNode // check <template v-for> key placement if ((__DEV__ || !__BROWSER__) && isTemplate) { node.children.some(c => { if (c.type === NodeTypes.ELEMENT) { const key = findProp(c, 'key') if (key) { context.onError( createCompilerError( ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT, key.loc ) ) return true } } }) } const needFragmentWrapper = children.length !== 1 || children[0].type !== NodeTypes.ELEMENT const slotOutlet = isSlotOutlet(node) ? node : isTemplate && node.children.length === 1 && isSlotOutlet(node.children[0]) ? (node.children[0] as SlotOutletNode) // api-extractor somehow fails to infer this : null if (slotOutlet) { // <slot v-for="..."> or <template v-for="..."><slot/></template> childBlock = slotOutlet.codegenNode as RenderSlotCall if (isTemplate && keyProperty) { // <template v-for="..." :key="..."><slot/></template> // we need to inject the key to the renderSlot() call. // the props for renderSlot is passed as the 3rd argument. injectProp(childBlock, keyProperty, context) } } else if (needFragmentWrapper) { // <template v-for="..."> with text or multi-elements // should generate a fragment block for each loop childBlock = createVNodeCall( context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, `${PatchFlags.STABLE_FRAGMENT} /* ${ PatchFlagNames[PatchFlags.STABLE_FRAGMENT] } */`, undefined, undefined, true ) } else { // Normal element v-for. Directly use the child's codegenNode // but mark it as a block. childBlock = (children[0] as PlainElementNode) .codegenNode as VNodeCall if (isTemplate && keyProperty) { injectProp(childBlock, keyProperty, context) } childBlock.isBlock = !isStableFragment if (childBlock.isBlock) { helper(OPEN_BLOCK) helper(CREATE_BLOCK) } } renderExp.arguments.push(createFunctionExpression( createForLoopParams(forNode.parseResult), childBlock, true /* force newline */ ) as ForIteratorExpression) } }) } ) // target-agnostic transform used for both Client and SSR export function processFor( node: ElementNode, dir: DirectiveNode, context: TransformContext, processCodegen?: (forNode: ForNode) => (() => void) | undefined ) { if (!dir.exp) { context.onError( createCompilerError(ErrorCodes.X_V_FOR_NO_EXPRESSION, dir.loc) ) return } const parseResult = parseForExpression( // can only be simple expression because vFor transform is applied // before expression transform. dir.exp as SimpleExpressionNode, context ) if (!parseResult) { context.onError( createCompilerError(ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION, dir.loc) ) return } const { addIdentifiers, removeIdentifiers, scopes } = context const { source, value, key, index } = parseResult const forNode: ForNode = { type: NodeTypes.FOR, loc: dir.loc, source, valueAlias: value, keyAlias: key, objectIndexAlias: index, parseResult, children: isTemplateNode(node) ? node.children : [node] } context.replaceNode(forNode) // bookkeeping scopes.vFor++ if (!__BROWSER__ && context.prefixIdentifiers) { // scope management // inject identifiers to context value && addIdentifiers(value) key && addIdentifiers(key) index && addIdentifiers(index) } const onExit = processCodegen && processCodegen(forNode) return () => { scopes.vFor-- if (!__BROWSER__ && context.prefixIdentifiers) { value && removeIdentifiers(value) key && removeIdentifiers(key) index && removeIdentifiers(index) } if (onExit) onExit() } } const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/ // This regex doesn't cover the case if key or index aliases have destructuring, // but those do not make sense in the first place, so this works in practice. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/ const stripParensRE = /^\(|\)$/g export interface ForParseResult { source: ExpressionNode value: ExpressionNode | undefined key: ExpressionNode | undefined index: ExpressionNode | undefined } export function parseForExpression( input: SimpleExpressionNode, context: TransformContext ): ForParseResult | undefined { const loc = input.loc const exp = input.content const inMatch = exp.match(forAliasRE) if (!inMatch) return const [, LHS, RHS] = inMatch const result: ForParseResult = { source: createAliasExpression( loc, RHS.trim(), exp.indexOf(RHS, LHS.length) ), value: undefined, key: undefined, index: undefined } if (!__BROWSER__ && context.prefixIdentifiers) { result.source = processExpression( result.source as SimpleExpressionNode, context ) } if (__DEV__ && __BROWSER__) { validateBrowserExpression(result.source as SimpleExpressionNode, context) } let valueContent = LHS.trim() .replace(stripParensRE, '') .trim() const trimmedOffset = LHS.indexOf(valueContent) const iteratorMatch = valueContent.match(forIteratorRE) if (iteratorMatch) { valueContent = valueContent.replace(forIteratorRE, '').trim() const keyContent = iteratorMatch[1].trim() let keyOffset: number | undefined if (keyContent) { keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length) result.key = createAliasExpression(loc, keyContent, keyOffset) if (!__BROWSER__ && context.prefixIdentifiers) { result.key = processExpression(result.key, context, true) } if (__DEV__ && __BROWSER__) { validateBrowserExpression( result.key as SimpleExpressionNode, context, true ) } } if (iteratorMatch[2]) { const indexContent = iteratorMatch[2].trim() if (indexContent) { result.index = createAliasExpression( loc, indexContent, exp.indexOf( indexContent, result.key ? keyOffset! + keyContent.length : trimmedOffset + valueContent.length ) ) if (!__BROWSER__ && context.prefixIdentifiers) { result.index = processExpression(result.index, context, true) } if (__DEV__ && __BROWSER__) { validateBrowserExpression( result.index as SimpleExpressionNode, context, true ) } } } } if (valueContent) { result.value = createAliasExpression(loc, valueContent, trimmedOffset) if (!__BROWSER__ && context.prefixIdentifiers) { result.value = processExpression(result.value, context, true) } if (__DEV__ && __BROWSER__) { validateBrowserExpression( result.value as SimpleExpressionNode, context, true ) } } return result } function createAliasExpression( range: SourceLocation, content: string, offset: number ): SimpleExpressionNode { return createSimpleExpression( content, false, getInnerRange(range, offset, content.length) ) } export function createForLoopParams({ value, key, index }: ForParseResult): ExpressionNode[] { const params: ExpressionNode[] = [] if (value) { params.push(value) } if (key) { if (!value) { params.push(createSimpleExpression(`_`, false)) } params.push(key) } if (index) { if (!key) { if (!value) { params.push(createSimpleExpression(`_`, false)) } params.push(createSimpleExpression(`__`, false)) } params.push(index) } return params }
packages/compiler-core/src/transforms/vFor.ts
1
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.8228013515472412, 0.024187488481402397, 0.0001628807804081589, 0.0001709221542114392, 0.1284899115562439 ]
{ "id": 0, "code_window": [ " if (\n", " !context.ssr &&\n", " getConstantType(child) === ConstantTypes.NOT_CONSTANT\n", " ) {\n", " callArgs.push(\n", " `${PatchFlags.TEXT} /* ${PatchFlagNames[PatchFlags.TEXT]} */`\n", " )\n", " }\n", " children[i] = {\n", " type: NodeTypes.TEXT_CALL,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " PatchFlags.TEXT +\n", " (__DEV__ ? ` /* ${PatchFlagNames[PatchFlags.TEXT]} */` : ``)\n" ], "file_path": "packages/compiler-core/src/transforms/transformText.ts", "type": "replace", "edit_start_line_idx": 87 }
import { compile } from '../src' describe('ssr: inject <style vars>', () => { test('basic', () => { expect( compile(`<div/>`, { ssrCssVars: `{ color }` }).code ).toMatchInlineSnapshot(` "const { mergeProps: _mergeProps } = require(\\"vue\\") const { ssrRenderAttrs: _ssrRenderAttrs } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { const _cssVars = { style: { color: _ctx.color }} _push(\`<div\${_ssrRenderAttrs(_mergeProps(_attrs, _cssVars))}></div>\`) }" `) }) test('fragment', () => { expect( compile(`<div/><div/>`, { ssrCssVars: `{ color }` }).code ).toMatchInlineSnapshot(` "const { ssrRenderAttrs: _ssrRenderAttrs } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { const _cssVars = { style: { color: _ctx.color }} _push(\`<!--[--><div\${ _ssrRenderAttrs(_cssVars) }></div><div\${ _ssrRenderAttrs(_cssVars) }></div><!--]-->\`) }" `) }) test('passing on to components', () => { expect( compile(`<div/><foo/>`, { ssrCssVars: `{ color }` }).code ).toMatchInlineSnapshot(` "const { resolveComponent: _resolveComponent } = require(\\"vue\\") const { ssrRenderAttrs: _ssrRenderAttrs, ssrRenderComponent: _ssrRenderComponent } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { const _component_foo = _resolveComponent(\\"foo\\") const _cssVars = { style: { color: _ctx.color }} _push(\`<!--[--><div\${_ssrRenderAttrs(_cssVars)}></div>\`) _push(_ssrRenderComponent(_component_foo, _cssVars, null, _parent)) _push(\`<!--]-->\`) }" `) }) test('v-if branches', () => { expect( compile(`<div v-if="ok"/><template v-else><div/><div/></template>`, { ssrCssVars: `{ color }` }).code ).toMatchInlineSnapshot(` "const { mergeProps: _mergeProps } = require(\\"vue\\") const { ssrRenderAttrs: _ssrRenderAttrs } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { const _cssVars = { style: { color: _ctx.color }} if (_ctx.ok) { _push(\`<div\${_ssrRenderAttrs(_mergeProps(_attrs, _cssVars))}></div>\`) } else { _push(\`<!--[--><div\${ _ssrRenderAttrs(_cssVars) }></div><div\${ _ssrRenderAttrs(_cssVars) }></div><!--]-->\`) } }" `) }) test('w/ suspense', () => { expect( compile( `<Suspense> <div>ok</div> <template #fallback> <div>fallback</div> </template> </Suspense>`, { ssrCssVars: `{ color }` } ).code ).toMatchInlineSnapshot(` "const { withCtx: _withCtx } = require(\\"vue\\") const { ssrRenderAttrs: _ssrRenderAttrs, ssrRenderSuspense: _ssrRenderSuspense } = require(\\"@vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { const _cssVars = { style: { color: _ctx.color }} _ssrRenderSuspense(_push, { fallback: () => { _push(\`<div\${_ssrRenderAttrs(_cssVars)}>fallback</div>\`) }, default: () => { _push(\`<div\${_ssrRenderAttrs(_cssVars)}>ok</div>\`) }, _: 1 }) }" `) }) })
packages/compiler-ssr/__tests__/ssrInjectCssVars.spec.ts
0
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.0001756653218762949, 0.00017141038551926613, 0.00016634335042908788, 0.0001715068065095693, 0.0000027923219931835774 ]
{ "id": 0, "code_window": [ " if (\n", " !context.ssr &&\n", " getConstantType(child) === ConstantTypes.NOT_CONSTANT\n", " ) {\n", " callArgs.push(\n", " `${PatchFlags.TEXT} /* ${PatchFlagNames[PatchFlags.TEXT]} */`\n", " )\n", " }\n", " children[i] = {\n", " type: NodeTypes.TEXT_CALL,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " PatchFlags.TEXT +\n", " (__DEV__ ? ` /* ${PatchFlagNames[PatchFlags.TEXT]} */` : ``)\n" ], "file_path": "packages/compiler-core/src/transforms/transformText.ts", "type": "replace", "edit_start_line_idx": 87 }
import { h, render, nodeOps, VNodeProps, TestElement, NodeTypes, VNode } from '@vue/runtime-test' describe('renderer: vnode hooks', () => { function assertHooks(hooks: VNodeProps, vnode1: VNode, vnode2: VNode) { const root = nodeOps.createElement('div') render(vnode1, root) expect(hooks.onVnodeBeforeMount).toHaveBeenCalledWith(vnode1, null) expect(hooks.onVnodeMounted).toHaveBeenCalledWith(vnode1, null) expect(hooks.onVnodeBeforeUpdate).not.toHaveBeenCalled() expect(hooks.onVnodeUpdated).not.toHaveBeenCalled() expect(hooks.onVnodeBeforeUnmount).not.toHaveBeenCalled() expect(hooks.onVnodeUnmounted).not.toHaveBeenCalled() // update render(vnode2, root) expect(hooks.onVnodeBeforeMount).toHaveBeenCalledTimes(1) expect(hooks.onVnodeMounted).toHaveBeenCalledTimes(1) expect(hooks.onVnodeBeforeUpdate).toHaveBeenCalledWith(vnode2, vnode1) expect(hooks.onVnodeUpdated).toHaveBeenCalledWith(vnode2, vnode1) expect(hooks.onVnodeBeforeUnmount).not.toHaveBeenCalled() expect(hooks.onVnodeUnmounted).not.toHaveBeenCalled() // unmount render(null, root) expect(hooks.onVnodeBeforeMount).toHaveBeenCalledTimes(1) expect(hooks.onVnodeMounted).toHaveBeenCalledTimes(1) expect(hooks.onVnodeBeforeUpdate).toHaveBeenCalledTimes(1) expect(hooks.onVnodeUpdated).toHaveBeenCalledTimes(1) expect(hooks.onVnodeBeforeUnmount).toHaveBeenCalledWith(vnode2, null) expect(hooks.onVnodeUnmounted).toHaveBeenCalledWith(vnode2, null) } test('should work on element', () => { const hooks: VNodeProps = { onVnodeBeforeMount: jest.fn(), onVnodeMounted: jest.fn(), onVnodeBeforeUpdate: jest.fn(vnode => { expect((vnode.el as TestElement).children[0]).toMatchObject({ type: NodeTypes.TEXT, text: 'foo' }) }), onVnodeUpdated: jest.fn(vnode => { expect((vnode.el as TestElement).children[0]).toMatchObject({ type: NodeTypes.TEXT, text: 'bar' }) }), onVnodeBeforeUnmount: jest.fn(), onVnodeUnmounted: jest.fn() } assertHooks(hooks, h('div', hooks, 'foo'), h('div', hooks, 'bar')) }) test('should work on component', () => { const Comp = (props: { msg: string }) => props.msg const hooks: VNodeProps = { onVnodeBeforeMount: jest.fn(), onVnodeMounted: jest.fn(), onVnodeBeforeUpdate: jest.fn(vnode => { expect(vnode.el as TestElement).toMatchObject({ type: NodeTypes.TEXT, text: 'foo' }) }), onVnodeUpdated: jest.fn(vnode => { expect(vnode.el as TestElement).toMatchObject({ type: NodeTypes.TEXT, text: 'bar' }) }), onVnodeBeforeUnmount: jest.fn(), onVnodeUnmounted: jest.fn() } assertHooks( hooks, h(Comp, { ...hooks, msg: 'foo' }), h(Comp, { ...hooks, msg: 'bar' }) ) }) })
packages/runtime-core/__tests__/vnodeHooks.spec.ts
0
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.00042780209332704544, 0.00020461918029468507, 0.000169438382727094, 0.00017406267579644918, 0.00007597490912303329 ]
{ "id": 0, "code_window": [ " if (\n", " !context.ssr &&\n", " getConstantType(child) === ConstantTypes.NOT_CONSTANT\n", " ) {\n", " callArgs.push(\n", " `${PatchFlags.TEXT} /* ${PatchFlagNames[PatchFlags.TEXT]} */`\n", " )\n", " }\n", " children[i] = {\n", " type: NodeTypes.TEXT_CALL,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " PatchFlags.TEXT +\n", " (__DEV__ ? ` /* ${PatchFlagNames[PatchFlags.TEXT]} */` : ``)\n" ], "file_path": "packages/compiler-core/src/transforms/transformText.ts", "type": "replace", "edit_start_line_idx": 87 }
import { ComponentInternalInstance, Data } from './component' import { nextTick, queueJob } from './scheduler' import { instanceWatch, WatchOptions, WatchStopHandle } from './apiWatch' import { EMPTY_OBJ, hasOwn, isGloballyWhitelisted, NOOP, extend, isString } from '@vue/shared' import { ReactiveEffect, toRaw, shallowReadonly, ReactiveFlags, track, TrackOpTypes, ShallowUnwrapRef } from '@vue/reactivity' import { ExtractComputedReturns, ComponentOptionsBase, ComputedOptions, MethodOptions, ComponentOptionsMixin, OptionTypesType, OptionTypesKeys, resolveMergedOptions, isInBeforeCreate } from './componentOptions' import { EmitsOptions, EmitFn } from './componentEmits' import { Slots } from './componentSlots' import { currentRenderingInstance, markAttrsAccessed } from './componentRenderUtils' import { warn } from './warning' import { UnionToIntersection } from './helpers/typeUtils' /** * Custom properties added to component instances in any way and can be accessed through `this` * * @example * Here is an example of adding a property `$router` to every component instance: * ```ts * import { createApp } from 'vue' * import { Router, createRouter } from 'vue-router' * * declare module '@vue/runtime-core' { * interface ComponentCustomProperties { * $router: Router * } * } * * // effectively adding the router to every component instance * const app = createApp({}) * const router = createRouter() * app.config.globalProperties.$router = router * * const vm = app.mount('#app') * // we can access the router from the instance * vm.$router.push('/') * ``` */ export interface ComponentCustomProperties {} type IsDefaultMixinComponent<T> = T extends ComponentOptionsMixin ? ComponentOptionsMixin extends T ? true : false : false type MixinToOptionTypes<T> = T extends ComponentOptionsBase< infer P, infer B, infer D, infer C, infer M, infer Mixin, infer Extends, any, any, infer Defaults > ? OptionTypesType<P & {}, B & {}, D & {}, C & {}, M & {}, Defaults & {}> & IntersectionMixin<Mixin> & IntersectionMixin<Extends> : never // ExtractMixin(map type) is used to resolve circularly references type ExtractMixin<T> = { Mixin: MixinToOptionTypes<T> }[T extends ComponentOptionsMixin ? 'Mixin' : never] type IntersectionMixin<T> = IsDefaultMixinComponent<T> extends true ? OptionTypesType<{}, {}, {}, {}, {}> : UnionToIntersection<ExtractMixin<T>> type UnwrapMixinsType< T, Type extends OptionTypesKeys > = T extends OptionTypesType ? T[Type] : never type EnsureNonVoid<T> = T extends void ? {} : T export type ComponentPublicInstanceConstructor< T extends ComponentPublicInstance< Props, RawBindings, D, C, M > = ComponentPublicInstance<any>, Props = any, RawBindings = any, D = any, C extends ComputedOptions = ComputedOptions, M extends MethodOptions = MethodOptions > = { __isFragment?: never __isTeleport?: never __isSuspense?: never new (...args: any[]): T } export type CreateComponentPublicInstance< P = {}, B = {}, D = {}, C extends ComputedOptions = {}, M extends MethodOptions = {}, Mixin extends ComponentOptionsMixin = ComponentOptionsMixin, Extends extends ComponentOptionsMixin = ComponentOptionsMixin, E extends EmitsOptions = {}, PublicProps = P, Defaults = {}, MakeDefaultsOptional extends boolean = false, PublicMixin = IntersectionMixin<Mixin> & IntersectionMixin<Extends>, PublicP = UnwrapMixinsType<PublicMixin, 'P'> & EnsureNonVoid<P>, PublicB = UnwrapMixinsType<PublicMixin, 'B'> & EnsureNonVoid<B>, PublicD = UnwrapMixinsType<PublicMixin, 'D'> & EnsureNonVoid<D>, PublicC extends ComputedOptions = UnwrapMixinsType<PublicMixin, 'C'> & EnsureNonVoid<C>, PublicM extends MethodOptions = UnwrapMixinsType<PublicMixin, 'M'> & EnsureNonVoid<M>, PublicDefaults = UnwrapMixinsType<PublicMixin, 'Defaults'> & EnsureNonVoid<Defaults> > = ComponentPublicInstance< PublicP, PublicB, PublicD, PublicC, PublicM, E, PublicProps, PublicDefaults, MakeDefaultsOptional, ComponentOptionsBase<P, B, D, C, M, Mixin, Extends, E, string, Defaults> > // public properties exposed on the proxy, which is used as the render context // in templates (as `this` in the render option) export type ComponentPublicInstance< P = {}, // props type extracted from props option B = {}, // raw bindings returned from setup() D = {}, // return from data() C extends ComputedOptions = {}, M extends MethodOptions = {}, E extends EmitsOptions = {}, PublicProps = P, Defaults = {}, MakeDefaultsOptional extends boolean = false, Options = ComponentOptionsBase<any, any, any, any, any, any, any, any, any> > = { $: ComponentInternalInstance $data: D $props: MakeDefaultsOptional extends true ? Partial<Defaults> & Omit<P & PublicProps, keyof Defaults> : P & PublicProps $attrs: Data $refs: Data $slots: Slots $root: ComponentPublicInstance | null $parent: ComponentPublicInstance | null $emit: EmitFn<E> $el: any $options: Options $forceUpdate: ReactiveEffect $nextTick: typeof nextTick $watch( source: string | Function, cb: Function, options?: WatchOptions ): WatchStopHandle } & P & ShallowUnwrapRef<B> & D & ExtractComputedReturns<C> & M & ComponentCustomProperties type PublicPropertiesMap = Record<string, (i: ComponentInternalInstance) => any> /** * #2437 In Vue 3, functional components do not have a public instance proxy but * they exist in the internal parent chain. For code that relies on traversing * public $parent chains, skip functional ones and go to the parent instead. */ const getPublicInstance = ( i: ComponentInternalInstance | null ): ComponentPublicInstance | null => i && (i.proxy ? i.proxy : getPublicInstance(i.parent)) const publicPropertiesMap: PublicPropertiesMap = extend(Object.create(null), { $: i => i, $el: i => i.vnode.el, $data: i => i.data, $props: i => (__DEV__ ? shallowReadonly(i.props) : i.props), $attrs: i => (__DEV__ ? shallowReadonly(i.attrs) : i.attrs), $slots: i => (__DEV__ ? shallowReadonly(i.slots) : i.slots), $refs: i => (__DEV__ ? shallowReadonly(i.refs) : i.refs), $parent: i => getPublicInstance(i.parent), $root: i => i.root && i.root.proxy, $emit: i => i.emit, $options: i => (__FEATURE_OPTIONS_API__ ? resolveMergedOptions(i) : i.type), $forceUpdate: i => () => queueJob(i.update), $nextTick: i => nextTick.bind(i.proxy!), $watch: i => (__FEATURE_OPTIONS_API__ ? instanceWatch.bind(i) : NOOP) } as PublicPropertiesMap) const enum AccessTypes { SETUP, DATA, PROPS, CONTEXT, OTHER } export interface ComponentRenderContext { [key: string]: any _: ComponentInternalInstance } export const PublicInstanceProxyHandlers: ProxyHandler<any> = { get({ _: instance }: ComponentRenderContext, key: string) { const { ctx, setupState, data, props, accessCache, type, appContext } = instance // let @vue/reactivity know it should never observe Vue public instances. if (key === ReactiveFlags.SKIP) { return true } // for internal formatters to know that this is a Vue instance if (__DEV__ && key === '__isVue') { return true } // data / props / ctx // This getter gets called for every property access on the render context // during render and is a major hotspot. The most expensive part of this // is the multiple hasOwn() calls. It's much faster to do a simple property // access on a plain object, so we use an accessCache object (with null // prototype) to memoize what access type a key corresponds to. let normalizedProps if (key[0] !== '$') { const n = accessCache![key] if (n !== undefined) { switch (n) { case AccessTypes.SETUP: return setupState[key] case AccessTypes.DATA: return data[key] case AccessTypes.CONTEXT: return ctx[key] case AccessTypes.PROPS: return props![key] // default: just fallthrough } } else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) { accessCache![key] = AccessTypes.SETUP return setupState[key] } else if (data !== EMPTY_OBJ && hasOwn(data, key)) { accessCache![key] = AccessTypes.DATA return data[key] } else if ( // only cache other properties when instance has declared (thus stable) // props (normalizedProps = instance.propsOptions[0]) && hasOwn(normalizedProps, key) ) { accessCache![key] = AccessTypes.PROPS return props![key] } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) { accessCache![key] = AccessTypes.CONTEXT return ctx[key] } else if (!__FEATURE_OPTIONS_API__ || !isInBeforeCreate) { accessCache![key] = AccessTypes.OTHER } } const publicGetter = publicPropertiesMap[key] let cssModule, globalProperties // public $xxx properties if (publicGetter) { if (key === '$attrs') { track(instance, TrackOpTypes.GET, key) __DEV__ && markAttrsAccessed() } return publicGetter(instance) } else if ( // css module (injected by vue-loader) (cssModule = type.__cssModules) && (cssModule = cssModule[key]) ) { return cssModule } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) { // user may set custom properties to `this` that start with `$` accessCache![key] = AccessTypes.CONTEXT return ctx[key] } else if ( // global properties ((globalProperties = appContext.config.globalProperties), hasOwn(globalProperties, key)) ) { return globalProperties[key] } else if ( __DEV__ && currentRenderingInstance && (!isString(key) || // #1091 avoid internal isRef/isVNode checks on component instance leading // to infinite warning loop key.indexOf('__v') !== 0) ) { if ( data !== EMPTY_OBJ && (key[0] === '$' || key[0] === '_') && hasOwn(data, key) ) { warn( `Property ${JSON.stringify( key )} must be accessed via $data because it starts with a reserved ` + `character ("$" or "_") and is not proxied on the render context.` ) } else { warn( `Property ${JSON.stringify(key)} was accessed during render ` + `but is not defined on instance.` ) } } }, set( { _: instance }: ComponentRenderContext, key: string, value: any ): boolean { const { data, setupState, ctx } = instance if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) { setupState[key] = value } else if (data !== EMPTY_OBJ && hasOwn(data, key)) { data[key] = value } else if (key in instance.props) { __DEV__ && warn( `Attempting to mutate prop "${key}". Props are readonly.`, instance ) return false } if (key[0] === '$' && key.slice(1) in instance) { __DEV__ && warn( `Attempting to mutate public property "${key}". ` + `Properties starting with $ are reserved and readonly.`, instance ) return false } else { if (__DEV__ && key in instance.appContext.config.globalProperties) { Object.defineProperty(ctx, key, { enumerable: true, configurable: true, value }) } else { ctx[key] = value } } return true }, has( { _: { data, setupState, accessCache, ctx, appContext, propsOptions } }: ComponentRenderContext, key: string ) { let normalizedProps return ( accessCache![key] !== undefined || (data !== EMPTY_OBJ && hasOwn(data, key)) || (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) || ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) || hasOwn(ctx, key) || hasOwn(publicPropertiesMap, key) || hasOwn(appContext.config.globalProperties, key) ) } } if (__DEV__ && !__TEST__) { PublicInstanceProxyHandlers.ownKeys = (target: ComponentRenderContext) => { warn( `Avoid app logic that relies on enumerating keys on a component instance. ` + `The keys will be empty in production mode to avoid performance overhead.` ) return Reflect.ownKeys(target) } } export const RuntimeCompiledPublicInstanceProxyHandlers = extend( {}, PublicInstanceProxyHandlers, { get(target: ComponentRenderContext, key: string) { // fast path for unscopables when using `with` block if ((key as any) === Symbol.unscopables) { return } return PublicInstanceProxyHandlers.get!(target, key, target) }, has(_: ComponentRenderContext, key: string) { const has = key[0] !== '_' && !isGloballyWhitelisted(key) if (__DEV__ && !has && PublicInstanceProxyHandlers.has!(_, key)) { warn( `Property ${JSON.stringify( key )} should not start with _ which is a reserved prefix for Vue internals.` ) } return has } } ) // In dev mode, the proxy target exposes the same properties as seen on `this` // for easier console inspection. In prod mode it will be an empty object so // these properties definitions can be skipped. export function createRenderContext(instance: ComponentInternalInstance) { const target: Record<string, any> = {} // expose internal instance for proxy handlers Object.defineProperty(target, `_`, { configurable: true, enumerable: false, get: () => instance }) // expose public properties Object.keys(publicPropertiesMap).forEach(key => { Object.defineProperty(target, key, { configurable: true, enumerable: false, get: () => publicPropertiesMap[key](instance), // intercepted by the proxy so no need for implementation, // but needed to prevent set errors set: NOOP }) }) // expose global properties const { globalProperties } = instance.appContext.config Object.keys(globalProperties).forEach(key => { Object.defineProperty(target, key, { configurable: true, enumerable: false, get: () => globalProperties[key], set: NOOP }) }) return target as ComponentRenderContext } // dev only export function exposePropsOnRenderContext( instance: ComponentInternalInstance ) { const { ctx, propsOptions: [propsOptions] } = instance if (propsOptions) { Object.keys(propsOptions).forEach(key => { Object.defineProperty(ctx, key, { enumerable: true, configurable: true, get: () => instance.props[key], set: NOOP }) }) } } // dev only export function exposeSetupStateOnRenderContext( instance: ComponentInternalInstance ) { const { ctx, setupState } = instance Object.keys(toRaw(setupState)).forEach(key => { if (key[0] === '$' || key[0] === '_') { warn( `setup() return property ${JSON.stringify( key )} should not start with "$" or "_" ` + `which are reserved prefixes for Vue internals.` ) return } Object.defineProperty(ctx, key, { enumerable: true, configurable: true, get: () => setupState[key], set: NOOP }) }) }
packages/runtime-core/src/componentPublicInstance.ts
0
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.002917477861046791, 0.0002529445046093315, 0.0001623003336135298, 0.00017150654457509518, 0.00040012667886912823 ]
{ "id": 1, "code_window": [ " context,\n", " helper(FRAGMENT),\n", " undefined,\n", " renderExp,\n", " `${fragmentFlag} /* ${PatchFlagNames[fragmentFlag]} */`,\n", " undefined,\n", " undefined,\n", " true /* isBlock */,\n", " !isStableFragment /* disableTracking */,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " fragmentFlag +\n", " (__DEV__ ? ` /* ${PatchFlagNames[fragmentFlag]} */` : ``),\n" ], "file_path": "packages/compiler-core/src/transforms/vFor.ts", "type": "replace", "edit_start_line_idx": 90 }
import { createStructuralDirectiveTransform, TransformContext, traverseNode } from '../transform' import { NodeTypes, ElementTypes, ElementNode, DirectiveNode, IfBranchNode, SimpleExpressionNode, createCallExpression, createConditionalExpression, createSimpleExpression, createObjectProperty, createObjectExpression, IfConditionalExpression, BlockCodegenNode, IfNode, createVNodeCall, AttributeNode, locStub, CacheExpression, ConstantTypes } from '../ast' import { createCompilerError, ErrorCodes } from '../errors' import { processExpression } from './transformExpression' import { validateBrowserExpression } from '../validateExpression' import { CREATE_BLOCK, FRAGMENT, CREATE_COMMENT, OPEN_BLOCK } from '../runtimeHelpers' import { injectProp, findDir, findProp } from '../utils' import { PatchFlags, PatchFlagNames } from '@vue/shared' export const transformIf = createStructuralDirectiveTransform( /^(if|else|else-if)$/, (node, dir, context) => { return processIf(node, dir, context, (ifNode, branch, isRoot) => { // #1587: We need to dynamically increment the key based on the current // node's sibling nodes, since chained v-if/else branches are // rendered at the same depth const siblings = context.parent!.children let i = siblings.indexOf(ifNode) let key = 0 while (i-- >= 0) { const sibling = siblings[i] if (sibling && sibling.type === NodeTypes.IF) { key += sibling.branches.length } } // Exit callback. Complete the codegenNode when all children have been // transformed. return () => { if (isRoot) { ifNode.codegenNode = createCodegenNodeForBranch( branch, key, context ) as IfConditionalExpression } else { // attach this branch's codegen node to the v-if root. const parentCondition = getParentCondition(ifNode.codegenNode!) parentCondition.alternate = createCodegenNodeForBranch( branch, key + ifNode.branches.length - 1, context ) } } }) } ) // target-agnostic transform used for both Client and SSR export function processIf( node: ElementNode, dir: DirectiveNode, context: TransformContext, processCodegen?: ( node: IfNode, branch: IfBranchNode, isRoot: boolean ) => (() => void) | undefined ) { if ( dir.name !== 'else' && (!dir.exp || !(dir.exp as SimpleExpressionNode).content.trim()) ) { const loc = dir.exp ? dir.exp.loc : node.loc context.onError( createCompilerError(ErrorCodes.X_V_IF_NO_EXPRESSION, dir.loc) ) dir.exp = createSimpleExpression(`true`, false, loc) } if (!__BROWSER__ && context.prefixIdentifiers && dir.exp) { // dir.exp can only be simple expression because vIf transform is applied // before expression transform. dir.exp = processExpression(dir.exp as SimpleExpressionNode, context) } if (__DEV__ && __BROWSER__ && dir.exp) { validateBrowserExpression(dir.exp as SimpleExpressionNode, context) } if (dir.name === 'if') { const branch = createIfBranch(node, dir) const ifNode: IfNode = { type: NodeTypes.IF, loc: node.loc, branches: [branch] } context.replaceNode(ifNode) if (processCodegen) { return processCodegen(ifNode, branch, true) } } else { // locate the adjacent v-if const siblings = context.parent!.children const comments = [] let i = siblings.indexOf(node) while (i-- >= -1) { const sibling = siblings[i] if (__DEV__ && sibling && sibling.type === NodeTypes.COMMENT) { context.removeNode(sibling) comments.unshift(sibling) continue } if ( sibling && sibling.type === NodeTypes.TEXT && !sibling.content.trim().length ) { context.removeNode(sibling) continue } if (sibling && sibling.type === NodeTypes.IF) { // move the node to the if node's branches context.removeNode() const branch = createIfBranch(node, dir) if (__DEV__ && comments.length) { branch.children = [...comments, ...branch.children] } // check if user is forcing same key on different branches if (__DEV__ || !__BROWSER__) { const key = branch.userKey if (key) { sibling.branches.forEach(({ userKey }) => { if (isSameKey(userKey, key)) { context.onError( createCompilerError( ErrorCodes.X_V_IF_SAME_KEY, branch.userKey!.loc ) ) } }) } } sibling.branches.push(branch) const onExit = processCodegen && processCodegen(sibling, branch, false) // since the branch was removed, it will not be traversed. // make sure to traverse here. traverseNode(branch, context) // call on exit if (onExit) onExit() // make sure to reset currentNode after traversal to indicate this // node has been removed. context.currentNode = null } else { context.onError( createCompilerError(ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, node.loc) ) } break } } } function createIfBranch(node: ElementNode, dir: DirectiveNode): IfBranchNode { return { type: NodeTypes.IF_BRANCH, loc: node.loc, condition: dir.name === 'else' ? undefined : dir.exp, children: node.tagType === ElementTypes.TEMPLATE && !findDir(node, 'for') ? node.children : [node], userKey: findProp(node, `key`) } } function createCodegenNodeForBranch( branch: IfBranchNode, keyIndex: number, context: TransformContext ): IfConditionalExpression | BlockCodegenNode { if (branch.condition) { return createConditionalExpression( branch.condition, createChildrenCodegenNode(branch, keyIndex, context), // make sure to pass in asBlock: true so that the comment node call // closes the current block. createCallExpression(context.helper(CREATE_COMMENT), [ __DEV__ ? '"v-if"' : '""', 'true' ]) ) as IfConditionalExpression } else { return createChildrenCodegenNode(branch, keyIndex, context) } } function createChildrenCodegenNode( branch: IfBranchNode, keyIndex: number, context: TransformContext ): BlockCodegenNode { const { helper } = context const keyProperty = createObjectProperty( `key`, createSimpleExpression( `${keyIndex}`, false, locStub, ConstantTypes.CAN_HOIST ) ) const { children } = branch const firstChild = children[0] const needFragmentWrapper = children.length !== 1 || firstChild.type !== NodeTypes.ELEMENT if (needFragmentWrapper) { if (children.length === 1 && firstChild.type === NodeTypes.FOR) { // optimize away nested fragments when child is a ForNode const vnodeCall = firstChild.codegenNode! injectProp(vnodeCall, keyProperty, context) return vnodeCall } else { return createVNodeCall( context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, `${PatchFlags.STABLE_FRAGMENT} /* ${ PatchFlagNames[PatchFlags.STABLE_FRAGMENT] } */`, undefined, undefined, true, false, branch.loc ) } } else { const vnodeCall = (firstChild as ElementNode) .codegenNode as BlockCodegenNode // Change createVNode to createBlock. if (vnodeCall.type === NodeTypes.VNODE_CALL) { vnodeCall.isBlock = true helper(OPEN_BLOCK) helper(CREATE_BLOCK) } // inject branch key injectProp(vnodeCall, keyProperty, context) return vnodeCall } } function isSameKey( a: AttributeNode | DirectiveNode | undefined, b: AttributeNode | DirectiveNode ): boolean { if (!a || a.type !== b.type) { return false } if (a.type === NodeTypes.ATTRIBUTE) { if (a.value!.content !== (b as AttributeNode).value!.content) { return false } } else { // directive const exp = a.exp! const branchExp = (b as DirectiveNode).exp! if (exp.type !== branchExp.type) { return false } if ( exp.type !== NodeTypes.SIMPLE_EXPRESSION || (exp.isStatic !== (branchExp as SimpleExpressionNode).isStatic || exp.content !== (branchExp as SimpleExpressionNode).content) ) { return false } } return true } function getParentCondition( node: IfConditionalExpression | CacheExpression ): IfConditionalExpression { while (true) { if (node.type === NodeTypes.JS_CONDITIONAL_EXPRESSION) { if (node.alternate.type === NodeTypes.JS_CONDITIONAL_EXPRESSION) { node = node.alternate } else { return node } } else if (node.type === NodeTypes.JS_CACHE_EXPRESSION) { node = node.value as IfConditionalExpression } } }
packages/compiler-core/src/transforms/vIf.ts
1
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.0022189344745129347, 0.0003720753884408623, 0.00016537185001652688, 0.00017132124048657715, 0.000530557706952095 ]
{ "id": 1, "code_window": [ " context,\n", " helper(FRAGMENT),\n", " undefined,\n", " renderExp,\n", " `${fragmentFlag} /* ${PatchFlagNames[fragmentFlag]} */`,\n", " undefined,\n", " undefined,\n", " true /* isBlock */,\n", " !isStableFragment /* disableTracking */,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " fragmentFlag +\n", " (__DEV__ ? ` /* ${PatchFlagNames[fragmentFlag]} */` : ``),\n" ], "file_path": "packages/compiler-core/src/transforms/vFor.ts", "type": "replace", "edit_start_line_idx": 90 }
import { baseParse } from '../src/parse' import { transform, NodeTransform } from '../src/transform' import { ElementNode, NodeTypes, DirectiveNode, ExpressionNode, VNodeCall } from '../src/ast' import { ErrorCodes, createCompilerError } from '../src/errors' import { TO_DISPLAY_STRING, FRAGMENT, RENDER_SLOT, CREATE_COMMENT } from '../src/runtimeHelpers' import { transformIf } from '../src/transforms/vIf' import { transformFor } from '../src/transforms/vFor' import { transformElement } from '../src/transforms/transformElement' import { transformSlotOutlet } from '../src/transforms/transformSlotOutlet' import { transformText } from '../src/transforms/transformText' import { genFlagText } from './testUtils' import { PatchFlags } from '@vue/shared' describe('compiler: transform', () => { test('context state', () => { const ast = baseParse(`<div>hello {{ world }}</div>`) // manually store call arguments because context is mutable and shared // across calls const calls: any[] = [] const plugin: NodeTransform = (node, context) => { calls.push([node, { ...context }]) } transform(ast, { nodeTransforms: [plugin] }) const div = ast.children[0] as ElementNode expect(calls.length).toBe(4) expect(calls[0]).toMatchObject([ ast, { parent: null, currentNode: ast } ]) expect(calls[1]).toMatchObject([ div, { parent: ast, currentNode: div } ]) expect(calls[2]).toMatchObject([ div.children[0], { parent: div, currentNode: div.children[0] } ]) expect(calls[3]).toMatchObject([ div.children[1], { parent: div, currentNode: div.children[1] } ]) }) test('context.replaceNode', () => { const ast = baseParse(`<div/><span/>`) const plugin: NodeTransform = (node, context) => { if (node.type === NodeTypes.ELEMENT && node.tag === 'div') { // change the node to <p> context.replaceNode( Object.assign({}, node, { tag: 'p', children: [ { type: NodeTypes.TEXT, content: 'hello', isEmpty: false } ] }) ) } } const spy = jest.fn(plugin) transform(ast, { nodeTransforms: [spy] }) expect(ast.children.length).toBe(2) const newElement = ast.children[0] as ElementNode expect(newElement.tag).toBe('p') expect(spy).toHaveBeenCalledTimes(4) // should traverse the children of replaced node expect(spy.mock.calls[2][0]).toBe(newElement.children[0]) // should traverse the node after the replaced node expect(spy.mock.calls[3][0]).toBe(ast.children[1]) }) test('context.removeNode', () => { const ast = baseParse(`<span/><div>hello</div><span/>`) const c1 = ast.children[0] const c2 = ast.children[2] const plugin: NodeTransform = (node, context) => { if (node.type === NodeTypes.ELEMENT && node.tag === 'div') { context.removeNode() } } const spy = jest.fn(plugin) transform(ast, { nodeTransforms: [spy] }) expect(ast.children.length).toBe(2) expect(ast.children[0]).toBe(c1) expect(ast.children[1]).toBe(c2) // should not traverse children of remove node expect(spy).toHaveBeenCalledTimes(4) // should traverse nodes around removed expect(spy.mock.calls[1][0]).toBe(c1) expect(spy.mock.calls[3][0]).toBe(c2) }) test('context.removeNode (prev sibling)', () => { const ast = baseParse(`<span/><div/><span/>`) const c1 = ast.children[0] const c2 = ast.children[2] const plugin: NodeTransform = (node, context) => { if (node.type === NodeTypes.ELEMENT && node.tag === 'div') { context.removeNode() // remove previous sibling context.removeNode(context.parent!.children[0]) } } const spy = jest.fn(plugin) transform(ast, { nodeTransforms: [spy] }) expect(ast.children.length).toBe(1) expect(ast.children[0]).toBe(c2) expect(spy).toHaveBeenCalledTimes(4) // should still traverse first span before removal expect(spy.mock.calls[1][0]).toBe(c1) // should still traverse last span expect(spy.mock.calls[3][0]).toBe(c2) }) test('context.removeNode (next sibling)', () => { const ast = baseParse(`<span/><div/><span/>`) const c1 = ast.children[0] const d1 = ast.children[1] const plugin: NodeTransform = (node, context) => { if (node.type === NodeTypes.ELEMENT && node.tag === 'div') { context.removeNode() // remove next sibling context.removeNode(context.parent!.children[1]) } } const spy = jest.fn(plugin) transform(ast, { nodeTransforms: [spy] }) expect(ast.children.length).toBe(1) expect(ast.children[0]).toBe(c1) expect(spy).toHaveBeenCalledTimes(3) // should still traverse first span before removal expect(spy.mock.calls[1][0]).toBe(c1) // should not traverse last span expect(spy.mock.calls[2][0]).toBe(d1) }) test('context.hoist', () => { const ast = baseParse(`<div :id="foo"/><div :id="bar"/>`) const hoisted: ExpressionNode[] = [] const mock: NodeTransform = (node, context) => { if (node.type === NodeTypes.ELEMENT) { const dir = node.props[0] as DirectiveNode hoisted.push(dir.exp!) dir.exp = context.hoist(dir.exp!) } } transform(ast, { nodeTransforms: [mock] }) expect(ast.hoists).toMatchObject(hoisted) expect((ast as any).children[0].props[0].exp.content).toBe(`_hoisted_1`) expect((ast as any).children[1].props[0].exp.content).toBe(`_hoisted_2`) }) test('onError option', () => { const ast = baseParse(`<div/>`) const loc = ast.children[0].loc const plugin: NodeTransform = (node, context) => { context.onError( createCompilerError(ErrorCodes.X_INVALID_END_TAG, node.loc) ) } const spy = jest.fn() transform(ast, { nodeTransforms: [plugin], onError: spy }) expect(spy.mock.calls[0]).toMatchObject([ { code: ErrorCodes.X_INVALID_END_TAG, loc } ]) }) test('should inject toString helper for interpolations', () => { const ast = baseParse(`{{ foo }}`) transform(ast, {}) expect(ast.helpers).toContain(TO_DISPLAY_STRING) }) test('should inject createVNode and Comment for comments', () => { const ast = baseParse(`<!--foo-->`) transform(ast, {}) expect(ast.helpers).toContain(CREATE_COMMENT) }) describe('root codegenNode', () => { function transformWithCodegen(template: string) { const ast = baseParse(template) transform(ast, { nodeTransforms: [ transformIf, transformFor, transformText, transformSlotOutlet, transformElement ] }) return ast } function createBlockMatcher( tag: VNodeCall['tag'], props?: VNodeCall['props'], children?: VNodeCall['children'], patchFlag?: VNodeCall['patchFlag'] ) { return { type: NodeTypes.VNODE_CALL, isBlock: true, tag, props, children, patchFlag } } test('no children', () => { const ast = transformWithCodegen(``) expect(ast.codegenNode).toBeUndefined() }) test('single <slot/>', () => { const ast = transformWithCodegen(`<slot/>`) expect(ast.codegenNode).toMatchObject({ codegenNode: { type: NodeTypes.JS_CALL_EXPRESSION, callee: RENDER_SLOT } }) }) test('single element', () => { const ast = transformWithCodegen(`<div/>`) expect(ast.codegenNode).toMatchObject(createBlockMatcher(`"div"`)) }) test('root v-if', () => { const ast = transformWithCodegen(`<div v-if="ok" />`) expect(ast.codegenNode).toMatchObject({ type: NodeTypes.IF }) }) test('root v-for', () => { const ast = transformWithCodegen(`<div v-for="i in list" />`) expect(ast.codegenNode).toMatchObject({ type: NodeTypes.FOR }) }) test('root element with custom directive', () => { const ast = transformWithCodegen(`<div v-foo/>`) expect(ast.codegenNode).toMatchObject({ type: NodeTypes.VNODE_CALL, directives: { type: NodeTypes.JS_ARRAY_EXPRESSION } }) }) test('single text', () => { const ast = transformWithCodegen(`hello`) expect(ast.codegenNode).toMatchObject({ type: NodeTypes.TEXT }) }) test('single interpolation', () => { const ast = transformWithCodegen(`{{ foo }}`) expect(ast.codegenNode).toMatchObject({ type: NodeTypes.INTERPOLATION }) }) test('single CompoundExpression', () => { const ast = transformWithCodegen(`{{ foo }} bar baz`) expect(ast.codegenNode).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION }) }) test('multiple children', () => { const ast = transformWithCodegen(`<div/><div/>`) expect(ast.codegenNode).toMatchObject( createBlockMatcher( FRAGMENT, undefined, [ { type: NodeTypes.ELEMENT, tag: `div` }, { type: NodeTypes.ELEMENT, tag: `div` } ] as any, genFlagText(PatchFlags.STABLE_FRAGMENT) ) ) }) test('multiple children w/ single root + comments', () => { const ast = transformWithCodegen(`<!--foo--><div/><!--bar-->`) expect(ast.codegenNode).toMatchObject( createBlockMatcher( FRAGMENT, undefined, [ { type: NodeTypes.COMMENT }, { type: NodeTypes.ELEMENT, tag: `div` }, { type: NodeTypes.COMMENT } ] as any, genFlagText([ PatchFlags.STABLE_FRAGMENT, PatchFlags.DEV_ROOT_FRAGMENT ]) ) ) }) }) })
packages/compiler-core/__tests__/transform.spec.ts
0
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.00195958255790174, 0.00025177912903018296, 0.0001632788626011461, 0.00017196314001921564, 0.0003113620332442224 ]
{ "id": 1, "code_window": [ " context,\n", " helper(FRAGMENT),\n", " undefined,\n", " renderExp,\n", " `${fragmentFlag} /* ${PatchFlagNames[fragmentFlag]} */`,\n", " undefined,\n", " undefined,\n", " true /* isBlock */,\n", " !isStableFragment /* disableTracking */,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " fragmentFlag +\n", " (__DEV__ ? ` /* ${PatchFlagNames[fragmentFlag]} */` : ``),\n" ], "file_path": "packages/compiler-core/src/transforms/vFor.ts", "type": "replace", "edit_start_line_idx": 90 }
import { RootNode, BlockStatement, TemplateLiteral, createCallExpression, createTemplateLiteral, NodeTypes, TemplateChildNode, ElementTypes, createBlockStatement, CompilerOptions, IfStatement, CallExpression, isText, processExpression, createSimpleExpression, createCompoundExpression, createTransformContext, createRoot } from '@vue/compiler-dom' import { isString, escapeHtml } from '@vue/shared' import { SSR_INTERPOLATE, ssrHelpers } from './runtimeHelpers' import { ssrProcessIf } from './transforms/ssrVIf' import { ssrProcessFor } from './transforms/ssrVFor' import { ssrProcessSlotOutlet } from './transforms/ssrTransformSlotOutlet' import { ssrProcessComponent } from './transforms/ssrTransformComponent' import { ssrProcessElement } from './transforms/ssrTransformElement' import { createSSRCompilerError, SSRErrorCodes } from './errors' // Because SSR codegen output is completely different from client-side output // (e.g. multiple elements can be concatenated into a single template literal // instead of each getting a corresponding call), we need to apply an extra // transform pass to convert the template AST into a fresh JS AST before // passing it to codegen. export function ssrCodegenTransform(ast: RootNode, options: CompilerOptions) { const context = createSSRTransformContext(ast, options) // inject SFC <style> CSS variables // we do this instead of inlining the expression to ensure the vars are // only resolved once per render if (options.ssrCssVars) { const varsExp = processExpression( createSimpleExpression(options.ssrCssVars, false), createTransformContext(createRoot([]), options) ) context.body.push( createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`]) ) } const isFragment = ast.children.length > 1 && ast.children.some(c => !isText(c)) processChildren(ast.children, context, isFragment) ast.codegenNode = createBlockStatement(context.body) // Finalize helpers. // We need to separate helpers imported from 'vue' vs. '@vue/server-renderer' ast.ssrHelpers = [ ...ast.helpers.filter(h => h in ssrHelpers), ...context.helpers ] ast.helpers = ast.helpers.filter(h => !(h in ssrHelpers)) } export type SSRTransformContext = ReturnType<typeof createSSRTransformContext> function createSSRTransformContext( root: RootNode, options: CompilerOptions, helpers: Set<symbol> = new Set(), withSlotScopeId = false ) { const body: BlockStatement['body'] = [] let currentString: TemplateLiteral | null = null return { root, options, body, helpers, withSlotScopeId, onError: options.onError || (e => { throw e }), helper<T extends symbol>(name: T): T { helpers.add(name) return name }, pushStringPart(part: TemplateLiteral['elements'][0]) { if (!currentString) { const currentCall = createCallExpression(`_push`) body.push(currentCall) currentString = createTemplateLiteral([]) currentCall.arguments.push(currentString) } const bufferedElements = currentString.elements const lastItem = bufferedElements[bufferedElements.length - 1] if (isString(part) && isString(lastItem)) { bufferedElements[bufferedElements.length - 1] += part } else { bufferedElements.push(part) } }, pushStatement(statement: IfStatement | CallExpression) { // close current string currentString = null body.push(statement) } } } function createChildContext( parent: SSRTransformContext, withSlotScopeId = parent.withSlotScopeId ): SSRTransformContext { // ensure child inherits parent helpers return createSSRTransformContext( parent.root, parent.options, parent.helpers, withSlotScopeId ) } export function processChildren( children: TemplateChildNode[], context: SSRTransformContext, asFragment = false, disableNestedFragments = false ) { if (asFragment) { context.pushStringPart(`<!--[-->`) } for (let i = 0; i < children.length; i++) { const child = children[i] switch (child.type) { case NodeTypes.ELEMENT: switch (child.tagType) { case ElementTypes.ELEMENT: ssrProcessElement(child, context) break case ElementTypes.COMPONENT: ssrProcessComponent(child, context) break case ElementTypes.SLOT: ssrProcessSlotOutlet(child, context) break case ElementTypes.TEMPLATE: // TODO break default: context.onError( createSSRCompilerError( SSRErrorCodes.X_SSR_INVALID_AST_NODE, (child as any).loc ) ) // make sure we exhaust all possible types const exhaustiveCheck: never = child return exhaustiveCheck } break case NodeTypes.TEXT: context.pushStringPart(escapeHtml(child.content)) break case NodeTypes.COMMENT: // no need to escape comment here because the AST can only // contain valid comments. context.pushStringPart(`<!--${child.content}-->`) break case NodeTypes.INTERPOLATION: context.pushStringPart( createCallExpression(context.helper(SSR_INTERPOLATE), [child.content]) ) break case NodeTypes.IF: ssrProcessIf(child, context, disableNestedFragments) break case NodeTypes.FOR: ssrProcessFor(child, context, disableNestedFragments) break case NodeTypes.IF_BRANCH: // no-op - handled by ssrProcessIf break case NodeTypes.TEXT_CALL: case NodeTypes.COMPOUND_EXPRESSION: // no-op - these two types can never appear as template child node since // `transformText` is not used during SSR compile. break default: context.onError( createSSRCompilerError( SSRErrorCodes.X_SSR_INVALID_AST_NODE, (child as any).loc ) ) // make sure we exhaust all possible types const exhaustiveCheck: never = child return exhaustiveCheck } } if (asFragment) { context.pushStringPart(`<!--]-->`) } } export function processChildrenAsStatement( children: TemplateChildNode[], parentContext: SSRTransformContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId ): BlockStatement { const childContext = createChildContext(parentContext, withSlotScopeId) processChildren(children, childContext, asFragment) return createBlockStatement(childContext.body) }
packages/compiler-ssr/src/ssrCodegenTransform.ts
0
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.0037075665313750505, 0.0004839177126996219, 0.0001659408153500408, 0.00017500741523690522, 0.0007779311272315681 ]
{ "id": 1, "code_window": [ " context,\n", " helper(FRAGMENT),\n", " undefined,\n", " renderExp,\n", " `${fragmentFlag} /* ${PatchFlagNames[fragmentFlag]} */`,\n", " undefined,\n", " undefined,\n", " true /* isBlock */,\n", " !isStableFragment /* disableTracking */,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " fragmentFlag +\n", " (__DEV__ ? ` /* ${PatchFlagNames[fragmentFlag]} */` : ``),\n" ], "file_path": "packages/compiler-core/src/transforms/vFor.ts", "type": "replace", "edit_start_line_idx": 90 }
import { baseParse as parse, transform, ElementNode, DirectiveNode, NodeTypes, CompilerOptions, InterpolationNode, ConstantTypes } from '../../src' import { transformIf } from '../../src/transforms/vIf' import { transformExpression } from '../../src/transforms/transformExpression' function parseWithExpressionTransform( template: string, options: CompilerOptions = {} ) { const ast = parse(template) transform(ast, { prefixIdentifiers: true, nodeTransforms: [transformIf, transformExpression], ...options }) return ast.children[0] } describe('compiler: expression transform', () => { test('interpolation (root)', () => { const node = parseWithExpressionTransform(`{{ foo }}`) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.SIMPLE_EXPRESSION, content: `_ctx.foo` }) }) test('empty interpolation', () => { const node = parseWithExpressionTransform(`{{}}`) as InterpolationNode const node2 = parseWithExpressionTransform(`{{ }}`) as InterpolationNode const node3 = parseWithExpressionTransform( `<div>{{ }}</div>` ) as ElementNode const objectToBeMatched = { type: NodeTypes.SIMPLE_EXPRESSION, content: `` } expect(node.content).toMatchObject(objectToBeMatched) expect(node2.content).toMatchObject(objectToBeMatched) expect((node3.children[0] as InterpolationNode).content).toMatchObject( objectToBeMatched ) }) test('interpolation (children)', () => { const el = parseWithExpressionTransform( `<div>{{ foo }}</div>` ) as ElementNode const node = el.children[0] as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.SIMPLE_EXPRESSION, content: `_ctx.foo` }) }) test('interpolation (complex)', () => { const el = parseWithExpressionTransform( `<div>{{ foo + bar(baz.qux) }}</div>` ) as ElementNode const node = el.children[0] as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ { content: `_ctx.foo` }, ` + `, { content: `_ctx.bar` }, `(`, { content: `_ctx.baz` }, `.`, { content: `qux` }, `)` ] }) }) test('directive value', () => { const node = parseWithExpressionTransform( `<div v-foo:arg="baz"/>` ) as ElementNode const arg = (node.props[0] as DirectiveNode).arg! expect(arg).toMatchObject({ type: NodeTypes.SIMPLE_EXPRESSION, content: `arg` }) const exp = (node.props[0] as DirectiveNode).exp! expect(exp).toMatchObject({ type: NodeTypes.SIMPLE_EXPRESSION, content: `_ctx.baz` }) }) test('dynamic directive arg', () => { const node = parseWithExpressionTransform( `<div v-foo:[arg]="baz"/>` ) as ElementNode const arg = (node.props[0] as DirectiveNode).arg! expect(arg).toMatchObject({ type: NodeTypes.SIMPLE_EXPRESSION, content: `_ctx.arg` }) const exp = (node.props[0] as DirectiveNode).exp! expect(exp).toMatchObject({ type: NodeTypes.SIMPLE_EXPRESSION, content: `_ctx.baz` }) }) test('should prefix complex expressions', () => { const node = parseWithExpressionTransform( `{{ foo(baz + 1, { key: kuz }) }}` ) as InterpolationNode // should parse into compound expression expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ { content: `_ctx.foo`, loc: { source: `foo`, start: { offset: 3, line: 1, column: 4 }, end: { offset: 6, line: 1, column: 7 } } }, `(`, { content: `_ctx.baz`, loc: { source: `baz`, start: { offset: 7, line: 1, column: 8 }, end: { offset: 10, line: 1, column: 11 } } }, ` + 1, { key: `, { content: `_ctx.kuz`, loc: { source: `kuz`, start: { offset: 23, line: 1, column: 24 }, end: { offset: 26, line: 1, column: 27 } } }, ` })` ] }) }) test('should not prefix whitelisted globals', () => { const node = parseWithExpressionTransform( `{{ Math.max(1, 2) }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [{ content: `Math` }, `.`, { content: `max` }, `(1, 2)`] }) }) test('should not prefix reserved literals', () => { function assert(exp: string) { const node = parseWithExpressionTransform( `{{ ${exp} }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.SIMPLE_EXPRESSION, content: exp }) } assert(`true`) assert(`false`) assert(`null`) assert(`this`) }) test('should not prefix id of a function declaration', () => { const node = parseWithExpressionTransform( `{{ function foo() { return bar } }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ `function `, { content: `foo` }, `() { return `, { content: `_ctx.bar` }, ` }` ] }) }) test('should not prefix params of a function expression', () => { const node = parseWithExpressionTransform( `{{ foo => foo + bar }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ { content: `foo` }, ` => `, { content: `foo` }, ` + `, { content: `_ctx.bar` } ] }) }) test('should prefix default value of a function expression param', () => { const node = parseWithExpressionTransform( `{{ (foo = baz) => foo + bar }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ `(`, { content: `foo` }, ` = `, { content: `_ctx.baz` }, `) => `, { content: `foo` }, ` + `, { content: `_ctx.bar` } ] }) }) test('should not prefix function param destructuring', () => { const node = parseWithExpressionTransform( `{{ ({ foo }) => foo + bar }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ `({ `, { content: `foo` }, ` }) => `, { content: `foo` }, ` + `, { content: `_ctx.bar` } ] }) }) test('function params should not affect out of scope identifiers', () => { const node = parseWithExpressionTransform( `{{ { a: foo => foo, b: foo } }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ `{ a: `, { content: `foo` }, ` => `, { content: `foo` }, `, b: `, { content: `_ctx.foo` }, ` }` ] }) }) test('should prefix default value of function param destructuring', () => { const node = parseWithExpressionTransform( `{{ ({ foo = bar }) => foo + bar }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ `({ `, { content: `foo` }, ` = `, { content: `_ctx.bar` }, ` }) => `, { content: `foo` }, ` + `, { content: `_ctx.bar` } ] }) }) test('should not prefix an object property key', () => { const node = parseWithExpressionTransform( `{{ { foo() { baz() }, value: bar } }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ `{ foo() { `, { content: `_ctx.baz` }, `() }, value: `, { content: `_ctx.bar` }, ` }` ] }) }) test('should not duplicate object key with same name as value', () => { const node = parseWithExpressionTransform( `{{ { foo: foo } }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [`{ foo: `, { content: `_ctx.foo` }, ` }`] }) }) test('should prefix a computed object property key', () => { const node = parseWithExpressionTransform( `{{ { [foo]: bar } }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ `{ [`, { content: `_ctx.foo` }, `]: `, { content: `_ctx.bar` }, ` }` ] }) }) test('should prefix object property shorthand value', () => { const node = parseWithExpressionTransform( `{{ { foo } }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [`{ foo: `, { content: `_ctx.foo` }, ` }`] }) }) test('should not prefix id in a member expression', () => { const node = parseWithExpressionTransform( `{{ foo.bar.baz }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ { content: `_ctx.foo` }, `.`, { content: `bar` }, `.`, { content: `baz` } ] }) }) test('should prefix computed id in a member expression', () => { const node = parseWithExpressionTransform( `{{ foo[bar][baz] }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ { content: `_ctx.foo` }, `[`, { content: `_ctx.bar` }, `][`, { content: '_ctx.baz' }, `]` ] }) }) test('should handle parse error', () => { const onError = jest.fn() parseWithExpressionTransform(`{{ a( }}`, { onError }) expect(onError.mock.calls[0][0].message).toMatch( `Error parsing JavaScript expression: Unexpected token` ) }) describe('ES Proposals support', () => { test('bigInt', () => { const node = parseWithExpressionTransform( `{{ 13000n }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.SIMPLE_EXPRESSION, content: `13000n`, isStatic: false, constType: ConstantTypes.CAN_STRINGIFY }) }) test('nullish coalescing', () => { const node = parseWithExpressionTransform( `{{ a ?? b }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [{ content: `_ctx.a` }, ` ?? `, { content: `_ctx.b` }] }) }) test('optional chaining', () => { const node = parseWithExpressionTransform( `{{ a?.b?.c }}` ) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [ { content: `_ctx.a` }, `?.`, { content: `b` }, `?.`, { content: `c` } ] }) }) test('Enabling additional plugins', () => { // enabling pipeline operator to replace filters: const node = parseWithExpressionTransform(`{{ a |> uppercase }}`, { expressionPlugins: [ [ 'pipelineOperator', { proposal: 'minimal' } ] ] }) as InterpolationNode expect(node.content).toMatchObject({ type: NodeTypes.COMPOUND_EXPRESSION, children: [{ content: `_ctx.a` }, ` |> `, { content: `_ctx.uppercase` }] }) }) }) })
packages/compiler-core/__tests__/transforms/transformExpressions.spec.ts
0
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.0001745906047290191, 0.00017110547923948616, 0.00016658319509588182, 0.00017130655760411173, 0.0000017287964055867633 ]
{ "id": 2, "code_window": [ " context,\n", " helper(FRAGMENT),\n", " keyProperty ? createObjectExpression([keyProperty]) : undefined,\n", " node.children,\n", " `${PatchFlags.STABLE_FRAGMENT} /* ${\n", " PatchFlagNames[PatchFlags.STABLE_FRAGMENT]\n", " } */`,\n", " undefined,\n", " undefined,\n", " true\n", " )\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " PatchFlags.STABLE_FRAGMENT +\n", " (__DEV__\n", " ? ` /* ${PatchFlagNames[PatchFlags.STABLE_FRAGMENT]} */`\n", " : ``),\n" ], "file_path": "packages/compiler-core/src/transforms/vFor.ts", "type": "replace", "edit_start_line_idx": 149 }
import { createStructuralDirectiveTransform, TransformContext } from '../transform' import { NodeTypes, ExpressionNode, createSimpleExpression, SourceLocation, SimpleExpressionNode, createCallExpression, createFunctionExpression, createObjectExpression, createObjectProperty, ForCodegenNode, RenderSlotCall, SlotOutletNode, ElementNode, DirectiveNode, ForNode, PlainElementNode, createVNodeCall, VNodeCall, ForRenderListExpression, BlockCodegenNode, ForIteratorExpression } from '../ast' import { createCompilerError, ErrorCodes } from '../errors' import { getInnerRange, findProp, isTemplateNode, isSlotOutlet, injectProp } from '../utils' import { RENDER_LIST, OPEN_BLOCK, CREATE_BLOCK, FRAGMENT } from '../runtimeHelpers' import { processExpression } from './transformExpression' import { validateBrowserExpression } from '../validateExpression' import { PatchFlags, PatchFlagNames } from '@vue/shared' export const transformFor = createStructuralDirectiveTransform( 'for', (node, dir, context) => { const { helper } = context return processFor(node, dir, context, forNode => { // create the loop render function expression now, and add the // iterator on exit after all children have been traversed const renderExp = createCallExpression(helper(RENDER_LIST), [ forNode.source ]) as ForRenderListExpression const keyProp = findProp(node, `key`) const keyProperty = keyProp ? createObjectProperty( `key`, keyProp.type === NodeTypes.ATTRIBUTE ? createSimpleExpression(keyProp.value!.content, true) : keyProp.exp! ) : null if (!__BROWSER__ && context.prefixIdentifiers && keyProperty) { // #2085 process :key expression needs to be processed in order for it // to behave consistently for <template v-for> and <div v-for>. // In the case of `<template v-for>`, the node is discarded and never // traversed so its key expression won't be processed by the normal // transforms. keyProperty.value = processExpression( keyProperty.value as SimpleExpressionNode, context ) } const isStableFragment = forNode.source.type === NodeTypes.SIMPLE_EXPRESSION && forNode.source.constType > 0 const fragmentFlag = isStableFragment ? PatchFlags.STABLE_FRAGMENT : keyProp ? PatchFlags.KEYED_FRAGMENT : PatchFlags.UNKEYED_FRAGMENT forNode.codegenNode = createVNodeCall( context, helper(FRAGMENT), undefined, renderExp, `${fragmentFlag} /* ${PatchFlagNames[fragmentFlag]} */`, undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc ) as ForCodegenNode return () => { // finish the codegen now that all children have been traversed let childBlock: BlockCodegenNode const isTemplate = isTemplateNode(node) const { children } = forNode // check <template v-for> key placement if ((__DEV__ || !__BROWSER__) && isTemplate) { node.children.some(c => { if (c.type === NodeTypes.ELEMENT) { const key = findProp(c, 'key') if (key) { context.onError( createCompilerError( ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT, key.loc ) ) return true } } }) } const needFragmentWrapper = children.length !== 1 || children[0].type !== NodeTypes.ELEMENT const slotOutlet = isSlotOutlet(node) ? node : isTemplate && node.children.length === 1 && isSlotOutlet(node.children[0]) ? (node.children[0] as SlotOutletNode) // api-extractor somehow fails to infer this : null if (slotOutlet) { // <slot v-for="..."> or <template v-for="..."><slot/></template> childBlock = slotOutlet.codegenNode as RenderSlotCall if (isTemplate && keyProperty) { // <template v-for="..." :key="..."><slot/></template> // we need to inject the key to the renderSlot() call. // the props for renderSlot is passed as the 3rd argument. injectProp(childBlock, keyProperty, context) } } else if (needFragmentWrapper) { // <template v-for="..."> with text or multi-elements // should generate a fragment block for each loop childBlock = createVNodeCall( context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, `${PatchFlags.STABLE_FRAGMENT} /* ${ PatchFlagNames[PatchFlags.STABLE_FRAGMENT] } */`, undefined, undefined, true ) } else { // Normal element v-for. Directly use the child's codegenNode // but mark it as a block. childBlock = (children[0] as PlainElementNode) .codegenNode as VNodeCall if (isTemplate && keyProperty) { injectProp(childBlock, keyProperty, context) } childBlock.isBlock = !isStableFragment if (childBlock.isBlock) { helper(OPEN_BLOCK) helper(CREATE_BLOCK) } } renderExp.arguments.push(createFunctionExpression( createForLoopParams(forNode.parseResult), childBlock, true /* force newline */ ) as ForIteratorExpression) } }) } ) // target-agnostic transform used for both Client and SSR export function processFor( node: ElementNode, dir: DirectiveNode, context: TransformContext, processCodegen?: (forNode: ForNode) => (() => void) | undefined ) { if (!dir.exp) { context.onError( createCompilerError(ErrorCodes.X_V_FOR_NO_EXPRESSION, dir.loc) ) return } const parseResult = parseForExpression( // can only be simple expression because vFor transform is applied // before expression transform. dir.exp as SimpleExpressionNode, context ) if (!parseResult) { context.onError( createCompilerError(ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION, dir.loc) ) return } const { addIdentifiers, removeIdentifiers, scopes } = context const { source, value, key, index } = parseResult const forNode: ForNode = { type: NodeTypes.FOR, loc: dir.loc, source, valueAlias: value, keyAlias: key, objectIndexAlias: index, parseResult, children: isTemplateNode(node) ? node.children : [node] } context.replaceNode(forNode) // bookkeeping scopes.vFor++ if (!__BROWSER__ && context.prefixIdentifiers) { // scope management // inject identifiers to context value && addIdentifiers(value) key && addIdentifiers(key) index && addIdentifiers(index) } const onExit = processCodegen && processCodegen(forNode) return () => { scopes.vFor-- if (!__BROWSER__ && context.prefixIdentifiers) { value && removeIdentifiers(value) key && removeIdentifiers(key) index && removeIdentifiers(index) } if (onExit) onExit() } } const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/ // This regex doesn't cover the case if key or index aliases have destructuring, // but those do not make sense in the first place, so this works in practice. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/ const stripParensRE = /^\(|\)$/g export interface ForParseResult { source: ExpressionNode value: ExpressionNode | undefined key: ExpressionNode | undefined index: ExpressionNode | undefined } export function parseForExpression( input: SimpleExpressionNode, context: TransformContext ): ForParseResult | undefined { const loc = input.loc const exp = input.content const inMatch = exp.match(forAliasRE) if (!inMatch) return const [, LHS, RHS] = inMatch const result: ForParseResult = { source: createAliasExpression( loc, RHS.trim(), exp.indexOf(RHS, LHS.length) ), value: undefined, key: undefined, index: undefined } if (!__BROWSER__ && context.prefixIdentifiers) { result.source = processExpression( result.source as SimpleExpressionNode, context ) } if (__DEV__ && __BROWSER__) { validateBrowserExpression(result.source as SimpleExpressionNode, context) } let valueContent = LHS.trim() .replace(stripParensRE, '') .trim() const trimmedOffset = LHS.indexOf(valueContent) const iteratorMatch = valueContent.match(forIteratorRE) if (iteratorMatch) { valueContent = valueContent.replace(forIteratorRE, '').trim() const keyContent = iteratorMatch[1].trim() let keyOffset: number | undefined if (keyContent) { keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length) result.key = createAliasExpression(loc, keyContent, keyOffset) if (!__BROWSER__ && context.prefixIdentifiers) { result.key = processExpression(result.key, context, true) } if (__DEV__ && __BROWSER__) { validateBrowserExpression( result.key as SimpleExpressionNode, context, true ) } } if (iteratorMatch[2]) { const indexContent = iteratorMatch[2].trim() if (indexContent) { result.index = createAliasExpression( loc, indexContent, exp.indexOf( indexContent, result.key ? keyOffset! + keyContent.length : trimmedOffset + valueContent.length ) ) if (!__BROWSER__ && context.prefixIdentifiers) { result.index = processExpression(result.index, context, true) } if (__DEV__ && __BROWSER__) { validateBrowserExpression( result.index as SimpleExpressionNode, context, true ) } } } } if (valueContent) { result.value = createAliasExpression(loc, valueContent, trimmedOffset) if (!__BROWSER__ && context.prefixIdentifiers) { result.value = processExpression(result.value, context, true) } if (__DEV__ && __BROWSER__) { validateBrowserExpression( result.value as SimpleExpressionNode, context, true ) } } return result } function createAliasExpression( range: SourceLocation, content: string, offset: number ): SimpleExpressionNode { return createSimpleExpression( content, false, getInnerRange(range, offset, content.length) ) } export function createForLoopParams({ value, key, index }: ForParseResult): ExpressionNode[] { const params: ExpressionNode[] = [] if (value) { params.push(value) } if (key) { if (!value) { params.push(createSimpleExpression(`_`, false)) } params.push(key) } if (index) { if (!key) { if (!value) { params.push(createSimpleExpression(`_`, false)) } params.push(createSimpleExpression(`__`, false)) } params.push(index) } return params }
packages/compiler-core/src/transforms/vFor.ts
1
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.9901812076568604, 0.03556380048394203, 0.00016366448835469782, 0.00019748890190385282, 0.1630537062883377 ]
{ "id": 2, "code_window": [ " context,\n", " helper(FRAGMENT),\n", " keyProperty ? createObjectExpression([keyProperty]) : undefined,\n", " node.children,\n", " `${PatchFlags.STABLE_FRAGMENT} /* ${\n", " PatchFlagNames[PatchFlags.STABLE_FRAGMENT]\n", " } */`,\n", " undefined,\n", " undefined,\n", " true\n", " )\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " PatchFlags.STABLE_FRAGMENT +\n", " (__DEV__\n", " ? ` /* ${PatchFlagNames[PatchFlags.STABLE_FRAGMENT]} */`\n", " : ``),\n" ], "file_path": "packages/compiler-core/src/transforms/vFor.ts", "type": "replace", "edit_start_line_idx": 149 }
import { SourceLocation } from './ast' export interface CompilerError extends SyntaxError { code: number loc?: SourceLocation } export interface CoreCompilerError extends CompilerError { code: ErrorCodes } export function defaultOnError(error: CompilerError) { throw error } export function createCompilerError<T extends number>( code: T, loc?: SourceLocation, messages?: { [code: number]: string }, additionalMessage?: string ): T extends ErrorCodes ? CoreCompilerError : CompilerError { const msg = __DEV__ || !__BROWSER__ ? (messages || errorMessages)[code] + (additionalMessage || ``) : code const error = new SyntaxError(String(msg)) as CompilerError error.code = code error.loc = loc return error as any } export const enum ErrorCodes { // parse errors ABRUPT_CLOSING_OF_EMPTY_COMMENT, CDATA_IN_HTML_CONTENT, DUPLICATE_ATTRIBUTE, END_TAG_WITH_ATTRIBUTES, END_TAG_WITH_TRAILING_SOLIDUS, EOF_BEFORE_TAG_NAME, EOF_IN_CDATA, EOF_IN_COMMENT, EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT, EOF_IN_TAG, INCORRECTLY_CLOSED_COMMENT, INCORRECTLY_OPENED_COMMENT, INVALID_FIRST_CHARACTER_OF_TAG_NAME, MISSING_ATTRIBUTE_VALUE, MISSING_END_TAG_NAME, MISSING_WHITESPACE_BETWEEN_ATTRIBUTES, NESTED_COMMENT, UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME, UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE, UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME, UNEXPECTED_NULL_CHARACTER, UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME, UNEXPECTED_SOLIDUS_IN_TAG, // Vue-specific parse errors X_INVALID_END_TAG, X_MISSING_END_TAG, X_MISSING_INTERPOLATION_END, X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END, // transform errors X_V_IF_NO_EXPRESSION, X_V_IF_SAME_KEY, X_V_ELSE_NO_ADJACENT_IF, X_V_FOR_NO_EXPRESSION, X_V_FOR_MALFORMED_EXPRESSION, X_V_FOR_TEMPLATE_KEY_PLACEMENT, X_V_BIND_NO_EXPRESSION, X_V_ON_NO_EXPRESSION, X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET, X_V_SLOT_MIXED_SLOT_USAGE, X_V_SLOT_DUPLICATE_SLOT_NAMES, X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN, X_V_SLOT_MISPLACED, X_V_MODEL_NO_EXPRESSION, X_V_MODEL_MALFORMED_EXPRESSION, X_V_MODEL_ON_SCOPE_VARIABLE, X_INVALID_EXPRESSION, X_KEEP_ALIVE_INVALID_CHILDREN, // generic errors X_PREFIX_ID_NOT_SUPPORTED, X_MODULE_MODE_NOT_SUPPORTED, X_CACHE_HANDLER_NOT_SUPPORTED, X_SCOPE_ID_NOT_SUPPORTED, // Special value for higher-order compilers to pick up the last code // to avoid collision of error codes. This should always be kept as the last // item. __EXTEND_POINT__ } export const errorMessages: { [code: number]: string } = { // parse errors [ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT]: 'Illegal comment.', [ErrorCodes.CDATA_IN_HTML_CONTENT]: 'CDATA section is allowed only in XML context.', [ErrorCodes.DUPLICATE_ATTRIBUTE]: 'Duplicate attribute.', [ErrorCodes.END_TAG_WITH_ATTRIBUTES]: 'End tag cannot have attributes.', [ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS]: "Illegal '/' in tags.", [ErrorCodes.EOF_BEFORE_TAG_NAME]: 'Unexpected EOF in tag.', [ErrorCodes.EOF_IN_CDATA]: 'Unexpected EOF in CDATA section.', [ErrorCodes.EOF_IN_COMMENT]: 'Unexpected EOF in comment.', [ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT]: 'Unexpected EOF in script.', [ErrorCodes.EOF_IN_TAG]: 'Unexpected EOF in tag.', [ErrorCodes.INCORRECTLY_CLOSED_COMMENT]: 'Incorrectly closed comment.', [ErrorCodes.INCORRECTLY_OPENED_COMMENT]: 'Incorrectly opened comment.', [ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME]: "Illegal tag name. Use '&lt;' to print '<'.", [ErrorCodes.MISSING_ATTRIBUTE_VALUE]: 'Attribute value was expected.', [ErrorCodes.MISSING_END_TAG_NAME]: 'End tag name was expected.', [ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES]: 'Whitespace was expected.', [ErrorCodes.NESTED_COMMENT]: "Unexpected '<!--' in comment.", [ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).', [ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).', [ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME]: "Attribute name cannot start with '='.", [ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME]: "'<?' is allowed only in XML context.", [ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG]: "Illegal '/' in tags.", // Vue-specific parse errors [ErrorCodes.X_INVALID_END_TAG]: 'Invalid end tag.', [ErrorCodes.X_MISSING_END_TAG]: 'Element is missing end tag.', [ErrorCodes.X_MISSING_INTERPOLATION_END]: 'Interpolation end sign was not found.', [ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END]: 'End bracket for dynamic directive argument was not found. ' + 'Note that dynamic directive argument cannot contain spaces.', // transform errors [ErrorCodes.X_V_IF_NO_EXPRESSION]: `v-if/v-else-if is missing expression.`, [ErrorCodes.X_V_IF_SAME_KEY]: `v-if/else branches must use unique keys.`, [ErrorCodes.X_V_ELSE_NO_ADJACENT_IF]: `v-else/v-else-if has no adjacent v-if.`, [ErrorCodes.X_V_FOR_NO_EXPRESSION]: `v-for is missing expression.`, [ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION]: `v-for has invalid expression.`, [ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT]: `<template v-for> key should be placed on the <template> tag.`, [ErrorCodes.X_V_BIND_NO_EXPRESSION]: `v-bind is missing expression.`, [ErrorCodes.X_V_ON_NO_EXPRESSION]: `v-on is missing expression.`, [ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET]: `Unexpected custom directive on <slot> outlet.`, [ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE]: `Mixed v-slot usage on both the component and nested <template>.` + `When there are multiple named slots, all slots should use <template> ` + `syntax to avoid scope ambiguity.`, [ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES]: `Duplicate slot names found. `, [ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN]: `Extraneous children found when component already has explicitly named ` + `default slot. These children will be ignored.`, [ErrorCodes.X_V_SLOT_MISPLACED]: `v-slot can only be used on components or <template> tags.`, [ErrorCodes.X_V_MODEL_NO_EXPRESSION]: `v-model is missing expression.`, [ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION]: `v-model value must be a valid JavaScript member expression.`, [ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`, [ErrorCodes.X_INVALID_EXPRESSION]: `Error parsing JavaScript expression: `, [ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN]: `<KeepAlive> expects exactly one child component.`, // generic errors [ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED]: `"prefixIdentifiers" option is not supported in this build of compiler.`, [ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED]: `ES module mode is not supported in this build of compiler.`, [ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`, [ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED]: `"scopeId" option is only supported in module mode.` }
packages/compiler-core/src/errors.ts
0
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.0004501387884374708, 0.0002012308978009969, 0.00016165644046850502, 0.00016706340829841793, 0.0000713656991138123 ]
{ "id": 2, "code_window": [ " context,\n", " helper(FRAGMENT),\n", " keyProperty ? createObjectExpression([keyProperty]) : undefined,\n", " node.children,\n", " `${PatchFlags.STABLE_FRAGMENT} /* ${\n", " PatchFlagNames[PatchFlags.STABLE_FRAGMENT]\n", " } */`,\n", " undefined,\n", " undefined,\n", " true\n", " )\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " PatchFlags.STABLE_FRAGMENT +\n", " (__DEV__\n", " ? ` /* ${PatchFlagNames[PatchFlags.STABLE_FRAGMENT]} */`\n", " : ``),\n" ], "file_path": "packages/compiler-core/src/transforms/vFor.ts", "type": "replace", "edit_start_line_idx": 149 }
// Global compile-time constants declare var __DEV__: boolean declare var __TEST__: boolean declare var __BROWSER__: boolean declare var __GLOBAL__: boolean declare var __ESM_BUNDLER__: boolean declare var __ESM_BROWSER__: boolean declare var __NODE_JS__: boolean declare var __COMMIT__: string declare var __VERSION__: string // Feature flags declare var __FEATURE_OPTIONS_API__: boolean declare var __FEATURE_PROD_DEVTOOLS__: boolean declare var __FEATURE_SUSPENSE__: boolean // for tests declare namespace jest { interface Matchers<R, T> { toHaveBeenWarned(): R toHaveBeenWarnedLast(): R toHaveBeenWarnedTimes(n: number): R } }
packages/global.d.ts
0
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.0001722767628962174, 0.0001668469194555655, 0.0001625430304557085, 0.0001657210086705163, 0.000004052749318361748 ]
{ "id": 2, "code_window": [ " context,\n", " helper(FRAGMENT),\n", " keyProperty ? createObjectExpression([keyProperty]) : undefined,\n", " node.children,\n", " `${PatchFlags.STABLE_FRAGMENT} /* ${\n", " PatchFlagNames[PatchFlags.STABLE_FRAGMENT]\n", " } */`,\n", " undefined,\n", " undefined,\n", " true\n", " )\n", " } else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " PatchFlags.STABLE_FRAGMENT +\n", " (__DEV__\n", " ? ` /* ${PatchFlagNames[PatchFlags.STABLE_FRAGMENT]} */`\n", " : ``),\n" ], "file_path": "packages/compiler-core/src/transforms/vFor.ts", "type": "replace", "edit_start_line_idx": 149 }
import { isFunction } from '@vue/shared' import { currentInstance } from './component' import { currentRenderingInstance } from './componentRenderUtils' import { warn } from './warning' export interface InjectionKey<T> extends Symbol {} export function provide<T>(key: InjectionKey<T> | string, value: T) { if (!currentInstance) { if (__DEV__) { warn(`provide() can only be used inside setup().`) } } else { let provides = currentInstance.provides // by default an instance inherits its parent's provides object // but when it needs to provide values of its own, it creates its // own provides object using parent provides object as prototype. // this way in `inject` we can simply look up injections from direct // parent and let the prototype chain do the work. const parentProvides = currentInstance.parent && currentInstance.parent.provides if (parentProvides === provides) { provides = currentInstance.provides = Object.create(parentProvides) } // TS doesn't allow symbol as index type provides[key as string] = value } } export function inject<T>(key: InjectionKey<T> | string): T | undefined export function inject<T>( key: InjectionKey<T> | string, defaultValue: T, treatDefaultAsFactory?: false ): T export function inject<T>( key: InjectionKey<T> | string, defaultValue: T | (() => T), treatDefaultAsFactory: true ): T export function inject( key: InjectionKey<any> | string, defaultValue?: unknown, treatDefaultAsFactory = false ) { // fallback to `currentRenderingInstance` so that this can be called in // a functional component const instance = currentInstance || currentRenderingInstance if (instance) { // #2400 // to support `app.use` plugins, // fallback to appContext's `provides` if the intance is at root const provides = instance.parent == null ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides if (provides && (key as string | symbol) in provides) { // TS doesn't allow symbol as index type return provides[key as string] } else if (arguments.length > 1) { return treatDefaultAsFactory && isFunction(defaultValue) ? defaultValue() : defaultValue } else if (__DEV__) { warn(`injection "${String(key)}" not found.`) } } else if (__DEV__) { warn(`inject() can only be used inside setup() or functional components.`) } }
packages/runtime-core/src/apiInject.ts
0
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.00017182038573082536, 0.00016846612561494112, 0.00016048000543378294, 0.00016922494978643954, 0.0000034875174605986103 ]
{ "id": 3, "code_window": [ " context,\n", " helper(FRAGMENT),\n", " createObjectExpression([keyProperty]),\n", " children,\n", " `${PatchFlags.STABLE_FRAGMENT} /* ${\n", " PatchFlagNames[PatchFlags.STABLE_FRAGMENT]\n", " } */`,\n", " undefined,\n", " undefined,\n", " true,\n", " false,\n", " branch.loc\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " PatchFlags.STABLE_FRAGMENT +\n", " (__DEV__\n", " ? ` /* ${PatchFlagNames[PatchFlags.STABLE_FRAGMENT]} */`\n", " : ``),\n" ], "file_path": "packages/compiler-core/src/transforms/vIf.ts", "type": "replace", "edit_start_line_idx": 253 }
import { NodeTransform } from '../transform' import { NodeTypes, CompoundExpressionNode, createCallExpression, CallExpression, ElementTypes, ConstantTypes } from '../ast' import { isText } from '../utils' import { CREATE_TEXT } from '../runtimeHelpers' import { PatchFlags, PatchFlagNames } from '@vue/shared' import { getConstantType } from './hoistStatic' // Merge adjacent text nodes and expressions into a single expression // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child. export const transformText: NodeTransform = (node, context) => { if ( node.type === NodeTypes.ROOT || node.type === NodeTypes.ELEMENT || node.type === NodeTypes.FOR || node.type === NodeTypes.IF_BRANCH ) { // perform the transform on node exit so that all expressions have already // been processed. return () => { const children = node.children let currentContainer: CompoundExpressionNode | undefined = undefined let hasText = false for (let i = 0; i < children.length; i++) { const child = children[i] if (isText(child)) { hasText = true for (let j = i + 1; j < children.length; j++) { const next = children[j] if (isText(next)) { if (!currentContainer) { currentContainer = children[i] = { type: NodeTypes.COMPOUND_EXPRESSION, loc: child.loc, children: [child] } } // merge adjacent text node into current currentContainer.children.push(` + `, next) children.splice(j, 1) j-- } else { currentContainer = undefined break } } } } if ( !hasText || // if this is a plain element with a single text child, leave it // as-is since the runtime has dedicated fast path for this by directly // setting textContent of the element. // for component root it's always normalized anyway. (children.length === 1 && (node.type === NodeTypes.ROOT || (node.type === NodeTypes.ELEMENT && node.tagType === ElementTypes.ELEMENT))) ) { return } // pre-convert text nodes into createTextVNode(text) calls to avoid // runtime normalization. for (let i = 0; i < children.length; i++) { const child = children[i] if (isText(child) || child.type === NodeTypes.COMPOUND_EXPRESSION) { const callArgs: CallExpression['arguments'] = [] // createTextVNode defaults to single whitespace, so if it is a // single space the code could be an empty call to save bytes. if (child.type !== NodeTypes.TEXT || child.content !== ' ') { callArgs.push(child) } // mark dynamic text with flag so it gets patched inside a block if ( !context.ssr && getConstantType(child) === ConstantTypes.NOT_CONSTANT ) { callArgs.push( `${PatchFlags.TEXT} /* ${PatchFlagNames[PatchFlags.TEXT]} */` ) } children[i] = { type: NodeTypes.TEXT_CALL, content: child, loc: child.loc, codegenNode: createCallExpression( context.helper(CREATE_TEXT), callArgs ) } } } } } }
packages/compiler-core/src/transforms/transformText.ts
1
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.005616349168121815, 0.0010713859228417277, 0.00016372770187444985, 0.0002872180484700948, 0.0015392041532322764 ]
{ "id": 3, "code_window": [ " context,\n", " helper(FRAGMENT),\n", " createObjectExpression([keyProperty]),\n", " children,\n", " `${PatchFlags.STABLE_FRAGMENT} /* ${\n", " PatchFlagNames[PatchFlags.STABLE_FRAGMENT]\n", " } */`,\n", " undefined,\n", " undefined,\n", " true,\n", " false,\n", " branch.loc\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " PatchFlags.STABLE_FRAGMENT +\n", " (__DEV__\n", " ? ` /* ${PatchFlagNames[PatchFlags.STABLE_FRAGMENT]} */`\n", " : ``),\n" ], "file_path": "packages/compiler-core/src/transforms/vIf.ts", "type": "replace", "edit_start_line_idx": 253 }
import { patchProp } from '../src/patchProp' import { xlinkNS } from '../src/modules/attrs' describe('runtime-dom: attrs patching', () => { test('xlink attributes', () => { const el = document.createElementNS('http://www.w3.org/2000/svg', 'use') patchProp(el, 'xlink:href', null, 'a', true) expect(el.getAttributeNS(xlinkNS, 'href')).toBe('a') patchProp(el, 'xlink:href', 'a', null, true) expect(el.getAttributeNS(xlinkNS, 'href')).toBe(null) }) test('boolean attributes', () => { const el = document.createElement('input') patchProp(el, 'readonly', null, true) expect(el.getAttribute('readonly')).toBe('') patchProp(el, 'readonly', true, false) expect(el.getAttribute('readonly')).toBe(null) }) test('attributes', () => { const el = document.createElement('div') patchProp(el, 'foo', null, 'a') expect(el.getAttribute('foo')).toBe('a') patchProp(el, 'foo', 'a', null) expect(el.getAttribute('foo')).toBe(null) }) // #949 test('onxxx but non-listener attributes', () => { const el = document.createElement('div') patchProp(el, 'onwards', null, 'a') expect(el.getAttribute('onwards')).toBe('a') patchProp(el, 'onwards', 'a', null) expect(el.getAttribute('onwards')).toBe(null) }) })
packages/runtime-dom/__tests__/patchAttrs.spec.ts
0
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.0001721861190162599, 0.00017048013978637755, 0.0001685758907115087, 0.0001705792819848284, 0.0000015098356698217685 ]
{ "id": 3, "code_window": [ " context,\n", " helper(FRAGMENT),\n", " createObjectExpression([keyProperty]),\n", " children,\n", " `${PatchFlags.STABLE_FRAGMENT} /* ${\n", " PatchFlagNames[PatchFlags.STABLE_FRAGMENT]\n", " } */`,\n", " undefined,\n", " undefined,\n", " true,\n", " false,\n", " branch.loc\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " PatchFlags.STABLE_FRAGMENT +\n", " (__DEV__\n", " ? ` /* ${PatchFlagNames[PatchFlags.STABLE_FRAGMENT]} */`\n", " : ``),\n" ], "file_path": "packages/compiler-core/src/transforms/vIf.ts", "type": "replace", "edit_start_line_idx": 253 }
{ "extends": "../../api-extractor.json", "mainEntryPointFilePath": "./dist/packages/<unscopedPackageName>/src/index.d.ts", "dtsRollup": { "publicTrimmedFilePath": "./dist/<unscopedPackageName>.d.ts" } }
packages/shared/api-extractor.json
0
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.00017342304636258632, 0.00017342304636258632, 0.00017342304636258632, 0.00017342304636258632, 0 ]
{ "id": 3, "code_window": [ " context,\n", " helper(FRAGMENT),\n", " createObjectExpression([keyProperty]),\n", " children,\n", " `${PatchFlags.STABLE_FRAGMENT} /* ${\n", " PatchFlagNames[PatchFlags.STABLE_FRAGMENT]\n", " } */`,\n", " undefined,\n", " undefined,\n", " true,\n", " false,\n", " branch.loc\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " PatchFlags.STABLE_FRAGMENT +\n", " (__DEV__\n", " ? ` /* ${PatchFlagNames[PatchFlags.STABLE_FRAGMENT]} */`\n", " : ``),\n" ], "file_path": "packages/compiler-core/src/transforms/vIf.ts", "type": "replace", "edit_start_line_idx": 253 }
name: 'size' on: push: branches: - master pull_request: branches: - master jobs: size: runs-on: ubuntu-latest env: CI_JOB_NUMBER: 1 steps: - uses: actions/checkout@v1 - uses: bahmutov/npm-install@v1 - uses: posva/[email protected] with: github_token: ${{ secrets.GITHUB_TOKEN }} build_script: size files: packages/vue/dist/vue.global.prod.js packages/runtime-dom/dist/runtime-dom.global.prod.js packages/size-check/dist/size-check.global.prod.js
.github/workflows/size-check.yml
0
https://github.com/vuejs/core/commit/a76e58e5fde350026ab1bb15356ca1f51ad74bba
[ 0.00017340833437629044, 0.00016962092195171863, 0.00016583973774686456, 0.00016961473738774657, 0.0000030898695513315033 ]
{ "id": 0, "code_window": [ " * This source code is licensed under the MIT license found in the\n", " * LICENSE file in the root directory of this source tree.\n", " */\n", "\n", "async function execute() {\n", " require('../write-translations.js');\n", " const metadataUtils = require('./metadataUtils');\n", " const blog = require('./blog');\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const commander = require('commander');\n", " commander\n", " .option('--skip-image-compression')\n", " .option('--skip-next-release')\n", " .parse(process.argv);\n" ], "file_path": "packages/docusaurus-1.x/lib/server/generate.js", "type": "add", "edit_start_line_idx": 8 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const CWD = process.cwd(); const path = require('path'); const fs = require('fs'); const glob = require('glob'); const program = require('commander'); const metadataUtils = require('./metadataUtils'); const env = require('./env.js'); const blog = require('./blog.js'); const loadConfig = require('./config'); const siteConfig = loadConfig(`${CWD}/siteConfig.js`); const versionFallback = require('./versionFallback.js'); const utils = require('./utils.js'); const docsPart = `${siteConfig.docsUrl ? `${siteConfig.docsUrl}/` : ''}`; const SupportedHeaderFields = new Set([ 'id', 'title', 'author', 'authorURL', 'authorFBID', 'sidebar_label', 'original_id', 'hide_title', 'layout', 'custom_edit_url', ]); program.option('--skip-next-release').parse(process.argv); let allSidebars; if (fs.existsSync(`${CWD}/sidebars.json`)) { allSidebars = require(`${CWD}/sidebars.json`); } else { allSidebars = {}; } // Can have a custom docs path. Top level folder still needs to be in directory // at the same level as `website`, not inside `website`. // e.g., docs/whereDocsReallyExist // website-docs/ // All .md docs still (currently) must be in one flat directory hierarchy. // e.g., docs/whereDocsReallyExist/*.md (all .md files in this dir) function getDocsPath() { return siteConfig.customDocsPath ? siteConfig.customDocsPath : 'docs'; } function shouldGenerateNextReleaseDocs() { return !( env.versioning.enabled && program.name() === 'docusaurus-build' && program.skipNextRelease ); } // returns map from id to object containing sidebar ordering info function readSidebar(sidebars = {}) { Object.assign(sidebars, versionFallback.sidebarData()); const items = {}; Object.keys(sidebars).forEach(sidebar => { const categories = sidebars[sidebar]; const sidebarItems = []; Object.keys(categories).forEach(category => { const categoryItems = categories[category]; categoryItems.forEach(categoryItem => { if (typeof categoryItem === 'object') { switch (categoryItem.type) { case 'subcategory': categoryItem.ids.forEach(subcategoryItem => { sidebarItems.push({ id: subcategoryItem, category, subcategory: categoryItem.label, order: sidebarItems.length + 1, }); }); return; default: return; } } // Is a regular id value. sidebarItems.push({ id: categoryItem, category, subcategory: null, order: sidebarItems.length + 1, }); }); }); for (let i = 0; i < sidebarItems.length; i++) { const item = sidebarItems[i]; let previous = null; let next = null; if (i > 0) { previous = sidebarItems[i - 1].id; } if (i < sidebarItems.length - 1) { next = sidebarItems[i + 1].id; } items[item.id] = { previous, next, sidebar, category: item.category, subcategory: item.subcategory, order: item.order, }; } }); return items; } // process the metadata for a document found in either 'docs' or 'translated_docs' function processMetadata(file, refDir) { const result = metadataUtils.extractMetadata(fs.readFileSync(file, 'utf8')); const language = utils.getLanguage(file, refDir) || 'en'; const metadata = {}; Object.keys(result.metadata).forEach(fieldName => { if (SupportedHeaderFields.has(fieldName)) { metadata[fieldName] = result.metadata[fieldName]; } else { console.warn(`Header field "${fieldName}" in ${file} is not supported.`); } }); const rawContent = result.rawContent; if (!metadata.id) { metadata.id = path.basename(file, path.extname(file)); } if (metadata.id.includes('/')) { throw new Error('Document id cannot include "/".'); } // If a file is located in a subdirectory, prepend the subdir to it's ID // Example: // (file: 'docusaurus/docs/projectA/test.md', ID 'test', refDir: 'docusaurus/docs') // returns 'projectA/test' const subDir = utils.getSubDir(file, refDir); if (subDir) { metadata.id = `${subDir}/${metadata.id}`; } // Example: `docs/projectA/test.md` source is `projectA/test.md` metadata.source = subDir ? `${subDir}/${path.basename(file)}` : path.basename(file); if (!metadata.title) { metadata.title = metadata.id; } const langPart = env.translation.enabled || siteConfig.useEnglishUrl ? `${language}/` : ''; let versionPart = ''; if (env.versioning.enabled) { metadata.version = 'next'; versionPart = 'next/'; } metadata.permalink = `${docsPart}${langPart}${versionPart}${ metadata.id }.html`; // change ids previous, next metadata.localized_id = metadata.id; metadata.id = (env.translation.enabled ? `${language}-` : '') + metadata.id; metadata.language = env.translation.enabled ? language : 'en'; const items = readSidebar(allSidebars); const id = metadata.localized_id; const item = items[id]; if (item) { metadata.sidebar = item.sidebar; metadata.category = item.category; metadata.subcategory = item.subcategory; metadata.order = item.order; if (item.next) { metadata.next_id = item.next; metadata.next = (env.translation.enabled ? `${language}-` : '') + item.next; } if (item.previous) { metadata.previous_id = item.previous; metadata.previous = (env.translation.enabled ? `${language}-` : '') + item.previous; } } return {metadata, rawContent}; } // process metadata for all docs and save into core/metadata.js function generateMetadataDocs() { let order; try { order = readSidebar(allSidebars); } catch (e) { console.error(e); process.exit(1); } const enabledLanguages = env.translation .enabledLanguages() .map(language => language.tag); const metadatas = {}; const defaultMetadatas = {}; if (shouldGenerateNextReleaseDocs()) { // metadata for english files const docsDir = path.join(CWD, '../', getDocsPath()); let files = glob.sync(`${docsDir}/**`); files.forEach(file => { const extension = path.extname(file); if (extension === '.md' || extension === '.markdown') { const res = processMetadata(file, docsDir); if (!res) { return; } const metadata = res.metadata; metadatas[metadata.id] = metadata; // create a default list of documents for each enabled language based on docs in English // these will get replaced if/when the localized file is downloaded from crowdin enabledLanguages .filter(currentLanguage => currentLanguage !== 'en') .forEach(currentLanguage => { const baseMetadata = Object.assign({}, metadata); baseMetadata.id = baseMetadata.id .toString() .replace(/^en-/, `${currentLanguage}-`); if (baseMetadata.permalink) { baseMetadata.permalink = baseMetadata.permalink .toString() .replace( new RegExp(`^${docsPart}en/`), `${docsPart}${currentLanguage}/`, ); } if (baseMetadata.next) { baseMetadata.next = baseMetadata.next .toString() .replace(/^en-/, `${currentLanguage}-`); } if (baseMetadata.previous) { baseMetadata.previous = baseMetadata.previous .toString() .replace(/^en-/, `${currentLanguage}-`); } baseMetadata.language = currentLanguage; defaultMetadatas[baseMetadata.id] = baseMetadata; }); Object.assign(metadatas, defaultMetadatas); } }); // metadata for non-english docs const translatedDir = path.join(CWD, 'translated_docs'); files = glob.sync(`${CWD}/translated_docs/**`); files.forEach(file => { if (!utils.getLanguage(file, translatedDir)) { return; } const extension = path.extname(file); if (extension === '.md' || extension === '.markdown') { const res = processMetadata(file, translatedDir); if (!res) { return; } const metadata = res.metadata; metadatas[metadata.id] = metadata; } }); } // metadata for versioned docs const versionData = versionFallback.docData(); versionData.forEach(metadata => { const id = metadata.localized_id; if (order[id]) { metadata.sidebar = order[id].sidebar; metadata.category = order[id].category; metadata.subcategory = order[id].subcategory; metadata.order = order[id].order; if (order[id].next) { metadata.next_id = order[id].next.replace( `version-${metadata.version}-`, '', ); metadata.next = (env.translation.enabled ? `${metadata.language}-` : '') + order[id].next; } if (order[id].previous) { metadata.previous_id = order[id].previous.replace( `version-${metadata.version}-`, '', ); metadata.previous = (env.translation.enabled ? `${metadata.language}-` : '') + order[id].previous; } } metadatas[metadata.id] = metadata; }); // Get the titles of the previous and next ids so that we can use them in // navigation buttons in DocsLayout.js Object.keys(metadatas).forEach(metadata => { if (metadatas[metadata].previous) { if (metadatas[metadatas[metadata].previous]) { metadatas[metadata].previous_title = metadatas[metadatas[metadata].previous].title; } else { metadatas[metadata].previous_title = 'Previous'; } } if (metadatas[metadata].next) { if (metadatas[metadatas[metadata].next]) { metadatas[metadata].next_title = metadatas[metadatas[metadata].next].title; } else { metadatas[metadata].next_title = 'Next'; } } }); fs.writeFileSync( path.join(__dirname, '/../core/metadata.js'), `${'/**\n' + ' * @' + 'generated\n' + // separate this out for Nuclide treating @generated as readonly ' */\n' + 'module.exports = '}${JSON.stringify(metadatas, null, 2)};\n`, ); } // process metadata for blog posts and save into core/MetadataBlog.js function generateMetadataBlog() { const metadatas = []; const files = glob.sync(`${CWD}/blog/**/*.*`); files .sort() .reverse() .forEach(file => { const extension = path.extname(file); if (extension !== '.md' && extension !== '.markdown') { return; } const metadata = blog.getMetadata(file); // Extract, YYYY, MM, DD from the file name const filePathDateArr = path .basename(file) .toString() .split('-'); metadata.date = new Date( `${filePathDateArr[0]}-${filePathDateArr[1]}-${ filePathDateArr[2] }T06:00:00.000Z`, ); // allow easier sorting of blog by providing seconds since epoch metadata.seconds = Math.round(metadata.date.getTime() / 1000); metadatas.push(metadata); }); const sortedMetadatas = metadatas.sort( (a, b) => parseInt(b.seconds, 10) - parseInt(a.seconds, 10), ); fs.writeFileSync( path.join(__dirname, '/../core/MetadataBlog.js'), `${'/**\n' + ' * @' + 'generated\n' + // separate this out for Nuclide treating @generated as readonly ' */\n' + 'module.exports = '}${JSON.stringify(sortedMetadatas, null, 2)};\n`, ); } module.exports = { getDocsPath, readSidebar, processMetadata, generateMetadataDocs, generateMetadataBlog, };
packages/docusaurus-1.x/lib/server/readMetadata.js
1
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.9968855977058411, 0.07113731652498245, 0.00016218863311223686, 0.00017382949590682983, 0.2557571530342102 ]
{ "id": 0, "code_window": [ " * This source code is licensed under the MIT license found in the\n", " * LICENSE file in the root directory of this source tree.\n", " */\n", "\n", "async function execute() {\n", " require('../write-translations.js');\n", " const metadataUtils = require('./metadataUtils');\n", " const blog = require('./blog');\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const commander = require('commander');\n", " commander\n", " .option('--skip-image-compression')\n", " .option('--skip-next-release')\n", " .parse(process.argv);\n" ], "file_path": "packages/docusaurus-1.x/lib/server/generate.js", "type": "add", "edit_start_line_idx": 8 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const {parse} = require('@babel/parser'); const traverse = require('@babel/traverse').default; const stringifyObject = require('stringify-object'); const search = require('./search'); const parseOptions = { plugins: ['jsx'], sourceType: 'module', }; const isImport = child => child.type === 'import'; const hasImports = index => index > -1; const isExport = child => child.type === 'export'; const isTarget = (child, name) => { let found = false; const ast = parse(child.value, parseOptions); traverse(ast, { VariableDeclarator: path => { if (path.node.id.name === name) { found = true; } }, }); return found; }; const getOrCreateExistingTargetIndex = (children, name) => { let importsIndex = -1; let targetIndex = -1; children.forEach((child, index) => { if (isImport(child)) { importsIndex = index; } else if (isExport(child) && isTarget(child, name)) { targetIndex = index; } }); if (targetIndex === -1) { const target = { default: false, type: 'export', value: `export const ${name} = [];`, }; targetIndex = hasImports(importsIndex) ? importsIndex + 1 : 0; children.splice(targetIndex, 0, target); } return targetIndex; }; const plugin = (options = {}) => { const name = options.name || 'rightToc'; const transformer = node => { const headings = search(node); const {children} = node; const targetIndex = getOrCreateExistingTargetIndex(children, name); if (headings && headings.length) { children[targetIndex].value = `export const ${name} = ${stringifyObject( headings, )};`; } }; return transformer; }; module.exports = plugin;
packages/docusaurus-mdx-loader/src/rightToc/index.js
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.00017768143152352422, 0.00017349976405967027, 0.0001682919537415728, 0.00017464304983150214, 0.000003285708999101189 ]
{ "id": 0, "code_window": [ " * This source code is licensed under the MIT license found in the\n", " * LICENSE file in the root directory of this source tree.\n", " */\n", "\n", "async function execute() {\n", " require('../write-translations.js');\n", " const metadataUtils = require('./metadataUtils');\n", " const blog = require('./blog');\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const commander = require('commander');\n", " commander\n", " .option('--skip-image-compression')\n", " .option('--skip-next-release')\n", " .parse(process.argv);\n" ], "file_path": "packages/docusaurus-1.x/lib/server/generate.js", "type": "add", "edit_start_line_idx": 8 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable no-cond-assign */ function execute(port) { const extractTranslations = require('../write-translations'); const metadataUtils = require('./metadataUtils'); const blog = require('./blog'); const docs = require('./docs'); const env = require('./env.js'); const express = require('express'); const React = require('react'); const request = require('request'); const fs = require('fs-extra'); const path = require('path'); const {isSeparateCss} = require('./utils'); const mkdirp = require('mkdirp'); const glob = require('glob'); const chalk = require('chalk'); const translate = require('./translate'); const {renderToStaticMarkupWithDoctype} = require('./renderUtils'); const feed = require('./feed'); const sitemap = require('./sitemap'); const routing = require('./routing'); const loadConfig = require('./config'); const CWD = process.cwd(); const join = path.join; const sep = path.sep; function removeModulePathFromCache(moduleName) { /* eslint-disable no-underscore-dangle */ Object.keys(module.constructor._pathCache).forEach(cacheKey => { if (cacheKey.indexOf(moduleName) > 0) { delete module.constructor._pathCache[cacheKey]; } }); } // Remove a module and child modules from require cache, so server // does not have to be restarted. function removeModuleAndChildrenFromCache(moduleName) { let mod = require.resolve(moduleName); if (mod && (mod = require.cache[mod])) { mod.children.forEach(child => { delete require.cache[child.id]; removeModulePathFromCache(mod.id); }); delete require.cache[mod.id]; removeModulePathFromCache(mod.id); } } const readMetadata = require('./readMetadata.js'); let Metadata; let MetadataBlog; let siteConfig; function reloadMetadata() { removeModuleAndChildrenFromCache('./readMetadata.js'); readMetadata.generateMetadataDocs(); removeModuleAndChildrenFromCache('../core/metadata.js'); Metadata = require('../core/metadata.js'); } function reloadMetadataBlog() { if (fs.existsSync(join(__dirname, '..', 'core', 'MetadataBlog.js'))) { removeModuleAndChildrenFromCache(join('..', 'core', 'MetadataBlog.js')); fs.removeSync(join(__dirname, '..', 'core', 'MetadataBlog.js')); } readMetadata.generateMetadataBlog(); MetadataBlog = require(join('..', 'core', 'MetadataBlog.js')); } function reloadSiteConfig() { const siteConfigPath = join(CWD, 'siteConfig.js'); removeModuleAndChildrenFromCache(siteConfigPath); siteConfig = loadConfig(siteConfigPath); } function requestFile(url, res, notFoundCallback) { request.get(url, (error, response, body) => { if (!error) { if (response) { if (response.statusCode === 404 && notFoundCallback) { notFoundCallback(); } else { res.status(response.statusCode).send(body); } } else { console.error('No response'); } } else { console.error('Request failed:', error); } }); } reloadMetadata(); reloadMetadataBlog(); extractTranslations(); reloadSiteConfig(); const app = express(); app.get(routing.docs(siteConfig), (req, res, next) => { const url = decodeURI(req.path.toString().replace(siteConfig.baseUrl, '')); const metadata = Metadata[ Object.keys(Metadata).find(id => Metadata[id].permalink === url) ]; const file = docs.getFile(metadata); if (!file) { next(); return; } const rawContent = metadataUtils.extractMetadata(file).rawContent; removeModuleAndChildrenFromCache('../core/DocsLayout.js'); const mdToHtml = metadataUtils.mdToHtml(Metadata, siteConfig); res.send(docs.getMarkup(rawContent, mdToHtml, metadata)); }); app.get(routing.sitemap(siteConfig), (req, res) => { sitemap((err, xml) => { if (err) { res.status(500).send('Sitemap error'); } else { res.set('Content-Type', 'application/xml'); res.send(xml); } }); }); app.get(routing.feed(siteConfig), (req, res, next) => { res.set('Content-Type', 'application/rss+xml'); const file = req.path .toString() .split('blog/')[1] .toLowerCase(); if (file === 'atom.xml') { res.send(feed('atom')); } else if (file === 'feed.xml') { res.send(feed('rss')); } next(); }); app.get(routing.blog(siteConfig), (req, res, next) => { // Regenerate the blog metadata in case it has changed. Consider improving // this to regenerate on file save rather than on page request. reloadMetadataBlog(); removeModuleAndChildrenFromCache(join('..', 'core', 'BlogPageLayout.js')); const blogPages = blog.getPagesMarkup(MetadataBlog.length, siteConfig); const urlPath = req.path.toString().split('blog/')[1]; if (urlPath === 'index.html') { res.send(blogPages['/index.html']); } else if (urlPath.endsWith('/index.html') && blogPages[urlPath]) { res.send(blogPages[urlPath]); } else if (urlPath.match(/page([0-9]+)/)) { res.send(blogPages[`${urlPath.replace(/\/$/, '')}/index.html`]); } else { const file = join(CWD, 'blog', blog.urlToSource(urlPath)); removeModuleAndChildrenFromCache(join('..', 'core', 'BlogPostLayout.js')); const blogPost = blog.getPostMarkup(file, siteConfig); if (!blogPost) { next(); return; } res.send(blogPost); } }); app.get(routing.page(siteConfig), (req, res, next) => { // Look for user-provided HTML file first. let htmlFile = req.path.toString().replace(siteConfig.baseUrl, ''); htmlFile = join(CWD, 'pages', htmlFile); if ( fs.existsSync(htmlFile) || fs.existsSync( (htmlFile = htmlFile.replace( path.basename(htmlFile), join('en', path.basename(htmlFile)), )), ) ) { if (siteConfig.wrapPagesHTML) { removeModuleAndChildrenFromCache(join('..', 'core', 'Site.js')); const Site = require(join('..', 'core', 'Site.js')); const str = renderToStaticMarkupWithDoctype( <Site language="en" config={siteConfig} metadata={{id: path.basename(htmlFile, '.html')}}> <div dangerouslySetInnerHTML={{ __html: fs.readFileSync(htmlFile, {encoding: 'utf8'}), }} /> </Site>, ); res.send(str); } else { res.send(fs.readFileSync(htmlFile, {encoding: 'utf8'})); } next(); return; } // look for user provided react file either in specified path or in path for english files let file = req.path.toString().replace(/\.html$/, '.js'); file = file.replace(siteConfig.baseUrl, ''); let userFile = join(CWD, 'pages', file); let language = env.translation.enabled ? 'en' : ''; const regexLang = /(.*)\/.*\.html$/; const match = regexLang.exec(req.path); const parts = match[1].split('/'); const enabledLangTags = env.translation .enabledLanguages() .map(lang => lang.tag); for (let i = 0; i < parts.length; i++) { if (enabledLangTags.indexOf(parts[i]) !== -1) { language = parts[i]; } } let englishFile = join(CWD, 'pages', file); if (language && language !== 'en') { englishFile = englishFile.replace(sep + language + sep, `${sep}en${sep}`); } // check for: a file for the page, an english file for page with unspecified language, or an // english file for the page if ( fs.existsSync(userFile) || fs.existsSync( (userFile = userFile.replace( path.basename(userFile), `en${sep}${path.basename(userFile)}`, )), ) || fs.existsSync((userFile = englishFile)) ) { // copy into docusaurus so require paths work const userFileParts = userFile.split(`pages${sep}`); let tempFile = join(__dirname, '..', 'pages', userFileParts[1]); tempFile = tempFile.replace( path.basename(file), `temp${path.basename(file)}`, ); mkdirp.sync(path.dirname(tempFile)); fs.copySync(userFile, tempFile); // render into a string removeModuleAndChildrenFromCache(tempFile); const ReactComp = require(tempFile); removeModuleAndChildrenFromCache(join('..', 'core', 'Site.js')); const Site = require(join('..', 'core', 'Site.js')); translate.setLanguage(language); const str = renderToStaticMarkupWithDoctype( <Site language={language} config={siteConfig} title={ReactComp.title} description={ReactComp.description} metadata={{id: path.basename(userFile, '.js')}}> <ReactComp config={siteConfig} language={language} /> </Site>, ); fs.removeSync(tempFile); res.send(str); } else { next(); } }); app.get(`${siteConfig.baseUrl}css/main.css`, (req, res) => { const mainCssPath = join( __dirname, '..', 'static', req.path.toString().replace(siteConfig.baseUrl, '/'), ); let cssContent = fs.readFileSync(mainCssPath, {encoding: 'utf8'}); const files = glob.sync(join(CWD, 'static', '**', '*.css')); files.forEach(file => { if (isSeparateCss(file, siteConfig.separateCss)) { return; } cssContent = `${cssContent}\n${fs.readFileSync(file, { encoding: 'utf8', })}`; }); if ( !siteConfig.colors || !siteConfig.colors.primaryColor || !siteConfig.colors.secondaryColor ) { console.error( `${chalk.yellow( 'Missing color configuration.', )} Make sure siteConfig.colors includes primaryColor and secondaryColor fields.`, ); } Object.keys(siteConfig.colors).forEach(key => { const color = siteConfig.colors[key]; cssContent = cssContent.replace(new RegExp(`\\$${key}`, 'g'), color); }); if (siteConfig.fonts) { Object.keys(siteConfig.fonts).forEach(key => { const fontString = siteConfig.fonts[key] .map(font => `"${font}"`) .join(', '); cssContent = cssContent.replace( new RegExp(`\\$${key}`, 'g'), fontString, ); }); } res.header('Content-Type', 'text/css'); res.send(cssContent); }); // serve static assets from these locations app.use( `${siteConfig.baseUrl}${ siteConfig.docsUrl ? `${siteConfig.docsUrl}/` : '' }assets`, express.static(join(CWD, '..', readMetadata.getDocsPath(), 'assets')), ); app.use( `${siteConfig.baseUrl}blog/assets`, express.static(join(CWD, 'blog', 'assets')), ); app.use(siteConfig.baseUrl, express.static(join(CWD, 'static'))); app.use(siteConfig.baseUrl, express.static(join(__dirname, '..', 'static'))); // "redirect" requests to pages ending with "/" or no extension so that, // for example, request to "blog" returns "blog/index.html" or "blog.html" app.get(routing.noExtension(), (req, res, next) => { const slash = req.path.toString().endsWith('/') ? '' : '/'; const requestUrl = `http://localhost:${port}${req.path}`; requestFile(`${requestUrl + slash}index.html`, res, () => { requestFile( slash === '/' ? `${requestUrl}.html` : requestUrl.replace(/\/$/, '.html'), res, next, ); }); }); // handle special cleanUrl case like '/blog/1.2.3' & '/blog.robots.hai' // where we should try to serve '/blog/1.2.3.html' & '/blog.robots.hai.html' app.get(routing.dotfiles(), (req, res, next) => { if (!siteConfig.cleanUrl) { next(); return; } requestFile(`http://localhost:${port}${req.path}.html`, res, next); }); app.listen(port); } module.exports = execute;
packages/docusaurus-1.x/lib/server/server.js
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.9981829524040222, 0.09500741958618164, 0.00016908830730244517, 0.00017521633708383888, 0.27771180868148804 ]
{ "id": 0, "code_window": [ " * This source code is licensed under the MIT license found in the\n", " * LICENSE file in the root directory of this source tree.\n", " */\n", "\n", "async function execute() {\n", " require('../write-translations.js');\n", " const metadataUtils = require('./metadataUtils');\n", " const blog = require('./blog');\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const commander = require('commander');\n", " commander\n", " .option('--skip-image-compression')\n", " .option('--skip-next-release')\n", " .parse(process.argv);\n" ], "file_path": "packages/docusaurus-1.x/lib/server/generate.js", "type": "add", "edit_start_line_idx": 8 }
*/node_modules *.log
packages/docusaurus-1.x/examples/basics/dockerignore
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.00017384986858814955, 0.00017384986858814955, 0.00017384986858814955, 0.00017384986858814955, 0 ]
{ "id": 1, "code_window": [ " const join = path.join;\n", " const sep = path.sep;\n", " const escapeStringRegexp = require('escape-string-regexp');\n", " const {renderToStaticMarkupWithDoctype} = require('./renderUtils');\n", " const commander = require('commander');\n", " const imagemin = require('imagemin');\n", " const imageminJpegtran = require('imagemin-jpegtran');\n", " const imageminOptipng = require('imagemin-optipng');\n", " const imageminSvgo = require('imagemin-svgo');\n", " const imageminGifsicle = require('imagemin-gifsicle');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/docusaurus-1.x/lib/server/generate.js", "type": "replace", "edit_start_line_idx": 32 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const CWD = process.cwd(); const path = require('path'); const fs = require('fs'); const glob = require('glob'); const program = require('commander'); const metadataUtils = require('./metadataUtils'); const env = require('./env.js'); const blog = require('./blog.js'); const loadConfig = require('./config'); const siteConfig = loadConfig(`${CWD}/siteConfig.js`); const versionFallback = require('./versionFallback.js'); const utils = require('./utils.js'); const docsPart = `${siteConfig.docsUrl ? `${siteConfig.docsUrl}/` : ''}`; const SupportedHeaderFields = new Set([ 'id', 'title', 'author', 'authorURL', 'authorFBID', 'sidebar_label', 'original_id', 'hide_title', 'layout', 'custom_edit_url', ]); program.option('--skip-next-release').parse(process.argv); let allSidebars; if (fs.existsSync(`${CWD}/sidebars.json`)) { allSidebars = require(`${CWD}/sidebars.json`); } else { allSidebars = {}; } // Can have a custom docs path. Top level folder still needs to be in directory // at the same level as `website`, not inside `website`. // e.g., docs/whereDocsReallyExist // website-docs/ // All .md docs still (currently) must be in one flat directory hierarchy. // e.g., docs/whereDocsReallyExist/*.md (all .md files in this dir) function getDocsPath() { return siteConfig.customDocsPath ? siteConfig.customDocsPath : 'docs'; } function shouldGenerateNextReleaseDocs() { return !( env.versioning.enabled && program.name() === 'docusaurus-build' && program.skipNextRelease ); } // returns map from id to object containing sidebar ordering info function readSidebar(sidebars = {}) { Object.assign(sidebars, versionFallback.sidebarData()); const items = {}; Object.keys(sidebars).forEach(sidebar => { const categories = sidebars[sidebar]; const sidebarItems = []; Object.keys(categories).forEach(category => { const categoryItems = categories[category]; categoryItems.forEach(categoryItem => { if (typeof categoryItem === 'object') { switch (categoryItem.type) { case 'subcategory': categoryItem.ids.forEach(subcategoryItem => { sidebarItems.push({ id: subcategoryItem, category, subcategory: categoryItem.label, order: sidebarItems.length + 1, }); }); return; default: return; } } // Is a regular id value. sidebarItems.push({ id: categoryItem, category, subcategory: null, order: sidebarItems.length + 1, }); }); }); for (let i = 0; i < sidebarItems.length; i++) { const item = sidebarItems[i]; let previous = null; let next = null; if (i > 0) { previous = sidebarItems[i - 1].id; } if (i < sidebarItems.length - 1) { next = sidebarItems[i + 1].id; } items[item.id] = { previous, next, sidebar, category: item.category, subcategory: item.subcategory, order: item.order, }; } }); return items; } // process the metadata for a document found in either 'docs' or 'translated_docs' function processMetadata(file, refDir) { const result = metadataUtils.extractMetadata(fs.readFileSync(file, 'utf8')); const language = utils.getLanguage(file, refDir) || 'en'; const metadata = {}; Object.keys(result.metadata).forEach(fieldName => { if (SupportedHeaderFields.has(fieldName)) { metadata[fieldName] = result.metadata[fieldName]; } else { console.warn(`Header field "${fieldName}" in ${file} is not supported.`); } }); const rawContent = result.rawContent; if (!metadata.id) { metadata.id = path.basename(file, path.extname(file)); } if (metadata.id.includes('/')) { throw new Error('Document id cannot include "/".'); } // If a file is located in a subdirectory, prepend the subdir to it's ID // Example: // (file: 'docusaurus/docs/projectA/test.md', ID 'test', refDir: 'docusaurus/docs') // returns 'projectA/test' const subDir = utils.getSubDir(file, refDir); if (subDir) { metadata.id = `${subDir}/${metadata.id}`; } // Example: `docs/projectA/test.md` source is `projectA/test.md` metadata.source = subDir ? `${subDir}/${path.basename(file)}` : path.basename(file); if (!metadata.title) { metadata.title = metadata.id; } const langPart = env.translation.enabled || siteConfig.useEnglishUrl ? `${language}/` : ''; let versionPart = ''; if (env.versioning.enabled) { metadata.version = 'next'; versionPart = 'next/'; } metadata.permalink = `${docsPart}${langPart}${versionPart}${ metadata.id }.html`; // change ids previous, next metadata.localized_id = metadata.id; metadata.id = (env.translation.enabled ? `${language}-` : '') + metadata.id; metadata.language = env.translation.enabled ? language : 'en'; const items = readSidebar(allSidebars); const id = metadata.localized_id; const item = items[id]; if (item) { metadata.sidebar = item.sidebar; metadata.category = item.category; metadata.subcategory = item.subcategory; metadata.order = item.order; if (item.next) { metadata.next_id = item.next; metadata.next = (env.translation.enabled ? `${language}-` : '') + item.next; } if (item.previous) { metadata.previous_id = item.previous; metadata.previous = (env.translation.enabled ? `${language}-` : '') + item.previous; } } return {metadata, rawContent}; } // process metadata for all docs and save into core/metadata.js function generateMetadataDocs() { let order; try { order = readSidebar(allSidebars); } catch (e) { console.error(e); process.exit(1); } const enabledLanguages = env.translation .enabledLanguages() .map(language => language.tag); const metadatas = {}; const defaultMetadatas = {}; if (shouldGenerateNextReleaseDocs()) { // metadata for english files const docsDir = path.join(CWD, '../', getDocsPath()); let files = glob.sync(`${docsDir}/**`); files.forEach(file => { const extension = path.extname(file); if (extension === '.md' || extension === '.markdown') { const res = processMetadata(file, docsDir); if (!res) { return; } const metadata = res.metadata; metadatas[metadata.id] = metadata; // create a default list of documents for each enabled language based on docs in English // these will get replaced if/when the localized file is downloaded from crowdin enabledLanguages .filter(currentLanguage => currentLanguage !== 'en') .forEach(currentLanguage => { const baseMetadata = Object.assign({}, metadata); baseMetadata.id = baseMetadata.id .toString() .replace(/^en-/, `${currentLanguage}-`); if (baseMetadata.permalink) { baseMetadata.permalink = baseMetadata.permalink .toString() .replace( new RegExp(`^${docsPart}en/`), `${docsPart}${currentLanguage}/`, ); } if (baseMetadata.next) { baseMetadata.next = baseMetadata.next .toString() .replace(/^en-/, `${currentLanguage}-`); } if (baseMetadata.previous) { baseMetadata.previous = baseMetadata.previous .toString() .replace(/^en-/, `${currentLanguage}-`); } baseMetadata.language = currentLanguage; defaultMetadatas[baseMetadata.id] = baseMetadata; }); Object.assign(metadatas, defaultMetadatas); } }); // metadata for non-english docs const translatedDir = path.join(CWD, 'translated_docs'); files = glob.sync(`${CWD}/translated_docs/**`); files.forEach(file => { if (!utils.getLanguage(file, translatedDir)) { return; } const extension = path.extname(file); if (extension === '.md' || extension === '.markdown') { const res = processMetadata(file, translatedDir); if (!res) { return; } const metadata = res.metadata; metadatas[metadata.id] = metadata; } }); } // metadata for versioned docs const versionData = versionFallback.docData(); versionData.forEach(metadata => { const id = metadata.localized_id; if (order[id]) { metadata.sidebar = order[id].sidebar; metadata.category = order[id].category; metadata.subcategory = order[id].subcategory; metadata.order = order[id].order; if (order[id].next) { metadata.next_id = order[id].next.replace( `version-${metadata.version}-`, '', ); metadata.next = (env.translation.enabled ? `${metadata.language}-` : '') + order[id].next; } if (order[id].previous) { metadata.previous_id = order[id].previous.replace( `version-${metadata.version}-`, '', ); metadata.previous = (env.translation.enabled ? `${metadata.language}-` : '') + order[id].previous; } } metadatas[metadata.id] = metadata; }); // Get the titles of the previous and next ids so that we can use them in // navigation buttons in DocsLayout.js Object.keys(metadatas).forEach(metadata => { if (metadatas[metadata].previous) { if (metadatas[metadatas[metadata].previous]) { metadatas[metadata].previous_title = metadatas[metadatas[metadata].previous].title; } else { metadatas[metadata].previous_title = 'Previous'; } } if (metadatas[metadata].next) { if (metadatas[metadatas[metadata].next]) { metadatas[metadata].next_title = metadatas[metadatas[metadata].next].title; } else { metadatas[metadata].next_title = 'Next'; } } }); fs.writeFileSync( path.join(__dirname, '/../core/metadata.js'), `${'/**\n' + ' * @' + 'generated\n' + // separate this out for Nuclide treating @generated as readonly ' */\n' + 'module.exports = '}${JSON.stringify(metadatas, null, 2)};\n`, ); } // process metadata for blog posts and save into core/MetadataBlog.js function generateMetadataBlog() { const metadatas = []; const files = glob.sync(`${CWD}/blog/**/*.*`); files .sort() .reverse() .forEach(file => { const extension = path.extname(file); if (extension !== '.md' && extension !== '.markdown') { return; } const metadata = blog.getMetadata(file); // Extract, YYYY, MM, DD from the file name const filePathDateArr = path .basename(file) .toString() .split('-'); metadata.date = new Date( `${filePathDateArr[0]}-${filePathDateArr[1]}-${ filePathDateArr[2] }T06:00:00.000Z`, ); // allow easier sorting of blog by providing seconds since epoch metadata.seconds = Math.round(metadata.date.getTime() / 1000); metadatas.push(metadata); }); const sortedMetadatas = metadatas.sort( (a, b) => parseInt(b.seconds, 10) - parseInt(a.seconds, 10), ); fs.writeFileSync( path.join(__dirname, '/../core/MetadataBlog.js'), `${'/**\n' + ' * @' + 'generated\n' + // separate this out for Nuclide treating @generated as readonly ' */\n' + 'module.exports = '}${JSON.stringify(sortedMetadatas, null, 2)};\n`, ); } module.exports = { getDocsPath, readSidebar, processMetadata, generateMetadataDocs, generateMetadataBlog, };
packages/docusaurus-1.x/lib/server/readMetadata.js
1
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.000256984872976318, 0.00017636526899877936, 0.00016532755398657173, 0.00017417616618331522, 0.000014740657206857577 ]
{ "id": 1, "code_window": [ " const join = path.join;\n", " const sep = path.sep;\n", " const escapeStringRegexp = require('escape-string-regexp');\n", " const {renderToStaticMarkupWithDoctype} = require('./renderUtils');\n", " const commander = require('commander');\n", " const imagemin = require('imagemin');\n", " const imageminJpegtran = require('imagemin-jpegtran');\n", " const imageminOptipng = require('imagemin-optipng');\n", " const imageminSvgo = require('imagemin-svgo');\n", " const imageminGifsicle = require('imagemin-gifsicle');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/docusaurus-1.x/lib/server/generate.js", "type": "replace", "edit_start_line_idx": 32 }
# Breaking Changes ### `siteConfig.js` changes - `siteConfig.js` renamed to `docusaurus.config.js`. - Removed the following config options: - `docsUrl`. Use the plugin option on `docusaurus-plugin-content-docs` instead. - `customDocsPath`. Use the plugin option on `docusaurus-plugin-content-docs` instead. - `sidebars.json` now has to be explicitly loaded by users and passed into the the plugin option on `docusaurus-plugin-content-docs`. - `headerLinks` doc, page, blog is deprecated. The syntax is now: ```js headerLinks: [ // Link to internal page (without baseUrl) { url: "help", label: "Help" }, // Links to href destination/ external page { href: "https://github.com/", label: "GitHub" }, ], ``` - `headerLinks` is now moved to themeConfig # Additions ### Presets - Added presets for plugins that follow the [Babel preset convention](https://babeljs.io/docs/en/presets).
packages/docusaurus/CHANGES.md
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.0001715242542559281, 0.00017032655887305737, 0.00016958237392827868, 0.0001698730484349653, 8.551719474780839e-7 ]
{ "id": 1, "code_window": [ " const join = path.join;\n", " const sep = path.sep;\n", " const escapeStringRegexp = require('escape-string-regexp');\n", " const {renderToStaticMarkupWithDoctype} = require('./renderUtils');\n", " const commander = require('commander');\n", " const imagemin = require('imagemin');\n", " const imageminJpegtran = require('imagemin-jpegtran');\n", " const imageminOptipng = require('imagemin-optipng');\n", " const imageminSvgo = require('imagemin-svgo');\n", " const imageminGifsicle = require('imagemin-gifsicle');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/docusaurus-1.x/lib/server/generate.js", "type": "replace", "edit_start_line_idx": 32 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const renderToStaticMarkup = require('react-dom/server').renderToStaticMarkup; /** * Custom function that wraps renderToStaticMarkup so that we can inject * doctype before React renders the contents. All instance of full-page * rendering within Docusaurus should use this function instead. */ function renderToStaticMarkupWithDoctype(...args) { return `<!DOCTYPE html>${renderToStaticMarkup(...args)}`; } module.exports = { renderToStaticMarkupWithDoctype, };
packages/docusaurus-1.x/lib/server/renderUtils.js
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.010794578120112419, 0.004441718105226755, 0.00017029437003657222, 0.0023602815344929695, 0.004580256994813681 ]
{ "id": 1, "code_window": [ " const join = path.join;\n", " const sep = path.sep;\n", " const escapeStringRegexp = require('escape-string-regexp');\n", " const {renderToStaticMarkupWithDoctype} = require('./renderUtils');\n", " const commander = require('commander');\n", " const imagemin = require('imagemin');\n", " const imageminJpegtran = require('imagemin-jpegtran');\n", " const imageminOptipng = require('imagemin-optipng');\n", " const imageminSvgo = require('imagemin-svgo');\n", " const imageminGifsicle = require('imagemin-gifsicle');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/docusaurus-1.x/lib/server/generate.js", "type": "replace", "edit_start_line_idx": 32 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); const CompLibrary = require('../../core/CompLibrary.js'); const Container = CompLibrary.Container; const GridBlock = CompLibrary.GridBlock; const translate = require('../../server/translate.js').translate; class Help extends React.Component { render() { const supportLinks = [ { content: ( <translate> Learn more using the [documentation on this site.](/test-site/docs/en/doc1.html) </translate> ), title: <translate>Browse Docs</translate>, }, { content: ( <translate> Ask questions about the documentation and project </translate> ), title: <translate>Join the community</translate>, }, { content: <translate>Find out what's new with this project</translate>, title: <translate>Stay up to date</translate>, }, ]; return ( <div className="docMainWrapper wrapper"> <Container className="mainContainer documentContainer postContainer"> <div className="post"> <header className="postHeader"> <h2> <translate>Need help?</translate> </h2> </header> <p> <translate desc="statement made to reader"> This project is maintained by a dedicated group of people. </translate> </p> <GridBlock contents={supportLinks} layout="threeColumn" /> </div> </Container> </div> ); } } Help.defaultProps = { language: 'en', }; module.exports = Help;
packages/docusaurus-1.x/examples/translations/pages/en/help-with-translations.js
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.00017526479496154934, 0.00017300342733506113, 0.00017020362429320812, 0.00017325214867014438, 0.0000015300481663871324 ]
{ "id": 2, "code_window": [ " const imageminJpegtran = require('imagemin-jpegtran');\n", " const imageminOptipng = require('imagemin-optipng');\n", " const imageminSvgo = require('imagemin-svgo');\n", " const imageminGifsicle = require('imagemin-gifsicle');\n", "\n", " commander.option('--skip-image-compression').parse(process.argv);\n", "\n", " // create the folder path for a file if it does not exist, then write the file\n", " function writeFileAndCreateFolder(file, content) {\n", " mkdirp.sync(path.dirname(file));\n", " fs.writeFileSync(file, content);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/docusaurus-1.x/lib/server/generate.js", "type": "replace", "edit_start_line_idx": 39 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const CWD = process.cwd(); const path = require('path'); const fs = require('fs'); const glob = require('glob'); const program = require('commander'); const metadataUtils = require('./metadataUtils'); const env = require('./env.js'); const blog = require('./blog.js'); const loadConfig = require('./config'); const siteConfig = loadConfig(`${CWD}/siteConfig.js`); const versionFallback = require('./versionFallback.js'); const utils = require('./utils.js'); const docsPart = `${siteConfig.docsUrl ? `${siteConfig.docsUrl}/` : ''}`; const SupportedHeaderFields = new Set([ 'id', 'title', 'author', 'authorURL', 'authorFBID', 'sidebar_label', 'original_id', 'hide_title', 'layout', 'custom_edit_url', ]); program.option('--skip-next-release').parse(process.argv); let allSidebars; if (fs.existsSync(`${CWD}/sidebars.json`)) { allSidebars = require(`${CWD}/sidebars.json`); } else { allSidebars = {}; } // Can have a custom docs path. Top level folder still needs to be in directory // at the same level as `website`, not inside `website`. // e.g., docs/whereDocsReallyExist // website-docs/ // All .md docs still (currently) must be in one flat directory hierarchy. // e.g., docs/whereDocsReallyExist/*.md (all .md files in this dir) function getDocsPath() { return siteConfig.customDocsPath ? siteConfig.customDocsPath : 'docs'; } function shouldGenerateNextReleaseDocs() { return !( env.versioning.enabled && program.name() === 'docusaurus-build' && program.skipNextRelease ); } // returns map from id to object containing sidebar ordering info function readSidebar(sidebars = {}) { Object.assign(sidebars, versionFallback.sidebarData()); const items = {}; Object.keys(sidebars).forEach(sidebar => { const categories = sidebars[sidebar]; const sidebarItems = []; Object.keys(categories).forEach(category => { const categoryItems = categories[category]; categoryItems.forEach(categoryItem => { if (typeof categoryItem === 'object') { switch (categoryItem.type) { case 'subcategory': categoryItem.ids.forEach(subcategoryItem => { sidebarItems.push({ id: subcategoryItem, category, subcategory: categoryItem.label, order: sidebarItems.length + 1, }); }); return; default: return; } } // Is a regular id value. sidebarItems.push({ id: categoryItem, category, subcategory: null, order: sidebarItems.length + 1, }); }); }); for (let i = 0; i < sidebarItems.length; i++) { const item = sidebarItems[i]; let previous = null; let next = null; if (i > 0) { previous = sidebarItems[i - 1].id; } if (i < sidebarItems.length - 1) { next = sidebarItems[i + 1].id; } items[item.id] = { previous, next, sidebar, category: item.category, subcategory: item.subcategory, order: item.order, }; } }); return items; } // process the metadata for a document found in either 'docs' or 'translated_docs' function processMetadata(file, refDir) { const result = metadataUtils.extractMetadata(fs.readFileSync(file, 'utf8')); const language = utils.getLanguage(file, refDir) || 'en'; const metadata = {}; Object.keys(result.metadata).forEach(fieldName => { if (SupportedHeaderFields.has(fieldName)) { metadata[fieldName] = result.metadata[fieldName]; } else { console.warn(`Header field "${fieldName}" in ${file} is not supported.`); } }); const rawContent = result.rawContent; if (!metadata.id) { metadata.id = path.basename(file, path.extname(file)); } if (metadata.id.includes('/')) { throw new Error('Document id cannot include "/".'); } // If a file is located in a subdirectory, prepend the subdir to it's ID // Example: // (file: 'docusaurus/docs/projectA/test.md', ID 'test', refDir: 'docusaurus/docs') // returns 'projectA/test' const subDir = utils.getSubDir(file, refDir); if (subDir) { metadata.id = `${subDir}/${metadata.id}`; } // Example: `docs/projectA/test.md` source is `projectA/test.md` metadata.source = subDir ? `${subDir}/${path.basename(file)}` : path.basename(file); if (!metadata.title) { metadata.title = metadata.id; } const langPart = env.translation.enabled || siteConfig.useEnglishUrl ? `${language}/` : ''; let versionPart = ''; if (env.versioning.enabled) { metadata.version = 'next'; versionPart = 'next/'; } metadata.permalink = `${docsPart}${langPart}${versionPart}${ metadata.id }.html`; // change ids previous, next metadata.localized_id = metadata.id; metadata.id = (env.translation.enabled ? `${language}-` : '') + metadata.id; metadata.language = env.translation.enabled ? language : 'en'; const items = readSidebar(allSidebars); const id = metadata.localized_id; const item = items[id]; if (item) { metadata.sidebar = item.sidebar; metadata.category = item.category; metadata.subcategory = item.subcategory; metadata.order = item.order; if (item.next) { metadata.next_id = item.next; metadata.next = (env.translation.enabled ? `${language}-` : '') + item.next; } if (item.previous) { metadata.previous_id = item.previous; metadata.previous = (env.translation.enabled ? `${language}-` : '') + item.previous; } } return {metadata, rawContent}; } // process metadata for all docs and save into core/metadata.js function generateMetadataDocs() { let order; try { order = readSidebar(allSidebars); } catch (e) { console.error(e); process.exit(1); } const enabledLanguages = env.translation .enabledLanguages() .map(language => language.tag); const metadatas = {}; const defaultMetadatas = {}; if (shouldGenerateNextReleaseDocs()) { // metadata for english files const docsDir = path.join(CWD, '../', getDocsPath()); let files = glob.sync(`${docsDir}/**`); files.forEach(file => { const extension = path.extname(file); if (extension === '.md' || extension === '.markdown') { const res = processMetadata(file, docsDir); if (!res) { return; } const metadata = res.metadata; metadatas[metadata.id] = metadata; // create a default list of documents for each enabled language based on docs in English // these will get replaced if/when the localized file is downloaded from crowdin enabledLanguages .filter(currentLanguage => currentLanguage !== 'en') .forEach(currentLanguage => { const baseMetadata = Object.assign({}, metadata); baseMetadata.id = baseMetadata.id .toString() .replace(/^en-/, `${currentLanguage}-`); if (baseMetadata.permalink) { baseMetadata.permalink = baseMetadata.permalink .toString() .replace( new RegExp(`^${docsPart}en/`), `${docsPart}${currentLanguage}/`, ); } if (baseMetadata.next) { baseMetadata.next = baseMetadata.next .toString() .replace(/^en-/, `${currentLanguage}-`); } if (baseMetadata.previous) { baseMetadata.previous = baseMetadata.previous .toString() .replace(/^en-/, `${currentLanguage}-`); } baseMetadata.language = currentLanguage; defaultMetadatas[baseMetadata.id] = baseMetadata; }); Object.assign(metadatas, defaultMetadatas); } }); // metadata for non-english docs const translatedDir = path.join(CWD, 'translated_docs'); files = glob.sync(`${CWD}/translated_docs/**`); files.forEach(file => { if (!utils.getLanguage(file, translatedDir)) { return; } const extension = path.extname(file); if (extension === '.md' || extension === '.markdown') { const res = processMetadata(file, translatedDir); if (!res) { return; } const metadata = res.metadata; metadatas[metadata.id] = metadata; } }); } // metadata for versioned docs const versionData = versionFallback.docData(); versionData.forEach(metadata => { const id = metadata.localized_id; if (order[id]) { metadata.sidebar = order[id].sidebar; metadata.category = order[id].category; metadata.subcategory = order[id].subcategory; metadata.order = order[id].order; if (order[id].next) { metadata.next_id = order[id].next.replace( `version-${metadata.version}-`, '', ); metadata.next = (env.translation.enabled ? `${metadata.language}-` : '') + order[id].next; } if (order[id].previous) { metadata.previous_id = order[id].previous.replace( `version-${metadata.version}-`, '', ); metadata.previous = (env.translation.enabled ? `${metadata.language}-` : '') + order[id].previous; } } metadatas[metadata.id] = metadata; }); // Get the titles of the previous and next ids so that we can use them in // navigation buttons in DocsLayout.js Object.keys(metadatas).forEach(metadata => { if (metadatas[metadata].previous) { if (metadatas[metadatas[metadata].previous]) { metadatas[metadata].previous_title = metadatas[metadatas[metadata].previous].title; } else { metadatas[metadata].previous_title = 'Previous'; } } if (metadatas[metadata].next) { if (metadatas[metadatas[metadata].next]) { metadatas[metadata].next_title = metadatas[metadatas[metadata].next].title; } else { metadatas[metadata].next_title = 'Next'; } } }); fs.writeFileSync( path.join(__dirname, '/../core/metadata.js'), `${'/**\n' + ' * @' + 'generated\n' + // separate this out for Nuclide treating @generated as readonly ' */\n' + 'module.exports = '}${JSON.stringify(metadatas, null, 2)};\n`, ); } // process metadata for blog posts and save into core/MetadataBlog.js function generateMetadataBlog() { const metadatas = []; const files = glob.sync(`${CWD}/blog/**/*.*`); files .sort() .reverse() .forEach(file => { const extension = path.extname(file); if (extension !== '.md' && extension !== '.markdown') { return; } const metadata = blog.getMetadata(file); // Extract, YYYY, MM, DD from the file name const filePathDateArr = path .basename(file) .toString() .split('-'); metadata.date = new Date( `${filePathDateArr[0]}-${filePathDateArr[1]}-${ filePathDateArr[2] }T06:00:00.000Z`, ); // allow easier sorting of blog by providing seconds since epoch metadata.seconds = Math.round(metadata.date.getTime() / 1000); metadatas.push(metadata); }); const sortedMetadatas = metadatas.sort( (a, b) => parseInt(b.seconds, 10) - parseInt(a.seconds, 10), ); fs.writeFileSync( path.join(__dirname, '/../core/MetadataBlog.js'), `${'/**\n' + ' * @' + 'generated\n' + // separate this out for Nuclide treating @generated as readonly ' */\n' + 'module.exports = '}${JSON.stringify(sortedMetadatas, null, 2)};\n`, ); } module.exports = { getDocsPath, readSidebar, processMetadata, generateMetadataDocs, generateMetadataBlog, };
packages/docusaurus-1.x/lib/server/readMetadata.js
1
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.001862158882431686, 0.00024283592938445508, 0.0001651114143896848, 0.00017445745470467955, 0.00026964658172801137 ]
{ "id": 2, "code_window": [ " const imageminJpegtran = require('imagemin-jpegtran');\n", " const imageminOptipng = require('imagemin-optipng');\n", " const imageminSvgo = require('imagemin-svgo');\n", " const imageminGifsicle = require('imagemin-gifsicle');\n", "\n", " commander.option('--skip-image-compression').parse(process.argv);\n", "\n", " // create the folder path for a file if it does not exist, then write the file\n", " function writeFileAndCreateFolder(file, content) {\n", " mkdirp.sync(path.dirname(file));\n", " fs.writeFileSync(file, content);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/docusaurus-1.x/lib/server/generate.js", "type": "replace", "edit_start_line_idx": 39 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { 'en-doc1': { id: 'en-doc1', title: 'Document 1', source: 'doc1.md', version: 'next', permalink: 'docs/en/next/doc1.html', localized_id: 'doc1', language: 'en', sidebar: 'docs', category: 'Test', next_id: 'doc2', next: 'en-doc2', next_title: 'Document 2', subcategory: 'Sub Cat 1', sort: 1, }, 'en-doc2': { id: 'en-doc2', title: 'Document 2', source: 'doc2.md', version: 'next', permalink: 'docs/en/next/doc2.html', localized_id: 'doc2', language: 'en', sidebar: 'docs', category: 'Test', previous_id: 'doc1', previous: 'en-doc1', previous_title: 'Document 1', subcategory: 'Sub Cat 1', sort: 2, }, 'en-doc3': { id: 'en-doc3', title: 'Document 3', source: 'doc3.md', version: 'next', permalink: 'docs/en/next/doc3.html', localized_id: 'doc3', language: 'en', sidebar: 'docs', category: 'Test', previous_id: 'doc2', previous: 'en-doc2', previous_title: 'Document 2', subcategory: 'Sub Cat 2', sort: 3, }, 'en-doc4': { id: 'en-doc4', title: 'Document 4', source: 'doc4.md', version: 'next', permalink: 'docs/en/next/doc4.html', localized_id: 'doc4', language: 'en', sidebar: 'docs', category: 'Test 2', previous_id: 'doc3', previous: 'en-doc3', previous_title: 'Document 3', sort: 4, }, };
packages/docusaurus-1.x/lib/server/__tests__/__fixtures__/metadata-subcategories.js
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.00017643078172113746, 0.00017470426973886788, 0.00017146703612525016, 0.00017499743262305856, 0.0000015067234926391393 ]
{ "id": 2, "code_window": [ " const imageminJpegtran = require('imagemin-jpegtran');\n", " const imageminOptipng = require('imagemin-optipng');\n", " const imageminSvgo = require('imagemin-svgo');\n", " const imageminGifsicle = require('imagemin-gifsicle');\n", "\n", " commander.option('--skip-image-compression').parse(process.argv);\n", "\n", " // create the folder path for a file if it does not exist, then write the file\n", " function writeFileAndCreateFolder(file, content) {\n", " mkdirp.sync(path.dirname(file));\n", " fs.writeFileSync(file, content);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/docusaurus-1.x/lib/server/generate.js", "type": "replace", "edit_start_line_idx": 39 }
# Contributing to Docusaurus [Docusaurus](https://docusaurus.io) is our way to hopefully help creating open source documentation easier. We currently have [multiple open source projects using it](https://docusaurus.io/en/users.html), with many more planned. If you're interested in contributing to Docusaurus, hopefully this document makes the process for contributing clear. ## [Code of Conduct](https://code.fb.com/codeofconduct) Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](https://code.fb.com/codeofconduct) so that you can understand what actions will and will not be tolerated. ## Get involved There are many ways to contribute to Docusaurus, and many of them do not involve writing any code. Here's a few ideas to get started: - Simply start using Docusaurus. Go through the [Getting Started](https://docusaurus.io/docs/en/installation.html) guide. Does everything work as expected? If not, we're always looking for improvements. Let us know by [opening an issue](#reporting-new-issues). - Look through the [open issues](https://github.com/facebook/docusaurus/issues). Provide workarounds, ask for clarification, or suggest labels. Help [triage issues](#triaging-issues-and-pull-requests). - If you find an issue you would like to fix, [open a pull request](#your-first-pull-request). Issues tagged as [_Good first issue_](https://github.com/facebook/docusaurus/labels/Good%20first%20issue) are a good place to get started. - Read through the [Docusaurus docs](https://docusaurus.io/docs/en/installation). If you find anything that is confusing or can be improved, you can make edits by clicking "Edit" at the top of most docs. - Take a look at the [features requested](https://github.com/facebook/docusaurus/labels/enhancement) by others in the community and consider opening a pull request if you see something you want to work on. Contributions are very welcome. If you think you need help planning your contribution, please ping us on Twitter at [@docusaurus](https://twitter.com/docusaurus) and let us know you are looking for a bit of help. ### Versioned Docs If you only want to make content changes you just need to know about versioned docs. - `/docs` - The files in here are responsible for the "next" version at https://docusaurus.io/docs/en/next/installation. - `website-1.x/versioned_docs/version-X.Y.Z` - These are the docs for the X.Y.Z version at https://docusaurus.io/docs/en/X.Y.Z/installation. To make a fix to the published versions you must edit the corresponding markdown file in both folders. If you only made changes in `docs`, be sure to be viewing the `next` version to see the updates (ensure there's `next` in the URL). ### Join our Discord Channel We have `#docusaurus-dev` on [Discord](https://discord.gg/docusaurus) to discuss all things Docusaurus development. ### Triaging issues and pull requests One great way you can contribute to the project without writing any code is to help triage issues and pull requests as they come in. - Ask for more information if you believe the issue does not provide all the details required to solve it. - Suggest [labels](https://github.com/facebook/docusaurus/labels) that can help categorize issues. - Flag issues that are stale or that should be closed. - Ask for test plans and review code. ## Our development process Docusaurus uses [GitHub](https://github.com/facebook/docusaurus) as its source of truth. The core team will be working directly there. All changes will be public from the beginning. When a change made on GitHub is approved, it will be checked by our continuous integration system, CircleCI. ### Branch organization Docusaurus has two primary branches: `master` and `gh-pages`. `master` is where our code lives and development takes place. We will do our best to keep `master` in good shape, with tests passing at all times. We will also do our best not to publish updated `npm` packages that will break sites. But in order to move fast, we may make changes that could break existing sites. We will do our best to communicate these changes and version appropriately so you can lock into a specific Docusaurus version if need be. `gh-pages` contains the [Docusaurus documentation](https://docusaurus.io). This branch is pushed to by CI and not generally managed manually. ## Bugs We use [GitHub Issues](https://github.com/facebook/docusaurus/issues) for our public bugs. If you would like to report a problem, take a look around and see if someone already opened an issue about it. If you a are certain this is a new, unreported bug, you can submit a [bug report](#reporting-new-issues). If you have questions about using Docusaurus, contact the Docusaurus Twitter account at [@docusaurus](https://twitter.com/docusaurus), and we will do our best to answer your questions. You can also file issues as [feature requests or enhancements](https://github.com/facebook/Docusaurus/labels/feature%20request). If you see anything you'd like to be implemented, create an issue with [feature template](https://raw.githubusercontent.com/facebook/docusaurus/master/.github/ISSUE_TEMPLATE/feature.md) ## Reporting new issues When [opening a new issue](https://github.com/facebook/docusaurus/issues/new/choose), always make sure to fill out the issue template. **This step is very important!** Not doing so may result in your issue not managed in a timely fashion. Don't take this personally if this happens, and feel free to open a new issue once you've gathered all the information required by the template. - **One issue, one bug:** Please report a single bug per issue. - **Provide reproduction steps:** List all the steps necessary to reproduce the issue. The person reading your bug report should be able to follow these steps to reproduce your issue with minimal effort. ### Security bugs Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe disclosure of security bugs. With that in mind, please do not file public issues; go through the process outlined on that page. ## Installation 1. Ensure you have [Yarn](https://yarnpkg.com/) installed. 1. After cloning the repository, run `yarn install` in the root of the repository. - For Docusaurus 1 development, look into the `packages/docusaurus-1.x` and `website-1.x` directory. - For Docusaurus 2 development, go into the `packages/docusaurus` and `website` directory. 1. Run `yarn start` in the respective project directory to start a local development server serving the Docusaurus docs. ## Pull requests ### Your first pull request So you have decided to contribute code back to upstream by opening a pull request. You've invested a good chunk of time, and we appreciate it. We will do our best to work with you and get the PR looked at. Working on your first Pull Request? You can learn how from this free video series: [**How to Contribute to an Open Source Project on GitHub**](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github) We have a list of [beginner friendly issues](https://github.com/facebook/docusaurus/labels/good%20first%20issue) to help you get your feet wet in the Docusaurus codebase and familiar with our contribution process. This is a great place to get started. ### Proposing a change If you would like to request a new feature or enhancement but are not yet thinking about opening a pull request, you can also file an issue with [feature template](https://github.com/facebook/docusaurus/issues/new?template=feature.md). If you intend to change the public API (e.g., something in `siteConfig.js`), or make any non-trivial changes to the implementation, we recommend filing an issue with [proposal template](https://github.com/facebook/docusaurus/issues/new?template=proposal.md) and including `[Proposal]` in the title. This lets us reach an agreement on your proposal before you put significant effort into it. These types of issues should be rare. If you're only fixing a bug, it's fine to submit a pull request right away but we still recommend to file an issue detailing what you're fixing. This is helpful in case we don't accept that specific fix but want to keep track of the issue. ### Sending a pull request Small pull requests are much easier to review and more likely to get merged. Make sure the PR does only one thing, otherwise please split it. It is recommended to follow this [commit message style](#semantic-commit-messages). Please make sure the following is done when submitting a pull request: 1. Fork [the repository](https://github.com/facebook/docusaurus) and create your branch from `master`. 1. Add the copyright notice to the top of any code new files you've added. 1. Describe your [**test plan**](#test-plan) in your pull request description. Make sure to [test your changes](https://github.com/facebook/Docusaurus/blob/master/admin/testing-changes-on-Docusaurus-itself.md)! 1. Make sure your code lints (`yarn prettier && yarn lint`). 1. Make sure your Jest tests pass (`yarn test`). 1. If you haven't already, [sign the CLA](https://code.facebook.com/cla). All pull requests should be opened against the `master` branch. #### Test plan A good test plan has the exact commands you ran and their output, provides screenshots or videos if the pull request changes UI. - If you've changed APIs, update the documentation. #### Breaking changes When adding a new breaking change, follow this template in your pull request: ```md ### New breaking change here - **Who does this affect**: - **How to migrate**: - **Why make this breaking change**: - **Severity (number of people affected x effort)**: ``` #### Copyright Header for Source Code Copy and paste this to the top of your new file(s): ```js /** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ ``` #### Contributor License Agreement (CLA) In order to accept your pull request, we need you to submit a CLA. You only need to do this once, so if you've done this for another Facebook open source project, you're good to go. If you are submitting a pull request for the first time, the Facebook GitHub Bot will reply with a link to the CLA form. You may also [complete your CLA here](https://code.facebook.com/cla). ### What happens next? The core Docusaurus team will be monitoring for pull requests. Read [what to expect from maintainers](#handling-pull-requests) to understand what may happen after you open a pull request. ## Style Guide [Prettier](https://prettier.io) will catch most styling issues that may exist in your code. You can check the status of your code styling by simply running `npm run prettier`. However, there are still some styles that Prettier cannot pick up. ## Semantic Commit Messages See how a minor change to your commit message style can make you a better programmer. Format: `<type>(<scope>): <subject>` `<scope>` is optional ## Example ``` feat: allow overriding of webpack config ^--^ ^------------^ | | | +-> Summary in present tense. | +-------> Type: chore, docs, feat, fix, refactor, style, or test. ``` The various types of commits: - `feat`: (new feature for the user, not a new feature for build script) - `fix`: (bug fix for the user, not a fix to a build script) - `docs`: (changes to the documentation) - `style`: (formatting, missing semi colons, etc; no production code change) - `refactor`: (refactoring production code, eg. renaming a variable) - `test`: (adding missing tests, refactoring tests; no production code change) - `chore`: (updating grunt tasks etc; no production code change) Use lower case not title case! ### Code Conventions #### General - **Most important: Look around.** Match the style you see used in the rest of the project. This includes formatting, naming files, naming things in code, naming things in documentation. - "Attractive" #### JavaScript - ES6 standards. Prefer using modern language features where they make the code better. - Do not use the optional parameters of `setTimeout` and `setInterval` ### Documentation - Do not wrap lines at 80 characters - configure your editor to soft-wrap when editing documentation. ## License By contributing to Docusaurus, you agree that your contributions will be licensed under its MIT license.
CONTRIBUTING.md
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.0001769053196767345, 0.000172243409906514, 0.00016621602117083967, 0.00017226208001375198, 0.000002228305447715684 ]
{ "id": 2, "code_window": [ " const imageminJpegtran = require('imagemin-jpegtran');\n", " const imageminOptipng = require('imagemin-optipng');\n", " const imageminSvgo = require('imagemin-svgo');\n", " const imageminGifsicle = require('imagemin-gifsicle');\n", "\n", " commander.option('--skip-image-compression').parse(process.argv);\n", "\n", " // create the folder path for a file if it does not exist, then write the file\n", " function writeFileAndCreateFolder(file, content) {\n", " mkdirp.sync(path.dirname(file));\n", " fs.writeFileSync(file, content);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/docusaurus-1.x/lib/server/generate.js", "type": "replace", "edit_start_line_idx": 39 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const {getOptions} = require('loader-utils'); const mdx = require('@mdx-js/mdx'); const rehypePrism = require('@mapbox/rehype-prism'); const emoji = require('remark-emoji'); const slug = require('remark-slug'); const matter = require('gray-matter'); const stringifyObject = require('stringify-object'); const linkHeadings = require('./linkHeadings'); const rightToc = require('./rightToc'); const DEFAULT_OPTIONS = { rehypePlugins: [[rehypePrism, {ignoreMissing: true}], linkHeadings], remarkPlugins: [emoji, slug, rightToc], prismTheme: 'prism-themes/themes/prism-atom-dark.css', }; module.exports = async function(fileString) { const callback = this.async(); const {data, content} = matter(fileString); const options = Object.assign(DEFAULT_OPTIONS, getOptions(this), { filepath: this.resourcePath, }); let result; try { result = await mdx(content, options); } catch (err) { return callback(err); } let importStr = ''; // If webpack target is web, we can import the css if (this.target === 'web') { importStr = `import '${options.prismTheme}';`; } const code = ` import React from 'react'; import { mdx } from '@mdx-js/react'; ${importStr} export const frontMatter = ${stringifyObject(data)}; ${result} `; return callback(null, code); };
packages/docusaurus-mdx-loader/src/index.js
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.0002532531798351556, 0.00018591572006698698, 0.00016886160301510245, 0.00017322380153927952, 0.000030180499379639514 ]
{ "id": 3, "code_window": [ " 'custom_edit_url',\n", "]);\n", "\n", "program.option('--skip-next-release').parse(process.argv);\n", "\n", "let allSidebars;\n", "if (fs.existsSync(`${CWD}/sidebars.json`)) {\n", " allSidebars = require(`${CWD}/sidebars.json`);\n", "} else {\n", " allSidebars = {};\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/docusaurus-1.x/lib/server/readMetadata.js", "type": "replace", "edit_start_line_idx": 40 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const CWD = process.cwd(); const path = require('path'); const fs = require('fs'); const glob = require('glob'); const program = require('commander'); const metadataUtils = require('./metadataUtils'); const env = require('./env.js'); const blog = require('./blog.js'); const loadConfig = require('./config'); const siteConfig = loadConfig(`${CWD}/siteConfig.js`); const versionFallback = require('./versionFallback.js'); const utils = require('./utils.js'); const docsPart = `${siteConfig.docsUrl ? `${siteConfig.docsUrl}/` : ''}`; const SupportedHeaderFields = new Set([ 'id', 'title', 'author', 'authorURL', 'authorFBID', 'sidebar_label', 'original_id', 'hide_title', 'layout', 'custom_edit_url', ]); program.option('--skip-next-release').parse(process.argv); let allSidebars; if (fs.existsSync(`${CWD}/sidebars.json`)) { allSidebars = require(`${CWD}/sidebars.json`); } else { allSidebars = {}; } // Can have a custom docs path. Top level folder still needs to be in directory // at the same level as `website`, not inside `website`. // e.g., docs/whereDocsReallyExist // website-docs/ // All .md docs still (currently) must be in one flat directory hierarchy. // e.g., docs/whereDocsReallyExist/*.md (all .md files in this dir) function getDocsPath() { return siteConfig.customDocsPath ? siteConfig.customDocsPath : 'docs'; } function shouldGenerateNextReleaseDocs() { return !( env.versioning.enabled && program.name() === 'docusaurus-build' && program.skipNextRelease ); } // returns map from id to object containing sidebar ordering info function readSidebar(sidebars = {}) { Object.assign(sidebars, versionFallback.sidebarData()); const items = {}; Object.keys(sidebars).forEach(sidebar => { const categories = sidebars[sidebar]; const sidebarItems = []; Object.keys(categories).forEach(category => { const categoryItems = categories[category]; categoryItems.forEach(categoryItem => { if (typeof categoryItem === 'object') { switch (categoryItem.type) { case 'subcategory': categoryItem.ids.forEach(subcategoryItem => { sidebarItems.push({ id: subcategoryItem, category, subcategory: categoryItem.label, order: sidebarItems.length + 1, }); }); return; default: return; } } // Is a regular id value. sidebarItems.push({ id: categoryItem, category, subcategory: null, order: sidebarItems.length + 1, }); }); }); for (let i = 0; i < sidebarItems.length; i++) { const item = sidebarItems[i]; let previous = null; let next = null; if (i > 0) { previous = sidebarItems[i - 1].id; } if (i < sidebarItems.length - 1) { next = sidebarItems[i + 1].id; } items[item.id] = { previous, next, sidebar, category: item.category, subcategory: item.subcategory, order: item.order, }; } }); return items; } // process the metadata for a document found in either 'docs' or 'translated_docs' function processMetadata(file, refDir) { const result = metadataUtils.extractMetadata(fs.readFileSync(file, 'utf8')); const language = utils.getLanguage(file, refDir) || 'en'; const metadata = {}; Object.keys(result.metadata).forEach(fieldName => { if (SupportedHeaderFields.has(fieldName)) { metadata[fieldName] = result.metadata[fieldName]; } else { console.warn(`Header field "${fieldName}" in ${file} is not supported.`); } }); const rawContent = result.rawContent; if (!metadata.id) { metadata.id = path.basename(file, path.extname(file)); } if (metadata.id.includes('/')) { throw new Error('Document id cannot include "/".'); } // If a file is located in a subdirectory, prepend the subdir to it's ID // Example: // (file: 'docusaurus/docs/projectA/test.md', ID 'test', refDir: 'docusaurus/docs') // returns 'projectA/test' const subDir = utils.getSubDir(file, refDir); if (subDir) { metadata.id = `${subDir}/${metadata.id}`; } // Example: `docs/projectA/test.md` source is `projectA/test.md` metadata.source = subDir ? `${subDir}/${path.basename(file)}` : path.basename(file); if (!metadata.title) { metadata.title = metadata.id; } const langPart = env.translation.enabled || siteConfig.useEnglishUrl ? `${language}/` : ''; let versionPart = ''; if (env.versioning.enabled) { metadata.version = 'next'; versionPart = 'next/'; } metadata.permalink = `${docsPart}${langPart}${versionPart}${ metadata.id }.html`; // change ids previous, next metadata.localized_id = metadata.id; metadata.id = (env.translation.enabled ? `${language}-` : '') + metadata.id; metadata.language = env.translation.enabled ? language : 'en'; const items = readSidebar(allSidebars); const id = metadata.localized_id; const item = items[id]; if (item) { metadata.sidebar = item.sidebar; metadata.category = item.category; metadata.subcategory = item.subcategory; metadata.order = item.order; if (item.next) { metadata.next_id = item.next; metadata.next = (env.translation.enabled ? `${language}-` : '') + item.next; } if (item.previous) { metadata.previous_id = item.previous; metadata.previous = (env.translation.enabled ? `${language}-` : '') + item.previous; } } return {metadata, rawContent}; } // process metadata for all docs and save into core/metadata.js function generateMetadataDocs() { let order; try { order = readSidebar(allSidebars); } catch (e) { console.error(e); process.exit(1); } const enabledLanguages = env.translation .enabledLanguages() .map(language => language.tag); const metadatas = {}; const defaultMetadatas = {}; if (shouldGenerateNextReleaseDocs()) { // metadata for english files const docsDir = path.join(CWD, '../', getDocsPath()); let files = glob.sync(`${docsDir}/**`); files.forEach(file => { const extension = path.extname(file); if (extension === '.md' || extension === '.markdown') { const res = processMetadata(file, docsDir); if (!res) { return; } const metadata = res.metadata; metadatas[metadata.id] = metadata; // create a default list of documents for each enabled language based on docs in English // these will get replaced if/when the localized file is downloaded from crowdin enabledLanguages .filter(currentLanguage => currentLanguage !== 'en') .forEach(currentLanguage => { const baseMetadata = Object.assign({}, metadata); baseMetadata.id = baseMetadata.id .toString() .replace(/^en-/, `${currentLanguage}-`); if (baseMetadata.permalink) { baseMetadata.permalink = baseMetadata.permalink .toString() .replace( new RegExp(`^${docsPart}en/`), `${docsPart}${currentLanguage}/`, ); } if (baseMetadata.next) { baseMetadata.next = baseMetadata.next .toString() .replace(/^en-/, `${currentLanguage}-`); } if (baseMetadata.previous) { baseMetadata.previous = baseMetadata.previous .toString() .replace(/^en-/, `${currentLanguage}-`); } baseMetadata.language = currentLanguage; defaultMetadatas[baseMetadata.id] = baseMetadata; }); Object.assign(metadatas, defaultMetadatas); } }); // metadata for non-english docs const translatedDir = path.join(CWD, 'translated_docs'); files = glob.sync(`${CWD}/translated_docs/**`); files.forEach(file => { if (!utils.getLanguage(file, translatedDir)) { return; } const extension = path.extname(file); if (extension === '.md' || extension === '.markdown') { const res = processMetadata(file, translatedDir); if (!res) { return; } const metadata = res.metadata; metadatas[metadata.id] = metadata; } }); } // metadata for versioned docs const versionData = versionFallback.docData(); versionData.forEach(metadata => { const id = metadata.localized_id; if (order[id]) { metadata.sidebar = order[id].sidebar; metadata.category = order[id].category; metadata.subcategory = order[id].subcategory; metadata.order = order[id].order; if (order[id].next) { metadata.next_id = order[id].next.replace( `version-${metadata.version}-`, '', ); metadata.next = (env.translation.enabled ? `${metadata.language}-` : '') + order[id].next; } if (order[id].previous) { metadata.previous_id = order[id].previous.replace( `version-${metadata.version}-`, '', ); metadata.previous = (env.translation.enabled ? `${metadata.language}-` : '') + order[id].previous; } } metadatas[metadata.id] = metadata; }); // Get the titles of the previous and next ids so that we can use them in // navigation buttons in DocsLayout.js Object.keys(metadatas).forEach(metadata => { if (metadatas[metadata].previous) { if (metadatas[metadatas[metadata].previous]) { metadatas[metadata].previous_title = metadatas[metadatas[metadata].previous].title; } else { metadatas[metadata].previous_title = 'Previous'; } } if (metadatas[metadata].next) { if (metadatas[metadatas[metadata].next]) { metadatas[metadata].next_title = metadatas[metadatas[metadata].next].title; } else { metadatas[metadata].next_title = 'Next'; } } }); fs.writeFileSync( path.join(__dirname, '/../core/metadata.js'), `${'/**\n' + ' * @' + 'generated\n' + // separate this out for Nuclide treating @generated as readonly ' */\n' + 'module.exports = '}${JSON.stringify(metadatas, null, 2)};\n`, ); } // process metadata for blog posts and save into core/MetadataBlog.js function generateMetadataBlog() { const metadatas = []; const files = glob.sync(`${CWD}/blog/**/*.*`); files .sort() .reverse() .forEach(file => { const extension = path.extname(file); if (extension !== '.md' && extension !== '.markdown') { return; } const metadata = blog.getMetadata(file); // Extract, YYYY, MM, DD from the file name const filePathDateArr = path .basename(file) .toString() .split('-'); metadata.date = new Date( `${filePathDateArr[0]}-${filePathDateArr[1]}-${ filePathDateArr[2] }T06:00:00.000Z`, ); // allow easier sorting of blog by providing seconds since epoch metadata.seconds = Math.round(metadata.date.getTime() / 1000); metadatas.push(metadata); }); const sortedMetadatas = metadatas.sort( (a, b) => parseInt(b.seconds, 10) - parseInt(a.seconds, 10), ); fs.writeFileSync( path.join(__dirname, '/../core/MetadataBlog.js'), `${'/**\n' + ' * @' + 'generated\n' + // separate this out for Nuclide treating @generated as readonly ' */\n' + 'module.exports = '}${JSON.stringify(sortedMetadatas, null, 2)};\n`, ); } module.exports = { getDocsPath, readSidebar, processMetadata, generateMetadataDocs, generateMetadataBlog, };
packages/docusaurus-1.x/lib/server/readMetadata.js
1
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.9991171956062317, 0.12118835747241974, 0.00016837894509080797, 0.0001751564268488437, 0.32218924164772034 ]
{ "id": 3, "code_window": [ " 'custom_edit_url',\n", "]);\n", "\n", "program.option('--skip-next-release').parse(process.argv);\n", "\n", "let allSidebars;\n", "if (fs.existsSync(`${CWD}/sidebars.json`)) {\n", " allSidebars = require(`${CWD}/sidebars.json`);\n", "} else {\n", " allSidebars = {};\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/docusaurus-1.x/lib/server/readMetadata.js", "type": "replace", "edit_start_line_idx": 40 }
module.exports = function preset(context, opts = {}) { return { plugins: [ { name: '@docusaurus/plugin-content-pages', options: opts.pages, }, { name: '@docusaurus/plugin-sitemap', options: opts.sitemap, }, ], }; };
packages/docusaurus/src/server/load/__tests__/__fixtures__/preset-foo.js
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.00017236090207006782, 0.00017132479115389287, 0.00017028869478963315, 0.00017132479115389287, 0.000001036103640217334 ]
{ "id": 3, "code_window": [ " 'custom_edit_url',\n", "]);\n", "\n", "program.option('--skip-next-release').parse(process.argv);\n", "\n", "let allSidebars;\n", "if (fs.existsSync(`${CWD}/sidebars.json`)) {\n", " allSidebars = require(`${CWD}/sidebars.json`);\n", "} else {\n", " allSidebars = {};\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/docusaurus-1.x/lib/server/readMetadata.js", "type": "replace", "edit_start_line_idx": 40 }
--- id: version-1.9.0-site-preparation title: Site Preparation original_id: site-preparation --- After [installing Docusaurus](getting-started-installation.md), you now have a skeleton to work from for your specific website. The following discusses the rest of the Docusaurus structure in order for you to prepare your site. ## Directory Structure As shown after you [installed Docusaurus](getting-started-installation.md), the initialization script created a directory structure similar to: ```bash root-directory ├── docs │ ├── doc1.md │ ├── doc2.md │ ├── doc3.md │ ├── exampledoc4.md │ └── exampledoc5.md └── website ├── blog │ ├── 2016-03-11-blog-post.md │ ├── 2017-04-10-blog-post-two.md │ ├── 2017-09-25-testing-rss.md │ ├── 2017-09-26-adding-rss.md │ └── 2017-10-24-new-version-1.0.0.md ├── core │ └── Footer.js ├── package.json ├── pages ├── sidebars.json ├── siteConfig.js └── static ``` ### Directory Descriptions * **Documentation Source Files**: The `docs` directory contains example documentation files written in Markdown. * **Blog**: The `website/blog` directory contains examples of blog posts written in markdown. * **Pages**: The `website/pages` directory contains example top-level pages for the site. * **Static files and images**: The `website/static` directory contains static assets used by the example site. ### Key Files * **Footer**: The `website/core/Footer.js` file is a React component that acts as the footer for the site generated by Docusaurus and should be customized by the user. * **Configuration file**: The `website/siteConfig.js` file is the main configuration file used by Docusaurus. * **Sidebars**: The `sidebars.json` file contains the structure and ordering of the documentation files. ## Preparation Notes You will need to keep the `website/siteConfig.js` and `website/core/Footer.js` files, but may edit them as you wish. The value of the `customDocsPath` key in `website/siteConfig.js` can be modified if you wish to use a different directory name or path. The `website` directory can also be renamed to anything you want it to be. However, you should keep the `website/pages` and `website/static` directories. You may change the content inside them as you wish. At the bare minimum you should have an `en/index.js` or `en/index.html` file inside `website/pages` and an image to use as your header icon inside `website/static`.
website-1.x/versioned_docs/version-1.9.0/getting-started-preparation.md
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.06699115037918091, 0.011801350861787796, 0.00017126751481555402, 0.00017291010590270162, 0.02470521815121174 ]
{ "id": 3, "code_window": [ " 'custom_edit_url',\n", "]);\n", "\n", "program.option('--skip-next-release').parse(process.argv);\n", "\n", "let allSidebars;\n", "if (fs.existsSync(`${CWD}/sidebars.json`)) {\n", " allSidebars = require(`${CWD}/sidebars.json`);\n", "} else {\n", " allSidebars = {};\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/docusaurus-1.x/lib/server/readMetadata.js", "type": "replace", "edit_start_line_idx": 40 }
--- id: cli title: CLI --- TODO: Add CLI reference here. #### References - TODO
website/docs/cli.md
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.00017560353444423527, 0.00017498427769169211, 0.00017436502093914896, 0.00017498427769169211, 6.192567525431514e-7 ]
{ "id": 4, "code_window": [ "}\n", "\n", "function shouldGenerateNextReleaseDocs() {\n", " return !(\n", " env.versioning.enabled &&\n", " program.name() === 'docusaurus-build' &&\n", " program.skipNextRelease\n", " );\n", "}\n", "\n", "// returns map from id to object containing sidebar ordering info\n", "function readSidebar(sidebars = {}) {\n", " Object.assign(sidebars, versionFallback.sidebarData());\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return !(env.versioning.enabled && program.skipNextRelease);\n" ], "file_path": "packages/docusaurus-1.x/lib/server/readMetadata.js", "type": "replace", "edit_start_line_idx": 60 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ async function execute() { require('../write-translations.js'); const metadataUtils = require('./metadataUtils'); const blog = require('./blog'); const docs = require('./docs'); const CWD = process.cwd(); const fs = require('fs-extra'); const readMetadata = require('./readMetadata.js'); const path = require('path'); const {minifyCss, isSeparateCss, autoPrefixCss} = require('./utils'); const React = require('react'); const mkdirp = require('mkdirp'); const glob = require('glob'); const chalk = require('chalk'); const Site = require('../core/Site.js'); const env = require('./env.js'); const loadConfig = require('./config.js'); const siteConfig = loadConfig(`${CWD}/siteConfig.js`); const translate = require('./translate.js'); const feed = require('./feed.js'); const sitemap = require('./sitemap.js'); const join = path.join; const sep = path.sep; const escapeStringRegexp = require('escape-string-regexp'); const {renderToStaticMarkupWithDoctype} = require('./renderUtils'); const commander = require('commander'); const imagemin = require('imagemin'); const imageminJpegtran = require('imagemin-jpegtran'); const imageminOptipng = require('imagemin-optipng'); const imageminSvgo = require('imagemin-svgo'); const imageminGifsicle = require('imagemin-gifsicle'); commander.option('--skip-image-compression').parse(process.argv); // create the folder path for a file if it does not exist, then write the file function writeFileAndCreateFolder(file, content) { mkdirp.sync(path.dirname(file)); fs.writeFileSync(file, content); // build extra file for extension-less url if "cleanUrl" siteConfig is true if (siteConfig.cleanUrl && file.indexOf('index.html') === -1) { const extraFile = file.replace(/\.html$/, '/index.html'); mkdirp.sync(path.dirname(extraFile)); fs.writeFileSync(extraFile, content); } } console.log('generate.js triggered...'); readMetadata.generateMetadataDocs(); const Metadata = require('../core/metadata.js'); // TODO: what if the project is a github org page? We should not use // siteConfig.projectName in this case. Otherwise a GitHub org doc URL would // look weird: https://myorg.github.io/myorg/docs // TODO: siteConfig.projectName is a misnomer. The actual project name is // `title`. `projectName` is only used to generate a folder, which isn't // needed when the project's a GitHub org page const buildDir = join(CWD, 'build', siteConfig.projectName); fs.removeSync(join(CWD, 'build')); // create html files for all docs by going through all doc ids const mdToHtml = metadataUtils.mdToHtml(Metadata, siteConfig); Object.keys(Metadata).forEach(id => { const metadata = Metadata[id]; const file = docs.getFile(metadata); if (!file) { return; } const rawContent = metadataUtils.extractMetadata(file).rawContent; const str = docs.getMarkup(rawContent, mdToHtml, metadata); const targetFile = join(buildDir, metadata.permalink); writeFileAndCreateFolder(targetFile, str); // generate english page redirects when languages are enabled const redirectMarkup = docs.getRedirectMarkup(metadata); if (!redirectMarkup) { return; } const docsPart = `${siteConfig.docsUrl ? `${siteConfig.docsUrl}/` : ''}`; const redirectFile = join( buildDir, metadata.permalink.replace( new RegExp(`^${docsPart}en`), siteConfig.docsUrl, ), ); writeFileAndCreateFolder(redirectFile, redirectMarkup); }); // copy docs assets if they exist if (fs.existsSync(join(CWD, '..', readMetadata.getDocsPath(), 'assets'))) { fs.copySync( join(CWD, '..', readMetadata.getDocsPath(), 'assets'), join(buildDir, siteConfig.docsUrl, 'assets'), ); } // create html files for all blog posts (each article) if (fs.existsSync(join(__dirname, '..', 'core', 'MetadataBlog.js'))) { fs.removeSync(join(__dirname, '..', 'core', 'MetadataBlog.js')); } readMetadata.generateMetadataBlog(); const MetadataBlog = require('../core/MetadataBlog.js'); let files = glob.sync(join(CWD, 'blog', '**', '*.*')); files .sort() .reverse() .forEach(file => { // Why normalize? In case we are on Windows. // Remember the nuance of glob: https://www.npmjs.com/package/glob#windows const normalizedFile = path.normalize(file); const extension = path.extname(normalizedFile); if (extension !== '.md' && extension !== '.markdown') { return; } const urlPath = blog.fileToUrl(normalizedFile); const blogPost = blog.getPostMarkup(normalizedFile, siteConfig); if (!blogPost) { return; } const targetFile = join(buildDir, 'blog', urlPath); writeFileAndCreateFolder(targetFile, blogPost); }); // create html files for all blog pages (collections of article previews) const blogPages = blog.getPagesMarkup(MetadataBlog.length, siteConfig); Object.keys(blogPages).forEach(pagePath => { const targetFile = join(buildDir, 'blog', pagePath); writeFileAndCreateFolder(targetFile, blogPages[pagePath]); }); // create rss files for all blog pages, if there are any blog files if (MetadataBlog.length > 0) { let targetFile = join(buildDir, 'blog', 'feed.xml'); writeFileAndCreateFolder(targetFile, feed()); targetFile = join(buildDir, 'blog', 'atom.xml'); writeFileAndCreateFolder(targetFile, feed('atom')); } // create sitemap if (MetadataBlog.length > 0 || Object.keys(Metadata).length > 0) { sitemap((err, xml) => { if (!err) { const targetFile = join(buildDir, 'sitemap.xml'); writeFileAndCreateFolder(targetFile, xml); } }); } // copy blog assets if they exist if (fs.existsSync(join(CWD, 'blog', 'assets'))) { fs.copySync(join(CWD, 'blog', 'assets'), join(buildDir, 'blog', 'assets')); } // copy all static files from docusaurus const libStaticDir = join(__dirname, '..', 'static'); files = glob.sync(join(libStaticDir, '**')); files.forEach(file => { // Why normalize? In case we are on Windows. // Remember the nuance of glob: https://www.npmjs.com/package/glob#windows const targetFile = path.normalize(file).replace(libStaticDir, buildDir); // parse css files to replace colors according to siteConfig if (file.match(/\.css$/)) { let cssContent = fs.readFileSync(file, 'utf8'); if ( !siteConfig.colors || !siteConfig.colors.primaryColor || !siteConfig.colors.secondaryColor ) { console.error( `${chalk.yellow( 'Missing color configuration.', )} Make sure siteConfig.colors includes primaryColor and secondaryColor fields.`, ); } Object.keys(siteConfig.colors).forEach(key => { const color = siteConfig.colors[key]; cssContent = cssContent.replace(new RegExp(`\\$${key}`, 'g'), color); }); if (siteConfig.fonts) { Object.keys(siteConfig.fonts).forEach(key => { const fontString = siteConfig.fonts[key] .map(font => `"${font}"`) .join(', '); cssContent = cssContent.replace( new RegExp(`\\$${key}`, 'g'), fontString, ); }); } mkdirp.sync(path.dirname(targetFile)); fs.writeFileSync(targetFile, cssContent); } else if (!fs.lstatSync(file).isDirectory()) { mkdirp.sync(path.dirname(targetFile)); fs.copySync(file, targetFile); } }); // Copy all static files from user. const userStaticDir = join(CWD, 'static'); files = glob.sync(join(userStaticDir, '**'), {dot: true}); files.forEach(file => { // Why normalize? In case we are on Windows. // Remember the nuance of glob: https://www.npmjs.com/package/glob#windows const normalizedFile = path.normalize(file); // parse css files to replace colors and fonts according to siteConfig if ( normalizedFile.match(/\.css$/) && !isSeparateCss(normalizedFile, siteConfig.separateCss) ) { const mainCss = join(buildDir, 'css', 'main.css'); let cssContent = fs.readFileSync(normalizedFile, 'utf8'); cssContent = `${fs.readFileSync(mainCss, 'utf8')}\n${cssContent}`; Object.keys(siteConfig.colors).forEach(key => { const color = siteConfig.colors[key]; cssContent = cssContent.replace(new RegExp(`\\$${key}`, 'g'), color); }); if (siteConfig.fonts) { Object.keys(siteConfig.fonts).forEach(key => { const fontString = siteConfig.fonts[key] .map(font => `"${font}"`) .join(', '); cssContent = cssContent.replace( new RegExp(`\\$${key}`, 'g'), fontString, ); }); } fs.writeFileSync(mainCss, cssContent); } else if ( normalizedFile.match(/\.png$|.jpg$|.svg$|.gif$/) && !commander.skipImageCompression ) { const parts = normalizedFile.split(`${sep}static${sep}`); const targetFile = join(buildDir, parts[1]); const targetDirectory = path.dirname(targetFile); mkdirp.sync(targetDirectory); imagemin([normalizedFile], targetDirectory, { use: [ imageminOptipng(), imageminJpegtran(), imageminSvgo({ plugins: [{removeViewBox: false}], }), imageminGifsicle(), ], }).catch(error => { // if image compression fail, just copy it as it is console.error(error); fs.copySync(normalizedFile, targetFile); }); } else if (!fs.lstatSync(normalizedFile).isDirectory()) { const targetFile = normalizedFile.replace(userStaticDir, buildDir); mkdirp.sync(path.dirname(targetFile)); fs.copySync(normalizedFile, targetFile); } }); // Use cssnano to minify the final combined CSS. // Use autoprefixer to add vendor prefixes const mainCss = join(buildDir, 'css', 'main.css'); const cssContent = fs.readFileSync(mainCss, 'utf8'); const minifiedCSS = await minifyCss(cssContent); const css = await autoPrefixCss(minifiedCSS); fs.writeFileSync(mainCss, css); // compile/copy pages from user const enabledLanguages = env.translation .enabledLanguages() .map(lang => lang.tag); const userPagesDir = join(CWD, 'pages'); files = glob.sync(join(userPagesDir, '**')); files.forEach(file => { // Why normalize? In case we are on Windows. // Remember the nuance of glob: https://www.npmjs.com/package/glob#windows const normalizedFile = path.normalize(file); const relativeFile = normalizedFile.replace(userPagesDir, ''); // render .js files to strings if (normalizedFile.match(/\.js$/)) { const pageID = path.basename(normalizedFile, '.js'); // make temp file for sake of require paths let tempFile = join(__dirname, '..', 'pages', relativeFile); tempFile = tempFile.replace( path.basename(normalizedFile), `temp${path.basename(normalizedFile)}`, ); mkdirp.sync(path.dirname(tempFile)); fs.copySync(normalizedFile, tempFile); const ReactComp = require(tempFile); let targetFile = join(buildDir, relativeFile); targetFile = targetFile.replace(/\.js$/, '.html'); const regexLang = new RegExp( `${escapeStringRegexp(`${userPagesDir}${sep}`)}(.*)${escapeStringRegexp( sep, )}`, ); const match = regexLang.exec(normalizedFile); const langParts = match[1].split(sep); if (langParts.indexOf('en') !== -1) { // Copy and compile a page for each enabled language from the English file. for (let i = 0; i < enabledLanguages.length; i++) { const language = enabledLanguages[i]; // Skip conversion from English file if a file exists for this language. if ( language === 'en' || !fs.existsSync( normalizedFile.replace(`${sep}en${sep}`, sep + language + sep), ) ) { translate.setLanguage(language); const str = renderToStaticMarkupWithDoctype( <Site language={language} config={siteConfig} title={ReactComp.title} description={ReactComp.description} metadata={{id: pageID}}> <ReactComp config={siteConfig} language={language} /> </Site>, ); writeFileAndCreateFolder( // TODO: use path functions targetFile.replace(`${sep}en${sep}`, sep + language + sep), str, ); } } // write to base level const language = env.translation.enabled ? 'en' : ''; translate.setLanguage(language); const str = renderToStaticMarkupWithDoctype( <Site title={ReactComp.title} language={language} config={siteConfig} description={ReactComp.description} metadata={{id: pageID}}> <ReactComp config={siteConfig} language={language} /> </Site>, ); writeFileAndCreateFolder( targetFile.replace(`${sep}en${sep}`, sep), str, ); } else { // allow for rendering of other files not in pages/en folder const language = env.translation.enabled ? 'en' : ''; translate.setLanguage(language); const str = renderToStaticMarkupWithDoctype( <Site title={ReactComp.title} language={language} config={siteConfig} description={ReactComp.description} metadata={{id: pageID}}> <ReactComp config={siteConfig} language={language} /> </Site>, ); writeFileAndCreateFolder( targetFile.replace(`${sep}en${sep}`, sep), str, ); } fs.removeSync(tempFile); } else if (siteConfig.wrapPagesHTML && normalizedFile.match(/\.html$/)) { const pageID = path.basename(normalizedFile, '.html'); const targetFile = join(buildDir, relativeFile); const str = renderToStaticMarkupWithDoctype( <Site language="en" config={siteConfig} metadata={{id: pageID}}> <div dangerouslySetInnerHTML={{ __html: fs.readFileSync(normalizedFile, {encoding: 'utf8'}), }} /> </Site>, ); writeFileAndCreateFolder(targetFile, str); } else if (!fs.lstatSync(normalizedFile).isDirectory()) { // copy other non .js files const targetFile = join(buildDir, relativeFile); mkdirp.sync(path.dirname(targetFile)); fs.copySync(normalizedFile, targetFile); } }); // Generate CNAME file if a custom domain is specified in siteConfig if (siteConfig.cname) { const targetFile = join(buildDir, 'CNAME'); fs.writeFileSync(targetFile, siteConfig.cname); } } module.exports = execute;
packages/docusaurus-1.x/lib/server/generate.js
1
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.0010538854403421283, 0.00019981602963525802, 0.0001673799124546349, 0.00017525439034216106, 0.00013612823386210948 ]
{ "id": 4, "code_window": [ "}\n", "\n", "function shouldGenerateNextReleaseDocs() {\n", " return !(\n", " env.versioning.enabled &&\n", " program.name() === 'docusaurus-build' &&\n", " program.skipNextRelease\n", " );\n", "}\n", "\n", "// returns map from id to object containing sidebar ordering info\n", "function readSidebar(sidebars = {}) {\n", " Object.assign(sidebars, versionFallback.sidebarData());\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return !(env.versioning.enabled && program.skipNextRelease);\n" ], "file_path": "packages/docusaurus-1.x/lib/server/readMetadata.js", "type": "replace", "edit_start_line_idx": 60 }
<svg id="ad7c1fe1-eb22-473c-bc85-8b4fe073a50d" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1094.72" height="788.69" viewBox="0 0 1094.72 788.69"><defs><linearGradient id="f137b292-0aa2-40b3-a442-9a256144b6d8" x1="2938.83" y1="215.4" x2="2938.83" y2="-91.93" gradientTransform="matrix(0.51, 0.86, -0.86, 0.51, -713.07, -2373.14)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="gray" stop-opacity="0.25"/><stop offset="0.54" stop-color="gray" stop-opacity="0.12"/><stop offset="1" stop-color="gray" stop-opacity="0.1"/></linearGradient><linearGradient id="ab747304-1bb2-44ed-8687-72ce94e318d2" x1="1364.21" y1="820.42" x2="1364.21" y2="492.03" gradientTransform="matrix(-1, -0.04, -0.04, 1, 2349.24, 29.65)" xlink:href="#f137b292-0aa2-40b3-a442-9a256144b6d8"/></defs><title>monitor</title><g opacity="0.5"><rect x="960.72" y="367.69" width="134" height="134" rx="14.12" fill="#d0d2d5"/><path d="M1061.36,461.85h38s32,28,0,57h-38S1029.36,492.85,1061.36,461.85Z" transform="translate(-52.64 -55.65)" opacity="0.1"/><rect x="1012.72" y="422.19" width="5" height="15" fill="#3f3d56"/><rect x="1037.72" y="420.19" width="5" height="18" fill="#3f3d56"/><path d="M1027.72,446.19h0a6,6,0,0,1,6,6v5a0,0,0,0,1,0,0h-12a0,0,0,0,1,0,0v-5A6,6,0,0,1,1027.72,446.19Z" fill="#3f3d56"/></g><path d="M674.41,294.11c3.17-.07,6.33.17,9.49,0,2.89-.14,5.76-.61,8.65-.9,4.94-.49,9.92-.45,14.88-.66,3.26-.14,6.7-.46,9.34-2.38,2.48-1.79,3.86-4.71,6.07-6.83,9-8.65,15.17-20.22,23.17-29.82,2-2.44,4.09-4.87,5.9-7.48,3.47-5,5.92-10.67,8.36-16.27a45.11,45.11,0,0,0,2.4-6.42c.45-1.76.68-3.58,1.28-5.3,1.24-3.52,4.22-6.6,4.58-10.31l-.42.06c3.64-4.63,3.08-12.7,4.88-18.63a80.28,80.28,0,0,1,4.17-10.29l6.69-14.57c1.15-2.5,2.35-5.08,4.34-7,2.41-2.33,5.77-3.49,8.19-5.81a12.71,12.71,0,0,0,3.14-5.11l.21.2c1.28,1.25,2.28,2.78,3.53,4.07,2.69,2.78,6.42,4.37,9.16,7.1,1.4,1.39,2.55,3.08,4.24,4.09a4.7,4.7,0,0,0,5.44-.67c4.91-4.32,12.23-4.72,17.54-8.53,1.47-1.06,2.75-2.35,4.13-3.51a56.32,56.32,0,0,1,10.67-6.7,26.61,26.61,0,0,1,6.59.94c3.08.85,6.09,2.26,9.29,2.2a13.4,13.4,0,0,0,7.81-3c1.63-1.26,3.12-3,3.36-5a6.42,6.42,0,0,0-2.4-5.4c-.22-.19-.45-.36-.68-.53A6.68,6.68,0,0,0,876,127a16,16,0,0,0-5.45-2.78,11.69,11.69,0,0,0-3.44-.78,15.7,15.7,0,0,0-5.34,1.25,51.34,51.34,0,0,1-10.47,2.2c-.63.06-1.91-.07-3-.08l-.37-1.06c-4.16,1.92-9,.34-13.56.35-2.22,0-4.43.39-6.64.53a59.92,59.92,0,0,1-7.34-.16L813,126a87.11,87.11,0,0,1-9.42-1c-.83-1.69-1.66-3.38-2.59-5a46.27,46.27,0,0,0-5.49-7.63,26.52,26.52,0,0,1,2.64-2l.18-.11c.23-.13.51-.27.82-.41A18.93,18.93,0,0,0,826.2,92.77a14.5,14.5,0,0,0,1.6-.73c.3-.16.6-.33.89-.52l.43-.29a8.34,8.34,0,0,0,.78-.67c.12-.12.24-.24.35-.37a4.78,4.78,0,0,0,.57-.84l0,0c.06-.12.12-.23.17-.35s0-.09.05-.14.07-.18.1-.26,0-.12.05-.18l.06-.24a1.29,1.29,0,0,0,0-.19c0-.08,0-.16,0-.23l0-.21a1.64,1.64,0,0,1,0-.22,1.7,1.7,0,0,0,0-.22c0-.07,0-.15,0-.22a1.62,1.62,0,0,0,0-.22V86.4a1.79,1.79,0,0,0,0-.23c0-.07,0-.14,0-.21l0-.24,0-.2c0-.09,0-.18,0-.26a1.16,1.16,0,0,0,0-.18,2.33,2.33,0,0,0,0-.28c0-.06,0-.11,0-.16s0-.2-.07-.3l0-.14-.09-.32,0-.12c0-.11-.07-.22-.1-.33l0-.1-.12-.36,0-.06c0-.17-.11-.35-.17-.52-.75-2.16-1.56-4.31-2.42-6.43a15.64,15.64,0,0,0-2.78-4.86c-1.77-1.88-4.31-2.82-6.43-4.32-2.5-1.76-4.37-4.25-6.49-6.47s-4.69-4.23-7.74-4.6A15.16,15.16,0,0,0,797.78,57c-18.37,6.78-33.41,20.14-49.88,30.74-6.41,4.13-13.59,8-21.18,7.47l6.7,10.64c.32.52.65,1,1,1.54s.7,1,1.07,1.5a12.07,12.07,0,0,0,3.51,3.22,7.69,7.69,0,0,0,1.08.52,8.88,8.88,0,0,0,1,.31c2.39.57,5,.09,7.42-.39.83-.16,1.66-.33,2.48-.52l1-.28.16,0c0,.06,0,.11,0,.16-.56,1-1.09,1.91-1.56,2.9a60.81,60.81,0,0,0-3.57,11.12c-1.89,7.5-3.79,15.16-3.29,22.86.17,2.6.61,5.26-.14,7.76-.36,1.23-1,2.49-.66,3.71a17.12,17.12,0,0,1,.92,2.18c.16,1.16-.76,2.16-1.42,3.12s-1,2.49-.06,3.16a5.39,5.39,0,0,0-3.57,4.45,3.79,3.79,0,0,1-.34,1.71,4.23,4.23,0,0,1-1,.93,5.39,5.39,0,0,0-1.87,3.36c-1.93,0-3.56,1.88-5.32,3a21.45,21.45,0,0,1-4.85,1.76c-4.83,1.54-9,4.71-12.77,8.05-2.1,1.83-4.22,3.85-5.14,6.47-.3.86-.46,1.76-.72,2.63a18.14,18.14,0,0,1-2.32,4.74,34.23,34.23,0,0,1-7,7.82,18.59,18.59,0,0,0-3.6,3.86c-1.53,2.21-4.64,2.87-6.28,5a23.75,23.75,0,0,1-2,3c-1.27,1.2-3.19,1.3-4.81,2-3.79,1.57-5.54,6-8.92,8.34a.94.94,0,0,1-.67.22c-.29,0-.46-.35-.71-.52-.49-.33-1.14-.08-1.72.07s-1.36.09-1.51-.49c-8.15-4.94-16.16-10.3-24.32-15.24l-3.72-2.25-19.9-12.06a1.48,1.48,0,0,0-1.57,0l-.62.43c-1-1.06-2.11-2-2.77-2.78-.27-.31-.54-.62-.82-.92a1.22,1.22,0,0,0,.53-.1,1,1,0,0,0,.43-1.3,3.26,3.26,0,0,0-.92-1.17,22.15,22.15,0,0,1-2.39-2.73,25.24,25.24,0,0,0-2.63-3.44,4.83,4.83,0,0,0-3.9-1.55,6.33,6.33,0,0,0-2.26.91,37.09,37.09,0,0,0-7.5,5.75.79.79,0,0,0-.33.62c0,.2.2.35.22.54a.7.7,0,0,1-.19.5,20.93,20.93,0,0,1-4.73,4.31q-3.81,2.85-7.45,5.92a10.42,10.42,0,0,0-3.48,4.25,8.31,8.31,0,0,0,.61,5.9c1.66,3.91,4.57,7.15,7.45,10.28a3.64,3.64,0,0,0,1.91,1.34,2.43,2.43,0,0,0,1.73-.42c1.77-1.16,2.06-3.56,2.19-5.66.05-1,.11-1.92.17-2.88a1.33,1.33,0,0,1,.11-.56,1.4,1.4,0,0,1,.61-.49l2.75-1.45c-.08-.13-.17-.26-.26-.39a11.21,11.21,0,0,1,6.49-.42c1.46.43,2.8,1.3,4.2,1.84a9.29,9.29,0,0,0,1,5.42c5.13.53,9.75,2.81,14.34,5.11A114.33,114.33,0,0,1,633,238.52q4.24,2.76,8.3,5.77c3.84,2.84,7.55,5.85,11.22,8.89a54.11,54.11,0,0,0,7.67,5.65c7.22,4.05,16.9,4.19,23.53-.86,8.36-6.37,19-9.68,28-15.19a31.6,31.6,0,0,0,7.25-5.57,4.94,4.94,0,0,1-.12.77c-.54,2.49-2.69,4.29-3.5,6.81-.63,2-.4,4.31-1.62,6-.93,1.29-2.67,2.21-2.72,3.8,0,.44.13.88.13,1.32a4.13,4.13,0,0,1-.48,1.59c-1,2.25-2.12,4.61-4.17,6-.8.55-1.82,1.05-2,2a1.89,1.89,0,0,1-.21.79c-.34.47-1.09.22-1.63.42-.75.28-.87,1.25-1.17,2a3.24,3.24,0,0,1-3.27,1.92c-6.83-.83-13.54,2.26-20.42,2.08-2.37-.07-4.73-.31-7.11-.33-7.3-.06-14.45,2-21.48,4a11.34,11.34,0,0,0-1.42,4.5,17.37,17.37,0,0,1-7.35.28,15.67,15.67,0,0,0-1.84-.25,2.77,2.77,0,0,0,.16-1.42,40.15,40.15,0,0,0-8.23,3.67c-1.71,1-3.52,2.4-3.68,4.37a6.57,6.57,0,0,0,.32,2.24l.93,3.53a3.72,3.72,0,0,0,.83,1.77c.31.3.72.48,1,.8a3.14,3.14,0,0,1,.54,1.27l.78,3.06a19.46,19.46,0,0,1,.62,3.11c.09,1,0,1.92.07,2.88a29.93,29.93,0,0,0,.69,4.7l1.11,5.54a18.91,18.91,0,0,0,1.31,4.5c.47,1,1.1,1.86,1.48,2.86.3.77.44,1.59.8,2.32a6.19,6.19,0,0,0,2.9,2.68,3.23,3.23,0,0,0,1.41.44c1.42,0,2.44-1.32,3.1-2.58a15.6,15.6,0,0,0,2.07-7.52c0-1.06-.21-2.11-.3-3.17-.24-3,.62-5.92.62-8.91a1.75,1.75,0,0,0-1.25-1.82c.09-2.54.08-5.23,1.42-7.4a11.15,11.15,0,0,1,2.44-2.65c.37,1.18.78,2.35,1.24,3.49C658.58,296.45,666.44,294.31,674.41,294.11ZM837,140.54c-.54.2-1.09.4-1.65.58-4.66,1.55-10,3.06-14.82,2a12.87,12.87,0,0,1-4.06-2l-.35-.22C822.91,139.71,830,140,837,140.54Z" transform="translate(-52.64 -55.65)" fill="url(#f137b292-0aa2-40b3-a442-9a256144b6d8)"/><path d="M864.06,130.25a15.45,15.45,0,0,1,5.31-1.23,11.65,11.65,0,0,1,3.42.79,16.08,16.08,0,0,1,5.44,2.8,6.51,6.51,0,0,1,2.41,5.4c-.23,2-1.71,3.73-3.33,5a13.27,13.27,0,0,1-7.76,3c-3.18.05-6.18-1.38-9.25-2.23a26.56,26.56,0,0,0-6.86-1,15,15,0,0,1-3.49-.22,3.74,3.74,0,0,1-2.68-2.06,5.28,5.28,0,0,1,0-3c.23-1.24.19-4.18,1.29-4.92.88-.6,4-.12,5.08-.21A50.14,50.14,0,0,0,864.06,130.25Z" transform="translate(-52.64 -55.65)" fill="#fbbebe"/><path d="M792.67,110.12a46.24,46.24,0,0,1,7.75,10c3.52,6.14,5.76,13.28,11.06,18a37.32,37.32,0,0,0,4.47,3.23,12.9,12.9,0,0,0,4.06,2c4.76,1.07,10.1-.42,14.74-2a93.35,93.35,0,0,0,13.33-6,11,11,0,0,0,1.56,5.48c1.11,1.57,3.38,2.49,5,1.5a59.3,59.3,0,0,0-11.53,7.13c-1.37,1.16-2.64,2.44-4.1,3.49-5.27,3.79-12.56,4.17-17.43,8.47a4.69,4.69,0,0,1-5.41.65c-1.69-1-2.84-2.72-4.23-4.11-2.74-2.74-6.46-4.34-9.15-7.13-1.25-1.29-2.25-2.82-3.53-4.08-1.83-1.8-4.21-3-5.89-5-1.25-1.47-2-3.26-3.17-4.83-1-1.36-2.18-2.55-3.07-4-2.18-3.47-2.16-8-.91-11.89S790.34,113.51,792.67,110.12Z" transform="translate(-52.64 -55.65)" fill="#f86d70"/><path d="M792.67,110.12a46.24,46.24,0,0,1,7.75,10c3.52,6.14,5.76,13.28,11.06,18a37.32,37.32,0,0,0,4.47,3.23,12.9,12.9,0,0,0,4.06,2c4.76,1.07,10.1-.42,14.74-2a93.35,93.35,0,0,0,13.33-6,11,11,0,0,0,1.56,5.48c1.11,1.57,3.38,2.49,5,1.5a59.3,59.3,0,0,0-11.53,7.13c-1.37,1.16-2.64,2.44-4.1,3.49-5.27,3.79-12.56,4.17-17.43,8.47a4.69,4.69,0,0,1-5.41.65c-1.69-1-2.84-2.72-4.23-4.11-2.74-2.74-6.46-4.34-9.15-7.13-1.25-1.29-2.25-2.82-3.53-4.08-1.83-1.8-4.21-3-5.89-5-1.25-1.47-2-3.26-3.17-4.83-1-1.36-2.18-2.55-3.07-4-2.18-3.47-2.16-8-.91-11.89S790.34,113.51,792.67,110.12Z" transform="translate(-52.64 -55.65)" opacity="0.1"/><path d="M614.94,202.47a10.36,10.36,0,0,0-2.82-2.55,8.54,8.54,0,0,0-5.27-.54c-4.46.68-8.6,2.72-12.52,5-3.16,1.81-6.3,3.82-8.56,6.67a6.85,6.85,0,0,0-1.51,3,6.18,6.18,0,0,0,.23,2.73,6.6,6.6,0,0,0,3.57,4.62c2.09.82,4.42-.05,6.52-.85,2.82-1.09,5.92-2.1,8.82-1.24,2.15.64,4,2.27,6.27,2.33,2.67.08,4.83-2.08,6.53-4.14,1.47-1.8,4.69-5.05,4.48-7.58S616.52,204.28,614.94,202.47Z" transform="translate(-52.64 -55.65)" fill="#fbbebe"/><path d="M648.64,280.3a17.27,17.27,0,0,1-7.5.31c-1.52-.28-3.38-.64-4.35.55a3.58,3.58,0,0,0-.61,1.48c-2.49,10.19-.21,21,4,30.65a.94.94,0,0,0,.28.42c.27.2.64.06.95-.07a11.28,11.28,0,0,0,2.83-1.65c1.92-1.74,2.33-4.57,2.42-7.16s.05-5.33,1.39-7.55c1.68-2.75,5.19-4.09,6.57-7,1.11-2.37.53-5.18-.45-7.6-.33-.84-.46-3-1.24-3.41S649.53,280.06,648.64,280.3Z" transform="translate(-52.64 -55.65)" fill="#fbbebe"/><path d="M614.65,201.45a1,1,0,0,0,.42-1.3,3.38,3.38,0,0,0-.92-1.18,20.69,20.69,0,0,1-2.38-2.74,27.68,27.68,0,0,0-2.63-3.44,4.85,4.85,0,0,0-3.89-1.56,6,6,0,0,0-2.25.9,36.36,36.36,0,0,0-7.45,5.72c-.17.17-.36.38-.32.62s.2.34.22.54a.69.69,0,0,1-.18.49,20.68,20.68,0,0,1-4.7,4.29q-3.78,2.84-7.4,5.9a10.3,10.3,0,0,0-3.45,4.23,8.41,8.41,0,0,0,.63,5.89c1.67,3.92,4.58,7.16,7.45,10.31a3.78,3.78,0,0,0,1.92,1.35,2.42,2.42,0,0,0,1.72-.42c1.75-1.15,2-3.55,2.15-5.64l.16-2.89a1.29,1.29,0,0,1,.11-.55,1.35,1.35,0,0,1,.61-.49l2.72-1.44a8.77,8.77,0,0,0-8-4.16,3,3,0,0,1-2.14-.29,1.76,1.76,0,0,1,0-2.44,5.38,5.38,0,0,1,2.36-1.31c7.17-2.63,13.65-6.85,20.61-10a5.29,5.29,0,0,1,2.46-.57C613.18,201.32,614,201.73,614.65,201.45Z" transform="translate(-52.64 -55.65)" fill="#f86d70"/><path d="M642.9,306.17c-.32.6-.43,1.3-.78,1.89s-1.11,1-1.7.7a1.75,1.75,0,0,1-.66-.89,37.36,37.36,0,0,1-2.45-22.06,13.91,13.91,0,0,1,1.07-3.52c.53-1.08,1.3-2.18,1.08-3.36a39.64,39.64,0,0,0-8.18,3.64c-1.7,1-3.49,2.39-3.65,4.35a6.84,6.84,0,0,0,.33,2.24l.94,3.53a3.65,3.65,0,0,0,.84,1.77c.3.3.71.49,1,.81a3,3,0,0,1,.54,1.26l.79,3.06a19.6,19.6,0,0,1,.63,3.12c.09,1,0,1.92.08,2.88a31,31,0,0,0,.7,4.69l1.13,5.54a19.26,19.26,0,0,0,1.32,4.5c.47,1,1.1,1.86,1.49,2.87.29.77.44,1.59.8,2.32a6.29,6.29,0,0,0,2.89,2.69,3.39,3.39,0,0,0,1.41.45c1.41.05,2.42-1.32,3.08-2.58a15.56,15.56,0,0,0,2-7.5c0-1.06-.22-2.11-.31-3.17-.25-3,.59-5.91.58-8.9C647.89,303.7,643.93,304.23,642.9,306.17Z" transform="translate(-52.64 -55.65)" fill="#f86d70"/><path d="M789.62,131.94a22.08,22.08,0,0,1-8-6.25,38.19,38.19,0,0,1-3-4.45,135.15,135.15,0,0,1-9.75-20.07c4.26.87,8.73,1.66,12.92.46a17.84,17.84,0,0,0,6-3.18,51.87,51.87,0,0,0,6.32-6.17,60.76,60.76,0,0,0,5,8c1.07,1.44,4.69,4.37,4.42,6.33s-4.27,2.94-5.89,3.87l-.17.11a22.68,22.68,0,0,0-6.15,5.73C788.18,120.78,787.09,127,789.62,131.94Z" transform="translate(-52.64 -55.65)" fill="#fbbebe"/><path d="M797.72,110.44a18.74,18.74,0,0,1-9.85-12,51.87,51.87,0,0,0,6.32-6.17,60.76,60.76,0,0,0,5,8c1.07,1.44,4.69,4.37,4.42,6.33S799.34,109.51,797.72,110.44Z" transform="translate(-52.64 -55.65)" opacity="0.1"/><circle cx="754.08" cy="37.53" r="18.73" fill="#fbbebe"/><path d="M765.75,209.85a8.74,8.74,0,0,1-8.62.21,16.59,16.59,0,0,1-3.72-3.13c-6.15-6.31-12-13-16.11-20.83a14.44,14.44,0,0,1-1.82-5.37,5.9,5.9,0,0,1,1.93-5.12,4.16,4.16,0,0,0,1-.93,3.75,3.75,0,0,0,.33-1.7,5.31,5.31,0,0,1,3.54-4.43c-1-.68-.6-2.19.05-3.16s1.56-2,1.4-3.12a17.12,17.12,0,0,0-.92-2.18c-.36-1.22.29-2.48.64-3.7.73-2.5.29-5.16.11-7.76-.53-7.7,1.34-15.34,3.19-22.83a61.24,61.24,0,0,1,3.52-11.1c.47-1,1-2,1.54-2.89a76.83,76.83,0,0,1,6.29-8.75,11.36,11.36,0,0,1,4.29-3.84,4.24,4.24,0,0,1,.5-.18,10.88,10.88,0,0,1,3.82-.29c3.38.21,6.93,1,9.34,3.38s3.19,5.72,4.28,8.94a24.63,24.63,0,0,0,1.26,3.15c1.59,3.16,4.18,5.68,6.73,8.13l2.77,2.67c1.39,1.34,3.8,1,5.11,2.41a6.48,6.48,0,0,1,1.17,2.24A34.75,34.75,0,0,1,799.92,141a18.75,18.75,0,0,1-.15,2.59,13.64,13.64,0,0,1-3.79,8c-2.4,2.31-5.74,3.45-8.13,5.77-2,1.92-3.16,4.49-4.3,7q-3.3,7.26-6.61,14.54a82.39,82.39,0,0,0-4.11,10.25C770.75,196.14,771.93,206,765.75,209.85Z" transform="translate(-52.64 -55.65)" fill="#f86d70"/><path d="M708,292.25c-4.94.2-9.89.14-14.81.61-2.87.28-5.73.75-8.61.87-3.14.14-6.29-.11-9.44-.05-7.93.17-15.75,2.28-23.38,4.46a44.4,44.4,0,0,1-3.31-16.57,10.57,10.57,0,0,1,0-1.13,11.37,11.37,0,0,1,1.41-4.58c7-2,14.1-4,21.37-3.9,2.37,0,4.72.28,7.08.35,6.85.21,13.51-2.86,20.31-2a3.2,3.2,0,0,0,3.25-1.91c.29-.74.41-1.71,1.16-2,.54-.2,1.28.05,1.62-.41a2.1,2.1,0,0,0,.21-.79c.2-1,1.21-1.45,2-2,2-1.38,3.13-3.74,4.13-6a4.07,4.07,0,0,0,.47-1.58c0-.44-.14-.88-.13-1.33,0-1.58,1.77-2.49,2.69-3.78,1.21-1.7,1-4,1.59-6,.8-2.52,2.93-4.31,3.46-6.79a4.94,4.94,0,0,0,.12-.77,31.32,31.32,0,0,1-7.21,5.54c-8.88,5.47-19.5,8.74-27.79,15.07-6.58,5-16.22,4.85-23.42.78a54.16,54.16,0,0,1-7.66-5.67c-3.66-3-7.36-6.07-11.19-8.93q-4-3-8.29-5.79a114.13,114.13,0,0,0-10.74-6.29c-4.58-2.32-9.19-4.62-14.29-5.17a10.53,10.53,0,0,1-.28-8.64A29.14,29.14,0,0,1,613,210.3a21.78,21.78,0,0,1,5.36-5.47,1.46,1.46,0,0,1,1.56,0L639.74,217l3.71,2.27c8.13,5,16.13,10.35,24.26,15.32.15.57.94.64,1.51.49s1.22-.39,1.71-.06c.24.16.41.46.71.52a1,1,0,0,0,.66-.22c3.36-2.31,5.08-6.75,8.85-8.3,1.61-.66,3.52-.76,4.78-2a22.71,22.71,0,0,0,2-3c1.63-2.13,4.72-2.77,6.23-5a18.35,18.35,0,0,1,3.57-3.84,33.83,33.83,0,0,0,7-7.79,18.08,18.08,0,0,0,2.29-4.72c.26-.87.42-1.77.71-2.63.91-2.62,3-4.63,5.09-6.45,3.79-3.32,7.88-6.47,12.68-8a21.44,21.44,0,0,0,4.83-1.75c1.93-1.18,3.7-3.37,5.91-2.86a5,5,0,0,1,2.19,1.38,69.61,69.61,0,0,1,7.45,8.53q5.35,6.81,10.69,13.63a15.75,15.75,0,0,0,4.19,4.15,11.49,11.49,0,0,0,7.75,1c-.35,3.71-3.3,6.77-4.52,10.29-.59,1.71-.82,3.53-1.26,5.28a43.25,43.25,0,0,1-2.37,6.41c-2.4,5.59-4.82,11.21-8.26,16.23-1.78,2.61-3.83,5-5.84,7.45-7.93,9.57-14,21.11-23,29.72-2.18,2.11-3.56,5-6,6.81C714.61,291.82,711.19,292.12,708,292.25Z" transform="translate(-52.64 -55.65)" fill="#434175"/><path d="M745.68,165.37a5.43,5.43,0,0,0-2.5.75c1.83-.64,4.06,1.07,5.75.26.79-.38.67-.49,0-.72C747.92,165.32,746.7,165.63,745.68,165.37Z" transform="translate(-52.64 -55.65)" opacity="0.1"/><rect x="987.99" y="508.41" width="78" height="14" transform="translate(-165.92 317.79) rotate(-19.55)" fill="#d0d2d5"/><path d="M1012.57,535.77h71a7,7,0,0,1,7,7v0a7,7,0,0,1-7,7h-71a0,0,0,0,1,0,0v-14A0,0,0,0,1,1012.57,535.77Z" transform="translate(-173.65 327.59) rotate(-19.55)" fill="#d0d2d5"/><path d="M963.62,496.55h17.3a58,58,0,0,1,58,58v17.3a22.68,22.68,0,0,1-22.68,22.68H963.62a22.68,22.68,0,0,1-22.68-22.68V519.23a22.68,22.68,0,0,1,22.68-22.68Z" transform="translate(-178.14 307.13) rotate(-19.55)" fill="#3f3d56"/><path d="M744.78,175.13a3.88,3.88,0,0,0-2.11-.13,4.46,4.46,0,0,0-2.75,1.35,1.5,1.5,0,0,0,1.23,0,7.27,7.27,0,0,1,2-.22c.58,0,2.31.64,2.76.36C746.57,176.06,745.23,175.3,744.78,175.13Z" transform="translate(-52.64 -55.65)" opacity="0.1"/><path d="M799.77,143.59a19.42,19.42,0,0,1-4.28-2.06c-3.51-2.23-6.46-5.26-9.93-7.54a55.25,55.25,0,0,0-5.43-3l-11.71-6a11.87,11.87,0,0,0-2.84-1.16c-1.91-.42-4.06.86-6,.59a7.23,7.23,0,0,1-4.88-3.37,17.57,17.57,0,0,1-2.2-5.67,29.09,29.09,0,0,1-.67-3.59,16,16,0,0,1-.07-3.79,9.48,9.48,0,0,1,3.3-6.46,12.09,12.09,0,0,1,4.64-2,19.37,19.37,0,0,1,3.21-.53,11.43,11.43,0,0,1,1.85,0c4.42.35,8.16,3.35,11.11,6.65,1.55,1.74,3,3.61,4.48,5.38a24.63,24.63,0,0,0,1.26,3.15c1.59,3.16,4.18,5.68,6.73,8.13l2.77,2.67c1.39,1.34,3.8,1,5.11,2.41a6.48,6.48,0,0,1,1.17,2.24A34.75,34.75,0,0,1,799.92,141,18.75,18.75,0,0,1,799.77,143.59Z" transform="translate(-52.64 -55.65)" opacity="0.1"/><path d="M708.7,271.57l-60.26,8.87a11.37,11.37,0,0,1,1.41-4.58c7-2,14.1-4,21.37-3.9,2.37,0,4.72.28,7.08.35,6.85.21,13.51-2.86,20.31-2a3.2,3.2,0,0,0,3.25-1.91c.29-.74.41-1.71,1.16-2,.54-.2,1.28.05,1.62-.41a2.1,2.1,0,0,0,.21-.79c.2-1,1.21-1.45,2-2,2-1.38,3.13-3.74,4.13-6a4.07,4.07,0,0,0,.47-1.58c0-.44-.14-.88-.13-1.33,0-1.58,1.77-2.49,2.69-3.78,1.21-1.7,1-4,1.59-6,.8-2.52,2.93-4.31,3.46-6.79l.26-.34,10.26-4Z" transform="translate(-52.64 -55.65)" opacity="0.1"/><ellipse cx="425" cy="668.67" rx="425" ry="33" fill="{{primaryColor}}" opacity="0.1"/><ellipse cx="800.72" cy="752.92" rx="275" ry="35.77" fill="{{primaryColor}}" opacity="0.1"/><path d="M527.89,697.6l.28-14.16q20-1.14,40-1.52c7.74-.14,15.58-.19,23.07,1.75,5.19,1.35,10.1,3.63,15.22,5.23,10.2,3.18,21,3.6,31.71,3.89,10.39.29,21.24.39,30.57-4.2,16.15-8,22.94-27.65,23.73-45.64s-2.79-36.12-.3-54" transform="translate(-52.64 -55.65)" fill="none" stroke="#3f3d56" stroke-miterlimit="10" stroke-width="12"/><polygon points="511.81 669.66 333.62 667.38 334.14 662.81 342.76 587.42 499.24 587.42 510.76 662.81 511.64 668.52 511.81 669.66" fill="#d0d2d5"/><polygon points="511.64 668.52 422.71 668.52 333.62 667.38 334.14 662.81 510.76 662.81 511.64 668.52" opacity="0.1"/><rect x="303.92" y="663.95" width="236.45" height="5.71" fill="#d0d2d5"/><path d="M818.6,190.27a14.87,14.87,0,0,0-14.8-15H143.48a14.88,14.88,0,0,0-14.8,15V590.53H818.6Z" transform="translate(-52.64 -55.65)" fill="#3f3d56"/><path d="M128.68,586.53v46.89a14.8,14.8,0,0,0,14.8,14.8H803.8a14.8,14.8,0,0,0,14.8-14.8V586.53Z" transform="translate(-52.64 -55.65)" fill="#d0d2d5"/><rect x="104.6" y="144.8" width="636.23" height="359.81" fill="#2f2e41"/><path d="M477.07,630.43a15.43,15.43,0,0,0,12.13-5.89h0a15.28,15.28,0,0,0,1.2-1.77l-8.46-1.39,9.15.07a15.44,15.44,0,0,0,.29-12.22l-12.27,6.37,11.32-8.32A15.42,15.42,0,1,0,465,624.53h0A15.4,15.4,0,0,0,477.07,630.43Z" transform="translate(-52.64 -55.65)" fill="{{primaryColor}}"/><polygon points="439.85 592.56 510.94 663.95 500.03 592.56 439.85 592.56" opacity="0.1"/><path d="M797.82,197.52,836,146.93c2.28-3,4.63-6.13,7.76-8.29,9-6.22,22.19-2.54,29.72,5.43s10.69,19.06,13,29.78A316.11,316.11,0,0,1,893.64,249c-.32,13.29-1.51,26.72-5.74,39.33-6.42,19.18-19.43,35.33-29.26,53-15.83,28.47-22.46,66.44-2.42,92.13,6.53,8.37,15.42,14.77,21.45,23.51,6.81,9.87,9.46,21.94,12,33.66,3.79,17.7,7.59,35.51,8.29,53.6,2.26,58.49-31.09,116.93-82.59,144.75-35.75,19.32-79,24.92-110.09,51.12-11,9.23-20.48,22.8-17.78,36.86,2.2,11.41,12.22,20.08,23.22,23.85s22.93,3.46,34.53,2.8a636.33,636.33,0,0,0,83-10.25c23.23-4.44,46.42-8.27,66.67-20.49a14,14,0,0,0,5.05-4.53c1.31-2.19,1.53-4.84,1.71-7.39.55-7.51,1.07-15.3-1.58-22.35-3.09-8.24-10.14-14.48-13.52-22.6s-2.77-17.47-.58-26c2.7-10.54,7.61-20.36,12.55-30.05,4.81-9.44,9.69-18.85,15.35-27.8,15.94-25.16,37.72-46,59.27-66.55" transform="translate(-52.64 -55.65)" fill="none" stroke="#3f3d56" stroke-miterlimit="10" stroke-width="12"/><path d="M861,125a15,15,0,0,1,5.31-1.23,12,12,0,0,1,3.42.78,16.1,16.1,0,0,1,5.44,2.81,6.49,6.49,0,0,1,2.41,5.4c-.23,2-1.71,3.72-3.33,5a13.22,13.22,0,0,1-7.76,3c-3.18,0-6.18-1.38-9.25-2.24a26.55,26.55,0,0,0-6.86-1,15,15,0,0,1-3.49-.23,3.73,3.73,0,0,1-2.68-2.05,5.38,5.38,0,0,1,0-2.95c.24-1.24.2-4.19,1.3-4.93.88-.59,4-.11,5.08-.2A51.46,51.46,0,0,0,861,125Z" transform="translate(-52.64 -55.65)" fill="#fbbebe"/><path d="M847.13,126c-4.14,1.9-9,.32-13.5.31-2.21,0-4.41.37-6.61.5a59.44,59.44,0,0,1-7.31-.19l-7.32-.5a62.44,62.44,0,0,1-12.79-1.76c-3.58-4.22-9.39-6.08-13.71-9.52-3.46-2.76-5.94-6.52-8.89-9.83s-6.69-6.3-11.1-6.65a16.41,16.41,0,0,0-5.07.54,11.82,11.82,0,0,0-4.63,2,9.44,9.44,0,0,0-3.3,6.46,21.68,21.68,0,0,0,.73,7.38,17.62,17.62,0,0,0,2.2,5.68,7.34,7.34,0,0,0,4.89,3.37c1.93.26,4.07-1,6-.6a11.87,11.87,0,0,1,2.84,1.16l11.72,6a56.26,56.26,0,0,1,5.42,3c3.48,2.28,6.42,5.31,9.93,7.54s7.94,3.63,11.84,2.17c12-4.47,25.52-2.39,38.25-1.28-.08-.24.44-.46.59-.66a10.75,10.75,0,0,0,2-7.49C849,131,848,128.52,847.13,126Z" transform="translate(-52.64 -55.65)" fill="#f86d70"/><path d="M827,92.31a6.85,6.85,0,0,0,3-2.68c1.14-2.11.44-4.7-.34-7s-1.57-4.31-2.44-6.43a15.49,15.49,0,0,0-2.78-4.87c-1.77-1.89-4.3-2.84-6.41-4.33-2.5-1.77-4.37-4.28-6.48-6.49s-4.69-4.26-7.73-4.63A14.94,14.94,0,0,0,797,57.15c-18.26,6.71-33.19,20-49.54,30.54-6.36,4.11-13.5,7.94-21,7.39l6.71,10.66c1.71,2.73,3.63,5.62,6.63,6.79,2.65,1,5.61.5,8.39,0a22.61,22.61,0,0,0,6.39-1.92c4-2.17,6.57-6.68,10.87-8.25,3.21-1.17,6.79-.45,10,.67s6.36,2.64,9.74,3.1c6,.81,12-1.9,17-5.4,3-2.08,5.73-4.47,9-6a13.56,13.56,0,0,1,8-1.41C822.22,93.74,824,93.88,827,92.31Z" transform="translate(-52.64 -55.65)" fill="#2f2e41"/><path d="M830,89.63c1.12-2.07.46-4.61-.3-6.84a6,6,0,0,1-.5,3.77,7,7,0,0,1-3,2.68c-3,1.58-4.82,1.44-7.9.93a13.66,13.66,0,0,0-8,1.41c-3.25,1.57-6,4-9,6-5,3.5-11,6.2-17,5.39-3.39-.45-6.52-2-9.74-3.1s-6.81-1.84-10-.67c-4.29,1.57-6.83,6.09-10.86,8.25a22.71,22.71,0,0,1-6.39,1.92c-2.79.54-5.75,1.07-8.39,0-3-1.16-4.92-4.06-6.64-6.79l-4.75-7.55c-.38,0-.77,0-1.15,0l6.71,10.66c1.71,2.73,3.63,5.62,6.63,6.79,2.65,1,5.61.5,8.39,0a22.61,22.61,0,0,0,6.39-1.92c4-2.17,6.57-6.68,10.87-8.25,3.21-1.17,6.79-.45,10,.67s6.36,2.64,9.74,3.1c6,.81,12-1.9,17-5.4,3-2.08,5.73-4.47,9-6a13.56,13.56,0,0,1,8-1.41c3.08.5,4.9.64,7.89-.93A6.85,6.85,0,0,0,830,89.63Z" transform="translate(-52.64 -55.65)" opacity="0.1"/><path d="M881.7,773.66a10,10,0,0,1,2.18-2.42c4.37-4.12,6.4-10.18,7.48-16.12s1.39-12,3.12-17.81a57.24,57.24,0,0,1,3.52-8.67c1-2.14,2.25-6.34,4.09-7.83a2.66,2.66,0,0,1,1.26-.61,14.65,14.65,0,0,1,3.62-4.82c2.86-2.59,6.35-4.65,8.26-8a17.64,17.64,0,0,1,1.93-3.29c1.29-1.43,3.33-2,4.52-3.51,1.55-1.94,1.2-4.71,1-7.19s0-5.43,2.14-6.72c1.28-.79,2.93-.72,4.26-1.41,2-1,2.79-3.53,2.75-5.78s-.74-4.44-.92-6.68c-.56-7.16,4.16-14.28,2.33-21.22-.69-2.63-2.26-4.92-3.43-7.36a17.2,17.2,0,0,1-1-2.54,35.57,35.57,0,0,1-9.73,2.35c5.51-12.36,4.11-26.73,6.68-40l-.33-.46a20.71,20.71,0,0,1-4.22-11.85c0-5,2.31-9.57,3.35-14.4.88-4.12.85-8.41,2-12.45a38.32,38.32,0,0,1,3.17-7.22c1.25-2.32,2.56-4.59,3.93-6.83q1.92-6.36,3.85-12.72c1.8-6,3.65-12,7.15-17.14,1.28-1.89,1.67-5.7,3.64-6.84a8.73,8.73,0,0,1,5.2-.91c2.78-1.56,5.22-3.81,5.57-6.89a6.68,6.68,0,0,0-.2-2l-.34,0c-4.41-.41-6.63-4.29-8.92-7.68-3.71-5.51-2.29-12.95,0-19.2a13,13,0,0,1,3-5.29c3.21-3,8.29-2.34,12.43-3.79a42.64,42.64,0,0,1,4.11-1.55c2.75-.65,5.63.26,8.15,1.52s4.87,2.92,7.51,3.92,5.9,1.79,6.55,4.5a4.91,4.91,0,0,1-.23,2.73,10.18,10.18,0,0,1-3.08,4.45,17.82,17.82,0,0,1-10.87,24.83c-.76,1.21-1.47,2.46-2.12,3.73-1.16,2.24-2.14,4.88-1.75,7.28a21.37,21.37,0,0,1,2,2.44c2.87,4,4.5,8.7,6,13.38a139.66,139.66,0,0,1,4.84,18.27c2.44,5.18,5.42,10.14,7.19,15.59a35.2,35.2,0,0,0,9.38-1.25l8.44-1.92c2.93-.66,6-1.38,8.3-3.32,1.22-1,2.17-2.33,3.41-3.33s3.73-2.15,5.09-1.33a4,4,0,0,1,.69.53c1.23-2.5,9.1,7.73,3.72,8.74l.35,1c.71,2.07,2.22,4.59,1.84,6.75L997,588.21a23.19,23.19,0,0,1-7.56,1.67,12.21,12.21,0,0,1-3-.4l0,1.92v.07c-.1,13.19,2,26.3,2.39,39.48.07,2.4,0,5-1.52,6.88-1.7,2.06-4.72,2.46-7.35,2a16.65,16.65,0,0,1-1.86-.41,69.45,69.45,0,0,0-1.92,10.1l-2.49,17.76a26.45,26.45,0,0,0-.39,5.54c.29,4.18,2.5,7.94,4.1,11.81s2.55,8.5.44,12.11c-.65,1.12-1.56,2.08-2.15,3.24a13.1,13.1,0,0,0-1,5.67q-.23,8.1-.44,16.18a1.89,1.89,0,0,1,1.26.26c2.08,1.61,1.85,9.33,2,11.72.16,4,0,8.08.22,12.12a71.1,71.1,0,0,0,2.68,16.13,10.29,10.29,0,0,0,2.29,4.61,9.82,9.82,0,0,0,4.06,2.11,46.58,46.58,0,0,0,15.42,2.1c2.11-.07,4.31-.27,6.27.53s3.54,3,2.83,5c-.61,1.68-2.46,2.48-4.13,3.11a64.81,64.81,0,0,0-11,5.06,29.31,29.31,0,0,1-4.26,2.41,21.58,21.58,0,0,1-4.38,1.08l-17.72,3c-3.63.63-8,1-10.31-2-1.25-1.62-1.43-3.82-1.37-5.87.1-4,.9-8.07.37-12.07a36.46,36.46,0,0,0-1.85-6.94l-5.32-15.72c-1.78-5.27-3.58-10.58-4.27-16.1-.25-2-.23-4.27,1.3-5.52a3.54,3.54,0,0,1,1.32-.68c.06-4.82.69-9.65.42-14.47-.07-1.2-.19-2.41-.29-3.61a16.82,16.82,0,0,0-2.48,2.92c-1.7,2.67-2.33,6.21-4.94,8-2.22,1.52-5.51,1.44-7.07,3.64a10.26,10.26,0,0,0-1.12,2.71,19.6,19.6,0,0,1-4,6.35,32.91,32.91,0,0,1-2.47,6.34q-2.21,4.65-4.4,9.3c-1.57,3.32-3.15,6.64-5,9.78a27,27,0,0,0-3.35,6.46c-1.41,4.94.88,10.36,4.53,14s8.44,5.73,13.16,7.68a3.62,3.62,0,0,1,1.35.8,2.58,2.58,0,0,1,.6,1.74c0,2.31-1.89,4.29-4.07,5a15.27,15.27,0,0,1-6.83.25c-12.78-1.55-25.52-4.67-36.82-10.88a13.22,13.22,0,0,1-4.4-3.39A5.18,5.18,0,0,1,881.7,773.66Z" transform="translate(-52.64 -55.65)" fill="url(#ab747304-1bb2-44ed-8687-72ce94e318d2)"/><path d="M935.72,549.41q-3.19,4.9-6,10.06a37.17,37.17,0,0,0-3.17,7.16c-1.17,4-1.13,8.28-2,12.36-1,4.8-3.34,9.38-3.34,14.29a20.5,20.5,0,0,0,4.22,11.77,56.63,56.63,0,0,0,8.82,9.1,187.62,187.62,0,0,0,12.48-61.21c.1-2.9.11-5.9-.94-8.6-.66-1.7-3.77-6.36-5.78-4.53-.73.67-.92,3.69-1.37,4.69A36.23,36.23,0,0,1,935.72,549.41Z" transform="translate(-52.64 -55.65)" fill="#f86d70"/><path d="M935.72,549.41q-3.19,4.9-6,10.06a37.17,37.17,0,0,0-3.17,7.16c-1.17,4-1.13,8.28-2,12.36-1,4.8-3.34,9.38-3.34,14.29a20.5,20.5,0,0,0,4.22,11.77,56.63,56.63,0,0,0,8.82,9.1,187.62,187.62,0,0,0,12.48-61.21c.1-2.9.11-5.9-.94-8.6-.66-1.7-3.77-6.36-5.78-4.53-.73.67-.92,3.69-1.37,4.69A36.23,36.23,0,0,1,935.72,549.41Z" transform="translate(-52.64 -55.65)" opacity="0.1"/><path d="M1043.07,560.34c3.91-.65,8.25-.33,11.29,2.2a9.32,9.32,0,0,1,3.24,6.16c.26,2.78-1.35,6.06-4.13,6.28a13.17,13.17,0,0,1-2-.13,29.88,29.88,0,0,0-5.24.43,21.42,21.42,0,0,1-18.24-7.36c-2.38-2.94.76-4.29,3.59-4.89C1035.44,562.21,1039.21,561,1043.07,560.34Z" transform="translate(-52.64 -55.65)" fill="#fbbebe"/><path d="M976.19,650.66l-2.48,17.62a26,26,0,0,0-.38,5.5c.29,4.15,2.49,7.88,4.09,11.72s2.56,8.43.45,12c-.65,1.12-1.57,2.06-2.15,3.21a13,13,0,0,0-1,5.64l-.68,25a158.71,158.71,0,0,1-23.18-.13A1.35,1.35,0,0,1,950,731a1.38,1.38,0,0,1-.29-.91c-.34-5.85.68-11.71.35-17.56-.12-2.14-.43-4.27-.46-6.42-.13-8.71,4.18-17.24,2.88-25.86a57.35,57.35,0,0,0-1.6-6.42c-4.11-15-3.24-30.77-2.34-46.25a1.18,1.18,0,0,1,.2-.7,1.23,1.23,0,0,1,.55-.3,28.48,28.48,0,0,1,25.78,4.91c1.09.88,3.84,1.73,4.56,2.77,1,1.47-.32,2.92-.89,4.48A56.89,56.89,0,0,0,976.19,650.66Z" transform="translate(-52.64 -55.65)" fill="#3f3d56"/><path d="M976.19,650.66l-2.48,17.62a26,26,0,0,0-.38,5.5c.29,4.15,2.49,7.88,4.09,11.72s2.56,8.43.45,12c-.65,1.12-1.57,2.06-2.15,3.21a13,13,0,0,0-1,5.64l-.68,25a158.71,158.71,0,0,1-23.18-.13A1.35,1.35,0,0,1,950,731a1.38,1.38,0,0,1-.29-.91c-.34-5.85.68-11.71.35-17.56-.12-2.14-.43-4.27-.46-6.42-.13-8.71,4.18-17.24,2.88-25.86a57.35,57.35,0,0,0-1.6-6.42c-4.11-15-3.24-30.77-2.34-46.25a1.18,1.18,0,0,1,.2-.7,1.23,1.23,0,0,1,.55-.3,28.48,28.48,0,0,1,25.78,4.91c1.09.88,3.84,1.73,4.56,2.77,1,1.47-.32,2.92-.89,4.48A56.89,56.89,0,0,0,976.19,650.66Z" transform="translate(-52.64 -55.65)" opacity="0.1"/><path d="M929.82,645.34c1.17,2.43,2.74,4.7,3.43,7.31,1.83,6.89-2.88,14-2.32,21.06.18,2.23.87,4.4.92,6.63s-.77,4.71-2.75,5.73c-1.33.69-3,.62-4.25,1.4-2.11,1.28-2.35,4.22-2.14,6.67s.55,5.21-1,7.14c-1.19,1.49-3.23,2.06-4.51,3.47a17.3,17.3,0,0,0-1.94,3.27c-1.91,3.33-5.39,5.38-8.25,8s-5.28,6.46-4,10.08c.94,2.67,3.58,4.31,6.12,5.56a64.93,64.93,0,0,0,14.57,5.15,3.51,3.51,0,0,0,1.67.08,3.64,3.64,0,0,0,1.46-1c2.95-2.89,6-5.92,7.36-9.81a10.27,10.27,0,0,1,1.12-2.69c1.56-2.18,4.84-2.11,7.07-3.61,2.6-1.77,3.23-5.29,4.93-7.94,1.61-2.5,4.19-4.22,6-6.56,3-3.88,3.81-9.05,6-13.48.93-1.89,2.12-3.64,2.86-5.61a30.4,30.4,0,0,0,1.37-7.23c1.41-11.68,5-23.44,2.74-35-.5-2.55-1.27-5-1.59-7.62-.56-4.54.32-9.17-.35-13.7a3.73,3.73,0,0,0-1.51-2.9,4.18,4.18,0,0,0-1.72-.36,118.6,118.6,0,0,0-17.78.41c-3,.29-6.37.9-8.16,3.35-1.53,2.09-1.45,4.91-2,7.46-.6,3.13-2.19,4.85-3.86,7.31S928.59,642.81,929.82,645.34Z" transform="translate(-52.64 -55.65)" fill="#3f3d56"/><path d="M952.89,726.6c-1.58,0-3.33-.09-4.55.91-1.52,1.24-1.55,3.53-1.3,5.49.7,5.47,2.49,10.74,4.28,16l5.32,15.61a35.87,35.87,0,0,1,1.85,6.88c.53,4-.27,8-.37,12,0,2,.13,4.22,1.38,5.83,2.26,2.9,6.67,2.56,10.3,1.94l17.71-3a21.72,21.72,0,0,0,4.38-1.07,29.68,29.68,0,0,0,4.25-2.4,65.38,65.38,0,0,1,11-5c1.66-.62,3.52-1.42,4.12-3.09.71-2-.87-4.19-2.83-5s-4.15-.6-6.27-.53a46.72,46.72,0,0,1-15.4-2.09,9.61,9.61,0,0,1-4.06-2.09,10.12,10.12,0,0,1-2.3-4.57,71.27,71.27,0,0,1-2.68-16c-.2-4-.06-8-.22-12-.1-2.37.13-10-2-11.63-1.59-1.22-8.14,2.15-10.28,2.64A49.57,49.57,0,0,1,952.89,726.6Z" transform="translate(-52.64 -55.65)" fill="#2f2e41"/><path d="M894.54,737.72c-1.72,5.74-2,11.79-3.11,17.68s-3.1,11.91-7.47,16a9.69,9.69,0,0,0-2.17,2.4,5.06,5.06,0,0,0,.75,5.23,13.13,13.13,0,0,0,4.39,3.37c11.29,6.16,24,9.26,36.81,10.8a15.36,15.36,0,0,0,6.82-.24c2.18-.74,4.11-2.7,4.07-5a2.53,2.53,0,0,0-.6-1.72,3.73,3.73,0,0,0-1.35-.79c-4.72-1.94-9.52-4.06-13.16-7.63s-5.94-9-4.53-13.86a27.38,27.38,0,0,1,3.34-6.41,106.05,106.05,0,0,0,5-9.7l4.4-9.23c1.28-2.69,2.59-5.47,2.8-8.46a40.57,40.57,0,0,1-16.21-2.59,25.54,25.54,0,0,1-6.67-4c-1.7-1.42-3.25-4.06-5.54-2.21-1.84,1.48-3,5.64-4.09,7.76A59.48,59.48,0,0,0,894.54,737.72Z" transform="translate(-52.64 -55.65)" fill="#2f2e41"/><path d="M959,508.54c-.44,3.83-4.16,6.37-7.71,7.88l22.46,7.18c-1.45-2.78-.27-6.18,1.17-9a50.81,50.81,0,0,1,4-6.4c.22-.31.47-.71.31-1.06a1.12,1.12,0,0,0-.63-.49c-4.62-2.06-9.38-4.19-14.43-4.94-1.46-.22-4.22-.8-5.31.69S959.24,506.77,959,508.54Z" transform="translate(-52.64 -55.65)" fill="#fbbebe"/><path d="M959,508.54c-.44,3.83-4.16,6.37-7.71,7.88l22.46,7.18c-1.45-2.78-.27-6.18,1.17-9a50.81,50.81,0,0,1,4-6.4c.22-.31.47-.71.31-1.06a1.12,1.12,0,0,0-.63-.49c-4.62-2.06-9.38-4.19-14.43-4.94-1.46-.22-4.22-.8-5.31.69S959.24,506.77,959,508.54Z" transform="translate(-52.64 -55.65)" opacity="0.1"/><circle cx="919.45" cy="438.38" r="17.62" fill="#fbbebe"/><path d="M987.31,639c-1.7,2-4.71,2.44-7.34,2-6.15-1-11.19-5.53-17.2-7.16-7.38-2-15.2.57-22.16,3.71s-13.9,6.95-21.52,7.55c6.89-15.36,2.95-33.85,9.53-49.34,1.62-3.78,3.87-7.44,4.23-11.53.45-5.09-2.09-10-2.48-15.07-.36-4.51,1-9,2.29-13.29l4.83-15.85c1.8-5.9,3.65-11.91,7.14-17,1.28-1.87,1.68-5.65,3.64-6.79,4.28-2.46,10.77.65,15.41.82s8.87,3.47,11.58,7.2c2.87,3.94,4.5,8.63,6,13.27a125.22,125.22,0,0,1,5.34,21.23c.15,1.08.28,2.16.38,3.25,1,10.27-.46,20.6-.54,30.91,0,0,0,0,0,.08-.09,13.08,2,26.09,2.4,39.17C988.9,634.59,988.84,637.2,987.31,639Z" transform="translate(-52.64 -55.65)" fill="#f86d70"/><path d="M986.44,593c-3.45-.87-6.58-3.09-9.25-5.53a39,39,0,0,1-6.14-6.95,50.28,50.28,0,0,1-5.29-11.16,129.34,129.34,0,0,1-7-32.28c-.26-3-.34-6.21,1.45-8.59a7.23,7.23,0,0,1,8.74-2.13c2.37,1.16,3.9,3.49,5.31,5.71,2.82,4.43,5.65,8.9,7.46,13.82.8,2.18,1.39,4.43,2.17,6.62a61,61,0,0,0,2.74,6.33c.15,1.08.28,2.16.38,3.25C987.94,572.31,986.52,582.64,986.44,593Z" transform="translate(-52.64 -55.65)" opacity="0.1"/><path d="M960.25,526.55c-1.78,2.37-1.7,5.62-1.45,8.59a129.28,129.28,0,0,0,7,32.27,49.43,49.43,0,0,0,5.29,11.16,38.67,38.67,0,0,0,6.14,6.95c3.4,3.11,7.54,5.88,12.15,5.92a23.42,23.42,0,0,0,7.56-1.65l37.51-12.74c.38-2.15-1.13-4.64-1.84-6.7l-2-5.94c-.57-1.63-1.24-3.4-2.72-4.29s-3.85.33-5.09,1.32-2.19,2.29-3.4,3.3c-2.32,1.92-5.37,2.63-8.3,3.29l-8.43,1.9a35.6,35.6,0,0,1-9.38,1.24c-2.35-7.17-6.82-13.49-9.35-20.61-.78-2.18-1.38-4.43-2.18-6.61-1.81-4.92-4.64-9.39-7.45-13.82-1.41-2.23-2.94-4.56-5.31-5.71A7.25,7.25,0,0,0,960.25,526.55Z" transform="translate(-52.64 -55.65)" fill="#f86d70"/><path d="M966.47,498a8.9,8.9,0,0,1,1.06-3.29,2.79,2.79,0,0,1,3-1.33c1.76.55,2.35,3.28,4.19,3.37,1.24.06,2.13-1.2,2.52-2.39s.6-2.52,1.53-3.36a5.61,5.61,0,0,1,2.18-1c4.27-1.35,8.68-3.85,10.1-8.1a4.9,4.9,0,0,0,.23-2.7c-.65-2.69-4-3.5-6.55-4.48s-5-2.62-7.5-3.88-5.4-2.16-8.15-1.52a40.67,40.67,0,0,0-4.11,1.54c-4.14,1.43-9.22.77-12.43,3.75a13,13,0,0,0-3,5.25c-2.25,6.21-3.66,13.6.05,19.06,2.28,3.37,4.51,7.22,8.91,7.62C963.62,507,965.66,502.32,966.47,498Z" transform="translate(-52.64 -55.65)" fill="#2f2e41"/><g opacity="0.1"><path d="M974.29,492.24c.39-1.18.6-2.52,1.52-3.36a5.83,5.83,0,0,1,2.18-1c4.28-1.35,8.68-3.84,10.11-8.1a4.89,4.89,0,0,0,.22-2.7,3.39,3.39,0,0,0-.53-1.19c1.63.7,3.05,1.65,3.45,3.31a4.9,4.9,0,0,1-.23,2.7c-1.42,4.25-5.83,6.75-10.1,8.1a5.61,5.61,0,0,0-2.18,1c-.93.84-1.14,2.18-1.53,3.36s-1.28,2.45-2.52,2.39-1.84-1.19-2.63-2.14C973.14,494.47,973.92,493.33,974.29,492.24Z" transform="translate(-52.64 -55.65)"/><path d="M955.57,504.4c5.14.47,7.17-4.2,8-8.52a8.9,8.9,0,0,1,1.06-3.29,2.78,2.78,0,0,1,3-1.32c.95.29,1.56,1.23,2.21,2a3,3,0,0,0-2.26,1.4,8.9,8.9,0,0,0-1.06,3.29c-.81,4.32-2.85,9-8,8.52a8.2,8.2,0,0,1-5.28-2.73A7.45,7.45,0,0,0,955.57,504.4Z" transform="translate(-52.64 -55.65)"/></g><path d="M223.42,705.94l19.14-11.26a46.29,46.29,0,0,0-9.79-11.7l-36.11,11.23L225,677.57a46,46,0,0,0-68.1,40.35c0,25.4,20.59,26.29,46,26.29s46-.89,46-26.29a45.71,45.71,0,0,0-4-18.66Z" transform="translate(-52.64 -55.65)" fill="{{primaryColor}}"/><path d="M228.29,730.64a35.81,35.81,0,0,0-6.78-5.33c-3.48-2.31-7.07-4.67-11.17-5.45-3.6-.69-7.31-.11-11-.31a25.65,25.65,0,0,1-16.81-7.71c-2.61-2.7-4.67-6-7.81-8.09-3.39-2.22-7.69-2.7-11.71-2.15a31.2,31.2,0,0,0-3.46.71,45.9,45.9,0,0,0-2.72,15.61c0,25.4,20.59,26.29,46,26.29,12.33,0,23.52-.21,31.78-3.33l-1.38-2.58A36.08,36.08,0,0,0,228.29,730.64Z" transform="translate(-52.64 -55.65)" opacity="0.1"/><path d="M636.6,770.25l-25.39-14.93a61.14,61.14,0,0,1,13-15.52l47.89,14.89-37.53-22.06a61,61,0,0,1,90.31,53.5c0,33.69-27.31,34.86-61,34.86s-61-1.17-61-34.86a60.84,60.84,0,0,1,5.23-24.75Z" transform="translate(-52.64 -55.65)" fill="{{primaryColor}}"/><path d="M630.13,803a47.57,47.57,0,0,1,9-7.07c4.61-3.06,9.38-6.18,14.81-7.22,4.77-.91,9.69-.14,14.54-.42a34.09,34.09,0,0,0,22.3-10.21c3.46-3.59,6.19-8,10.36-10.73,4.49-3,10.19-3.59,15.52-2.85a38.27,38.27,0,0,1,4.6.94,60.88,60.88,0,0,1,3.6,20.69c0,33.69-27.31,34.86-61,34.86-16.35,0-31.19-.27-42.15-4.41l1.83-3.42C625.45,809.59,627.39,806,630.13,803Z" transform="translate(-52.64 -55.65)" opacity="0.1"/></svg>
packages/docusaurus-1.x/examples/basics/static/img/undraw_monitor.svg
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.000239141532802023, 0.000239141532802023, 0.000239141532802023, 0.000239141532802023, 0 ]
{ "id": 4, "code_window": [ "}\n", "\n", "function shouldGenerateNextReleaseDocs() {\n", " return !(\n", " env.versioning.enabled &&\n", " program.name() === 'docusaurus-build' &&\n", " program.skipNextRelease\n", " );\n", "}\n", "\n", "// returns map from id to object containing sidebar ordering info\n", "function readSidebar(sidebars = {}) {\n", " Object.assign(sidebars, versionFallback.sidebarData());\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return !(env.versioning.enabled && program.skipNextRelease);\n" ], "file_path": "packages/docusaurus-1.x/lib/server/readMetadata.js", "type": "replace", "edit_start_line_idx": 60 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {validate} from 'webpack'; import path from 'path'; import {applyConfigureWebpack} from '../utils'; describe('extending generated webpack config', () => { test('direct mutation on generated webpack config object', async () => { // fake generated webpack config let config = { output: { path: __dirname, filename: 'bundle.js', }, }; /* eslint-disable */ const configureWebpack = (generatedConfig, isServer) => { if (!isServer) { generatedConfig.entry = 'entry.js'; generatedConfig.output = { path: path.join(__dirname, 'dist'), filename: 'new.bundle.js', }; } }; /* eslint-enable */ config = applyConfigureWebpack(configureWebpack, config, false); expect(config).toEqual({ entry: 'entry.js', output: { path: path.join(__dirname, 'dist'), filename: 'new.bundle.js', }, }); const errors = validate(config); expect(errors.length).toBe(0); }); test('webpack-merge with user webpack config object', async () => { // fake generated webpack config let config = { output: { path: __dirname, filename: 'bundle.js', }, }; /* eslint-disable */ const configureWebpack = { entry: 'entry.js', output: { path: path.join(__dirname, 'dist'), filename: 'new.bundle.js', }, }; /* eslint-enable */ config = applyConfigureWebpack(configureWebpack, config, false); expect(config).toEqual({ entry: 'entry.js', output: { path: path.join(__dirname, 'dist'), filename: 'new.bundle.js', }, }); const errors = validate(config); expect(errors.length).toBe(0); }); });
packages/docusaurus/src/webpack/__tests__/utils.test.js
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.00018006988102570176, 0.0001759122678777203, 0.0001730899966787547, 0.00017618469428271055, 0.0000023374202555714874 ]
{ "id": 4, "code_window": [ "}\n", "\n", "function shouldGenerateNextReleaseDocs() {\n", " return !(\n", " env.versioning.enabled &&\n", " program.name() === 'docusaurus-build' &&\n", " program.skipNextRelease\n", " );\n", "}\n", "\n", "// returns map from id to object containing sidebar ordering info\n", "function readSidebar(sidebars = {}) {\n", " Object.assign(sidebars, versionFallback.sidebarData());\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return !(env.versioning.enabled && program.skipNextRelease);\n" ], "file_path": "packages/docusaurus-1.x/lib/server/readMetadata.js", "type": "replace", "edit_start_line_idx": 60 }
{ "docs": { "Docusaurus": ["doc1"], "First Category": ["doc2"], "Second Category": ["doc3"] }, "docs-other": { "First Category": ["doc4", "doc5"] } }
packages/docusaurus-1.x/examples/basics/sidebars.json
0
https://github.com/facebook/docusaurus/commit/6b75bb3270c47ae0275e0975c9ee7e127013b4f6
[ 0.00017201971786562353, 0.00016912224236875772, 0.0001662247523199767, 0.00016912224236875772, 0.000002897482772823423 ]
{ "id": 0, "code_window": [ "/*---------------------------------------------------------------------------------------------\n", " * Copyright (c) Microsoft Corporation. All rights reserved.\n", " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { DisposableStore } from 'vs/base/common/lifecycle';\n", "import { URI as uri, UriComponents } from 'vs/base/common/uri';\n", "import { IDebugService, IConfig, IDebugConfigurationProvider, IBreakpoint, IFunctionBreakpoint, IBreakpointData, IDebugAdapter, IDebugAdapterDescriptorFactory, IDebugSession, IDebugAdapterFactory, IDataBreakpoint, IDebugSessionOptions, IInstructionBreakpoint, DebugConfigurationProviderTriggerKind } from 'vs/workbench/contrib/debug/common/debug';\n", "import {\n", "\tExtHostContext, ExtHostDebugServiceShape, MainThreadDebugServiceShape, DebugSessionUUID, MainContext,\n", "\tIBreakpointsDeltaDto, ISourceMultiBreakpointDto, ISourceBreakpointDto, IFunctionBreakpointDto, IDebugSessionDto, IDataBreakpointDto, IStartDebuggingOptions, IDebugConfiguration, IThreadFocusDto, IStackFrameFocusDto\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DisposableStore, toDisposable } from 'vs/base/common/lifecycle';\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadDebugService.ts", "type": "replace", "edit_start_line_idx": 5 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { DisposableStore } from 'vs/base/common/lifecycle'; import { URI as uri, UriComponents } from 'vs/base/common/uri'; import { IDebugService, IConfig, IDebugConfigurationProvider, IBreakpoint, IFunctionBreakpoint, IBreakpointData, IDebugAdapter, IDebugAdapterDescriptorFactory, IDebugSession, IDebugAdapterFactory, IDataBreakpoint, IDebugSessionOptions, IInstructionBreakpoint, DebugConfigurationProviderTriggerKind } from 'vs/workbench/contrib/debug/common/debug'; import { ExtHostContext, ExtHostDebugServiceShape, MainThreadDebugServiceShape, DebugSessionUUID, MainContext, IBreakpointsDeltaDto, ISourceMultiBreakpointDto, ISourceBreakpointDto, IFunctionBreakpointDto, IDebugSessionDto, IDataBreakpointDto, IStartDebuggingOptions, IDebugConfiguration, IThreadFocusDto, IStackFrameFocusDto } from 'vs/workbench/api/common/extHost.protocol'; import { extHostNamedCustomer, IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers'; import severity from 'vs/base/common/severity'; import { AbstractDebugAdapter } from 'vs/workbench/contrib/debug/common/abstractDebugAdapter'; import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { convertToVSCPaths, convertToDAPaths, isSessionAttach } from 'vs/workbench/contrib/debug/common/debugUtils'; import { ErrorNoTelemetry } from 'vs/base/common/errors'; @extHostNamedCustomer(MainContext.MainThreadDebugService) export class MainThreadDebugService implements MainThreadDebugServiceShape, IDebugAdapterFactory { private readonly _proxy: ExtHostDebugServiceShape; private readonly _toDispose = new DisposableStore(); private readonly _debugAdapters: Map<number, ExtensionHostDebugAdapter>; private _debugAdaptersHandleCounter = 1; private readonly _debugConfigurationProviders: Map<number, IDebugConfigurationProvider>; private readonly _debugAdapterDescriptorFactories: Map<number, IDebugAdapterDescriptorFactory>; private readonly _sessions: Set<DebugSessionUUID>; constructor( extHostContext: IExtHostContext, @IDebugService private readonly debugService: IDebugService ) { this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostDebugService); this._toDispose.add(debugService.onDidNewSession(session => { this._proxy.$acceptDebugSessionStarted(this.getSessionDto(session)); this._toDispose.add(session.onDidChangeName(name => { this._proxy.$acceptDebugSessionNameChanged(this.getSessionDto(session), name); })); })); // Need to start listening early to new session events because a custom event can come while a session is initialising this._toDispose.add(debugService.onWillNewSession(session => { this._toDispose.add(session.onDidCustomEvent(event => this._proxy.$acceptDebugSessionCustomEvent(this.getSessionDto(session), event))); })); this._toDispose.add(debugService.onDidEndSession(session => { this._proxy.$acceptDebugSessionTerminated(this.getSessionDto(session)); this._sessions.delete(session.getId()); })); this._toDispose.add(debugService.getViewModel().onDidFocusSession(session => { this._proxy.$acceptDebugSessionActiveChanged(this.getSessionDto(session)); })); this._debugAdapters = new Map(); this._debugConfigurationProviders = new Map(); this._debugAdapterDescriptorFactories = new Map(); this._sessions = new Set(); this._toDispose.add(this.debugService.getViewModel().onDidFocusThread(({ thread, explicit, session }) => { if (session) { const dto: IThreadFocusDto = { kind: 'thread', threadId: thread?.threadId, sessionId: session!.getId(), }; this._proxy.$acceptStackFrameFocus(dto); } })); this._toDispose.add(this.debugService.getViewModel().onDidFocusStackFrame(({ stackFrame, explicit, session }) => { if (session) { const dto: IStackFrameFocusDto = { kind: 'stackFrame', threadId: stackFrame?.thread.threadId, frameId: stackFrame?.frameId, sessionId: session.getId(), }; this._proxy.$acceptStackFrameFocus(dto); } })); this.sendBreakpointsAndListen(); } private sendBreakpointsAndListen(): void { // set up a handler to send more this._toDispose.add(this.debugService.getModel().onDidChangeBreakpoints(e => { // Ignore session only breakpoint events since they should only reflect in the UI if (e && !e.sessionOnly) { const delta: IBreakpointsDeltaDto = {}; if (e.added) { delta.added = this.convertToDto(e.added); } if (e.removed) { delta.removed = e.removed.map(x => x.getId()); } if (e.changed) { delta.changed = this.convertToDto(e.changed); } if (delta.added || delta.removed || delta.changed) { this._proxy.$acceptBreakpointsDelta(delta); } } })); // send all breakpoints const bps = this.debugService.getModel().getBreakpoints(); const fbps = this.debugService.getModel().getFunctionBreakpoints(); const dbps = this.debugService.getModel().getDataBreakpoints(); if (bps.length > 0 || fbps.length > 0) { this._proxy.$acceptBreakpointsDelta({ added: this.convertToDto(bps).concat(this.convertToDto(fbps)).concat(this.convertToDto(dbps)) }); } } public dispose(): void { this._toDispose.dispose(); } // interface IDebugAdapterProvider createDebugAdapter(session: IDebugSession): IDebugAdapter { const handle = this._debugAdaptersHandleCounter++; const da = new ExtensionHostDebugAdapter(this, handle, this._proxy, session); this._debugAdapters.set(handle, da); return da; } substituteVariables(folder: IWorkspaceFolder | undefined, config: IConfig): Promise<IConfig> { return Promise.resolve(this._proxy.$substituteVariables(folder ? folder.uri : undefined, config)); } runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments, sessionId: string): Promise<number | undefined> { return this._proxy.$runInTerminal(args, sessionId); } // RPC methods (MainThreadDebugServiceShape) public $registerDebugTypes(debugTypes: string[]) { this._toDispose.add(this.debugService.getAdapterManager().registerDebugAdapterFactory(debugTypes, this)); } public $registerBreakpoints(DTOs: Array<ISourceMultiBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto>): Promise<void> { for (const dto of DTOs) { if (dto.type === 'sourceMulti') { const rawbps = dto.lines.map(l => <IBreakpointData>{ id: l.id, enabled: l.enabled, lineNumber: l.line + 1, column: l.character > 0 ? l.character + 1 : undefined, // a column value of 0 results in an omitted column attribute; see #46784 condition: l.condition, hitCondition: l.hitCondition, logMessage: l.logMessage } ); this.debugService.addBreakpoints(uri.revive(dto.uri), rawbps); } else if (dto.type === 'function') { this.debugService.addFunctionBreakpoint(dto.functionName, dto.id); } else if (dto.type === 'data') { this.debugService.addDataBreakpoint(dto.label, dto.dataId, dto.canPersist, dto.accessTypes, dto.accessType); } } return Promise.resolve(); } public $unregisterBreakpoints(breakpointIds: string[], functionBreakpointIds: string[], dataBreakpointIds: string[]): Promise<void> { breakpointIds.forEach(id => this.debugService.removeBreakpoints(id)); functionBreakpointIds.forEach(id => this.debugService.removeFunctionBreakpoints(id)); dataBreakpointIds.forEach(id => this.debugService.removeDataBreakpoints(id)); return Promise.resolve(); } public $registerDebugConfigurationProvider(debugType: string, providerTriggerKind: DebugConfigurationProviderTriggerKind, hasProvide: boolean, hasResolve: boolean, hasResolve2: boolean, handle: number): Promise<void> { const provider = <IDebugConfigurationProvider>{ type: debugType, triggerKind: providerTriggerKind }; if (hasProvide) { provider.provideDebugConfigurations = (folder, token) => { return this._proxy.$provideDebugConfigurations(handle, folder, token); }; } if (hasResolve) { provider.resolveDebugConfiguration = (folder, config, token) => { return this._proxy.$resolveDebugConfiguration(handle, folder, config, token); }; } if (hasResolve2) { provider.resolveDebugConfigurationWithSubstitutedVariables = (folder, config, token) => { return this._proxy.$resolveDebugConfigurationWithSubstitutedVariables(handle, folder, config, token); }; } this._debugConfigurationProviders.set(handle, provider); this._toDispose.add(this.debugService.getConfigurationManager().registerDebugConfigurationProvider(provider)); return Promise.resolve(undefined); } public $unregisterDebugConfigurationProvider(handle: number): void { const provider = this._debugConfigurationProviders.get(handle); if (provider) { this._debugConfigurationProviders.delete(handle); this.debugService.getConfigurationManager().unregisterDebugConfigurationProvider(provider); } } public $registerDebugAdapterDescriptorFactory(debugType: string, handle: number): Promise<void> { const provider = <IDebugAdapterDescriptorFactory>{ type: debugType, createDebugAdapterDescriptor: session => { return Promise.resolve(this._proxy.$provideDebugAdapter(handle, this.getSessionDto(session))); } }; this._debugAdapterDescriptorFactories.set(handle, provider); this._toDispose.add(this.debugService.getAdapterManager().registerDebugAdapterDescriptorFactory(provider)); return Promise.resolve(undefined); } public $unregisterDebugAdapterDescriptorFactory(handle: number): void { const provider = this._debugAdapterDescriptorFactories.get(handle); if (provider) { this._debugAdapterDescriptorFactories.delete(handle); this.debugService.getAdapterManager().unregisterDebugAdapterDescriptorFactory(provider); } } private getSession(sessionId: DebugSessionUUID | undefined): IDebugSession | undefined { if (sessionId) { return this.debugService.getModel().getSession(sessionId, true); } return undefined; } public async $startDebugging(folder: UriComponents | undefined, nameOrConfig: string | IDebugConfiguration, options: IStartDebuggingOptions): Promise<boolean> { const folderUri = folder ? uri.revive(folder) : undefined; const launch = this.debugService.getConfigurationManager().getLaunch(folderUri); const parentSession = this.getSession(options.parentSessionID); const saveBeforeStart = typeof options.suppressSaveBeforeStart === 'boolean' ? !options.suppressSaveBeforeStart : undefined; const debugOptions: IDebugSessionOptions = { noDebug: options.noDebug, parentSession, lifecycleManagedByParent: options.lifecycleManagedByParent, repl: options.repl, compact: options.compact, compoundRoot: parentSession?.compoundRoot, saveBeforeRestart: saveBeforeStart, suppressDebugStatusbar: options.suppressDebugStatusbar, suppressDebugToolbar: options.suppressDebugToolbar, suppressDebugView: options.suppressDebugView, }; try { return this.debugService.startDebugging(launch, nameOrConfig, debugOptions, saveBeforeStart); } catch (err) { throw new ErrorNoTelemetry(err && err.message ? err.message : 'cannot start debugging'); } } public $setDebugSessionName(sessionId: DebugSessionUUID, name: string): void { const session = this.debugService.getModel().getSession(sessionId); session?.setName(name); } public $customDebugAdapterRequest(sessionId: DebugSessionUUID, request: string, args: any): Promise<any> { const session = this.debugService.getModel().getSession(sessionId, true); if (session) { return session.customRequest(request, args).then(response => { if (response && response.success) { return response.body; } else { return Promise.reject(new ErrorNoTelemetry(response ? response.message : 'custom request failed')); } }); } return Promise.reject(new ErrorNoTelemetry('debug session not found')); } public $getDebugProtocolBreakpoint(sessionId: DebugSessionUUID, breakpoinId: string): Promise<DebugProtocol.Breakpoint | undefined> { const session = this.debugService.getModel().getSession(sessionId, true); if (session) { return Promise.resolve(session.getDebugProtocolBreakpoint(breakpoinId)); } return Promise.reject(new ErrorNoTelemetry('debug session not found')); } public $stopDebugging(sessionId: DebugSessionUUID | undefined): Promise<void> { if (sessionId) { const session = this.debugService.getModel().getSession(sessionId, true); if (session) { return this.debugService.stopSession(session, isSessionAttach(session)); } } else { // stop all return this.debugService.stopSession(undefined); } return Promise.reject(new ErrorNoTelemetry('debug session not found')); } public $appendDebugConsole(value: string): void { // Use warning as severity to get the orange color for messages coming from the debug extension const session = this.debugService.getViewModel().focusedSession; session?.appendToRepl({ output: value, sev: severity.Warning }); } public $acceptDAMessage(handle: number, message: DebugProtocol.ProtocolMessage) { this.getDebugAdapter(handle).acceptMessage(convertToVSCPaths(message, false)); } public $acceptDAError(handle: number, name: string, message: string, stack: string) { this.getDebugAdapter(handle).fireError(handle, new Error(`${name}: ${message}\n${stack}`)); } public $acceptDAExit(handle: number, code: number, signal: string) { this.getDebugAdapter(handle).fireExit(handle, code, signal); } private getDebugAdapter(handle: number): ExtensionHostDebugAdapter { const adapter = this._debugAdapters.get(handle); if (!adapter) { throw new Error('Invalid debug adapter'); } return adapter; } // dto helpers public $sessionCached(sessionID: string) { // remember that the EH has cached the session and we do not have to send it again this._sessions.add(sessionID); } getSessionDto(session: undefined): undefined; getSessionDto(session: IDebugSession): IDebugSessionDto; getSessionDto(session: IDebugSession | undefined): IDebugSessionDto | undefined; getSessionDto(session: IDebugSession | undefined): IDebugSessionDto | undefined { if (session) { const sessionID = <DebugSessionUUID>session.getId(); if (this._sessions.has(sessionID)) { return sessionID; } else { // this._sessions.add(sessionID); // #69534: see $sessionCached above return { id: sessionID, type: session.configuration.type, name: session.name, folderUri: session.root ? session.root.uri : undefined, configuration: session.configuration, parent: session.parentSession?.getId(), }; } } return undefined; } private convertToDto(bps: (ReadonlyArray<IBreakpoint | IFunctionBreakpoint | IDataBreakpoint | IInstructionBreakpoint>)): Array<ISourceBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto> { return bps.map(bp => { if ('name' in bp) { const fbp = <IFunctionBreakpoint>bp; return <IFunctionBreakpointDto>{ type: 'function', id: fbp.getId(), enabled: fbp.enabled, condition: fbp.condition, hitCondition: fbp.hitCondition, logMessage: fbp.logMessage, functionName: fbp.name }; } else if ('dataId' in bp) { const dbp = <IDataBreakpoint>bp; return <IDataBreakpointDto>{ type: 'data', id: dbp.getId(), dataId: dbp.dataId, enabled: dbp.enabled, condition: dbp.condition, hitCondition: dbp.hitCondition, logMessage: dbp.logMessage, label: dbp.description, canPersist: dbp.canPersist }; } else { const sbp = <IBreakpoint>bp; return <ISourceBreakpointDto>{ type: 'source', id: sbp.getId(), enabled: sbp.enabled, condition: sbp.condition, hitCondition: sbp.hitCondition, logMessage: sbp.logMessage, uri: sbp.uri, line: sbp.lineNumber > 0 ? sbp.lineNumber - 1 : 0, character: (typeof sbp.column === 'number' && sbp.column > 0) ? sbp.column - 1 : 0, }; } }); } } /** * DebugAdapter that communicates via extension protocol with another debug adapter. */ class ExtensionHostDebugAdapter extends AbstractDebugAdapter { constructor(private readonly _ds: MainThreadDebugService, private _handle: number, private _proxy: ExtHostDebugServiceShape, private _session: IDebugSession) { super(); } fireError(handle: number, err: Error) { this._onError.fire(err); } fireExit(handle: number, code: number, signal: string) { this._onExit.fire(code); } startSession(): Promise<void> { return Promise.resolve(this._proxy.$startDASession(this._handle, this._ds.getSessionDto(this._session))); } sendMessage(message: DebugProtocol.ProtocolMessage): void { this._proxy.$sendDAMessage(this._handle, convertToDAPaths(message, true)); } async stopSession(): Promise<void> { await this.cancelPendingRequests(); return Promise.resolve(this._proxy.$stopDASession(this._handle)); } }
src/vs/workbench/api/browser/mainThreadDebugService.ts
1
https://github.com/microsoft/vscode/commit/ccbcba53e642136ce30465cd4f5605d60c760d7c
[ 0.03324133902788162, 0.0010886312229558825, 0.0001624309952603653, 0.00017317154561169446, 0.0049218893982470036 ]
{ "id": 0, "code_window": [ "/*---------------------------------------------------------------------------------------------\n", " * Copyright (c) Microsoft Corporation. All rights reserved.\n", " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { DisposableStore } from 'vs/base/common/lifecycle';\n", "import { URI as uri, UriComponents } from 'vs/base/common/uri';\n", "import { IDebugService, IConfig, IDebugConfigurationProvider, IBreakpoint, IFunctionBreakpoint, IBreakpointData, IDebugAdapter, IDebugAdapterDescriptorFactory, IDebugSession, IDebugAdapterFactory, IDataBreakpoint, IDebugSessionOptions, IInstructionBreakpoint, DebugConfigurationProviderTriggerKind } from 'vs/workbench/contrib/debug/common/debug';\n", "import {\n", "\tExtHostContext, ExtHostDebugServiceShape, MainThreadDebugServiceShape, DebugSessionUUID, MainContext,\n", "\tIBreakpointsDeltaDto, ISourceMultiBreakpointDto, ISourceBreakpointDto, IFunctionBreakpointDto, IDebugSessionDto, IDataBreakpointDto, IStartDebuggingOptions, IDebugConfiguration, IThreadFocusDto, IStackFrameFocusDto\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DisposableStore, toDisposable } from 'vs/base/common/lifecycle';\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadDebugService.ts", "type": "replace", "edit_start_line_idx": 5 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { Event, Emitter } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { RawContextKey, IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IFilesConfiguration, AutoSaveConfiguration, HotExitConfiguration, FILES_READONLY_INCLUDE_CONFIG, FILES_READONLY_EXCLUDE_CONFIG, IFileStatWithMetadata, IFileService, IBaseFileStat, hasReadonlyCapability } from 'vs/platform/files/common/files'; import { equals } from 'vs/base/common/objects'; import { URI } from 'vs/base/common/uri'; import { isWeb } from 'vs/base/common/platform'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ResourceGlobMatcher } from 'vs/workbench/common/resources'; import { IdleValue } from 'vs/base/common/async'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ResourceMap } from 'vs/base/common/map'; import { withNullAsUndefined } from 'vs/base/common/types'; import { IMarkdownString } from 'vs/base/common/htmlContent'; export const AutoSaveAfterShortDelayContext = new RawContextKey<boolean>('autoSaveAfterShortDelayContext', false, true); export interface IAutoSaveConfiguration { readonly autoSaveDelay?: number; readonly autoSaveFocusChange: boolean; readonly autoSaveApplicationChange: boolean; } export const enum AutoSaveMode { OFF, AFTER_SHORT_DELAY, AFTER_LONG_DELAY, ON_FOCUS_CHANGE, ON_WINDOW_CHANGE } export const IFilesConfigurationService = createDecorator<IFilesConfigurationService>('filesConfigurationService'); export interface IFilesConfigurationService { readonly _serviceBrand: undefined; //#region Auto Save readonly onAutoSaveConfigurationChange: Event<IAutoSaveConfiguration>; getAutoSaveConfiguration(): IAutoSaveConfiguration; getAutoSaveMode(): AutoSaveMode; toggleAutoSave(): Promise<void>; //#endregion //#region Configured Readonly readonly onReadonlyChange: Event<void>; isReadonly(resource: URI, stat?: IBaseFileStat): boolean | IMarkdownString; updateReadonly(resource: URI, readonly: true | false | 'toggle' | 'reset'): Promise<void>; //#endregion readonly onFilesAssociationChange: Event<void>; readonly isHotExitEnabled: boolean; readonly hotExitConfiguration: string | undefined; preventSaveConflicts(resource: URI, language?: string): boolean; } export class FilesConfigurationService extends Disposable implements IFilesConfigurationService { declare readonly _serviceBrand: undefined; private static readonly DEFAULT_AUTO_SAVE_MODE = isWeb ? AutoSaveConfiguration.AFTER_DELAY : AutoSaveConfiguration.OFF; private static readonly READONLY_MESSAGES = { providerReadonly: { value: localize('providerReadonly', "Editor is read-only because the file system of the file is read-only."), isTrusted: true }, sessionReadonly: { value: localize({ key: 'sessionReadonly', comment: ['Please do not translate the word "command", it is part of our internal syntax which must not change', '{Locked="](command:{0})"}'] }, "Editor is read-only because the file was set read-only in this session. [Click here](command:{0}) to set writeable.", 'workbench.action.files.setActiveEditorWriteableInSession'), isTrusted: true }, configuredReadonly: { value: localize({ key: 'configuredReadonly', comment: ['Please do not translate the word "command", it is part of our internal syntax which must not change', '{Locked="](command:{0})"}'] }, "Editor is read-only because the file was set read-only via settings. [Click here](command:{0}) to configure.", `workbench.action.openSettings?${encodeURIComponent('["files.readonly"]')}`), isTrusted: true }, fileLocked: { value: localize({ key: 'fileLocked', comment: ['Please do not translate the word "command", it is part of our internal syntax which must not change', '{Locked="](command:{0})"}'] }, "Editor is read-only because of file permissions. [Click here](command:{0}) to set writeable anyway.", 'workbench.action.files.setActiveEditorWriteableInSession'), isTrusted: true }, fileReadonly: { value: localize('fileReadonly', "Editor is read-only because the file is read-only."), isTrusted: true } }; private readonly _onAutoSaveConfigurationChange = this._register(new Emitter<IAutoSaveConfiguration>()); readonly onAutoSaveConfigurationChange = this._onAutoSaveConfigurationChange.event; private readonly _onFilesAssociationChange = this._register(new Emitter<void>()); readonly onFilesAssociationChange = this._onFilesAssociationChange.event; private readonly _onReadonlyConfigurationChange = this._register(new Emitter<void>()); readonly onReadonlyChange = this._onReadonlyConfigurationChange.event; private configuredAutoSaveDelay?: number; private configuredAutoSaveOnFocusChange: boolean | undefined; private configuredAutoSaveOnWindowChange: boolean | undefined; private autoSaveAfterShortDelayContext: IContextKey<boolean>; private currentFilesAssociationConfig: { [key: string]: string }; private currentHotExitConfig: string; private readonly readonlyIncludeMatcher = this._register(new IdleValue(() => this.createReadonlyMatcher(FILES_READONLY_INCLUDE_CONFIG))); private readonly readonlyExcludeMatcher = this._register(new IdleValue(() => this.createReadonlyMatcher(FILES_READONLY_EXCLUDE_CONFIG))); private configuredReadonlyFromPermissions: boolean | undefined; private readonly sessionReadonlyOverrides = new ResourceMap<boolean>(resource => this.uriIdentityService.extUri.getComparisonKey(resource)); constructor( @IContextKeyService contextKeyService: IContextKeyService, @IConfigurationService private readonly configurationService: IConfigurationService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IEnvironmentService private readonly environmentService: IEnvironmentService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService, @IFileService private readonly fileService: IFileService ) { super(); this.autoSaveAfterShortDelayContext = AutoSaveAfterShortDelayContext.bindTo(contextKeyService); const configuration = configurationService.getValue<IFilesConfiguration>(); this.currentFilesAssociationConfig = configuration?.files?.associations; this.currentHotExitConfig = configuration?.files?.hotExit || HotExitConfiguration.ON_EXIT; this.onFilesConfigurationChange(configuration); this.registerListeners(); } private createReadonlyMatcher(config: string) { const matcher = this._register(new ResourceGlobMatcher( resource => this.configurationService.getValue(config, { resource }), event => event.affectsConfiguration(config), this.contextService, this.configurationService )); this._register(matcher.onExpressionChange(() => this._onReadonlyConfigurationChange.fire())); return matcher; } isReadonly(resource: URI, stat?: IBaseFileStat): boolean | IMarkdownString { // if the entire file system provider is readonly, we respect that // and do not allow to change readonly. we take this as a hint that // the provider has no capabilities of writing. const provider = this.fileService.getProvider(resource.scheme); if (provider && hasReadonlyCapability(provider)) { return provider.readOnlyMessage ?? FilesConfigurationService.READONLY_MESSAGES.providerReadonly; } // session override always wins over the others const sessionReadonlyOverride = this.sessionReadonlyOverrides.get(resource); if (typeof sessionReadonlyOverride === 'boolean') { return sessionReadonlyOverride === true ? FilesConfigurationService.READONLY_MESSAGES.sessionReadonly : false; } if ( this.uriIdentityService.extUri.isEqualOrParent(resource, this.environmentService.userRoamingDataHome) || this.uriIdentityService.extUri.isEqual(resource, withNullAsUndefined(this.contextService.getWorkspace().configuration)) ) { return false; // explicitly exclude some paths from readonly that we need for configuration } // configured glob patterns win over stat information if (this.readonlyIncludeMatcher.value.matches(resource)) { return !this.readonlyExcludeMatcher.value.matches(resource) ? FilesConfigurationService.READONLY_MESSAGES.configuredReadonly : false; } // check if file is locked and configured to treat as readonly if (this.configuredReadonlyFromPermissions && stat?.locked) { return FilesConfigurationService.READONLY_MESSAGES.fileLocked; } // check if file is marked readonly from the file system provider if (stat?.readonly) { return FilesConfigurationService.READONLY_MESSAGES.fileReadonly; } return false; } async updateReadonly(resource: URI, readonly: true | false | 'toggle' | 'reset'): Promise<void> { if (readonly === 'toggle') { let stat: IFileStatWithMetadata | undefined = undefined; try { stat = await this.fileService.resolve(resource, { resolveMetadata: true }); } catch (error) { // ignore } readonly = !this.isReadonly(resource, stat); } if (readonly === 'reset') { this.sessionReadonlyOverrides.delete(resource); } else { this.sessionReadonlyOverrides.set(resource, readonly); } this._onReadonlyConfigurationChange.fire(); } private registerListeners(): void { // Files configuration changes this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('files')) { this.onFilesConfigurationChange(this.configurationService.getValue<IFilesConfiguration>()); } })); } protected onFilesConfigurationChange(configuration: IFilesConfiguration): void { // Auto Save const autoSaveMode = configuration?.files?.autoSave || FilesConfigurationService.DEFAULT_AUTO_SAVE_MODE; switch (autoSaveMode) { case AutoSaveConfiguration.AFTER_DELAY: this.configuredAutoSaveDelay = configuration?.files?.autoSaveDelay; this.configuredAutoSaveOnFocusChange = false; this.configuredAutoSaveOnWindowChange = false; break; case AutoSaveConfiguration.ON_FOCUS_CHANGE: this.configuredAutoSaveDelay = undefined; this.configuredAutoSaveOnFocusChange = true; this.configuredAutoSaveOnWindowChange = false; break; case AutoSaveConfiguration.ON_WINDOW_CHANGE: this.configuredAutoSaveDelay = undefined; this.configuredAutoSaveOnFocusChange = false; this.configuredAutoSaveOnWindowChange = true; break; default: this.configuredAutoSaveDelay = undefined; this.configuredAutoSaveOnFocusChange = false; this.configuredAutoSaveOnWindowChange = false; break; } this.autoSaveAfterShortDelayContext.set(this.getAutoSaveMode() === AutoSaveMode.AFTER_SHORT_DELAY); this._onAutoSaveConfigurationChange.fire(this.getAutoSaveConfiguration()); // Check for change in files associations const filesAssociation = configuration?.files?.associations; if (!equals(this.currentFilesAssociationConfig, filesAssociation)) { this.currentFilesAssociationConfig = filesAssociation; this._onFilesAssociationChange.fire(); } // Hot exit const hotExitMode = configuration?.files?.hotExit; if (hotExitMode === HotExitConfiguration.OFF || hotExitMode === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) { this.currentHotExitConfig = hotExitMode; } else { this.currentHotExitConfig = HotExitConfiguration.ON_EXIT; } // Readonly const readonlyFromPermissions = Boolean(configuration?.files?.readonlyFromPermissions); if (readonlyFromPermissions !== Boolean(this.configuredReadonlyFromPermissions)) { this.configuredReadonlyFromPermissions = readonlyFromPermissions; this._onReadonlyConfigurationChange.fire(); } } getAutoSaveMode(): AutoSaveMode { if (this.configuredAutoSaveOnFocusChange) { return AutoSaveMode.ON_FOCUS_CHANGE; } if (this.configuredAutoSaveOnWindowChange) { return AutoSaveMode.ON_WINDOW_CHANGE; } if (typeof this.configuredAutoSaveDelay === 'number' && this.configuredAutoSaveDelay >= 0) { return this.configuredAutoSaveDelay <= 1000 ? AutoSaveMode.AFTER_SHORT_DELAY : AutoSaveMode.AFTER_LONG_DELAY; } return AutoSaveMode.OFF; } getAutoSaveConfiguration(): IAutoSaveConfiguration { return { autoSaveDelay: typeof this.configuredAutoSaveDelay === 'number' && this.configuredAutoSaveDelay >= 0 ? this.configuredAutoSaveDelay : undefined, autoSaveFocusChange: !!this.configuredAutoSaveOnFocusChange, autoSaveApplicationChange: !!this.configuredAutoSaveOnWindowChange }; } async toggleAutoSave(): Promise<void> { const currentSetting = this.configurationService.getValue('files.autoSave'); let newAutoSaveValue: string; if ([AutoSaveConfiguration.AFTER_DELAY, AutoSaveConfiguration.ON_FOCUS_CHANGE, AutoSaveConfiguration.ON_WINDOW_CHANGE].some(setting => setting === currentSetting)) { newAutoSaveValue = AutoSaveConfiguration.OFF; } else { newAutoSaveValue = AutoSaveConfiguration.AFTER_DELAY; } return this.configurationService.updateValue('files.autoSave', newAutoSaveValue); } get isHotExitEnabled(): boolean { if (this.contextService.getWorkspace().transient) { // Transient workspace: hot exit is disabled because // transient workspaces are not restored upon restart return false; } return this.currentHotExitConfig !== HotExitConfiguration.OFF; } get hotExitConfiguration(): string { return this.currentHotExitConfig; } preventSaveConflicts(resource: URI, language?: string): boolean { return this.configurationService.getValue('files.saveConflictResolution', { resource, overrideIdentifier: language }) !== 'overwriteFileOnDisk'; } } registerSingleton(IFilesConfigurationService, FilesConfigurationService, InstantiationType.Eager);
src/vs/workbench/services/filesConfiguration/common/filesConfigurationService.ts
0
https://github.com/microsoft/vscode/commit/ccbcba53e642136ce30465cd4f5605d60c760d7c
[ 0.001818395685404539, 0.0002205863711424172, 0.00016368148499168456, 0.0001710111100692302, 0.00027847307501360774 ]
{ "id": 0, "code_window": [ "/*---------------------------------------------------------------------------------------------\n", " * Copyright (c) Microsoft Corporation. All rights reserved.\n", " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { DisposableStore } from 'vs/base/common/lifecycle';\n", "import { URI as uri, UriComponents } from 'vs/base/common/uri';\n", "import { IDebugService, IConfig, IDebugConfigurationProvider, IBreakpoint, IFunctionBreakpoint, IBreakpointData, IDebugAdapter, IDebugAdapterDescriptorFactory, IDebugSession, IDebugAdapterFactory, IDataBreakpoint, IDebugSessionOptions, IInstructionBreakpoint, DebugConfigurationProviderTriggerKind } from 'vs/workbench/contrib/debug/common/debug';\n", "import {\n", "\tExtHostContext, ExtHostDebugServiceShape, MainThreadDebugServiceShape, DebugSessionUUID, MainContext,\n", "\tIBreakpointsDeltaDto, ISourceMultiBreakpointDto, ISourceBreakpointDto, IFunctionBreakpointDto, IDebugSessionDto, IDataBreakpointDto, IStartDebuggingOptions, IDebugConfiguration, IThreadFocusDto, IStackFrameFocusDto\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DisposableStore, toDisposable } from 'vs/base/common/lifecycle';\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadDebugService.ts", "type": "replace", "edit_start_line_idx": 5 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "marked", "repositoryUrl": "https://github.com/markedjs/marked", "commitHash": "7e2ef307846427650114591f9257b5545868e928" } }, "license": "MIT", "version": "4.1.0" } ], "version": 1 }
src/vs/base/common/marked/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/ccbcba53e642136ce30465cd4f5605d60c760d7c
[ 0.0001719979045446962, 0.00017153771477751434, 0.0001710775395622477, 0.00017153771477751434, 4.6018249122425914e-7 ]
{ "id": 0, "code_window": [ "/*---------------------------------------------------------------------------------------------\n", " * Copyright (c) Microsoft Corporation. All rights reserved.\n", " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { DisposableStore } from 'vs/base/common/lifecycle';\n", "import { URI as uri, UriComponents } from 'vs/base/common/uri';\n", "import { IDebugService, IConfig, IDebugConfigurationProvider, IBreakpoint, IFunctionBreakpoint, IBreakpointData, IDebugAdapter, IDebugAdapterDescriptorFactory, IDebugSession, IDebugAdapterFactory, IDataBreakpoint, IDebugSessionOptions, IInstructionBreakpoint, DebugConfigurationProviderTriggerKind } from 'vs/workbench/contrib/debug/common/debug';\n", "import {\n", "\tExtHostContext, ExtHostDebugServiceShape, MainThreadDebugServiceShape, DebugSessionUUID, MainContext,\n", "\tIBreakpointsDeltaDto, ISourceMultiBreakpointDto, ISourceBreakpointDto, IFunctionBreakpointDto, IDebugSessionDto, IDataBreakpointDto, IStartDebuggingOptions, IDebugConfiguration, IThreadFocusDto, IStackFrameFocusDto\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { DisposableStore, toDisposable } from 'vs/base/common/lifecycle';\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadDebugService.ts", "type": "replace", "edit_start_line_idx": 5 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { AsyncIterableObject } from 'vs/base/common/async'; import { CancellationToken } from 'vs/base/common/cancellation'; import { IMarkdownString, isEmptyMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { ICodeEditor, IEditorMouseEvent, MouseTargetType } from 'vs/editor/browser/editorBrowser'; import { Position } from 'vs/editor/common/core/position'; import { IModelDecoration } from 'vs/editor/common/model'; import { ModelDecorationInjectedTextOptions } from 'vs/editor/common/model/textModel'; import { HoverAnchor, HoverForeignElementAnchor, IEditorHoverParticipant } from 'vs/editor/contrib/hover/browser/hoverTypes'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { ITextModelService } from 'vs/editor/common/services/resolverService'; import { getHover } from 'vs/editor/contrib/hover/browser/getHover'; import { MarkdownHover, MarkdownHoverParticipant } from 'vs/editor/contrib/hover/browser/markdownHoverParticipant'; import { RenderedInlayHintLabelPart, InlayHintsController } from 'vs/editor/contrib/inlayHints/browser/inlayHintsController'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { localize } from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import { asCommandLink } from 'vs/editor/contrib/inlayHints/browser/inlayHints'; import { isNonEmptyArray } from 'vs/base/common/arrays'; class InlayHintsHoverAnchor extends HoverForeignElementAnchor { constructor( readonly part: RenderedInlayHintLabelPart, owner: InlayHintsHover, initialMousePosX: number | undefined, initialMousePosY: number | undefined ) { super(10, owner, part.item.anchor.range, initialMousePosX, initialMousePosY, true); } } export class InlayHintsHover extends MarkdownHoverParticipant implements IEditorHoverParticipant<MarkdownHover> { public override readonly hoverOrdinal: number = 6; constructor( editor: ICodeEditor, @ILanguageService languageService: ILanguageService, @IOpenerService openerService: IOpenerService, @IConfigurationService configurationService: IConfigurationService, @ITextModelService private readonly _resolverService: ITextModelService, @ILanguageFeaturesService languageFeaturesService: ILanguageFeaturesService, ) { super(editor, languageService, openerService, configurationService, languageFeaturesService); } suggestHoverAnchor(mouseEvent: IEditorMouseEvent): HoverAnchor | null { const controller = InlayHintsController.get(this._editor); if (!controller) { return null; } if (mouseEvent.target.type !== MouseTargetType.CONTENT_TEXT) { return null; } const options = mouseEvent.target.detail.injectedText?.options; if (!(options instanceof ModelDecorationInjectedTextOptions && options.attachedData instanceof RenderedInlayHintLabelPart)) { return null; } return new InlayHintsHoverAnchor(options.attachedData, this, mouseEvent.event.posx, mouseEvent.event.posy); } override computeSync(): MarkdownHover[] { return []; } override computeAsync(anchor: HoverAnchor, _lineDecorations: IModelDecoration[], token: CancellationToken): AsyncIterableObject<MarkdownHover> { if (!(anchor instanceof InlayHintsHoverAnchor)) { return AsyncIterableObject.EMPTY; } return new AsyncIterableObject<MarkdownHover>(async executor => { const { part } = anchor; await part.item.resolve(token); if (token.isCancellationRequested) { return; } // (1) Inlay Tooltip let itemTooltip: IMarkdownString | undefined; if (typeof part.item.hint.tooltip === 'string') { itemTooltip = new MarkdownString().appendText(part.item.hint.tooltip); } else if (part.item.hint.tooltip) { itemTooltip = part.item.hint.tooltip; } if (itemTooltip) { executor.emitOne(new MarkdownHover(this, anchor.range, [itemTooltip], false, 0)); } // (1.2) Inlay dbl-click gesture if (isNonEmptyArray(part.item.hint.textEdits)) { executor.emitOne(new MarkdownHover(this, anchor.range, [new MarkdownString().appendText(localize('hint.dbl', "Double-click to insert"))], false, 10001)); } // (2) Inlay Label Part Tooltip let partTooltip: IMarkdownString | undefined; if (typeof part.part.tooltip === 'string') { partTooltip = new MarkdownString().appendText(part.part.tooltip); } else if (part.part.tooltip) { partTooltip = part.part.tooltip; } if (partTooltip) { executor.emitOne(new MarkdownHover(this, anchor.range, [partTooltip], false, 1)); } // (2.2) Inlay Label Part Help Hover if (part.part.location || part.part.command) { let linkHint: MarkdownString | undefined; const useMetaKey = this._editor.getOption(EditorOption.multiCursorModifier) === 'altKey'; const kb = useMetaKey ? platform.isMacintosh ? localize('links.navigate.kb.meta.mac', "cmd + click") : localize('links.navigate.kb.meta', "ctrl + click") : platform.isMacintosh ? localize('links.navigate.kb.alt.mac', "option + click") : localize('links.navigate.kb.alt', "alt + click"); if (part.part.location && part.part.command) { linkHint = new MarkdownString().appendText(localize('hint.defAndCommand', 'Go to Definition ({0}), right click for more', kb)); } else if (part.part.location) { linkHint = new MarkdownString().appendText(localize('hint.def', 'Go to Definition ({0})', kb)); } else if (part.part.command) { linkHint = new MarkdownString(`[${localize('hint.cmd', "Execute Command")}](${asCommandLink(part.part.command)} "${part.part.command.title}") (${kb})`, { isTrusted: true }); } if (linkHint) { executor.emitOne(new MarkdownHover(this, anchor.range, [linkHint], false, 10000)); } } // (3) Inlay Label Part Location tooltip const iterable = await this._resolveInlayHintLabelPartHover(part, token); for await (const item of iterable) { executor.emitOne(item); } }); } private async _resolveInlayHintLabelPartHover(part: RenderedInlayHintLabelPart, token: CancellationToken): Promise<AsyncIterableObject<MarkdownHover>> { if (!part.part.location) { return AsyncIterableObject.EMPTY; } const { uri, range } = part.part.location; const ref = await this._resolverService.createModelReference(uri); try { const model = ref.object.textEditorModel; if (!this._languageFeaturesService.hoverProvider.has(model)) { return AsyncIterableObject.EMPTY; } return getHover(this._languageFeaturesService.hoverProvider, model, new Position(range.startLineNumber, range.startColumn), token) .filter(item => !isEmptyMarkdownString(item.hover.contents)) .map(item => new MarkdownHover(this, part.item.anchor.range, item.hover.contents, false, 2 + item.ordinal)); } finally { ref.dispose(); } } }
src/vs/editor/contrib/inlayHints/browser/inlayHintsHover.ts
0
https://github.com/microsoft/vscode/commit/ccbcba53e642136ce30465cd4f5605d60c760d7c
[ 0.00017483148258179426, 0.00017065055726561695, 0.00016453336866106838, 0.00017188215861096978, 0.000003169536739733303 ]
{ "id": 1, "code_window": [ "\t\t\tthis._sessions.delete(session.getId());\n", "\t\t}));\n", "\t\tthis._toDispose.add(debugService.getViewModel().onDidFocusSession(session => {\n", "\t\t\tthis._proxy.$acceptDebugSessionActiveChanged(this.getSessionDto(session));\n", "\t\t}));\n", "\n", "\t\tthis._debugAdapters = new Map();\n", "\t\tthis._debugConfigurationProviders = new Map();\n", "\t\tthis._debugAdapterDescriptorFactories = new Map();\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._toDispose.add(toDisposable(() => {\n", "\t\t\tfor (const [handle, da] of this._debugAdapters) {\n", "\t\t\t\tda.fireError(handle, new Error('Extension host shut down'));\n", "\t\t\t}\n", "\t\t}));\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadDebugService.ts", "type": "add", "edit_start_line_idx": 52 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { Event, Emitter } from 'vs/base/common/event'; import * as objects from 'vs/base/common/objects'; import { toAction } from 'vs/base/common/actions'; import * as errors from 'vs/base/common/errors'; import { createErrorWithActions } from 'vs/base/common/errorMessage'; import { formatPII, isUri } from 'vs/workbench/contrib/debug/common/debugUtils'; import { IDebugAdapter, IConfig, AdapterEndEvent, IDebugger } from 'vs/workbench/contrib/debug/common/debug'; import { IExtensionHostDebugService, IOpenExtensionWindowResult } from 'vs/platform/debug/common/extensionHostDebug'; import { URI } from 'vs/base/common/uri'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { CancellationToken } from 'vs/base/common/cancellation'; import { INotificationService, Severity } from 'vs/platform/notification/common/notification'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { Schemas } from 'vs/base/common/network'; /** * This interface represents a single command line argument split into a "prefix" and a "path" half. * The optional "prefix" contains arbitrary text and the optional "path" contains a file system path. * Concatenating both results in the original command line argument. */ interface ILaunchVSCodeArgument { prefix?: string; path?: string; } interface ILaunchVSCodeArguments { args: ILaunchVSCodeArgument[]; debugRenderer?: boolean; env?: { [key: string]: string | null }; } /** * Encapsulates the DebugAdapter lifecycle and some idiosyncrasies of the Debug Adapter Protocol. */ export class RawDebugSession implements IDisposable { private allThreadsContinued = true; private _readyForBreakpoints = false; private _capabilities: DebugProtocol.Capabilities; // shutdown private debugAdapterStopped = false; private inShutdown = false; private terminated = false; private firedAdapterExitEvent = false; // telemetry private startTime = 0; private didReceiveStoppedEvent = false; // DAP events private readonly _onDidInitialize = new Emitter<DebugProtocol.InitializedEvent>(); private readonly _onDidStop = new Emitter<DebugProtocol.StoppedEvent>(); private readonly _onDidContinued = new Emitter<DebugProtocol.ContinuedEvent>(); private readonly _onDidTerminateDebugee = new Emitter<DebugProtocol.TerminatedEvent>(); private readonly _onDidExitDebugee = new Emitter<DebugProtocol.ExitedEvent>(); private readonly _onDidThread = new Emitter<DebugProtocol.ThreadEvent>(); private readonly _onDidOutput = new Emitter<DebugProtocol.OutputEvent>(); private readonly _onDidBreakpoint = new Emitter<DebugProtocol.BreakpointEvent>(); private readonly _onDidLoadedSource = new Emitter<DebugProtocol.LoadedSourceEvent>(); private readonly _onDidProgressStart = new Emitter<DebugProtocol.ProgressStartEvent>(); private readonly _onDidProgressUpdate = new Emitter<DebugProtocol.ProgressUpdateEvent>(); private readonly _onDidProgressEnd = new Emitter<DebugProtocol.ProgressEndEvent>(); private readonly _onDidInvalidated = new Emitter<DebugProtocol.InvalidatedEvent>(); private readonly _onDidInvalidateMemory = new Emitter<DebugProtocol.MemoryEvent>(); private readonly _onDidCustomEvent = new Emitter<DebugProtocol.Event>(); private readonly _onDidEvent = new Emitter<DebugProtocol.Event>(); // DA events private readonly _onDidExitAdapter = new Emitter<AdapterEndEvent>(); private debugAdapter: IDebugAdapter | null; private toDispose: IDisposable[] = []; constructor( debugAdapter: IDebugAdapter, public readonly dbgr: IDebugger, private readonly sessionId: string, private readonly name: string, @IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService, @IOpenerService private readonly openerService: IOpenerService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogSerivce: IDialogService, ) { this.debugAdapter = debugAdapter; this._capabilities = Object.create(null); this.toDispose.push(this.debugAdapter.onError(err => { this.shutdown(err); })); this.toDispose.push(this.debugAdapter.onExit(code => { if (code !== 0) { this.shutdown(new Error(`exit code: ${code}`)); } else { // normal exit this.shutdown(); } })); this.debugAdapter.onEvent(event => { switch (event.event) { case 'initialized': this._readyForBreakpoints = true; this._onDidInitialize.fire(event); break; case 'loadedSource': this._onDidLoadedSource.fire(<DebugProtocol.LoadedSourceEvent>event); break; case 'capabilities': if (event.body) { const capabilities = (<DebugProtocol.CapabilitiesEvent>event).body.capabilities; this.mergeCapabilities(capabilities); } break; case 'stopped': this.didReceiveStoppedEvent = true; // telemetry: remember that debugger stopped successfully this._onDidStop.fire(<DebugProtocol.StoppedEvent>event); break; case 'continued': this.allThreadsContinued = (<DebugProtocol.ContinuedEvent>event).body.allThreadsContinued === false ? false : true; this._onDidContinued.fire(<DebugProtocol.ContinuedEvent>event); break; case 'thread': this._onDidThread.fire(<DebugProtocol.ThreadEvent>event); break; case 'output': this._onDidOutput.fire(<DebugProtocol.OutputEvent>event); break; case 'breakpoint': this._onDidBreakpoint.fire(<DebugProtocol.BreakpointEvent>event); break; case 'terminated': this._onDidTerminateDebugee.fire(<DebugProtocol.TerminatedEvent>event); break; case 'exit': this._onDidExitDebugee.fire(<DebugProtocol.ExitedEvent>event); break; case 'progressStart': this._onDidProgressStart.fire(event as DebugProtocol.ProgressStartEvent); break; case 'progressUpdate': this._onDidProgressUpdate.fire(event as DebugProtocol.ProgressUpdateEvent); break; case 'progressEnd': this._onDidProgressEnd.fire(event as DebugProtocol.ProgressEndEvent); break; case 'invalidated': this._onDidInvalidated.fire(event as DebugProtocol.InvalidatedEvent); break; case 'memory': this._onDidInvalidateMemory.fire(event as DebugProtocol.MemoryEvent); break; case 'process': break; case 'module': break; default: this._onDidCustomEvent.fire(event); break; } this._onDidEvent.fire(event); }); this.debugAdapter.onRequest(request => this.dispatchRequest(request)); } get isInShutdown() { return this.inShutdown; } get onDidExitAdapter(): Event<AdapterEndEvent> { return this._onDidExitAdapter.event; } get capabilities(): DebugProtocol.Capabilities { return this._capabilities; } /** * DA is ready to accepts setBreakpoint requests. * Becomes true after "initialized" events has been received. */ get readyForBreakpoints(): boolean { return this._readyForBreakpoints; } //---- DAP events get onDidInitialize(): Event<DebugProtocol.InitializedEvent> { return this._onDidInitialize.event; } get onDidStop(): Event<DebugProtocol.StoppedEvent> { return this._onDidStop.event; } get onDidContinued(): Event<DebugProtocol.ContinuedEvent> { return this._onDidContinued.event; } get onDidTerminateDebugee(): Event<DebugProtocol.TerminatedEvent> { return this._onDidTerminateDebugee.event; } get onDidExitDebugee(): Event<DebugProtocol.ExitedEvent> { return this._onDidExitDebugee.event; } get onDidThread(): Event<DebugProtocol.ThreadEvent> { return this._onDidThread.event; } get onDidOutput(): Event<DebugProtocol.OutputEvent> { return this._onDidOutput.event; } get onDidBreakpoint(): Event<DebugProtocol.BreakpointEvent> { return this._onDidBreakpoint.event; } get onDidLoadedSource(): Event<DebugProtocol.LoadedSourceEvent> { return this._onDidLoadedSource.event; } get onDidCustomEvent(): Event<DebugProtocol.Event> { return this._onDidCustomEvent.event; } get onDidProgressStart(): Event<DebugProtocol.ProgressStartEvent> { return this._onDidProgressStart.event; } get onDidProgressUpdate(): Event<DebugProtocol.ProgressUpdateEvent> { return this._onDidProgressUpdate.event; } get onDidProgressEnd(): Event<DebugProtocol.ProgressEndEvent> { return this._onDidProgressEnd.event; } get onDidInvalidated(): Event<DebugProtocol.InvalidatedEvent> { return this._onDidInvalidated.event; } get onDidInvalidateMemory(): Event<DebugProtocol.MemoryEvent> { return this._onDidInvalidateMemory.event; } get onDidEvent(): Event<DebugProtocol.Event> { return this._onDidEvent.event; } //---- DebugAdapter lifecycle /** * Starts the underlying debug adapter and tracks the session time for telemetry. */ async start(): Promise<void> { if (!this.debugAdapter) { return Promise.reject(new Error(nls.localize('noDebugAdapterStart', "No debug adapter, can not start debug session."))); } await this.debugAdapter.startSession(); this.startTime = new Date().getTime(); } /** * Send client capabilities to the debug adapter and receive DA capabilities in return. */ async initialize(args: DebugProtocol.InitializeRequestArguments): Promise<DebugProtocol.InitializeResponse | undefined> { const response = await this.send('initialize', args, undefined, undefined, false); if (response) { this.mergeCapabilities(response.body); } return response; } /** * Terminate the debuggee and shutdown the adapter */ disconnect(args: DebugProtocol.DisconnectArguments): Promise<any> { const terminateDebuggee = this.capabilities.supportTerminateDebuggee ? args.terminateDebuggee : undefined; const suspendDebuggee = this.capabilities.supportTerminateDebuggee && this.capabilities.supportSuspendDebuggee ? args.suspendDebuggee : undefined; return this.shutdown(undefined, args.restart, terminateDebuggee, suspendDebuggee); } //---- DAP requests async launchOrAttach(config: IConfig): Promise<DebugProtocol.Response | undefined> { const response = await this.send(config.request, config, undefined, undefined, false); if (response) { this.mergeCapabilities(response.body); } return response; } /** * Try killing the debuggee softly... */ terminate(restart = false): Promise<DebugProtocol.TerminateResponse | undefined> { if (this.capabilities.supportsTerminateRequest) { if (!this.terminated) { this.terminated = true; return this.send('terminate', { restart }, undefined); } return this.disconnect({ terminateDebuggee: true, restart }); } return Promise.reject(new Error('terminated not supported')); } restart(args: DebugProtocol.RestartArguments): Promise<DebugProtocol.RestartResponse | undefined> { if (this.capabilities.supportsRestartRequest) { return this.send('restart', args); } return Promise.reject(new Error('restart not supported')); } async next(args: DebugProtocol.NextArguments): Promise<DebugProtocol.NextResponse | undefined> { const response = await this.send('next', args); this.fireSimulatedContinuedEvent(args.threadId); return response; } async stepIn(args: DebugProtocol.StepInArguments): Promise<DebugProtocol.StepInResponse | undefined> { const response = await this.send('stepIn', args); this.fireSimulatedContinuedEvent(args.threadId); return response; } async stepOut(args: DebugProtocol.StepOutArguments): Promise<DebugProtocol.StepOutResponse | undefined> { const response = await this.send('stepOut', args); this.fireSimulatedContinuedEvent(args.threadId); return response; } async continue(args: DebugProtocol.ContinueArguments): Promise<DebugProtocol.ContinueResponse | undefined> { const response = await this.send<DebugProtocol.ContinueResponse>('continue', args); if (response && response.body && response.body.allThreadsContinued !== undefined) { this.allThreadsContinued = response.body.allThreadsContinued; } this.fireSimulatedContinuedEvent(args.threadId, this.allThreadsContinued); return response; } pause(args: DebugProtocol.PauseArguments): Promise<DebugProtocol.PauseResponse | undefined> { return this.send('pause', args); } terminateThreads(args: DebugProtocol.TerminateThreadsArguments): Promise<DebugProtocol.TerminateThreadsResponse | undefined> { if (this.capabilities.supportsTerminateThreadsRequest) { return this.send('terminateThreads', args); } return Promise.reject(new Error('terminateThreads not supported')); } setVariable(args: DebugProtocol.SetVariableArguments): Promise<DebugProtocol.SetVariableResponse | undefined> { if (this.capabilities.supportsSetVariable) { return this.send<DebugProtocol.SetVariableResponse>('setVariable', args); } return Promise.reject(new Error('setVariable not supported')); } setExpression(args: DebugProtocol.SetExpressionArguments): Promise<DebugProtocol.SetExpressionResponse | undefined> { if (this.capabilities.supportsSetExpression) { return this.send<DebugProtocol.SetExpressionResponse>('setExpression', args); } return Promise.reject(new Error('setExpression not supported')); } async restartFrame(args: DebugProtocol.RestartFrameArguments, threadId: number): Promise<DebugProtocol.RestartFrameResponse | undefined> { if (this.capabilities.supportsRestartFrame) { const response = await this.send('restartFrame', args); this.fireSimulatedContinuedEvent(threadId); return response; } return Promise.reject(new Error('restartFrame not supported')); } stepInTargets(args: DebugProtocol.StepInTargetsArguments): Promise<DebugProtocol.StepInTargetsResponse | undefined> { if (this.capabilities.supportsStepInTargetsRequest) { return this.send('stepInTargets', args); } return Promise.reject(new Error('stepInTargets not supported')); } completions(args: DebugProtocol.CompletionsArguments, token: CancellationToken): Promise<DebugProtocol.CompletionsResponse | undefined> { if (this.capabilities.supportsCompletionsRequest) { return this.send<DebugProtocol.CompletionsResponse>('completions', args, token); } return Promise.reject(new Error('completions not supported')); } setBreakpoints(args: DebugProtocol.SetBreakpointsArguments): Promise<DebugProtocol.SetBreakpointsResponse | undefined> { return this.send<DebugProtocol.SetBreakpointsResponse>('setBreakpoints', args); } setFunctionBreakpoints(args: DebugProtocol.SetFunctionBreakpointsArguments): Promise<DebugProtocol.SetFunctionBreakpointsResponse | undefined> { if (this.capabilities.supportsFunctionBreakpoints) { return this.send<DebugProtocol.SetFunctionBreakpointsResponse>('setFunctionBreakpoints', args); } return Promise.reject(new Error('setFunctionBreakpoints not supported')); } dataBreakpointInfo(args: DebugProtocol.DataBreakpointInfoArguments): Promise<DebugProtocol.DataBreakpointInfoResponse | undefined> { if (this.capabilities.supportsDataBreakpoints) { return this.send<DebugProtocol.DataBreakpointInfoResponse>('dataBreakpointInfo', args); } return Promise.reject(new Error('dataBreakpointInfo not supported')); } setDataBreakpoints(args: DebugProtocol.SetDataBreakpointsArguments): Promise<DebugProtocol.SetDataBreakpointsResponse | undefined> { if (this.capabilities.supportsDataBreakpoints) { return this.send<DebugProtocol.SetDataBreakpointsResponse>('setDataBreakpoints', args); } return Promise.reject(new Error('setDataBreakpoints not supported')); } setExceptionBreakpoints(args: DebugProtocol.SetExceptionBreakpointsArguments): Promise<DebugProtocol.SetExceptionBreakpointsResponse | undefined> { return this.send<DebugProtocol.SetExceptionBreakpointsResponse>('setExceptionBreakpoints', args); } breakpointLocations(args: DebugProtocol.BreakpointLocationsArguments): Promise<DebugProtocol.BreakpointLocationsResponse | undefined> { if (this.capabilities.supportsBreakpointLocationsRequest) { return this.send('breakpointLocations', args); } return Promise.reject(new Error('breakpointLocations is not supported')); } configurationDone(): Promise<DebugProtocol.ConfigurationDoneResponse | undefined> { if (this.capabilities.supportsConfigurationDoneRequest) { return this.send('configurationDone', null); } return Promise.reject(new Error('configurationDone not supported')); } stackTrace(args: DebugProtocol.StackTraceArguments, token: CancellationToken): Promise<DebugProtocol.StackTraceResponse | undefined> { return this.send<DebugProtocol.StackTraceResponse>('stackTrace', args, token); } exceptionInfo(args: DebugProtocol.ExceptionInfoArguments): Promise<DebugProtocol.ExceptionInfoResponse | undefined> { if (this.capabilities.supportsExceptionInfoRequest) { return this.send<DebugProtocol.ExceptionInfoResponse>('exceptionInfo', args); } return Promise.reject(new Error('exceptionInfo not supported')); } scopes(args: DebugProtocol.ScopesArguments, token: CancellationToken): Promise<DebugProtocol.ScopesResponse | undefined> { return this.send<DebugProtocol.ScopesResponse>('scopes', args, token); } variables(args: DebugProtocol.VariablesArguments, token?: CancellationToken): Promise<DebugProtocol.VariablesResponse | undefined> { return this.send<DebugProtocol.VariablesResponse>('variables', args, token); } source(args: DebugProtocol.SourceArguments): Promise<DebugProtocol.SourceResponse | undefined> { return this.send<DebugProtocol.SourceResponse>('source', args); } loadedSources(args: DebugProtocol.LoadedSourcesArguments): Promise<DebugProtocol.LoadedSourcesResponse | undefined> { if (this.capabilities.supportsLoadedSourcesRequest) { return this.send<DebugProtocol.LoadedSourcesResponse>('loadedSources', args); } return Promise.reject(new Error('loadedSources not supported')); } threads(): Promise<DebugProtocol.ThreadsResponse | undefined> { return this.send<DebugProtocol.ThreadsResponse>('threads', null); } evaluate(args: DebugProtocol.EvaluateArguments): Promise<DebugProtocol.EvaluateResponse | undefined> { return this.send<DebugProtocol.EvaluateResponse>('evaluate', args); } async stepBack(args: DebugProtocol.StepBackArguments): Promise<DebugProtocol.StepBackResponse | undefined> { if (this.capabilities.supportsStepBack) { const response = await this.send('stepBack', args); this.fireSimulatedContinuedEvent(args.threadId); return response; } return Promise.reject(new Error('stepBack not supported')); } async reverseContinue(args: DebugProtocol.ReverseContinueArguments): Promise<DebugProtocol.ReverseContinueResponse | undefined> { if (this.capabilities.supportsStepBack) { const response = await this.send('reverseContinue', args); this.fireSimulatedContinuedEvent(args.threadId); return response; } return Promise.reject(new Error('reverseContinue not supported')); } gotoTargets(args: DebugProtocol.GotoTargetsArguments): Promise<DebugProtocol.GotoTargetsResponse | undefined> { if (this.capabilities.supportsGotoTargetsRequest) { return this.send('gotoTargets', args); } return Promise.reject(new Error('gotoTargets is not supported')); } async goto(args: DebugProtocol.GotoArguments): Promise<DebugProtocol.GotoResponse | undefined> { if (this.capabilities.supportsGotoTargetsRequest) { const response = await this.send('goto', args); this.fireSimulatedContinuedEvent(args.threadId); return response; } return Promise.reject(new Error('goto is not supported')); } async setInstructionBreakpoints(args: DebugProtocol.SetInstructionBreakpointsArguments): Promise<DebugProtocol.SetInstructionBreakpointsResponse | undefined> { if (this.capabilities.supportsInstructionBreakpoints) { return await this.send('setInstructionBreakpoints', args); } return Promise.reject(new Error('setInstructionBreakpoints is not supported')); } async disassemble(args: DebugProtocol.DisassembleArguments): Promise<DebugProtocol.DisassembleResponse | undefined> { if (this.capabilities.supportsDisassembleRequest) { return await this.send('disassemble', args); } return Promise.reject(new Error('disassemble is not supported')); } async readMemory(args: DebugProtocol.ReadMemoryArguments): Promise<DebugProtocol.ReadMemoryResponse | undefined> { if (this.capabilities.supportsReadMemoryRequest) { return await this.send('readMemory', args); } return Promise.reject(new Error('readMemory is not supported')); } async writeMemory(args: DebugProtocol.WriteMemoryArguments): Promise<DebugProtocol.WriteMemoryResponse | undefined> { if (this.capabilities.supportsWriteMemoryRequest) { return await this.send('writeMemory', args); } return Promise.reject(new Error('writeMemory is not supported')); } cancel(args: DebugProtocol.CancelArguments): Promise<DebugProtocol.CancelResponse | undefined> { return this.send('cancel', args); } custom(request: string, args: any): Promise<DebugProtocol.Response | undefined> { return this.send(request, args); } //---- private private async shutdown(error?: Error, restart = false, terminateDebuggee: boolean | undefined = undefined, suspendDebuggee: boolean | undefined = undefined): Promise<any> { if (!this.inShutdown) { this.inShutdown = true; if (this.debugAdapter) { try { const args: DebugProtocol.DisconnectArguments = { restart }; if (typeof terminateDebuggee === 'boolean') { args.terminateDebuggee = terminateDebuggee; } if (typeof suspendDebuggee === 'boolean') { args.suspendDebuggee = suspendDebuggee; } await this.send('disconnect', args, undefined, 2000); } catch (e) { // Catch the potential 'disconnect' error - no need to show it to the user since the adapter is shutting down } finally { await this.stopAdapter(error); } } else { return this.stopAdapter(error); } } } private async stopAdapter(error?: Error): Promise<any> { try { if (this.debugAdapter) { const da = this.debugAdapter; this.debugAdapter = null; await da.stopSession(); this.debugAdapterStopped = true; } } finally { this.fireAdapterExitEvent(error); } } private fireAdapterExitEvent(error?: Error): void { if (!this.firedAdapterExitEvent) { this.firedAdapterExitEvent = true; const e: AdapterEndEvent = { emittedStopped: this.didReceiveStoppedEvent, sessionLengthInSeconds: (new Date().getTime() - this.startTime) / 1000 }; if (error && !this.debugAdapterStopped) { e.error = error; } this._onDidExitAdapter.fire(e); } } private async dispatchRequest(request: DebugProtocol.Request): Promise<void> { const response: DebugProtocol.Response = { type: 'response', seq: 0, command: request.command, request_seq: request.seq, success: true }; const safeSendResponse = (response: DebugProtocol.Response) => this.debugAdapter && this.debugAdapter.sendResponse(response); if (request.command === 'launchVSCode') { try { let result = await this.launchVsCode(<ILaunchVSCodeArguments>request.arguments); if (!result.success) { const { confirmed } = await this.dialogSerivce.confirm({ type: Severity.Warning, message: nls.localize('canNotStart', "The debugger needs to open a new tab or window for the debuggee but the browser prevented this. You must give permission to continue."), primaryButton: nls.localize({ key: 'continue', comment: ['&& denotes a mnemonic'] }, "&&Continue") }); if (confirmed) { result = await this.launchVsCode(<ILaunchVSCodeArguments>request.arguments); } else { response.success = false; safeSendResponse(response); await this.shutdown(); } } response.body = { rendererDebugPort: result.rendererDebugPort, }; safeSendResponse(response); } catch (err) { response.success = false; response.message = err.message; safeSendResponse(response); } } else if (request.command === 'runInTerminal') { try { const shellProcessId = await this.dbgr.runInTerminal(request.arguments as DebugProtocol.RunInTerminalRequestArguments, this.sessionId); const resp = response as DebugProtocol.RunInTerminalResponse; resp.body = {}; if (typeof shellProcessId === 'number') { resp.body.shellProcessId = shellProcessId; } safeSendResponse(resp); } catch (err) { response.success = false; response.message = err.message; safeSendResponse(response); } } else if (request.command === 'startDebugging') { try { const args = (request.arguments as DebugProtocol.StartDebuggingRequestArguments); const config: IConfig = { ...args.configuration, ...{ request: args.request, type: this.dbgr.type, name: args.configuration.name || this.name } }; const success = await this.dbgr.startDebugging(config, this.sessionId); if (success) { safeSendResponse(response); } else { response.success = false; response.message = 'Failed to start debugging'; safeSendResponse(response); } } catch (err) { response.success = false; response.message = err.message; safeSendResponse(response); } } else { response.success = false; response.message = `unknown request '${request.command}'`; safeSendResponse(response); } } private launchVsCode(vscodeArgs: ILaunchVSCodeArguments): Promise<IOpenExtensionWindowResult> { const args: string[] = []; for (const arg of vscodeArgs.args) { const a2 = (arg.prefix || '') + (arg.path || ''); const match = /^--(.+)=(.+)$/.exec(a2); if (match && match.length === 3) { const key = match[1]; let value = match[2]; if ((key === 'file-uri' || key === 'folder-uri') && !isUri(arg.path)) { value = isUri(value) ? value : URI.file(value).toString(); } args.push(`--${key}=${value}`); } else { args.push(a2); } } if (vscodeArgs.env) { args.push(`--extensionEnvironment=${JSON.stringify(vscodeArgs.env)}`); } return this.extensionHostDebugService.openExtensionDevelopmentHostWindow(args, !!vscodeArgs.debugRenderer); } private send<R extends DebugProtocol.Response>(command: string, args: any, token?: CancellationToken, timeout?: number, showErrors = true): Promise<R | undefined> { return new Promise<DebugProtocol.Response | undefined>((completeDispatch, errorDispatch) => { if (!this.debugAdapter) { if (this.inShutdown) { // We are in shutdown silently complete completeDispatch(undefined); } else { errorDispatch(new Error(nls.localize('noDebugAdapter', "No debugger available found. Can not send '{0}'.", command))); } return; } let cancelationListener: IDisposable; const requestId = this.debugAdapter.sendRequest(command, args, (response: DebugProtocol.Response) => { cancelationListener?.dispose(); if (response.success) { completeDispatch(response); } else { errorDispatch(response); } }, timeout); if (token) { cancelationListener = token.onCancellationRequested(() => { cancelationListener.dispose(); if (this.capabilities.supportsCancelRequest) { this.cancel({ requestId }); } }); } }).then(undefined, err => Promise.reject(this.handleErrorResponse(err, showErrors))); } private handleErrorResponse(errorResponse: DebugProtocol.Response, showErrors: boolean): Error { if (errorResponse.command === 'canceled' && errorResponse.message === 'canceled') { return new errors.CancellationError(); } const error: DebugProtocol.Message | undefined = errorResponse?.body?.error; const errorMessage = errorResponse?.message || ''; const userMessage = error ? formatPII(error.format, false, error.variables) : errorMessage; const url = error?.url; if (error && url) { const label = error.urlLabel ? error.urlLabel : nls.localize('moreInfo', "More Info"); const uri = URI.parse(url); // Use a suffixed id if uri invokes a command, so default 'Open launch.json' command is suppressed on dialog const actionId = uri.scheme === Schemas.command ? 'debug.moreInfo.command' : 'debug.moreInfo'; return createErrorWithActions(userMessage, [toAction({ id: actionId, label, run: () => this.openerService.open(uri, { allowCommands: true }) })]); } if (showErrors && error && error.format && error.showUser) { this.notificationService.error(userMessage); } const result = new errors.ErrorNoTelemetry(userMessage); (<any>result).showUser = error?.showUser; return result; } private mergeCapabilities(capabilities: DebugProtocol.Capabilities | undefined): void { if (capabilities) { this._capabilities = objects.mixin(this._capabilities, capabilities); } } private fireSimulatedContinuedEvent(threadId: number, allThreadsContinued = false): void { this._onDidContinued.fire({ type: 'event', event: 'continued', body: { threadId, allThreadsContinued }, seq: undefined! }); } dispose(): void { dispose(this.toDispose); } }
src/vs/workbench/contrib/debug/browser/rawDebugSession.ts
1
https://github.com/microsoft/vscode/commit/ccbcba53e642136ce30465cd4f5605d60c760d7c
[ 0.005365318153053522, 0.0003279150987509638, 0.00015852507203817368, 0.0001714559184620157, 0.0007316349656321108 ]
{ "id": 1, "code_window": [ "\t\t\tthis._sessions.delete(session.getId());\n", "\t\t}));\n", "\t\tthis._toDispose.add(debugService.getViewModel().onDidFocusSession(session => {\n", "\t\t\tthis._proxy.$acceptDebugSessionActiveChanged(this.getSessionDto(session));\n", "\t\t}));\n", "\n", "\t\tthis._debugAdapters = new Map();\n", "\t\tthis._debugConfigurationProviders = new Map();\n", "\t\tthis._debugAdapterDescriptorFactories = new Map();\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._toDispose.add(toDisposable(() => {\n", "\t\t\tfor (const [handle, da] of this._debugAdapters) {\n", "\t\t\t\tda.fireError(handle, new Error('Extension host shut down'));\n", "\t\t\t}\n", "\t\t}));\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadDebugService.ts", "type": "add", "edit_start_line_idx": 52 }
extensions/css-language-features/server/test/pathCompletionFixtures/about/about.html
0
https://github.com/microsoft/vscode/commit/ccbcba53e642136ce30465cd4f5605d60c760d7c
[ 0.00016842599143274128, 0.00016842599143274128, 0.00016842599143274128, 0.00016842599143274128, 0 ]
{ "id": 1, "code_window": [ "\t\t\tthis._sessions.delete(session.getId());\n", "\t\t}));\n", "\t\tthis._toDispose.add(debugService.getViewModel().onDidFocusSession(session => {\n", "\t\t\tthis._proxy.$acceptDebugSessionActiveChanged(this.getSessionDto(session));\n", "\t\t}));\n", "\n", "\t\tthis._debugAdapters = new Map();\n", "\t\tthis._debugConfigurationProviders = new Map();\n", "\t\tthis._debugAdapterDescriptorFactories = new Map();\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._toDispose.add(toDisposable(() => {\n", "\t\t\tfor (const [handle, da] of this._debugAdapters) {\n", "\t\t\t\tda.fireError(handle, new Error('Extension host shut down'));\n", "\t\t\t}\n", "\t\t}));\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadDebugService.ts", "type": "add", "edit_start_line_idx": 52 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { KeyboardLayoutContribution } from 'vs/workbench/services/keybinding/browser/keyboardLayouts/_.contribution'; KeyboardLayoutContribution.INSTANCE.registerKeyboardLayout({ layout: { model: 'pc104', group: 0, layout: 'ru', variant: ',', options: '', rules: 'base' }, secondaryLayouts: [], mapping: { Sleep: [], WakeUp: [], KeyA: ['ф', 'Ф', 'ф', 'Ф', 0], KeyB: ['и', 'И', 'и', 'И', 0], KeyC: ['с', 'С', 'с', 'С', 0], KeyD: ['в', 'В', 'в', 'В', 0], KeyE: ['у', 'У', 'у', 'У', 0], KeyF: ['а', 'А', 'а', 'А', 0], KeyG: ['п', 'П', 'п', 'П', 0], KeyH: ['р', 'Р', 'р', 'Р', 0], KeyI: ['ш', 'Ш', 'ш', 'Ш', 0], KeyJ: ['о', 'О', 'о', 'О', 0], KeyK: ['л', 'Л', 'л', 'Л', 0], KeyL: ['д', 'Д', 'д', 'Д', 0], KeyM: ['ь', 'Ь', 'ь', 'Ь', 0], KeyN: ['т', 'Т', 'т', 'Т', 0], KeyO: ['щ', 'Щ', 'щ', 'Щ', 0], KeyP: ['з', 'З', 'з', 'З', 0], KeyQ: ['й', 'Й', 'й', 'Й', 0], KeyR: ['к', 'К', 'к', 'К', 0], KeyS: ['ы', 'Ы', 'ы', 'Ы', 0], KeyT: ['е', 'Е', 'е', 'Е', 0], KeyU: ['г', 'Г', 'г', 'Г', 0], KeyV: ['м', 'М', 'м', 'М', 0], KeyW: ['ц', 'Ц', 'ц', 'Ц', 0], KeyX: ['ч', 'Ч', 'ч', 'Ч', 0], KeyY: ['н', 'Н', 'н', 'Н', 0], KeyZ: ['я', 'Я', 'я', 'Я', 0], Digit1: ['1', '!', '1', '!', 0], Digit2: ['2', '"', '2', '"', 0], Digit3: ['3', '№', '3', '№', 0], Digit4: ['4', ';', '4', ';', 0], Digit5: ['5', '%', '5', '%', 0], Digit6: ['6', ':', '6', ':', 0], Digit7: ['7', '?', '7', '?', 0], Digit8: ['8', '*', '₽', '', 0], Digit9: ['9', '(', '9', '(', 0], Digit0: ['0', ')', '0', ')', 0], Enter: ['\r', '\r', '\r', '\r', 0], Escape: ['\u001b', '\u001b', '\u001b', '\u001b', 0], Backspace: ['\b', '\b', '\b', '\b', 0], Tab: ['\t', '', '\t', '', 0], Space: [' ', ' ', ' ', ' ', 0], Minus: ['-', '_', '-', '_', 0], Equal: ['=', '+', '=', '+', 0], BracketLeft: ['х', 'Х', 'х', 'Х', 0], BracketRight: ['ъ', 'Ъ', 'ъ', 'Ъ', 0], Backslash: ['\\', '/', '\\', '/', 0], Semicolon: ['ж', 'Ж', 'ж', 'Ж', 0], Quote: ['э', 'Э', 'э', 'Э', 0], Backquote: ['ё', 'Ё', 'ё', 'Ё', 0], Comma: ['б', 'Б', 'б', 'Б', 0], Period: ['ю', 'Ю', 'ю', 'Ю', 0], Slash: ['.', ',', '.', ',', 0], CapsLock: [], F1: [], F2: [], F3: [], F4: [], F5: [], F6: [], F7: [], F8: [], F9: [], F10: [], F11: [], F12: [], PrintScreen: ['', '', '', '', 0], ScrollLock: [], Pause: [], Insert: [], Home: [], PageUp: ['/', '/', '/', '/', 0], Delete: [], End: [], PageDown: [], ArrowRight: [], ArrowLeft: [], ArrowDown: [], ArrowUp: [], NumLock: [], NumpadDivide: [], NumpadMultiply: ['*', '*', '*', '*', 0], NumpadSubtract: ['-', '-', '-', '-', 0], NumpadAdd: ['+', '+', '+', '+', 0], NumpadEnter: [], Numpad1: ['', '1', '', '1', 0], Numpad2: ['', '2', '', '2', 0], Numpad3: ['', '3', '', '3', 0], Numpad4: ['', '4', '', '4', 0], Numpad5: ['', '5', '', '5', 0], Numpad6: ['', '6', '', '6', 0], Numpad7: ['', '7', '', '7', 0], Numpad8: ['', '8', '', '8', 0], Numpad9: ['', '9', '', '9', 0], Numpad0: ['', '0', '', '0', 0], NumpadDecimal: ['', ',', '', ',', 0], IntlBackslash: ['/', '|', '|', '¦', 0], ContextMenu: [], Power: [], NumpadEqual: [], F13: [], F14: [], F15: [], F16: [], F17: [], F18: [], F19: [], F20: [], F21: [], F22: [], F23: [], F24: [], Open: [], Help: [], Select: [], Again: [], Undo: [], Cut: [], Copy: [], Paste: [], Find: [], AudioVolumeMute: [], AudioVolumeUp: [], AudioVolumeDown: [], NumpadComma: [], IntlRo: [], KanaMode: [], IntlYen: [], Convert: [], NonConvert: [], Lang1: [], Lang2: [], Lang3: [], Lang4: [], Lang5: [], NumpadParenLeft: [], NumpadParenRight: [], ControlLeft: [], ShiftLeft: [], AltLeft: [], MetaLeft: [], ControlRight: [], ShiftRight: [], AltRight: ['\r', '\r', '\r', '\r', 0], MetaRight: ['.', '.', '.', '.', 0], BrightnessUp: [], BrightnessDown: [], MediaPlay: [], MediaRecord: [], MediaFastForward: [], MediaRewind: [], MediaTrackNext: [], MediaTrackPrevious: [], MediaStop: [], Eject: [], MediaPlayPause: [], MediaSelect: [], LaunchMail: [], LaunchApp2: [], LaunchApp1: [], SelectTask: [], LaunchScreenSaver: [], BrowserSearch: [], BrowserHome: [], BrowserBack: [], BrowserForward: [], BrowserStop: [], BrowserRefresh: [], BrowserFavorites: [], MailReply: [], MailForward: [], MailSend: [] } });
src/vs/workbench/services/keybinding/browser/keyboardLayouts/ru.linux.ts
0
https://github.com/microsoft/vscode/commit/ccbcba53e642136ce30465cd4f5605d60c760d7c
[ 0.00017605199536774307, 0.00017350917914882302, 0.00017041084356606007, 0.00017395467148162425, 0.0000016676555105732405 ]
{ "id": 1, "code_window": [ "\t\t\tthis._sessions.delete(session.getId());\n", "\t\t}));\n", "\t\tthis._toDispose.add(debugService.getViewModel().onDidFocusSession(session => {\n", "\t\t\tthis._proxy.$acceptDebugSessionActiveChanged(this.getSessionDto(session));\n", "\t\t}));\n", "\n", "\t\tthis._debugAdapters = new Map();\n", "\t\tthis._debugConfigurationProviders = new Map();\n", "\t\tthis._debugAdapterDescriptorFactories = new Map();\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._toDispose.add(toDisposable(() => {\n", "\t\t\tfor (const [handle, da] of this._debugAdapters) {\n", "\t\t\t\tda.fireError(handle, new Error('Extension host shut down'));\n", "\t\t\t}\n", "\t\t}));\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadDebugService.ts", "type": "add", "edit_start_line_idx": 52 }
{ "name": "vb", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin textmate/asp.vb.net.tmbundle Syntaxes/ASP%%20VB.net.plist ./syntaxes/asp-vb-net.tmlanguage.json" }, "contributes": { "languages": [ { "id": "vb", "extensions": [ ".vb", ".brs", ".vbs", ".bas", ".vba" ], "aliases": [ "Visual Basic", "vb" ], "configuration": "./language-configuration.json" } ], "grammars": [ { "language": "vb", "scopeName": "source.asp.vb.net", "path": "./syntaxes/asp-vb-net.tmlanguage.json" } ], "snippets": [ { "language": "vb", "path": "./snippets/vb.code-snippets" } ] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }
extensions/vb/package.json
0
https://github.com/microsoft/vscode/commit/ccbcba53e642136ce30465cd4f5605d60c760d7c
[ 0.0001765391498338431, 0.0001740159495966509, 0.000168425845913589, 0.00017487691366113722, 0.000002739342107815901 ]
{ "id": 2, "code_window": [ "\n", "\t\t\t\t\tif (typeof suspendDebuggee === 'boolean') {\n", "\t\t\t\t\t\targs.suspendDebuggee = suspendDebuggee;\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\tawait this.send('disconnect', args, undefined, 2000);\n", "\t\t\t\t} catch (e) {\n", "\t\t\t\t\t// Catch the potential 'disconnect' error - no need to show it to the user since the adapter is shutting down\n", "\t\t\t\t} finally {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t// if there's an error, the DA is probably already gone, so give it a much shorter timeout.\n", "\t\t\t\t\tawait this.send('disconnect', args, undefined, error ? 200 : 2000);\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/rawDebugSession.ts", "type": "replace", "edit_start_line_idx": 575 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { DisposableStore } from 'vs/base/common/lifecycle'; import { URI as uri, UriComponents } from 'vs/base/common/uri'; import { IDebugService, IConfig, IDebugConfigurationProvider, IBreakpoint, IFunctionBreakpoint, IBreakpointData, IDebugAdapter, IDebugAdapterDescriptorFactory, IDebugSession, IDebugAdapterFactory, IDataBreakpoint, IDebugSessionOptions, IInstructionBreakpoint, DebugConfigurationProviderTriggerKind } from 'vs/workbench/contrib/debug/common/debug'; import { ExtHostContext, ExtHostDebugServiceShape, MainThreadDebugServiceShape, DebugSessionUUID, MainContext, IBreakpointsDeltaDto, ISourceMultiBreakpointDto, ISourceBreakpointDto, IFunctionBreakpointDto, IDebugSessionDto, IDataBreakpointDto, IStartDebuggingOptions, IDebugConfiguration, IThreadFocusDto, IStackFrameFocusDto } from 'vs/workbench/api/common/extHost.protocol'; import { extHostNamedCustomer, IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers'; import severity from 'vs/base/common/severity'; import { AbstractDebugAdapter } from 'vs/workbench/contrib/debug/common/abstractDebugAdapter'; import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { convertToVSCPaths, convertToDAPaths, isSessionAttach } from 'vs/workbench/contrib/debug/common/debugUtils'; import { ErrorNoTelemetry } from 'vs/base/common/errors'; @extHostNamedCustomer(MainContext.MainThreadDebugService) export class MainThreadDebugService implements MainThreadDebugServiceShape, IDebugAdapterFactory { private readonly _proxy: ExtHostDebugServiceShape; private readonly _toDispose = new DisposableStore(); private readonly _debugAdapters: Map<number, ExtensionHostDebugAdapter>; private _debugAdaptersHandleCounter = 1; private readonly _debugConfigurationProviders: Map<number, IDebugConfigurationProvider>; private readonly _debugAdapterDescriptorFactories: Map<number, IDebugAdapterDescriptorFactory>; private readonly _sessions: Set<DebugSessionUUID>; constructor( extHostContext: IExtHostContext, @IDebugService private readonly debugService: IDebugService ) { this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostDebugService); this._toDispose.add(debugService.onDidNewSession(session => { this._proxy.$acceptDebugSessionStarted(this.getSessionDto(session)); this._toDispose.add(session.onDidChangeName(name => { this._proxy.$acceptDebugSessionNameChanged(this.getSessionDto(session), name); })); })); // Need to start listening early to new session events because a custom event can come while a session is initialising this._toDispose.add(debugService.onWillNewSession(session => { this._toDispose.add(session.onDidCustomEvent(event => this._proxy.$acceptDebugSessionCustomEvent(this.getSessionDto(session), event))); })); this._toDispose.add(debugService.onDidEndSession(session => { this._proxy.$acceptDebugSessionTerminated(this.getSessionDto(session)); this._sessions.delete(session.getId()); })); this._toDispose.add(debugService.getViewModel().onDidFocusSession(session => { this._proxy.$acceptDebugSessionActiveChanged(this.getSessionDto(session)); })); this._debugAdapters = new Map(); this._debugConfigurationProviders = new Map(); this._debugAdapterDescriptorFactories = new Map(); this._sessions = new Set(); this._toDispose.add(this.debugService.getViewModel().onDidFocusThread(({ thread, explicit, session }) => { if (session) { const dto: IThreadFocusDto = { kind: 'thread', threadId: thread?.threadId, sessionId: session!.getId(), }; this._proxy.$acceptStackFrameFocus(dto); } })); this._toDispose.add(this.debugService.getViewModel().onDidFocusStackFrame(({ stackFrame, explicit, session }) => { if (session) { const dto: IStackFrameFocusDto = { kind: 'stackFrame', threadId: stackFrame?.thread.threadId, frameId: stackFrame?.frameId, sessionId: session.getId(), }; this._proxy.$acceptStackFrameFocus(dto); } })); this.sendBreakpointsAndListen(); } private sendBreakpointsAndListen(): void { // set up a handler to send more this._toDispose.add(this.debugService.getModel().onDidChangeBreakpoints(e => { // Ignore session only breakpoint events since they should only reflect in the UI if (e && !e.sessionOnly) { const delta: IBreakpointsDeltaDto = {}; if (e.added) { delta.added = this.convertToDto(e.added); } if (e.removed) { delta.removed = e.removed.map(x => x.getId()); } if (e.changed) { delta.changed = this.convertToDto(e.changed); } if (delta.added || delta.removed || delta.changed) { this._proxy.$acceptBreakpointsDelta(delta); } } })); // send all breakpoints const bps = this.debugService.getModel().getBreakpoints(); const fbps = this.debugService.getModel().getFunctionBreakpoints(); const dbps = this.debugService.getModel().getDataBreakpoints(); if (bps.length > 0 || fbps.length > 0) { this._proxy.$acceptBreakpointsDelta({ added: this.convertToDto(bps).concat(this.convertToDto(fbps)).concat(this.convertToDto(dbps)) }); } } public dispose(): void { this._toDispose.dispose(); } // interface IDebugAdapterProvider createDebugAdapter(session: IDebugSession): IDebugAdapter { const handle = this._debugAdaptersHandleCounter++; const da = new ExtensionHostDebugAdapter(this, handle, this._proxy, session); this._debugAdapters.set(handle, da); return da; } substituteVariables(folder: IWorkspaceFolder | undefined, config: IConfig): Promise<IConfig> { return Promise.resolve(this._proxy.$substituteVariables(folder ? folder.uri : undefined, config)); } runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments, sessionId: string): Promise<number | undefined> { return this._proxy.$runInTerminal(args, sessionId); } // RPC methods (MainThreadDebugServiceShape) public $registerDebugTypes(debugTypes: string[]) { this._toDispose.add(this.debugService.getAdapterManager().registerDebugAdapterFactory(debugTypes, this)); } public $registerBreakpoints(DTOs: Array<ISourceMultiBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto>): Promise<void> { for (const dto of DTOs) { if (dto.type === 'sourceMulti') { const rawbps = dto.lines.map(l => <IBreakpointData>{ id: l.id, enabled: l.enabled, lineNumber: l.line + 1, column: l.character > 0 ? l.character + 1 : undefined, // a column value of 0 results in an omitted column attribute; see #46784 condition: l.condition, hitCondition: l.hitCondition, logMessage: l.logMessage } ); this.debugService.addBreakpoints(uri.revive(dto.uri), rawbps); } else if (dto.type === 'function') { this.debugService.addFunctionBreakpoint(dto.functionName, dto.id); } else if (dto.type === 'data') { this.debugService.addDataBreakpoint(dto.label, dto.dataId, dto.canPersist, dto.accessTypes, dto.accessType); } } return Promise.resolve(); } public $unregisterBreakpoints(breakpointIds: string[], functionBreakpointIds: string[], dataBreakpointIds: string[]): Promise<void> { breakpointIds.forEach(id => this.debugService.removeBreakpoints(id)); functionBreakpointIds.forEach(id => this.debugService.removeFunctionBreakpoints(id)); dataBreakpointIds.forEach(id => this.debugService.removeDataBreakpoints(id)); return Promise.resolve(); } public $registerDebugConfigurationProvider(debugType: string, providerTriggerKind: DebugConfigurationProviderTriggerKind, hasProvide: boolean, hasResolve: boolean, hasResolve2: boolean, handle: number): Promise<void> { const provider = <IDebugConfigurationProvider>{ type: debugType, triggerKind: providerTriggerKind }; if (hasProvide) { provider.provideDebugConfigurations = (folder, token) => { return this._proxy.$provideDebugConfigurations(handle, folder, token); }; } if (hasResolve) { provider.resolveDebugConfiguration = (folder, config, token) => { return this._proxy.$resolveDebugConfiguration(handle, folder, config, token); }; } if (hasResolve2) { provider.resolveDebugConfigurationWithSubstitutedVariables = (folder, config, token) => { return this._proxy.$resolveDebugConfigurationWithSubstitutedVariables(handle, folder, config, token); }; } this._debugConfigurationProviders.set(handle, provider); this._toDispose.add(this.debugService.getConfigurationManager().registerDebugConfigurationProvider(provider)); return Promise.resolve(undefined); } public $unregisterDebugConfigurationProvider(handle: number): void { const provider = this._debugConfigurationProviders.get(handle); if (provider) { this._debugConfigurationProviders.delete(handle); this.debugService.getConfigurationManager().unregisterDebugConfigurationProvider(provider); } } public $registerDebugAdapterDescriptorFactory(debugType: string, handle: number): Promise<void> { const provider = <IDebugAdapterDescriptorFactory>{ type: debugType, createDebugAdapterDescriptor: session => { return Promise.resolve(this._proxy.$provideDebugAdapter(handle, this.getSessionDto(session))); } }; this._debugAdapterDescriptorFactories.set(handle, provider); this._toDispose.add(this.debugService.getAdapterManager().registerDebugAdapterDescriptorFactory(provider)); return Promise.resolve(undefined); } public $unregisterDebugAdapterDescriptorFactory(handle: number): void { const provider = this._debugAdapterDescriptorFactories.get(handle); if (provider) { this._debugAdapterDescriptorFactories.delete(handle); this.debugService.getAdapterManager().unregisterDebugAdapterDescriptorFactory(provider); } } private getSession(sessionId: DebugSessionUUID | undefined): IDebugSession | undefined { if (sessionId) { return this.debugService.getModel().getSession(sessionId, true); } return undefined; } public async $startDebugging(folder: UriComponents | undefined, nameOrConfig: string | IDebugConfiguration, options: IStartDebuggingOptions): Promise<boolean> { const folderUri = folder ? uri.revive(folder) : undefined; const launch = this.debugService.getConfigurationManager().getLaunch(folderUri); const parentSession = this.getSession(options.parentSessionID); const saveBeforeStart = typeof options.suppressSaveBeforeStart === 'boolean' ? !options.suppressSaveBeforeStart : undefined; const debugOptions: IDebugSessionOptions = { noDebug: options.noDebug, parentSession, lifecycleManagedByParent: options.lifecycleManagedByParent, repl: options.repl, compact: options.compact, compoundRoot: parentSession?.compoundRoot, saveBeforeRestart: saveBeforeStart, suppressDebugStatusbar: options.suppressDebugStatusbar, suppressDebugToolbar: options.suppressDebugToolbar, suppressDebugView: options.suppressDebugView, }; try { return this.debugService.startDebugging(launch, nameOrConfig, debugOptions, saveBeforeStart); } catch (err) { throw new ErrorNoTelemetry(err && err.message ? err.message : 'cannot start debugging'); } } public $setDebugSessionName(sessionId: DebugSessionUUID, name: string): void { const session = this.debugService.getModel().getSession(sessionId); session?.setName(name); } public $customDebugAdapterRequest(sessionId: DebugSessionUUID, request: string, args: any): Promise<any> { const session = this.debugService.getModel().getSession(sessionId, true); if (session) { return session.customRequest(request, args).then(response => { if (response && response.success) { return response.body; } else { return Promise.reject(new ErrorNoTelemetry(response ? response.message : 'custom request failed')); } }); } return Promise.reject(new ErrorNoTelemetry('debug session not found')); } public $getDebugProtocolBreakpoint(sessionId: DebugSessionUUID, breakpoinId: string): Promise<DebugProtocol.Breakpoint | undefined> { const session = this.debugService.getModel().getSession(sessionId, true); if (session) { return Promise.resolve(session.getDebugProtocolBreakpoint(breakpoinId)); } return Promise.reject(new ErrorNoTelemetry('debug session not found')); } public $stopDebugging(sessionId: DebugSessionUUID | undefined): Promise<void> { if (sessionId) { const session = this.debugService.getModel().getSession(sessionId, true); if (session) { return this.debugService.stopSession(session, isSessionAttach(session)); } } else { // stop all return this.debugService.stopSession(undefined); } return Promise.reject(new ErrorNoTelemetry('debug session not found')); } public $appendDebugConsole(value: string): void { // Use warning as severity to get the orange color for messages coming from the debug extension const session = this.debugService.getViewModel().focusedSession; session?.appendToRepl({ output: value, sev: severity.Warning }); } public $acceptDAMessage(handle: number, message: DebugProtocol.ProtocolMessage) { this.getDebugAdapter(handle).acceptMessage(convertToVSCPaths(message, false)); } public $acceptDAError(handle: number, name: string, message: string, stack: string) { this.getDebugAdapter(handle).fireError(handle, new Error(`${name}: ${message}\n${stack}`)); } public $acceptDAExit(handle: number, code: number, signal: string) { this.getDebugAdapter(handle).fireExit(handle, code, signal); } private getDebugAdapter(handle: number): ExtensionHostDebugAdapter { const adapter = this._debugAdapters.get(handle); if (!adapter) { throw new Error('Invalid debug adapter'); } return adapter; } // dto helpers public $sessionCached(sessionID: string) { // remember that the EH has cached the session and we do not have to send it again this._sessions.add(sessionID); } getSessionDto(session: undefined): undefined; getSessionDto(session: IDebugSession): IDebugSessionDto; getSessionDto(session: IDebugSession | undefined): IDebugSessionDto | undefined; getSessionDto(session: IDebugSession | undefined): IDebugSessionDto | undefined { if (session) { const sessionID = <DebugSessionUUID>session.getId(); if (this._sessions.has(sessionID)) { return sessionID; } else { // this._sessions.add(sessionID); // #69534: see $sessionCached above return { id: sessionID, type: session.configuration.type, name: session.name, folderUri: session.root ? session.root.uri : undefined, configuration: session.configuration, parent: session.parentSession?.getId(), }; } } return undefined; } private convertToDto(bps: (ReadonlyArray<IBreakpoint | IFunctionBreakpoint | IDataBreakpoint | IInstructionBreakpoint>)): Array<ISourceBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto> { return bps.map(bp => { if ('name' in bp) { const fbp = <IFunctionBreakpoint>bp; return <IFunctionBreakpointDto>{ type: 'function', id: fbp.getId(), enabled: fbp.enabled, condition: fbp.condition, hitCondition: fbp.hitCondition, logMessage: fbp.logMessage, functionName: fbp.name }; } else if ('dataId' in bp) { const dbp = <IDataBreakpoint>bp; return <IDataBreakpointDto>{ type: 'data', id: dbp.getId(), dataId: dbp.dataId, enabled: dbp.enabled, condition: dbp.condition, hitCondition: dbp.hitCondition, logMessage: dbp.logMessage, label: dbp.description, canPersist: dbp.canPersist }; } else { const sbp = <IBreakpoint>bp; return <ISourceBreakpointDto>{ type: 'source', id: sbp.getId(), enabled: sbp.enabled, condition: sbp.condition, hitCondition: sbp.hitCondition, logMessage: sbp.logMessage, uri: sbp.uri, line: sbp.lineNumber > 0 ? sbp.lineNumber - 1 : 0, character: (typeof sbp.column === 'number' && sbp.column > 0) ? sbp.column - 1 : 0, }; } }); } } /** * DebugAdapter that communicates via extension protocol with another debug adapter. */ class ExtensionHostDebugAdapter extends AbstractDebugAdapter { constructor(private readonly _ds: MainThreadDebugService, private _handle: number, private _proxy: ExtHostDebugServiceShape, private _session: IDebugSession) { super(); } fireError(handle: number, err: Error) { this._onError.fire(err); } fireExit(handle: number, code: number, signal: string) { this._onExit.fire(code); } startSession(): Promise<void> { return Promise.resolve(this._proxy.$startDASession(this._handle, this._ds.getSessionDto(this._session))); } sendMessage(message: DebugProtocol.ProtocolMessage): void { this._proxy.$sendDAMessage(this._handle, convertToDAPaths(message, true)); } async stopSession(): Promise<void> { await this.cancelPendingRequests(); return Promise.resolve(this._proxy.$stopDASession(this._handle)); } }
src/vs/workbench/api/browser/mainThreadDebugService.ts
1
https://github.com/microsoft/vscode/commit/ccbcba53e642136ce30465cd4f5605d60c760d7c
[ 0.0007868905668146908, 0.00019038164464291185, 0.00016060919733718038, 0.00016968310228548944, 0.00009331099863629788 ]
{ "id": 2, "code_window": [ "\n", "\t\t\t\t\tif (typeof suspendDebuggee === 'boolean') {\n", "\t\t\t\t\t\targs.suspendDebuggee = suspendDebuggee;\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\tawait this.send('disconnect', args, undefined, 2000);\n", "\t\t\t\t} catch (e) {\n", "\t\t\t\t\t// Catch the potential 'disconnect' error - no need to show it to the user since the adapter is shutting down\n", "\t\t\t\t} finally {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t// if there's an error, the DA is probably already gone, so give it a much shorter timeout.\n", "\t\t\t\t\tawait this.send('disconnect', args, undefined, error ? 200 : 2000);\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/rawDebugSession.ts", "type": "replace", "edit_start_line_idx": 575 }
name: Prevent yarn.lock changes in PRs on: [pull_request] jobs: main: name: Prevent yarn.lock changes in PRs runs-on: ubuntu-latest steps: - uses: octokit/[email protected] id: get_permissions with: route: GET /repos/microsoft/vscode/collaborators/{username}/permission username: ${{ github.event.pull_request.user.login }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Set control output variable id: control run: | echo "user: ${{ github.event.pull_request.user.login }}" echo "role: ${{ fromJson(steps.get_permissions.outputs.data).permission }}" echo "is dependabot: ${{ github.event.pull_request.user.login == 'dependabot[bot]' }}" echo "should_run: ${{ !contains(fromJson('["admin", "maintain", "write"]'), fromJson(steps.get_permissions.outputs.data).permission) }}" echo "should_run=${{ !contains(fromJson('["admin", "maintain", "write"]'), fromJson(steps.get_permissions.outputs.data).permission) && github.event.pull_request.user.login != 'dependabot[bot]' }}" >> $GITHUB_OUTPUT - name: Get file changes uses: trilom/file-changes-action@ce38c8ce2459ca3c303415eec8cb0409857b4272 if: ${{ steps.control.outputs.should_run == 'true' }} - name: Check for yarn.lock changes if: ${{ steps.control.outputs.should_run == 'true' }} run: | cat $HOME/files.json | jq -e 'any(test("yarn\\.lock$")) | not' \ || (echo "Changes to yarn.lock files aren't allowed in PRs." && exit 1)
.github/workflows/no-yarn-lock-changes.yml
0
https://github.com/microsoft/vscode/commit/ccbcba53e642136ce30465cd4f5605d60c760d7c
[ 0.00017359394405502826, 0.0001725598849589005, 0.00017028252477757633, 0.00017318149912171066, 0.0000013442235058391816 ]
{ "id": 2, "code_window": [ "\n", "\t\t\t\t\tif (typeof suspendDebuggee === 'boolean') {\n", "\t\t\t\t\t\targs.suspendDebuggee = suspendDebuggee;\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\tawait this.send('disconnect', args, undefined, 2000);\n", "\t\t\t\t} catch (e) {\n", "\t\t\t\t\t// Catch the potential 'disconnect' error - no need to show it to the user since the adapter is shutting down\n", "\t\t\t\t} finally {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t// if there's an error, the DA is probably already gone, so give it a much shorter timeout.\n", "\t\t\t\t\tawait this.send('disconnect', args, undefined, error ? 200 : 2000);\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/rawDebugSession.ts", "type": "replace", "edit_start_line_idx": 575 }
function foo3() { const foo = (): any => ({ 'bar': 'baz' }) }
extensions/vscode-colorize-tests/test/colorize-fixtures/test-issue5566.ts
0
https://github.com/microsoft/vscode/commit/ccbcba53e642136ce30465cd4f5605d60c760d7c
[ 0.00017042190302163363, 0.00017042190302163363, 0.00017042190302163363, 0.00017042190302163363, 0 ]
{ "id": 2, "code_window": [ "\n", "\t\t\t\t\tif (typeof suspendDebuggee === 'boolean') {\n", "\t\t\t\t\t\targs.suspendDebuggee = suspendDebuggee;\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\tawait this.send('disconnect', args, undefined, 2000);\n", "\t\t\t\t} catch (e) {\n", "\t\t\t\t\t// Catch the potential 'disconnect' error - no need to show it to the user since the adapter is shutting down\n", "\t\t\t\t} finally {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t// if there's an error, the DA is probably already gone, so give it a much shorter timeout.\n", "\t\t\t\t\tawait this.send('disconnect', args, undefined, error ? 200 : 2000);\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/rawDebugSession.ts", "type": "replace", "edit_start_line_idx": 575 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ declare module 'vscode' { //resolvers: @alexdima export interface MessageOptions { /** * Do not render a native message box. */ useCustom?: boolean; } export interface RemoteAuthorityResolverContext { resolveAttempt: number; /** * Exec server from a recursively-resolved remote authority. If the * remote authority includes nested authorities delimited by `@`, it is * resolved from outer to inner authorities with ExecServer passed down * to each resolver in the chain. */ execServer?: ExecServer; } export class ResolvedAuthority { readonly host: string; readonly port: number; readonly connectionToken: string | undefined; constructor(host: string, port: number, connectionToken?: string); } export interface ManagedMessagePassing { onDidReceiveMessage: Event<Uint8Array>; onDidClose: Event<Error | undefined>; onDidEnd: Event<void>; send: (data: Uint8Array) => void; end: () => void; drain?: () => Thenable<void>; } export class ManagedResolvedAuthority { readonly makeConnection: () => Thenable<ManagedMessagePassing>; readonly connectionToken: string | undefined; constructor(makeConnection: () => Thenable<ManagedMessagePassing>, connectionToken?: string); } export interface ResolvedOptions { extensionHostEnv?: { [key: string]: string | null }; isTrusted?: boolean; /** * When provided, remote server will be initialized with the extensions synced using the given user account. */ authenticationSessionForInitializingExtensions?: AuthenticationSession & { providerId: string }; } export interface TunnelPrivacy { themeIcon: string; id: string; label: string; } export namespace env { /** Quality of the application. May be undefined if running from sources. */ export const appQuality: string | undefined; /** Commit of the application. May be undefined if running from sources. */ export const appCommit: string | undefined; } interface TunnelOptions { remoteAddress: { port: number; host: string }; // The desired local port. If this port can't be used, then another will be chosen. localAddressPort?: number; label?: string; /** * @deprecated Use privacy instead */ public?: boolean; privacy?: string; protocol?: string; } interface TunnelDescription { remoteAddress: { port: number; host: string }; //The complete local address(ex. localhost:1234) localAddress: { port: number; host: string } | string; /** * @deprecated Use privacy instead */ public?: boolean; privacy?: string; // If protocol is not provided it is assumed to be http, regardless of the localAddress. protocol?: string; } interface Tunnel extends TunnelDescription { // Implementers of Tunnel should fire onDidDispose when dispose is called. onDidDispose: Event<void>; dispose(): void | Thenable<void>; } /** * Used as part of the ResolverResult if the extension has any candidate, * published, or forwarded ports. */ export interface TunnelInformation { /** * Tunnels that are detected by the extension. The remotePort is used for display purposes. * The localAddress should be the complete local address (ex. localhost:1234) for connecting to the port. Tunnels provided through * detected are read-only from the forwarded ports UI. */ environmentTunnels?: TunnelDescription[]; tunnelFeatures?: { elevation: boolean; /** * One of the the options must have the ID "private". */ privacyOptions: TunnelPrivacy[]; }; } export interface TunnelCreationOptions { /** * True when the local operating system will require elevation to use the requested local port. */ elevationRequired?: boolean; } export enum CandidatePortSource { None = 0, Process = 1, Output = 2 } export type ResolverResult = (ResolvedAuthority | ManagedResolvedAuthority) & ResolvedOptions & TunnelInformation; export class RemoteAuthorityResolverError extends Error { static NotAvailable(message?: string, handled?: boolean): RemoteAuthorityResolverError; static TemporarilyNotAvailable(message?: string): RemoteAuthorityResolverError; constructor(message?: string); } /** * Exec server used for nested resolvers. The type is currently not maintained * in these types, and is a contract between extensions. */ export type ExecServer = unknown; export interface RemoteAuthorityResolver { /** * Resolve the authority part of the current opened `vscode-remote://` URI. * * This method will be invoked once during the startup of the editor and again each time * the editor detects a disconnection. * * @param authority The authority part of the current opened `vscode-remote://` URI. * @param context A context indicating if this is the first call or a subsequent call. */ resolve(authority: string, context: RemoteAuthorityResolverContext): ResolverResult | Thenable<ResolverResult>; /** * Resolves an exec server interface for the authority. Called if an * authority is a midpoint in a transit to the desired remote. * * @param authority The authority part of the current opened `vscode-remote://` URI. * @returns The exec server interface, as defined in a contract between extensions. */ resolveExecServer?(remoteAuthority: string, context: RemoteAuthorityResolverContext): ExecServer | Thenable<ExecServer>; /** * Get the canonical URI (if applicable) for a `vscode-remote://` URI. * * @returns The canonical URI or undefined if the uri is already canonical. */ getCanonicalURI?(uri: Uri): ProviderResult<Uri>; /** * Can be optionally implemented if the extension can forward ports better than the core. * When not implemented, the core will use its default forwarding logic. * When implemented, the core will use this to forward ports. * * To enable the "Change Local Port" action on forwarded ports, make sure to set the `localAddress` of * the returned `Tunnel` to a `{ port: number, host: string; }` and not a string. */ tunnelFactory?: (tunnelOptions: TunnelOptions, tunnelCreationOptions: TunnelCreationOptions) => Thenable<Tunnel> | undefined; /**p * Provides filtering for candidate ports. */ showCandidatePort?: (host: string, port: number, detail: string) => Thenable<boolean>; /** * @deprecated Return tunnelFeatures as part of the resolver result in tunnelInformation. */ tunnelFeatures?: { elevation: boolean; public: boolean; privacyOptions: TunnelPrivacy[]; }; candidatePortSource?: CandidatePortSource; } export interface ResourceLabelFormatter { scheme: string; authority?: string; formatting: ResourceLabelFormatting; } export interface ResourceLabelFormatting { label: string; // myLabel:/${path} // For historic reasons we use an or string here. Once we finalize this API we should start using enums instead and adopt it in extensions. // eslint-disable-next-line local/vscode-dts-literal-or-types, local/vscode-dts-string-type-literals separator: '/' | '\\' | ''; tildify?: boolean; normalizeDriveLetter?: boolean; workspaceSuffix?: string; workspaceTooltip?: string; authorityPrefix?: string; stripPathStartingSeparator?: boolean; } export namespace workspace { export function registerRemoteAuthorityResolver(authorityPrefix: string, resolver: RemoteAuthorityResolver): Disposable; export function registerResourceLabelFormatter(formatter: ResourceLabelFormatter): Disposable; export function getRemoteExecServer(authority: string): Thenable<ExecServer | undefined>; } export namespace env { /** * The authority part of the current opened `vscode-remote://` URI. * Defined by extensions, e.g. `ssh-remote+${host}` for remotes using a secure shell. * * *Note* that the value is `undefined` when there is no remote extension host but that the * value is defined in all extension hosts (local and remote) in case a remote extension host * exists. Use {@link Extension.extensionKind} to know if * a specific extension runs remote or not. */ export const remoteAuthority: string | undefined; } }
src/vscode-dts/vscode.proposed.resolvers.d.ts
0
https://github.com/microsoft/vscode/commit/ccbcba53e642136ce30465cd4f5605d60c760d7c
[ 0.00017731331172399223, 0.00016760476864874363, 0.0001609939063200727, 0.00016661988047417253, 0.000004334578989073634 ]
{ "id": 0, "code_window": [ " test: string;\n", " message: string;\n", " stack: string;\n", "}export interface NewmanRunFailure {\n", " error: NewmanRunExecutionAssertionError;\n", " /** The event where the failure occurred */\n", " at: string;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "}\n", "export interface NewmanRunFailure {\n" ], "file_path": "types/newman/index.d.ts", "type": "replace", "edit_start_line_idx": 175 }
import { EventEmitter } from "events"; import { run, NewmanRun, NewmanRunExecution, NewmanRunExecutionAssertion, NewmanRunExecutionAssertionError, NewmanRunExecutionItem, NewmanRunFailure, NewmanRunSummary } from "newman"; import { CollectionDefinition, VariableScopeDefinition } from "postman-collection"; const collection: CollectionDefinition = {}; const environment: VariableScopeDefinition = {}; const globals: VariableScopeDefinition = {}; // $ExpectType EventEmitter run( { collection, environment, globals }, (err, summary: NewmanRunSummary) => { summary.run; // $ExpectType NewmanRun summary.run.executions; // $ExpectType NewmanRunExecution[] summary.run.failures; // $ExpectType NewmanRunFailure[] } );
types/newman/newman-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/924bcd457ff84c1c48fb7db7196ac6da3edfc0ad
[ 0.9992669224739075, 0.5242390632629395, 0.00017800887871999294, 0.5487556457519531, 0.47508078813552856 ]
{ "id": 0, "code_window": [ " test: string;\n", " message: string;\n", " stack: string;\n", "}export interface NewmanRunFailure {\n", " error: NewmanRunExecutionAssertionError;\n", " /** The event where the failure occurred */\n", " at: string;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "}\n", "export interface NewmanRunFailure {\n" ], "file_path": "types/newman/index.d.ts", "type": "replace", "edit_start_line_idx": 175 }
// From https://hapijs.com/api/16.1.1#response-events import * as Hapi from 'hapi'; const Crypto = require('crypto'); const server = new Hapi.Server(); server.connection({ port: 80 }); const preResponse: Hapi.ServerExtRequestHandler = function (request, reply) { const response = request.response!; if (response.isBoom) { return reply(); } const hash = Crypto.createHash('sha1'); response.on('peek', (chunk) => { hash.update(chunk); }); response.once('finish', () => { console.log(hash.digest('hex')); }); return reply.continue(); }; server.ext('onPreResponse', preResponse);
types/hapi/v16/test/response/events.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/924bcd457ff84c1c48fb7db7196ac6da3edfc0ad
[ 0.0001804127387003973, 0.00017690837557893246, 0.00017460892559029162, 0.00017630591173656285, 0.000002337265641472186 ]
{ "id": 0, "code_window": [ " test: string;\n", " message: string;\n", " stack: string;\n", "}export interface NewmanRunFailure {\n", " error: NewmanRunExecutionAssertionError;\n", " /** The event where the failure occurred */\n", " at: string;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "}\n", "export interface NewmanRunFailure {\n" ], "file_path": "types/newman/index.d.ts", "type": "replace", "edit_start_line_idx": 175 }
{ "extends": "dtslint/dt.json" }
types/expired/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/924bcd457ff84c1c48fb7db7196ac6da3edfc0ad
[ 0.0001758141297614202, 0.0001758141297614202, 0.0001758141297614202, 0.0001758141297614202, 0 ]
{ "id": 0, "code_window": [ " test: string;\n", " message: string;\n", " stack: string;\n", "}export interface NewmanRunFailure {\n", " error: NewmanRunExecutionAssertionError;\n", " /** The event where the failure occurred */\n", " at: string;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "}\n", "export interface NewmanRunFailure {\n" ], "file_path": "types/newman/index.d.ts", "type": "replace", "edit_start_line_idx": 175 }
{ "extends": "dtslint/dt.json" }
types/pkgcloud/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/924bcd457ff84c1c48fb7db7196ac6da3edfc0ad
[ 0.0001758141297614202, 0.0001758141297614202, 0.0001758141297614202, 0.0001758141297614202, 0 ]
{ "id": 1, "code_window": [ " error: NewmanRunExecutionAssertionError;\n", " /** The event where the failure occurred */\n", " at: string;\n", "}\n", "export function run(\n", " options: NewmanRunOptions,\n", " callback?: (err: Error | null, summary: NewmanRunSummary) => void\n", "): EventEmitter;" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " source: NewmanRunExecutionItem | undefined;\n", " parent: any;\n", " cursor: { ref: string } | {};\n" ], "file_path": "types/newman/index.d.ts", "type": "add", "edit_start_line_idx": 179 }
import { EventEmitter } from "events"; import { run, NewmanRun, NewmanRunExecution, NewmanRunExecutionAssertion, NewmanRunExecutionAssertionError, NewmanRunExecutionItem, NewmanRunFailure, NewmanRunSummary } from "newman"; import { CollectionDefinition, VariableScopeDefinition } from "postman-collection"; const collection: CollectionDefinition = {}; const environment: VariableScopeDefinition = {}; const globals: VariableScopeDefinition = {}; // $ExpectType EventEmitter run( { collection, environment, globals }, (err, summary: NewmanRunSummary) => { summary.run; // $ExpectType NewmanRun summary.run.executions; // $ExpectType NewmanRunExecution[] summary.run.failures; // $ExpectType NewmanRunFailure[] } );
types/newman/newman-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/924bcd457ff84c1c48fb7db7196ac6da3edfc0ad
[ 0.997149646282196, 0.7134143114089966, 0.00017856441263575107, 0.9281644821166992, 0.41386082768440247 ]
{ "id": 1, "code_window": [ " error: NewmanRunExecutionAssertionError;\n", " /** The event where the failure occurred */\n", " at: string;\n", "}\n", "export function run(\n", " options: NewmanRunOptions,\n", " callback?: (err: Error | null, summary: NewmanRunSummary) => void\n", "): EventEmitter;" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " source: NewmanRunExecutionItem | undefined;\n", " parent: any;\n", " cursor: { ref: string } | {};\n" ], "file_path": "types/newman/index.d.ts", "type": "add", "edit_start_line_idx": 179 }
{ "extends": "dtslint/dt.json" }
types/react-axe/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/924bcd457ff84c1c48fb7db7196ac6da3edfc0ad
[ 0.0001749063521856442, 0.0001749063521856442, 0.0001749063521856442, 0.0001749063521856442, 0 ]
{ "id": 1, "code_window": [ " error: NewmanRunExecutionAssertionError;\n", " /** The event where the failure occurred */\n", " at: string;\n", "}\n", "export function run(\n", " options: NewmanRunOptions,\n", " callback?: (err: Error | null, summary: NewmanRunSummary) => void\n", "): EventEmitter;" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " source: NewmanRunExecutionItem | undefined;\n", " parent: any;\n", " cursor: { ref: string } | {};\n" ], "file_path": "types/newman/index.d.ts", "type": "add", "edit_start_line_idx": 179 }
{ "extends": "dtslint/dt.json" }
types/hapi__code/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/924bcd457ff84c1c48fb7db7196ac6da3edfc0ad
[ 0.0001749063521856442, 0.0001749063521856442, 0.0001749063521856442, 0.0001749063521856442, 0 ]
{ "id": 1, "code_window": [ " error: NewmanRunExecutionAssertionError;\n", " /** The event where the failure occurred */\n", " at: string;\n", "}\n", "export function run(\n", " options: NewmanRunOptions,\n", " callback?: (err: Error | null, summary: NewmanRunSummary) => void\n", "): EventEmitter;" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " source: NewmanRunExecutionItem | undefined;\n", " parent: any;\n", " cursor: { ref: string } | {};\n" ], "file_path": "types/newman/index.d.ts", "type": "add", "edit_start_line_idx": 179 }
import swaggerSailsHook = require("swagger-sails-hook"); import * as express from "express"; const mockSailsApp = { models: {}, conf: {}, sockets: {}, hooks: {}, lift: () => { /* do nothing */ } }; // create and register hook const swaggerHookRef = swaggerSailsHook(mockSailsApp); if (typeof swaggerHookRef.routes.after['/*'] === 'function') { // right type } swaggerHookRef.initialize(() => { // do something, when initialized });
types/swagger-sails-hook/swagger-sails-hook-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/924bcd457ff84c1c48fb7db7196ac6da3edfc0ad
[ 0.00017508088785689324, 0.00017269204545300454, 0.00017099191609304398, 0.00017200331785716116, 0.000001738903165460215 ]
{ "id": 2, "code_window": [ " (err, summary: NewmanRunSummary) => {\n", " summary.run; // $ExpectType NewmanRun\n", " summary.run.executions; // $ExpectType NewmanRunExecution[]\n", " summary.run.failures; // $ExpectType NewmanRunFailure[]\n", " }\n", ");" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " summary.run.failures[0].source; // $ExpectType NewmanRunExecutionItem | undefined\n" ], "file_path": "types/newman/newman-tests.ts", "type": "add", "edit_start_line_idx": 31 }
import { EventEmitter } from "events"; import { run, NewmanRun, NewmanRunExecution, NewmanRunExecutionAssertion, NewmanRunExecutionAssertionError, NewmanRunExecutionItem, NewmanRunFailure, NewmanRunSummary } from "newman"; import { CollectionDefinition, VariableScopeDefinition } from "postman-collection"; const collection: CollectionDefinition = {}; const environment: VariableScopeDefinition = {}; const globals: VariableScopeDefinition = {}; // $ExpectType EventEmitter run( { collection, environment, globals }, (err, summary: NewmanRunSummary) => { summary.run; // $ExpectType NewmanRun summary.run.executions; // $ExpectType NewmanRunExecution[] summary.run.failures; // $ExpectType NewmanRunFailure[] } );
types/newman/newman-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/924bcd457ff84c1c48fb7db7196ac6da3edfc0ad
[ 0.9966354966163635, 0.3152981698513031, 0.00017926213331520557, 0.13218894600868225, 0.4001369774341583 ]
{ "id": 2, "code_window": [ " (err, summary: NewmanRunSummary) => {\n", " summary.run; // $ExpectType NewmanRun\n", " summary.run.executions; // $ExpectType NewmanRunExecution[]\n", " summary.run.failures; // $ExpectType NewmanRunFailure[]\n", " }\n", ");" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " summary.run.failures[0].source; // $ExpectType NewmanRunExecutionItem | undefined\n" ], "file_path": "types/newman/newman-tests.ts", "type": "add", "edit_start_line_idx": 31 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6", "dom" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true, "strictFunctionTypes": true }, "files": [ "index.d.ts", "gapi.client.clouduseraccounts-tests.ts" ] }
types/gapi.client.clouduseraccounts/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/924bcd457ff84c1c48fb7db7196ac6da3edfc0ad
[ 0.0001776887074811384, 0.00017682732141111046, 0.000176319939782843, 0.00017647334607318044, 6.122963895904832e-7 ]
{ "id": 2, "code_window": [ " (err, summary: NewmanRunSummary) => {\n", " summary.run; // $ExpectType NewmanRun\n", " summary.run.executions; // $ExpectType NewmanRunExecution[]\n", " summary.run.failures; // $ExpectType NewmanRunFailure[]\n", " }\n", ");" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " summary.run.failures[0].source; // $ExpectType NewmanRunExecutionItem | undefined\n" ], "file_path": "types/newman/newman-tests.ts", "type": "add", "edit_start_line_idx": 31 }
{ "extends": "dtslint/dt.json" }
types/react-devtools/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/924bcd457ff84c1c48fb7db7196ac6da3edfc0ad
[ 0.00017743304488249123, 0.00017743304488249123, 0.00017743304488249123, 0.00017743304488249123, 0 ]
{ "id": 2, "code_window": [ " (err, summary: NewmanRunSummary) => {\n", " summary.run; // $ExpectType NewmanRun\n", " summary.run.executions; // $ExpectType NewmanRunExecution[]\n", " summary.run.failures; // $ExpectType NewmanRunFailure[]\n", " }\n", ");" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " summary.run.failures[0].source; // $ExpectType NewmanRunExecutionItem | undefined\n" ], "file_path": "types/newman/newman-tests.ts", "type": "add", "edit_start_line_idx": 31 }
import * as React from "react"; import { Component, ValidationMap } from "react"; import * as ReactDOM from "react-dom"; import { renderToString } from "react-dom/server"; import { applyRouterMiddleware, browserHistory, hashHistory, match, createMemoryHistory, useRouterHistory, withRouter, routerShape, Router, Route, IndexRoute, InjectedRouter, Link, RouterContext, LinkProps, RedirectFunction, RouteComponentProps, WithRouterProps } from "react-router"; import { matchPattern } from 'react-router/lib/PatternUtils'; import { createHistory, History } from "history"; const routerHistory = useRouterHistory(createHistory)({ basename: "/test" }); interface CustomHistory { test(): void; } type CombinedHistory = History & CustomHistory; function createCustomHistory(history: History): CombinedHistory { return Object.assign(history, { test() { } }); // tslint:disable-line prefer-object-spread } const customHistory = createCustomHistory(browserHistory); const NavLink = (props: LinkProps) => ( <Link {...props} activeClassName="active" /> ); interface MasterContext { router: InjectedRouter; } class Master extends Component { static contextTypes: ValidationMap<any> = { router: routerShape }; // tslint:disable-next-line:no-object-literal-type-assertion context = {} as MasterContext; navigate() { const router = this.context.router; router.push("/users"); router.push({ pathname: "/users/12", query: { modal: true }, state: { fromDashboard: true } }); } render() { return <div> <h1>Master</h1> <Link to="/">Dashboard</Link> <NavLink to="/users">Users</NavLink> <p>{this.props.children}</p> </div>; } } class Dashboard extends React.Component<WithRouterProps> { static staticMethodToBeHoisted(): void { } navigate() { const router = this.props.router; router.push("/users"); router.push({ pathname: "/users/12", query: { modal: true }, state: { fromDashboard: true } }); } render() { return <div> This is a dashboard </div>; } } const DashboardWithRouter = withRouter(Dashboard); DashboardWithRouter.staticMethodToBeHoisted(); class NotFound extends React.Component { render() { return <div> This path does not exists </div>; } } interface UserListProps { users: string; } class UserList extends React.Component<UserListProps & WithRouterProps> { render() { const { location, params, router, routes } = this.props; return <div> <ul> <li>{this.props.users}</li> </ul> </div>; } } const UserListWithRouter = withRouter(UserList); type UsersProps = RouteComponentProps<{}, {}>; class Users extends React.Component<UsersProps> { render() { const { location, params, route, routes, router, routeParams } = this.props; return <div> This is a user list <UserListWithRouter users="Suzanne, Fred" /> </div>; } } ReactDOM.render(( <Router history={hashHistory}> <Route path="/" component={Master}> <IndexRoute component={DashboardWithRouter} /> <Route path="users" component={Users} /> <Route path="*" component={NotFound} /> </Route> </Router> ), document.body); ReactDOM.render(( <Router history={routerHistory}> <Route path="/" component={Master} /> </Router> ), document.body); ReactDOM.render(( <Router history={customHistory}> <Route path="/" component={Master} /> </Router> ), document.body); const history = createMemoryHistory({ current: "baseurl" }); const routes = ( <Route path="/" component={Master}> <IndexRoute component={DashboardWithRouter} /> <Route path="users" component={Users} /> </Route> ); match({ routes, location: "baseurl" }, (error, redirectLocation, renderProps) => { renderToString(<RouterContext {...renderProps} />); }); match({ history, routes }, (error, redirectLocation, renderProps) => { renderToString(<RouterContext {...renderProps} />); }); ReactDOM.render(( <Router history={history} routes={routes} render={applyRouterMiddleware({ renderRouteComponent: child => child })} > </Router> ), document.body); const matchedPattern = matchPattern("/foo", "/foo/bar"); if (matchedPattern) { matchedPattern.remainingPathname === "/bar"; matchedPattern.paramNames.forEach(name => {}); matchedPattern.paramValues.forEach(value => {}); } matchPattern("/foo", "/baz") === null; const CreateHref: React.SFC<WithRouterProps> = ({ router }) => ( <div> {router.createHref({ pathname: "/foo", query: { bar: "baz" } })} {router.createHref("/foo?bar=baz")} </div> ); const CreateHrefWithRouter = withRouter<{}>(CreateHref); ReactDOM.render(<CreateHrefWithRouter />, document.body);
types/react-router/v3/react-router-tests.tsx
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/924bcd457ff84c1c48fb7db7196ac6da3edfc0ad
[ 0.00017896531790029258, 0.0001746418565744534, 0.0001678859698586166, 0.00017478100198786706, 0.0000027834503271151334 ]
{ "id": 0, "code_window": [ "* [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com)\n", "\n", "Click on the links above and click the `Enable` button:\n", "\n", "![Enable GCP APIs](/img/docs/v53/stackdriver_enable_api.png)\n", "\n", "#### Create a GCP Service Account for a Project\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "{{< docs-imagebox img=\"/img/docs/v53/stackdriver_enable_api.png\" class=\"docs-image--no-shadow\" caption=\"Enable GCP APIs\" >}}\n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 50 }
+++ title = "Using Stackdriver in Grafana" description = "Guide for using Stackdriver in Grafana" keywords = ["grafana", "stackdriver", "google", "guide"] type = "docs" aliases = ["/datasources/stackdriver"] [menu.docs] name = "Stackdriver" parent = "datasources" weight = 11 +++ # Using Google Stackdriver in Grafana > Only available in Grafana v5.3+. > The datasource is currently a beta feature and is subject to change. Grafana ships with built-in support for Google Stackdriver. Just add it as a datasource and you are ready to build dashboards for your Stackdriver metrics. ## Adding the data source to Grafana 1. Open the side menu by clicking the Grafana icon in the top header. 2. In the side menu under the `Dashboards` link you should find a link named `Data Sources`. 3. Click the `+ Add data source` button in the top header. 4. Select `Stackdriver` from the _Type_ dropdown. 5. Upload or paste in the Service Account Key file. See below for steps on how to create a Service Account Key file. > NOTE: If you're not seeing the `Data Sources` link in your side menu it means that your current user does not have the `Admin` role for the current organization. | Name | Description | | --------------------- | ----------------------------------------------------------------------------------- | | _Name_ | The datasource name. This is how you refer to the datasource in panels & queries. | | _Default_ | Default datasource means that it will be pre-selected for new panels. | | _Service Account Key_ | Service Account Key File for a GCP Project. Instructions below on how to create it. | ## Authentication ### Service Account Credentials - Private Key File To authenticate with the Stackdriver API, you need to create a Google Cloud Platform (GCP) Service Account for the Project you want to show data for. A Grafana datasource integrates with one GCP Project. If you want to visualize data from multiple GCP Projects then you need to create one datasource per GCP Project. #### Enable APIs The following APIs need to be enabled first: * [Monitoring API](https://console.cloud.google.com/apis/library/monitoring.googleapis.com) * [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com) Click on the links above and click the `Enable` button: ![Enable GCP APIs](/img/docs/v53/stackdriver_enable_api.png) #### Create a GCP Service Account for a Project 1. Navigate to the [APIs & Services Credentials page](https://console.cloud.google.com/apis/credentials). 2. Click on the `Create credentials` dropdown/button and choose the `Service account key` option. ![Create service account button](/img/docs/v53/stackdriver_create_service_account_button.png) 3. On the `Create service account key` page, choose key type `JSON`. Then in the `Service Account` dropdown, choose the `New service account` option: ![Create service account key](/img/docs/v53/stackdriver_create_service_account_key.png) 4. Some new fields will appear. Fill in a name for the service account in the `Service account name` field and then choose the `Monitoring Viewer` role from the `Role` dropdown: ![Choose role](/img/docs/v53/stackdriver_service_account_choose_role.png) 5. Click the Create button. A JSON key file will be created and downloaded to your computer. Store this file in a secure place as it allows access to your Stackdriver data. 6. Upload it to Grafana on the datasource Configuration page. You can either upload the file or paste in the contents of the file. ![Choose role](/img/docs/v53/stackdriver_grafana_upload_key.png) 7. The file contents will be encrypted and saved in the Grafana database. Don't forget to save after uploading the file! ![Choose role](/img/docs/v53/stackdriver_grafana_key_uploaded.png) ## Metric Query Editor {{< docs-imagebox img="/img/docs/v53/stackdriver_query_editor.png" max-width= "400px" class="docs-image--right" >}} The Stackdriver query editor allows you to select metrics and group by multiple labels and use filter the results. Begin by choosing a `Service` and then a metric from the `Metric` dropdown. Use the plus and minus icons in the filter and group by sections to add/remove filters or group by clauses. Stackdriver metrics can be of different kinds (GAUGE, DELTA, CUMULATIVE) and these kinds have support for different aggregation options (reducers and aligners). The Grafana query editor shows the list of available aggregation methods for a selected metric and sets a default reducer and aligner when you select the metric. Units for the Y-axis are also automatically selected by the query editor. ### Filter To add a filter, click the plus icon and choose a field to filter by and enter a filter value e.g. `instance_name = grafana-1`. You can remove the filter by clicking on the filter name and select `--remove filter--`. #### Simple wildcards When the operator is set to `=` or `!=` it is possible to add wildcards to the filter value field. E.g `us-*` will capture all values that starts with "us-" and `*central-a` will capture all values that ends with "central-a". `*-central-*` captures all values that has the substring of -central-. Simple wildcards are less expensive than regular expressions. #### Regular expressions When the operator is set to `=~` or `!=~` it is possible to add regular expressions to the filter value field. E.g `us-central[1-3]-[af]` would match all values that starts with "us-central", is followed by a number in the range of 1 to 3, a dash and then either an "a" or an "f". Leading and trailing slashes are not needed when creating regular expressions. ### Aggregation The aggregation field lets you combine time series based on common statistics. Read more about this option [here](https://cloud.google.com/monitoring/charts/metrics-selector#aggregation-options). The `Aligner` field allows you to align multiple time series after the same group by time interval. Read more about how it works [here](https://cloud.google.com/monitoring/charts/metrics-selector#alignment). #### Alignment Period/Group by Time The `Alignment Period` groups a metric by time if an aggregation is chosen. The default is to use the GCP Stackdriver default groupings (which allows you to compare graphs in Grafana with graphs in the Stackdriver UI). The option is called `Stackdriver auto` and the defaults are: * 1m for time ranges < 23 hours * 5m for time ranges >= 23 hours and < 6 days * 1h for time ranges >= 6 days The other automatic option is `Grafana auto`. This will automatically set the group by time depending on the time range chosen and the width of the graph panel. Read more about the details [here](http://docs.grafana.org/reference/templating/#the-interval-variable). It is also possible to choose fixed time intervals to group by, like `1h` or `1d`. ### Group By Group by resource or metric labels to reduce the number of time series and to aggregate the results by a group by. E.g. Group by instance_name to see an aggregated metric for a Compute instance. ### Alias Patterns The Alias By field allows you to control the format of the legend keys. The default is to show the metric name and labels. This can be long and hard to read. Using the following patterns in the alias field, you can format the legend key the way you want it. #### Metric Type Patterns | Alias Pattern | Description | Example Result | | -------------------- | ---------------------------- | ------------------------------------------------- | | `{{metric.type}}` | returns the full Metric Type | `compute.googleapis.com/instance/cpu/utilization` | | `{{metric.name}}` | returns the metric name part | `instance/cpu/utilization` | | `{{metric.service}}` | returns the service part | `compute` | #### Label Patterns In the Group By dropdown, you can see a list of metric and resource labels for a metric. These can be included in the legend key using alias patterns. | Alias Pattern Format | Description | Alias Pattern Example | Example Result | | ------------------------ | -------------------------------- | -------------------------------- | ---------------- | | `{{metric.label.xxx}}` | returns the metric label value | `{{metric.label.instance_name}}` | `grafana-1-prod` | | `{{resource.label.xxx}}` | returns the resource label value | `{{resource.label.zone}}` | `us-east1-b` | Example Alias By: `{{metric.type}} - {{metric.labels.instance_name}}` Example Result: `compute.googleapis.com/instance/cpu/usage_time - server1-prod` ## Templating Instead of hard-coding things like server, application and sensor name in you metric queries you can use variables in their place. Variables are shown as dropdown select boxes at the top of the dashboard. These dropdowns makes it easy to change the data being displayed in your dashboard. Checkout the [Templating]({{< relref "reference/templating.md" >}}) documentation for an introduction to the templating feature and the different types of template variables. ### Query Variable Writing variable queries is not supported yet. ### Using variables in queries There are two syntaxes: * `$<varname>` Example: `metric.label.$metric_label` * `[[varname]]` Example: `metric.label.[[metric_label]]` Why two ways? The first syntax is easier to read and write but does not allow you to use a variable in the middle of a word. When the _Multi-value_ or _Include all value_ options are enabled, Grafana converts the labels from plain text to a regex compatible string, which means you have to use `=~` instead of `=`. ## Annotations {{< docs-imagebox img="/img/docs/v53/stackdriver_annotations_query_editor.png" max-width= "400px" class="docs-image--right" >}} [Annotations]({{< relref "reference/annotations.md" >}}) allows you to overlay rich event information on top of graphs. You add annotation queries via the Dashboard menu / Annotations view. Annotation rendering is expensive so it is important to limit the number of rows returned. There is no support for showing Stackdriver annotations and events yet but it works well with [custom metrics](https://cloud.google.com/monitoring/custom-metrics/) in Stackdriver. With the query editor for annotations, you can select a metric and filters. The `Title` and `Text` fields support templating and can use data returned from the query. For example, the Title field could have the following text: `{{metric.type}} has value: {{metric.value}}` Example Result: `monitoring.googleapis.com/uptime_check/http_status has this value: 502` ### Patterns for the Annotation Query Editor | Alias Pattern Format | Description | Alias Pattern Example | Example Result | | ------------------------ | -------------------------------- | -------------------------------- | ------------------------------------------------- | | `{{metric.value}}` | value of the metric/point | `{{metric.value}}` | `555` | | `{{metric.type}}` | returns the full Metric Type | `{{metric.type}}` | `compute.googleapis.com/instance/cpu/utilization` | | `{{metric.name}}` | returns the metric name part | `{{metric.name}}` | `instance/cpu/utilization` | | `{{metric.service}}` | returns the service part | `{{metric.service}}` | `compute` | | `{{metric.label.xxx}}` | returns the metric label value | `{{metric.label.instance_name}}` | `grafana-1-prod` | | `{{resource.label.xxx}}` | returns the resource label value | `{{resource.label.zone}}` | `us-east1-b` | ## Configure the Datasource with Provisioning It's now possible to configure datasources using config files with Grafana's provisioning system. You can read more about how it works and all the settings you can set for datasources on the [provisioning docs page](/administration/provisioning/#datasources) Here is a provisioning example for this datasource. ```yaml apiVersion: 1 datasources: - name: Stackdriver type: stackdriver access: proxy jsonData: tokenUri: https://oauth2.googleapis.com/token clientEmail: [email protected] secureJsonData: privateKey: | -----BEGIN PRIVATE KEY----- POSEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCb1u1Srw8ICYHS ... yA+23427282348234= -----END PRIVATE KEY----- ```
docs/sources/features/datasources/stackdriver.md
1
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.03594284504652023, 0.002031012438237667, 0.0001624900323804468, 0.0001695162063697353, 0.007448200136423111 ]
{ "id": 0, "code_window": [ "* [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com)\n", "\n", "Click on the links above and click the `Enable` button:\n", "\n", "![Enable GCP APIs](/img/docs/v53/stackdriver_enable_api.png)\n", "\n", "#### Create a GCP Service Account for a Project\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "{{< docs-imagebox img=\"/img/docs/v53/stackdriver_enable_api.png\" class=\"docs-image--no-shadow\" caption=\"Enable GCP APIs\" >}}\n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 50 }
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package ec2
vendor/github.com/aws/aws-sdk-go/service/ec2/errors.go
0
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.00017082682461477816, 0.00017082682461477816, 0.00017082682461477816, 0.00017082682461477816, 0 ]
{ "id": 0, "code_window": [ "* [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com)\n", "\n", "Click on the links above and click the `Enable` button:\n", "\n", "![Enable GCP APIs](/img/docs/v53/stackdriver_enable_api.png)\n", "\n", "#### Create a GCP Service Account for a Project\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "{{< docs-imagebox img=\"/img/docs/v53/stackdriver_enable_api.png\" class=\"docs-image--no-shadow\" caption=\"Enable GCP APIs\" >}}\n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 50 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="64px" height="64px" viewBox="-479 353 64 64" style="enable-background:new -479 353 64 64;" xml:space="preserve"> <style type="text/css"> .st0{fill:#E2E2E2;} </style> <path class="st0" d="M-415.1,384c-0.4-0.7-9.5-16.6-31.6-16.6c0,0-0.1,0-0.1,0c0,0,0,0,0,0c0,0-0.1,0-0.1,0 c-22,0.1-31.3,15.9-31.6,16.6c-0.3,0.6-0.3,1.3,0,1.9c0.4,0.7,9.6,16.5,31.6,16.6c0,0,0.1,0,0.1,0c0,0,0,0,0,0c0,0,0.1,0,0.1,0 c22.2,0,31.2-16,31.6-16.6C-414.8,385.3-414.8,384.6-415.1,384z M-446.9,399.3c-7.9,0-14.3-6.4-14.3-14.3c0-7.9,6.4-14.3,14.3-14.3 c7.9,0,14.3,6.4,14.3,14.3C-432.6,392.9-439,399.3-446.9,399.3z"/> <g> <path class="st0" d="M-446.9,378.3c-0.9,0-1.8,0.2-2.6,0.5c1.2,0.4,2,1.5,2,2.9c0,1.7-1.4,3-3,3c-1.2,0-2.2-0.7-2.7-1.7 c-0.2,0.6-0.3,1.3-0.3,2c0,3.7,3,6.7,6.7,6.7c3.7,0,6.7-3,6.7-6.7S-443.2,378.3-446.9,378.3z"/> </g> </svg>
public/img/icons_dark_theme/icon_viewer.svg
0
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.0001654035586398095, 0.00016504773520864546, 0.0001646918972255662, 0.00016504773520864546, 3.5583070712164044e-7 ]
{ "id": 0, "code_window": [ "* [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com)\n", "\n", "Click on the links above and click the `Enable` button:\n", "\n", "![Enable GCP APIs](/img/docs/v53/stackdriver_enable_api.png)\n", "\n", "#### Create a GCP Service Account for a Project\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "{{< docs-imagebox img=\"/img/docs/v53/stackdriver_enable_api.png\" class=\"docs-image--no-shadow\" caption=\"Enable GCP APIs\" >}}\n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 50 }
module.exports = function (config, grunt) { 'use strict'; return { tslint: 'node ./node_modules/tslint/lib/tslintCli.js -c tslint.json --project ./tsconfig.json', tsc: 'yarn tsc --noEmit', jest: 'node ./node_modules/jest-cli/bin/jest.js --maxWorkers 2', webpack: 'node ./node_modules/webpack/bin/webpack.js --config scripts/webpack/webpack.prod.js', }; };
scripts/grunt/options/exec.js
0
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.00016897548630367965, 0.00016871222760528326, 0.00016844895435497165, 0.00016871222760528326, 2.632659743539989e-7 ]
{ "id": 1, "code_window": [ "1. Navigate to the [APIs & Services Credentials page](https://console.cloud.google.com/apis/credentials).\n", "2. Click on the `Create credentials` dropdown/button and choose the `Service account key` option.\n", "\n", " ![Create service account button](/img/docs/v53/stackdriver_create_service_account_button.png)\n", "\n", "3. On the `Create service account key` page, choose key type `JSON`. Then in the `Service Account` dropdown, choose the `New service account` option:\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " {{< docs-imagebox img=\"/img/docs/v53/stackdriver_create_service_account_button.png\" class=\"docs-image--no-shadow\" caption=\"Create service account button\" >}}\n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 57 }
+++ title = "Using Stackdriver in Grafana" description = "Guide for using Stackdriver in Grafana" keywords = ["grafana", "stackdriver", "google", "guide"] type = "docs" aliases = ["/datasources/stackdriver"] [menu.docs] name = "Stackdriver" parent = "datasources" weight = 11 +++ # Using Google Stackdriver in Grafana > Only available in Grafana v5.3+. > The datasource is currently a beta feature and is subject to change. Grafana ships with built-in support for Google Stackdriver. Just add it as a datasource and you are ready to build dashboards for your Stackdriver metrics. ## Adding the data source to Grafana 1. Open the side menu by clicking the Grafana icon in the top header. 2. In the side menu under the `Dashboards` link you should find a link named `Data Sources`. 3. Click the `+ Add data source` button in the top header. 4. Select `Stackdriver` from the _Type_ dropdown. 5. Upload or paste in the Service Account Key file. See below for steps on how to create a Service Account Key file. > NOTE: If you're not seeing the `Data Sources` link in your side menu it means that your current user does not have the `Admin` role for the current organization. | Name | Description | | --------------------- | ----------------------------------------------------------------------------------- | | _Name_ | The datasource name. This is how you refer to the datasource in panels & queries. | | _Default_ | Default datasource means that it will be pre-selected for new panels. | | _Service Account Key_ | Service Account Key File for a GCP Project. Instructions below on how to create it. | ## Authentication ### Service Account Credentials - Private Key File To authenticate with the Stackdriver API, you need to create a Google Cloud Platform (GCP) Service Account for the Project you want to show data for. A Grafana datasource integrates with one GCP Project. If you want to visualize data from multiple GCP Projects then you need to create one datasource per GCP Project. #### Enable APIs The following APIs need to be enabled first: * [Monitoring API](https://console.cloud.google.com/apis/library/monitoring.googleapis.com) * [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com) Click on the links above and click the `Enable` button: ![Enable GCP APIs](/img/docs/v53/stackdriver_enable_api.png) #### Create a GCP Service Account for a Project 1. Navigate to the [APIs & Services Credentials page](https://console.cloud.google.com/apis/credentials). 2. Click on the `Create credentials` dropdown/button and choose the `Service account key` option. ![Create service account button](/img/docs/v53/stackdriver_create_service_account_button.png) 3. On the `Create service account key` page, choose key type `JSON`. Then in the `Service Account` dropdown, choose the `New service account` option: ![Create service account key](/img/docs/v53/stackdriver_create_service_account_key.png) 4. Some new fields will appear. Fill in a name for the service account in the `Service account name` field and then choose the `Monitoring Viewer` role from the `Role` dropdown: ![Choose role](/img/docs/v53/stackdriver_service_account_choose_role.png) 5. Click the Create button. A JSON key file will be created and downloaded to your computer. Store this file in a secure place as it allows access to your Stackdriver data. 6. Upload it to Grafana on the datasource Configuration page. You can either upload the file or paste in the contents of the file. ![Choose role](/img/docs/v53/stackdriver_grafana_upload_key.png) 7. The file contents will be encrypted and saved in the Grafana database. Don't forget to save after uploading the file! ![Choose role](/img/docs/v53/stackdriver_grafana_key_uploaded.png) ## Metric Query Editor {{< docs-imagebox img="/img/docs/v53/stackdriver_query_editor.png" max-width= "400px" class="docs-image--right" >}} The Stackdriver query editor allows you to select metrics and group by multiple labels and use filter the results. Begin by choosing a `Service` and then a metric from the `Metric` dropdown. Use the plus and minus icons in the filter and group by sections to add/remove filters or group by clauses. Stackdriver metrics can be of different kinds (GAUGE, DELTA, CUMULATIVE) and these kinds have support for different aggregation options (reducers and aligners). The Grafana query editor shows the list of available aggregation methods for a selected metric and sets a default reducer and aligner when you select the metric. Units for the Y-axis are also automatically selected by the query editor. ### Filter To add a filter, click the plus icon and choose a field to filter by and enter a filter value e.g. `instance_name = grafana-1`. You can remove the filter by clicking on the filter name and select `--remove filter--`. #### Simple wildcards When the operator is set to `=` or `!=` it is possible to add wildcards to the filter value field. E.g `us-*` will capture all values that starts with "us-" and `*central-a` will capture all values that ends with "central-a". `*-central-*` captures all values that has the substring of -central-. Simple wildcards are less expensive than regular expressions. #### Regular expressions When the operator is set to `=~` or `!=~` it is possible to add regular expressions to the filter value field. E.g `us-central[1-3]-[af]` would match all values that starts with "us-central", is followed by a number in the range of 1 to 3, a dash and then either an "a" or an "f". Leading and trailing slashes are not needed when creating regular expressions. ### Aggregation The aggregation field lets you combine time series based on common statistics. Read more about this option [here](https://cloud.google.com/monitoring/charts/metrics-selector#aggregation-options). The `Aligner` field allows you to align multiple time series after the same group by time interval. Read more about how it works [here](https://cloud.google.com/monitoring/charts/metrics-selector#alignment). #### Alignment Period/Group by Time The `Alignment Period` groups a metric by time if an aggregation is chosen. The default is to use the GCP Stackdriver default groupings (which allows you to compare graphs in Grafana with graphs in the Stackdriver UI). The option is called `Stackdriver auto` and the defaults are: * 1m for time ranges < 23 hours * 5m for time ranges >= 23 hours and < 6 days * 1h for time ranges >= 6 days The other automatic option is `Grafana auto`. This will automatically set the group by time depending on the time range chosen and the width of the graph panel. Read more about the details [here](http://docs.grafana.org/reference/templating/#the-interval-variable). It is also possible to choose fixed time intervals to group by, like `1h` or `1d`. ### Group By Group by resource or metric labels to reduce the number of time series and to aggregate the results by a group by. E.g. Group by instance_name to see an aggregated metric for a Compute instance. ### Alias Patterns The Alias By field allows you to control the format of the legend keys. The default is to show the metric name and labels. This can be long and hard to read. Using the following patterns in the alias field, you can format the legend key the way you want it. #### Metric Type Patterns | Alias Pattern | Description | Example Result | | -------------------- | ---------------------------- | ------------------------------------------------- | | `{{metric.type}}` | returns the full Metric Type | `compute.googleapis.com/instance/cpu/utilization` | | `{{metric.name}}` | returns the metric name part | `instance/cpu/utilization` | | `{{metric.service}}` | returns the service part | `compute` | #### Label Patterns In the Group By dropdown, you can see a list of metric and resource labels for a metric. These can be included in the legend key using alias patterns. | Alias Pattern Format | Description | Alias Pattern Example | Example Result | | ------------------------ | -------------------------------- | -------------------------------- | ---------------- | | `{{metric.label.xxx}}` | returns the metric label value | `{{metric.label.instance_name}}` | `grafana-1-prod` | | `{{resource.label.xxx}}` | returns the resource label value | `{{resource.label.zone}}` | `us-east1-b` | Example Alias By: `{{metric.type}} - {{metric.labels.instance_name}}` Example Result: `compute.googleapis.com/instance/cpu/usage_time - server1-prod` ## Templating Instead of hard-coding things like server, application and sensor name in you metric queries you can use variables in their place. Variables are shown as dropdown select boxes at the top of the dashboard. These dropdowns makes it easy to change the data being displayed in your dashboard. Checkout the [Templating]({{< relref "reference/templating.md" >}}) documentation for an introduction to the templating feature and the different types of template variables. ### Query Variable Writing variable queries is not supported yet. ### Using variables in queries There are two syntaxes: * `$<varname>` Example: `metric.label.$metric_label` * `[[varname]]` Example: `metric.label.[[metric_label]]` Why two ways? The first syntax is easier to read and write but does not allow you to use a variable in the middle of a word. When the _Multi-value_ or _Include all value_ options are enabled, Grafana converts the labels from plain text to a regex compatible string, which means you have to use `=~` instead of `=`. ## Annotations {{< docs-imagebox img="/img/docs/v53/stackdriver_annotations_query_editor.png" max-width= "400px" class="docs-image--right" >}} [Annotations]({{< relref "reference/annotations.md" >}}) allows you to overlay rich event information on top of graphs. You add annotation queries via the Dashboard menu / Annotations view. Annotation rendering is expensive so it is important to limit the number of rows returned. There is no support for showing Stackdriver annotations and events yet but it works well with [custom metrics](https://cloud.google.com/monitoring/custom-metrics/) in Stackdriver. With the query editor for annotations, you can select a metric and filters. The `Title` and `Text` fields support templating and can use data returned from the query. For example, the Title field could have the following text: `{{metric.type}} has value: {{metric.value}}` Example Result: `monitoring.googleapis.com/uptime_check/http_status has this value: 502` ### Patterns for the Annotation Query Editor | Alias Pattern Format | Description | Alias Pattern Example | Example Result | | ------------------------ | -------------------------------- | -------------------------------- | ------------------------------------------------- | | `{{metric.value}}` | value of the metric/point | `{{metric.value}}` | `555` | | `{{metric.type}}` | returns the full Metric Type | `{{metric.type}}` | `compute.googleapis.com/instance/cpu/utilization` | | `{{metric.name}}` | returns the metric name part | `{{metric.name}}` | `instance/cpu/utilization` | | `{{metric.service}}` | returns the service part | `{{metric.service}}` | `compute` | | `{{metric.label.xxx}}` | returns the metric label value | `{{metric.label.instance_name}}` | `grafana-1-prod` | | `{{resource.label.xxx}}` | returns the resource label value | `{{resource.label.zone}}` | `us-east1-b` | ## Configure the Datasource with Provisioning It's now possible to configure datasources using config files with Grafana's provisioning system. You can read more about how it works and all the settings you can set for datasources on the [provisioning docs page](/administration/provisioning/#datasources) Here is a provisioning example for this datasource. ```yaml apiVersion: 1 datasources: - name: Stackdriver type: stackdriver access: proxy jsonData: tokenUri: https://oauth2.googleapis.com/token clientEmail: [email protected] secureJsonData: privateKey: | -----BEGIN PRIVATE KEY----- POSEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCb1u1Srw8ICYHS ... yA+23427282348234= -----END PRIVATE KEY----- ```
docs/sources/features/datasources/stackdriver.md
1
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.9764816164970398, 0.0452166423201561, 0.0001628116879146546, 0.00016852671978995204, 0.20323583483695984 ]
{ "id": 1, "code_window": [ "1. Navigate to the [APIs & Services Credentials page](https://console.cloud.google.com/apis/credentials).\n", "2. Click on the `Create credentials` dropdown/button and choose the `Service account key` option.\n", "\n", " ![Create service account button](/img/docs/v53/stackdriver_create_service_account_button.png)\n", "\n", "3. On the `Create service account key` page, choose key type `JSON`. Then in the `Service Account` dropdown, choose the `New service account` option:\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " {{< docs-imagebox img=\"/img/docs/v53/stackdriver_create_service_account_button.png\" class=\"docs-image--no-shadow\" caption=\"Create service account button\" >}}\n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 57 }
package ber import ( "errors" "io" ) func readHeader(reader io.Reader) (identifier Identifier, length int, read int, err error) { if i, c, err := readIdentifier(reader); err != nil { return Identifier{}, 0, read, err } else { identifier = i read += c } if l, c, err := readLength(reader); err != nil { return Identifier{}, 0, read, err } else { length = l read += c } // Validate length type with identifier (x.600, 8.1.3.2.a) if length == LengthIndefinite && identifier.TagType == TypePrimitive { return Identifier{}, 0, read, errors.New("indefinite length used with primitive type") } return identifier, length, read, nil }
vendor/gopkg.in/asn1-ber.v1/header.go
0
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.00016829757078085095, 0.00016680832777637988, 0.00016452647105325013, 0.0001676009560469538, 0.0000016383909269279684 ]
{ "id": 1, "code_window": [ "1. Navigate to the [APIs & Services Credentials page](https://console.cloud.google.com/apis/credentials).\n", "2. Click on the `Create credentials` dropdown/button and choose the `Service account key` option.\n", "\n", " ![Create service account button](/img/docs/v53/stackdriver_create_service_account_button.png)\n", "\n", "3. On the `Create service account key` page, choose key type `JSON`. Then in the `Service Account` dropdown, choose the `New service account` option:\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " {{< docs-imagebox img=\"/img/docs/v53/stackdriver_create_service_account_button.png\" class=\"docs-image--no-shadow\" caption=\"Create service account button\" >}}\n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 57 }
import '../history/history_srv'; import { versions, restore } from './history_mocks'; import { HistorySrv } from '../history/history_srv'; import { DashboardModel } from '../dashboard_model'; jest.mock('app/core/store'); describe('historySrv', () => { const versionsResponse = versions(); const restoreResponse = restore; const backendSrv = { get: jest.fn(() => Promise.resolve({})), post: jest.fn(() => Promise.resolve({})), }; let historySrv = new HistorySrv(backendSrv); const dash = new DashboardModel({ id: 1 }); const emptyDash = new DashboardModel({}); const historyListOpts = { limit: 10, start: 0 }; describe('getHistoryList', () => { it('should return a versions array for the given dashboard id', () => { backendSrv.get = jest.fn(() => Promise.resolve(versionsResponse)); historySrv = new HistorySrv(backendSrv); return historySrv.getHistoryList(dash, historyListOpts).then(versions => { expect(versions).toEqual(versionsResponse); }); }); it('should return an empty array when not given an id', () => { return historySrv.getHistoryList(emptyDash, historyListOpts).then(versions => { expect(versions).toEqual([]); }); }); it('should return an empty array when not given a dashboard', () => { return historySrv.getHistoryList(null, historyListOpts).then(versions => { expect(versions).toEqual([]); }); }); }); describe('restoreDashboard', () => { it('should return a success response given valid parameters', () => { const version = 6; backendSrv.post = jest.fn(() => Promise.resolve(restoreResponse(version))); historySrv = new HistorySrv(backendSrv); return historySrv.restoreDashboard(dash, version).then(response => { expect(response).toEqual(restoreResponse(version)); }); }); it('should return an empty object when not given an id', async () => { historySrv = new HistorySrv(backendSrv); const rsp = await historySrv.restoreDashboard(emptyDash, 6); expect(rsp).toEqual({}); }); }); });
public/app/features/dashboard/specs/history_srv.test.ts
0
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.00017240857414435595, 0.00017061557446140796, 0.0001689015480224043, 0.0001710321957943961, 0.0000011325934110573144 ]
{ "id": 1, "code_window": [ "1. Navigate to the [APIs & Services Credentials page](https://console.cloud.google.com/apis/credentials).\n", "2. Click on the `Create credentials` dropdown/button and choose the `Service account key` option.\n", "\n", " ![Create service account button](/img/docs/v53/stackdriver_create_service_account_button.png)\n", "\n", "3. On the `Create service account key` page, choose key type `JSON`. Then in the `Service Account` dropdown, choose the `New service account` option:\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " {{< docs-imagebox img=\"/img/docs/v53/stackdriver_create_service_account_button.png\" class=\"docs-image--no-shadow\" caption=\"Create service account button\" >}}\n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 57 }
/* Flot plugin for stacking data sets rather than overlyaing them. Copyright (c) 2007-2014 IOLA and Ole Laursen. Licensed under the MIT license. The plugin assumes the data is sorted on x (or y if stacking horizontally). For line charts, it is assumed that if a line has an undefined gap (from a null point), then the line above it should have the same gap - insert zeros instead of "null" if you want another behaviour. This also holds for the start and end of the chart. Note that stacking a mix of positive and negative values in most instances doesn't make sense (so it looks weird). Two or more series are stacked when their "stack" attribute is set to the same key (which can be any number or string or just "true"). To specify the default stack, you can set the stack option like this: series: { stack: null/false, true, or a key (number/string) } You can also specify it for a single series, like this: $.plot( $("#placeholder"), [{ data: [ ... ], stack: true }]) The stacking order is determined by the order of the data series in the array (later series end up on top of the previous). Internally, the plugin modifies the datapoints in each series, adding an offset to the y value. For line series, extra data points are inserted through interpolation. If there's a second y value, it's also adjusted (e.g for bar charts or filled areas). */ (function ($) { var options = { series: { stack: null } // or number/string }; function init(plot) { function findMatchingSeries(s, allseries) { var res = null; for (var i = 0; i < allseries.length; ++i) { if (s == allseries[i]) break; if (allseries[i].stack == s.stack) res = allseries[i]; } return res; } function stackData(plot, s, datapoints) { if (s.stack == null || s.stack === false) return; var other = findMatchingSeries(s, plot.getData()); if (!other) return; var ps = datapoints.pointsize, points = datapoints.points, otherps = other.datapoints.pointsize, otherpoints = other.datapoints.points, newpoints = [], px, py, intery, qx, qy, bottom, withlines = s.lines.show, horizontal = s.bars.horizontal, withbottom = ps > 2 && (horizontal ? datapoints.format[2].x : datapoints.format[2].y), withsteps = withlines && s.lines.steps, keyOffset = horizontal ? 1 : 0, accumulateOffset = horizontal ? 0 : 1, i = 0, j = 0, l, m; while (true) { if (i >= points.length && j >= otherpoints.length) break; l = newpoints.length; if (i < points.length && points[i] == null) { // copy gaps for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); i += ps; } else if (i >= points.length) { // take the remaining points from the previous series for (m = 0; m < ps; ++m) newpoints.push(otherpoints[j + m]); if (withbottom) newpoints[l + 2] = otherpoints[j + accumulateOffset]; j += otherps; } else if (j >= otherpoints.length) { // take the remaining points from the current series for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); i += ps; } else if (j < otherpoints.length && otherpoints[j] == null) { // ignore point j += otherps; } else { // cases where we actually got two points px = points[i + keyOffset]; py = points[i + accumulateOffset]; qx = otherpoints[j + keyOffset]; qy = otherpoints[j + accumulateOffset]; bottom = 0; if (px == qx) { for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); newpoints[l + accumulateOffset] += qy; bottom = qy; i += ps; j += otherps; } else if (px > qx) { // take the point from the previous series so that next series will correctly stack if (i == 0) { for (m = 0; m < ps; ++m) newpoints.push(otherpoints[j + m]); bottom = qy; } // we got past point below, might need to // insert interpolated extra point if (i > 0 && points[i - ps] != null) { intery = py + (points[i - ps + accumulateOffset] - py) * (qx - px) / (points[i - ps + keyOffset] - px); newpoints.push(qx); newpoints.push(intery + qy); for (m = 2; m < ps; ++m) newpoints.push(points[i + m]); bottom = qy; } j += otherps; } else { // px < qx for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); // we might be able to interpolate a point below, // this can give us a better y if (j > 0 && otherpoints[j - otherps] != null) bottom = qy + (otherpoints[j - otherps + accumulateOffset] - qy) * (px - qx) / (otherpoints[j - otherps + keyOffset] - qx); newpoints[l + accumulateOffset] += bottom; i += ps; } fromgap = false; if (l != newpoints.length && withbottom) newpoints[l + 2] = bottom; } // maintain the line steps invariant if (withsteps && l != newpoints.length && l > 0 && newpoints[l] != null && newpoints[l] != newpoints[l - ps] && newpoints[l + 1] != newpoints[l - ps + 1]) { for (m = 0; m < ps; ++m) newpoints[l + ps + m] = newpoints[l + m]; newpoints[l + 1] = newpoints[l - ps + 1]; } } datapoints.points = newpoints; } plot.hooks.processDatapoints.push(stackData); } $.plot.plugins.push({ init: init, options: options, name: 'stack', version: '1.2' }); })(jQuery);
public/vendor/flot/jquery.flot.stack.js
0
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.00018401900888420641, 0.00016992568271234632, 0.0001658887485973537, 0.00016864214558154345, 0.0000036823557820753194 ]
{ "id": 2, "code_window": [ "\n", "3. On the `Create service account key` page, choose key type `JSON`. Then in the `Service Account` dropdown, choose the `New service account` option:\n", "\n", " ![Create service account key](/img/docs/v53/stackdriver_create_service_account_key.png)\n", "\n", "4. Some new fields will appear. Fill in a name for the service account in the `Service account name` field and then choose the `Monitoring Viewer` role from the `Role` dropdown:\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " {{< docs-imagebox img=\"/img/docs/v53/stackdriver_create_service_account_key.png\" class=\"docs-image--no-shadow\" caption=\"Create service account key\" >}}\n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 61 }
+++ title = "Grafana documentation" description = "Guides, Installation & Feature Documentation" keywords = ["grafana", "installation", "documentation"] type = "docs" aliases = ["v1.1", "guides/reference/admin"] +++ # Grafana Documentation <h2>Installing Grafana</h2> <div class="nav-cards"> <a href="{{< relref "installation/debian.md" >}}" class="nav-cards__item nav-cards__item--install"> <div class="nav-cards__icon fa fa-linux"> </div> <h5>Installing on Linux</h5> </a> <a href="{{< relref "installation/mac.md" >}}" class="nav-cards__item nav-cards__item--install"> <div class="nav-cards__icon fa fa-apple"> </div> <h5>Installing on Mac OS X</h5> </a> <a href="{{< relref "installation/windows.md" >}}" class="nav-cards__item nav-cards__item--install"> <div class="nav-cards__icon fa fa-windows"> </div> <h5>Installing on Windows</h5> </a> <a href="https://grafana.com/cloud/grafana" class="nav-cards__item nav-cards__item--install"> <div class="nav-cards__icon fa fa-cloud"> </div> <h5>Grafana Cloud</h5> </a> <a href="https://grafana.com/grafana/download" class="nav-cards__item nav-cards__item--install"> <div class="nav-cards__icon fa fa-moon-o"> </div> <h5>Nightly Builds</h5> </a> <div class="nav-cards__item nav-cards__item--install"> <h5>For other platforms Read the <a href="{{< relref "project/building_from_source.md" >}}">build from source</a> instructions for more information.</h5> </div> </div> <h2>Guides</h2> <div class="nav-cards"> <a href="https://grafana.com/grafana" class="nav-cards__item nav-cards__item--guide"> <h4>What is Grafana?</h4> <p>Grafana feature highlights.</p> </a> <a href="{{< relref "installation/configuration.md" >}}" class="nav-cards__item nav-cards__item--guide"> <h4>Configure Grafana</h4> <p>Article on all the Grafana configuration and setup options.</p> </a> <a href="{{< relref "guides/getting_started.md" >}}" class="nav-cards__item nav-cards__item--guide"> <h4>Getting Started</h4> <p>A guide that walks you through the basics of using Grafana</p> </a> <a href="{{< relref "administration/provisioning.md" >}}" class="nav-cards__item nav-cards__item--guide"> <h4>Provisioning</h4> <p>A guide to help you automate your Grafana setup & configuration.</p> </a> <a href="{{< relref "guides/whats-new-in-v5-2.md" >}}" class="nav-cards__item nav-cards__item--guide"> <h4>What's new in v5.2</h4> <p>Article on all the new cool features and enhancements in v5.2</p> </a> <a href="{{< relref "tutorials/screencasts.md" >}}" class="nav-cards__item nav-cards__item--guide"> <h4>Screencasts</h4> <p>Video tutorials & guides</p> </a> </div> <h2>Data Source Guides</h2> <div class="nav-cards"> <a href="{{< relref "features/datasources/graphite.md" >}}" class="nav-cards__item nav-cards__item--ds"> <img src="/img/docs/logos/icon_graphite.svg" > <h5>Graphite</h5> </a> <a href="{{< relref "features/datasources/elasticsearch.md" >}}" class="nav-cards__item nav-cards__item--ds"> <img src="/img/docs/logos/icon_elasticsearch.svg" > <h5>Elasticsearch</h5> </a> <a href="{{< relref "features/datasources/influxdb.md" >}}" class="nav-cards__item nav-cards__item--ds"> <img src="/img/docs/logos/icon_influxdb.svg" > <h5>InfluxDB</h5> </a> <a href="{{< relref "features/datasources/prometheus.md" >}}" class="nav-cards__item nav-cards__item--ds"> <img src="/img/docs/logos/icon_prometheus.svg" > <h5>Prometheus</h5> </a> <a href="{{< relref "features/datasources/opentsdb.md" >}}" class="nav-cards__item nav-cards__item--ds"> <img src="/img/docs/logos/icon_opentsdb.png" > <h5>OpenTSDB</h5> </a> <a href="{{< relref "features/datasources/mysql.md" >}}" class="nav-cards__item nav-cards__item--ds"> <img src="/img/docs/logos/icon_mysql.png" > <h5>MySQL</h5> </a> <a href="{{< relref "features/datasources/postgres.md" >}}" class="nav-cards__item nav-cards__item--ds"> <img src="/img/docs/logos/icon_postgres.svg" > <h5>Postgres</h5> </a> <a href="{{< relref "features/datasources/cloudwatch.md" >}}" class="nav-cards__item nav-cards__item--ds"> <img src="/img/docs/logos/icon_cloudwatch.svg"> <h5>Cloudwatch</h5> </a> <a href="{{< relref "features/datasources/mssql.md" >}}" class="nav-cards__item nav-cards__item--ds"> <img src="/img/docs/logos/sql_server_logo.svg"> <h5>Microsoft SQL Server</h5> </a> <a href="{{< relref "features/datasources/stackdriver.md" >}}" class="nav-cards__item nav-cards__item--ds"> <img src="/img/docs/logos/stackdriver_logo.png"> <h5>Google Stackdriver</h5> </a> </div>
docs/sources/index.md
1
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.0001747448113746941, 0.0001733073004288599, 0.00017212654347531497, 0.00017331670096609741, 8.704295169081888e-7 ]
{ "id": 2, "code_window": [ "\n", "3. On the `Create service account key` page, choose key type `JSON`. Then in the `Service Account` dropdown, choose the `New service account` option:\n", "\n", " ![Create service account key](/img/docs/v53/stackdriver_create_service_account_key.png)\n", "\n", "4. Some new fields will appear. Fill in a name for the service account in the `Service account name` field and then choose the `Monitoring Viewer` role from the `Role` dropdown:\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " {{< docs-imagebox img=\"/img/docs/v53/stackdriver_create_service_account_key.png\" class=\"docs-image--no-shadow\" caption=\"Create service account key\" >}}\n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 61 }
package dtos type PlaylistDashboard struct { Id int64 `json:"id"` Slug string `json:"slug"` Title string `json:"title"` Uri string `json:"uri"` Order int `json:"order"` } type PlaylistDashboardsSlice []PlaylistDashboard func (slice PlaylistDashboardsSlice) Len() int { return len(slice) } func (slice PlaylistDashboardsSlice) Less(i, j int) bool { return slice[i].Order < slice[j].Order } func (slice PlaylistDashboardsSlice) Swap(i, j int) { slice[i], slice[j] = slice[j], slice[i] }
pkg/api/dtos/playlist.go
0
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.0001713328529149294, 0.00016928039258345962, 0.00016746293113101274, 0.00016904542280826718, 0.0000015886021174082998 ]
{ "id": 2, "code_window": [ "\n", "3. On the `Create service account key` page, choose key type `JSON`. Then in the `Service Account` dropdown, choose the `New service account` option:\n", "\n", " ![Create service account key](/img/docs/v53/stackdriver_create_service_account_key.png)\n", "\n", "4. Some new fields will appear. Fill in a name for the service account in the `Service account name` field and then choose the `Monitoring Viewer` role from the `Role` dropdown:\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " {{< docs-imagebox img=\"/img/docs/v53/stackdriver_create_service_account_key.png\" class=\"docs-image--no-shadow\" caption=\"Create service account key\" >}}\n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 61 }
.editor-row { vertical-align: top; } .section { margin-right: 3rem; vertical-align: top; display: inline-block; } div.editor-option { vertical-align: top; display: inline-block; margin-right: 10px; } div.editor-option label { display: block; }
public/sass/components/_old_stuff.scss
0
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.0001723469322314486, 0.00017189914069604129, 0.00017145134916063398, 0.00017189914069604129, 4.4779153540730476e-7 ]
{ "id": 2, "code_window": [ "\n", "3. On the `Create service account key` page, choose key type `JSON`. Then in the `Service Account` dropdown, choose the `New service account` option:\n", "\n", " ![Create service account key](/img/docs/v53/stackdriver_create_service_account_key.png)\n", "\n", "4. Some new fields will appear. Fill in a name for the service account in the `Service account name` field and then choose the `Monitoring Viewer` role from the `Role` dropdown:\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " {{< docs-imagebox img=\"/img/docs/v53/stackdriver_create_service_account_key.png\" class=\"docs-image--no-shadow\" caption=\"Create service account key\" >}}\n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 61 }
// cgo -godefs types_darwin.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,darwin package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int32 _ [4]byte } type Timeval32 struct { Sec int32 Usec int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev int32 Mode uint16 Nlink uint16 Ino uint64 Uid uint32 Gid uint32 Rdev int32 _ [4]byte Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Birthtimespec Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 Lspare int32 Qspare [2]int64 } type Statfs_t struct { Bsize uint32 Iosize int32 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Owner uint32 Type uint32 Flags uint32 Fssubtype uint32 Fstypename [16]int8 Mntonname [1024]int8 Mntfromname [1024]int8 Reserved [8]uint32 } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Fstore_t struct { Flags uint32 Posmode int32 Offset int64 Length int64 Bytesalloc int64 } type Radvisory_t struct { Offset int64 Count int32 _ [4]byte } type Fbootstraptransfer_t struct { Offset int64 Length uint64 Buffer *byte } type Log2phys_t struct { Flags uint32 _ [8]byte _ [8]byte } type Fsid struct { Val [2]int32 } type Dirent struct { Ino uint64 Seekoff uint64 Reclen uint16 Namlen uint16 Type uint8 Name [1024]int8 _ [3]byte } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 _ [4]byte Iov *Iovec Iovlen int32 _ [4]byte Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex uint32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x14 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x30 SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint64 Filter int16 Flags uint16 Fflags uint32 Data int64 Udata *byte } type FdSet struct { Bits [32]int32 } const ( SizeofIfMsghdr = 0x70 SizeofIfData = 0x60 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfmaMsghdr2 = 0x14 SizeofRtMsghdr = 0x5c SizeofRtMetrics = 0x38 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Data IfData } type IfData struct { Type uint8 Typelen uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Recvquota uint8 Xmitquota uint8 Unused1 uint8 Mtu uint32 Metric uint32 Baudrate uint32 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Recvtiming uint32 Xmittiming uint32 Lastchange Timeval32 Unused2 uint32 Hwassist uint32 Reserved1 uint32 Reserved2 uint32 } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte } type IfmaMsghdr2 struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Refcount int32 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 _ [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Hopcount uint32 Expire int32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pksent uint32 Filler [4]uint32 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfProgram = 0x10 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfProgram struct { Len uint32 _ [4]byte Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval32 Caplen uint32 Datalen uint32 Hdrlen uint16 _ [2]byte } type Termios struct { Iflag uint64 Oflag uint64 Cflag uint64 Lflag uint64 Cc [20]uint8 _ [4]byte Ispeed uint64 Ospeed uint64 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } const ( AT_FDCWD = -0x2 AT_REMOVEDIR = 0x80 AT_SYMLINK_FOLLOW = 0x40 AT_SYMLINK_NOFOLLOW = 0x20 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLERR = 0x8 POLLHUP = 0x10 POLLIN = 0x1 POLLNVAL = 0x20 POLLOUT = 0x4 POLLPRI = 0x2 POLLRDBAND = 0x80 POLLRDNORM = 0x40 POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) type Utsname struct { Sysname [256]byte Nodename [256]byte Release [256]byte Version [256]byte Machine [256]byte }
vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go
0
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.00018563187040854245, 0.00016976414190139621, 0.0001640336704440415, 0.00016908347606658936, 0.000003975625531893456 ]
{ "id": 3, "code_window": [ "\n", "4. Some new fields will appear. Fill in a name for the service account in the `Service account name` field and then choose the `Monitoring Viewer` role from the `Role` dropdown:\n", "\n", " ![Choose role](/img/docs/v53/stackdriver_service_account_choose_role.png)\n", "\n", "5. Click the Create button. A JSON key file will be created and downloaded to your computer. Store this file in a secure place as it allows access to your Stackdriver data.\n", "6. Upload it to Grafana on the datasource Configuration page. You can either upload the file or paste in the contents of the file.\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " {{< docs-imagebox img=\"/img/docs/v53/stackdriver_service_account_choose_role.png\" class=\"docs-image--no-shadow\" caption=\"Choose role\" >}}\n", " \n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 65 }
+++ title = "Using Stackdriver in Grafana" description = "Guide for using Stackdriver in Grafana" keywords = ["grafana", "stackdriver", "google", "guide"] type = "docs" aliases = ["/datasources/stackdriver"] [menu.docs] name = "Stackdriver" parent = "datasources" weight = 11 +++ # Using Google Stackdriver in Grafana > Only available in Grafana v5.3+. > The datasource is currently a beta feature and is subject to change. Grafana ships with built-in support for Google Stackdriver. Just add it as a datasource and you are ready to build dashboards for your Stackdriver metrics. ## Adding the data source to Grafana 1. Open the side menu by clicking the Grafana icon in the top header. 2. In the side menu under the `Dashboards` link you should find a link named `Data Sources`. 3. Click the `+ Add data source` button in the top header. 4. Select `Stackdriver` from the _Type_ dropdown. 5. Upload or paste in the Service Account Key file. See below for steps on how to create a Service Account Key file. > NOTE: If you're not seeing the `Data Sources` link in your side menu it means that your current user does not have the `Admin` role for the current organization. | Name | Description | | --------------------- | ----------------------------------------------------------------------------------- | | _Name_ | The datasource name. This is how you refer to the datasource in panels & queries. | | _Default_ | Default datasource means that it will be pre-selected for new panels. | | _Service Account Key_ | Service Account Key File for a GCP Project. Instructions below on how to create it. | ## Authentication ### Service Account Credentials - Private Key File To authenticate with the Stackdriver API, you need to create a Google Cloud Platform (GCP) Service Account for the Project you want to show data for. A Grafana datasource integrates with one GCP Project. If you want to visualize data from multiple GCP Projects then you need to create one datasource per GCP Project. #### Enable APIs The following APIs need to be enabled first: * [Monitoring API](https://console.cloud.google.com/apis/library/monitoring.googleapis.com) * [Cloud Resource Manager API](https://console.cloud.google.com/apis/library/cloudresourcemanager.googleapis.com) Click on the links above and click the `Enable` button: ![Enable GCP APIs](/img/docs/v53/stackdriver_enable_api.png) #### Create a GCP Service Account for a Project 1. Navigate to the [APIs & Services Credentials page](https://console.cloud.google.com/apis/credentials). 2. Click on the `Create credentials` dropdown/button and choose the `Service account key` option. ![Create service account button](/img/docs/v53/stackdriver_create_service_account_button.png) 3. On the `Create service account key` page, choose key type `JSON`. Then in the `Service Account` dropdown, choose the `New service account` option: ![Create service account key](/img/docs/v53/stackdriver_create_service_account_key.png) 4. Some new fields will appear. Fill in a name for the service account in the `Service account name` field and then choose the `Monitoring Viewer` role from the `Role` dropdown: ![Choose role](/img/docs/v53/stackdriver_service_account_choose_role.png) 5. Click the Create button. A JSON key file will be created and downloaded to your computer. Store this file in a secure place as it allows access to your Stackdriver data. 6. Upload it to Grafana on the datasource Configuration page. You can either upload the file or paste in the contents of the file. ![Choose role](/img/docs/v53/stackdriver_grafana_upload_key.png) 7. The file contents will be encrypted and saved in the Grafana database. Don't forget to save after uploading the file! ![Choose role](/img/docs/v53/stackdriver_grafana_key_uploaded.png) ## Metric Query Editor {{< docs-imagebox img="/img/docs/v53/stackdriver_query_editor.png" max-width= "400px" class="docs-image--right" >}} The Stackdriver query editor allows you to select metrics and group by multiple labels and use filter the results. Begin by choosing a `Service` and then a metric from the `Metric` dropdown. Use the plus and minus icons in the filter and group by sections to add/remove filters or group by clauses. Stackdriver metrics can be of different kinds (GAUGE, DELTA, CUMULATIVE) and these kinds have support for different aggregation options (reducers and aligners). The Grafana query editor shows the list of available aggregation methods for a selected metric and sets a default reducer and aligner when you select the metric. Units for the Y-axis are also automatically selected by the query editor. ### Filter To add a filter, click the plus icon and choose a field to filter by and enter a filter value e.g. `instance_name = grafana-1`. You can remove the filter by clicking on the filter name and select `--remove filter--`. #### Simple wildcards When the operator is set to `=` or `!=` it is possible to add wildcards to the filter value field. E.g `us-*` will capture all values that starts with "us-" and `*central-a` will capture all values that ends with "central-a". `*-central-*` captures all values that has the substring of -central-. Simple wildcards are less expensive than regular expressions. #### Regular expressions When the operator is set to `=~` or `!=~` it is possible to add regular expressions to the filter value field. E.g `us-central[1-3]-[af]` would match all values that starts with "us-central", is followed by a number in the range of 1 to 3, a dash and then either an "a" or an "f". Leading and trailing slashes are not needed when creating regular expressions. ### Aggregation The aggregation field lets you combine time series based on common statistics. Read more about this option [here](https://cloud.google.com/monitoring/charts/metrics-selector#aggregation-options). The `Aligner` field allows you to align multiple time series after the same group by time interval. Read more about how it works [here](https://cloud.google.com/monitoring/charts/metrics-selector#alignment). #### Alignment Period/Group by Time The `Alignment Period` groups a metric by time if an aggregation is chosen. The default is to use the GCP Stackdriver default groupings (which allows you to compare graphs in Grafana with graphs in the Stackdriver UI). The option is called `Stackdriver auto` and the defaults are: * 1m for time ranges < 23 hours * 5m for time ranges >= 23 hours and < 6 days * 1h for time ranges >= 6 days The other automatic option is `Grafana auto`. This will automatically set the group by time depending on the time range chosen and the width of the graph panel. Read more about the details [here](http://docs.grafana.org/reference/templating/#the-interval-variable). It is also possible to choose fixed time intervals to group by, like `1h` or `1d`. ### Group By Group by resource or metric labels to reduce the number of time series and to aggregate the results by a group by. E.g. Group by instance_name to see an aggregated metric for a Compute instance. ### Alias Patterns The Alias By field allows you to control the format of the legend keys. The default is to show the metric name and labels. This can be long and hard to read. Using the following patterns in the alias field, you can format the legend key the way you want it. #### Metric Type Patterns | Alias Pattern | Description | Example Result | | -------------------- | ---------------------------- | ------------------------------------------------- | | `{{metric.type}}` | returns the full Metric Type | `compute.googleapis.com/instance/cpu/utilization` | | `{{metric.name}}` | returns the metric name part | `instance/cpu/utilization` | | `{{metric.service}}` | returns the service part | `compute` | #### Label Patterns In the Group By dropdown, you can see a list of metric and resource labels for a metric. These can be included in the legend key using alias patterns. | Alias Pattern Format | Description | Alias Pattern Example | Example Result | | ------------------------ | -------------------------------- | -------------------------------- | ---------------- | | `{{metric.label.xxx}}` | returns the metric label value | `{{metric.label.instance_name}}` | `grafana-1-prod` | | `{{resource.label.xxx}}` | returns the resource label value | `{{resource.label.zone}}` | `us-east1-b` | Example Alias By: `{{metric.type}} - {{metric.labels.instance_name}}` Example Result: `compute.googleapis.com/instance/cpu/usage_time - server1-prod` ## Templating Instead of hard-coding things like server, application and sensor name in you metric queries you can use variables in their place. Variables are shown as dropdown select boxes at the top of the dashboard. These dropdowns makes it easy to change the data being displayed in your dashboard. Checkout the [Templating]({{< relref "reference/templating.md" >}}) documentation for an introduction to the templating feature and the different types of template variables. ### Query Variable Writing variable queries is not supported yet. ### Using variables in queries There are two syntaxes: * `$<varname>` Example: `metric.label.$metric_label` * `[[varname]]` Example: `metric.label.[[metric_label]]` Why two ways? The first syntax is easier to read and write but does not allow you to use a variable in the middle of a word. When the _Multi-value_ or _Include all value_ options are enabled, Grafana converts the labels from plain text to a regex compatible string, which means you have to use `=~` instead of `=`. ## Annotations {{< docs-imagebox img="/img/docs/v53/stackdriver_annotations_query_editor.png" max-width= "400px" class="docs-image--right" >}} [Annotations]({{< relref "reference/annotations.md" >}}) allows you to overlay rich event information on top of graphs. You add annotation queries via the Dashboard menu / Annotations view. Annotation rendering is expensive so it is important to limit the number of rows returned. There is no support for showing Stackdriver annotations and events yet but it works well with [custom metrics](https://cloud.google.com/monitoring/custom-metrics/) in Stackdriver. With the query editor for annotations, you can select a metric and filters. The `Title` and `Text` fields support templating and can use data returned from the query. For example, the Title field could have the following text: `{{metric.type}} has value: {{metric.value}}` Example Result: `monitoring.googleapis.com/uptime_check/http_status has this value: 502` ### Patterns for the Annotation Query Editor | Alias Pattern Format | Description | Alias Pattern Example | Example Result | | ------------------------ | -------------------------------- | -------------------------------- | ------------------------------------------------- | | `{{metric.value}}` | value of the metric/point | `{{metric.value}}` | `555` | | `{{metric.type}}` | returns the full Metric Type | `{{metric.type}}` | `compute.googleapis.com/instance/cpu/utilization` | | `{{metric.name}}` | returns the metric name part | `{{metric.name}}` | `instance/cpu/utilization` | | `{{metric.service}}` | returns the service part | `{{metric.service}}` | `compute` | | `{{metric.label.xxx}}` | returns the metric label value | `{{metric.label.instance_name}}` | `grafana-1-prod` | | `{{resource.label.xxx}}` | returns the resource label value | `{{resource.label.zone}}` | `us-east1-b` | ## Configure the Datasource with Provisioning It's now possible to configure datasources using config files with Grafana's provisioning system. You can read more about how it works and all the settings you can set for datasources on the [provisioning docs page](/administration/provisioning/#datasources) Here is a provisioning example for this datasource. ```yaml apiVersion: 1 datasources: - name: Stackdriver type: stackdriver access: proxy jsonData: tokenUri: https://oauth2.googleapis.com/token clientEmail: [email protected] secureJsonData: privateKey: | -----BEGIN PRIVATE KEY----- POSEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCb1u1Srw8ICYHS ... yA+23427282348234= -----END PRIVATE KEY----- ```
docs/sources/features/datasources/stackdriver.md
1
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.9975807666778564, 0.04586680978536606, 0.00016259138647001237, 0.00018380879191681743, 0.2076827585697174 ]
{ "id": 3, "code_window": [ "\n", "4. Some new fields will appear. Fill in a name for the service account in the `Service account name` field and then choose the `Monitoring Viewer` role from the `Role` dropdown:\n", "\n", " ![Choose role](/img/docs/v53/stackdriver_service_account_choose_role.png)\n", "\n", "5. Click the Create button. A JSON key file will be created and downloaded to your computer. Store this file in a secure place as it allows access to your Stackdriver data.\n", "6. Upload it to Grafana on the datasource Configuration page. You can either upload the file or paste in the contents of the file.\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " {{< docs-imagebox img=\"/img/docs/v53/stackdriver_service_account_choose_role.png\" class=\"docs-image--no-shadow\" caption=\"Choose role\" >}}\n", " \n" ], "file_path": "docs/sources/features/datasources/stackdriver.md", "type": "replace", "edit_start_line_idx": 65 }
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build s390x package crc32 const ( vxMinLen = 64 vxAlignMask = 15 // align to 16 bytes ) // hasVectorFacility reports whether the machine has the z/Architecture // vector facility installed and enabled. func hasVectorFacility() bool var hasVX = hasVectorFacility() // vectorizedCastagnoli implements CRC32 using vector instructions. // It is defined in crc32_s390x.s. //go:noescape func vectorizedCastagnoli(crc uint32, p []byte) uint32 // vectorizedIEEE implements CRC32 using vector instructions. // It is defined in crc32_s390x.s. //go:noescape func vectorizedIEEE(crc uint32, p []byte) uint32 func archAvailableCastagnoli() bool { return hasVX } var archCastagnoliTable8 *slicing8Table func archInitCastagnoli() { if !hasVX { panic("not available") } // We still use slicing-by-8 for small buffers. archCastagnoliTable8 = slicingMakeTable(Castagnoli) } // archUpdateCastagnoli calculates the checksum of p using // vectorizedCastagnoli. func archUpdateCastagnoli(crc uint32, p []byte) uint32 { if !hasVX { panic("not available") } // Use vectorized function if data length is above threshold. if len(p) >= vxMinLen { aligned := len(p) & ^vxAlignMask crc = vectorizedCastagnoli(crc, p[:aligned]) p = p[aligned:] } if len(p) == 0 { return crc } return slicingUpdate(crc, archCastagnoliTable8, p) } func archAvailableIEEE() bool { return hasVX } var archIeeeTable8 *slicing8Table func archInitIEEE() { if !hasVX { panic("not available") } // We still use slicing-by-8 for small buffers. archIeeeTable8 = slicingMakeTable(IEEE) } // archUpdateIEEE calculates the checksum of p using vectorizedIEEE. func archUpdateIEEE(crc uint32, p []byte) uint32 { if !hasVX { panic("not available") } // Use vectorized function if data length is above threshold. if len(p) >= vxMinLen { aligned := len(p) & ^vxAlignMask crc = vectorizedIEEE(crc, p[:aligned]) p = p[aligned:] } if len(p) == 0 { return crc } return slicingUpdate(crc, archIeeeTable8, p) }
vendor/github.com/klauspost/crc32/crc32_s390x.go
0
https://github.com/grafana/grafana/commit/03fefd7beaa322ea4fbfb2cb0aa2f8bc3d5dd6ff
[ 0.00017399580974597484, 0.0001697978877928108, 0.00016523267549928278, 0.00016891775885596871, 0.000002592910732346354 ]