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": 7, "code_window": [ "var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules')\n", "var fs = require('fs')\n", "if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) {\n", " // Resolve Redux to source\n", " module.exports.resolve = { alias: { 'redux': reduxSrc } }\n", " // Compile Redux from source\n", " module.exports.module.loaders.push({\n", " test: /\\.js$/,\n", " loaders: [ 'babel' ],\n", " include: reduxSrc\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Our root .babelrc needs this flag for CommonJS output\n", " process.env.BABEL_ENV = 'commonjs'\n" ], "file_path": "examples/tree-view/webpack.config.js", "type": "add", "edit_start_line_idx": 40 }
<!DOCTYPE html> <html> <head> <title>Redux tree-view example</title> </head> <body> <div id="root"> </div> <script src="/static/bundle.js"></script> </body> </html>
examples/tree-view/index.html
0
https://github.com/reduxjs/redux/commit/872f2314838f44da9ff6dcbd5ad09f78bec5dbd6
[ 0.0001681373396422714, 0.00016706748283468187, 0.00016599762602709234, 0.00016706748283468187, 0.000001069856807589531 ]
{ "id": 7, "code_window": [ "var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules')\n", "var fs = require('fs')\n", "if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) {\n", " // Resolve Redux to source\n", " module.exports.resolve = { alias: { 'redux': reduxSrc } }\n", " // Compile Redux from source\n", " module.exports.module.loaders.push({\n", " test: /\\.js$/,\n", " loaders: [ 'babel' ],\n", " include: reduxSrc\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Our root .babelrc needs this flag for CommonJS output\n", " process.env.BABEL_ENV = 'commonjs'\n" ], "file_path": "examples/tree-view/webpack.config.js", "type": "add", "edit_start_line_idx": 40 }
import { createStore, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import rootReducer from '../reducers' export default function configureStore(initialState) { const store = createStore( rootReducer, initialState, applyMiddleware(thunk) ) if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextRootReducer = require('../reducers').default store.replaceReducer(nextRootReducer) }) } return store }
examples/universal/common/store/configureStore.js
0
https://github.com/reduxjs/redux/commit/872f2314838f44da9ff6dcbd5ad09f78bec5dbd6
[ 0.00022414779232349247, 0.00018598604947328568, 0.00016683322610333562, 0.00016697710088919848, 0.00002698449679883197 ]
{ "id": 8, "code_window": [ "var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules')\n", "var fs = require('fs')\n", "if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) {\n", " // Resolve Redux to source\n", " module.exports.resolve = { alias: { 'redux': reduxSrc } }\n", " // Compile Redux from source\n", " module.exports.module.loaders.push({\n", " test: /\\.js$/,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // Our root .babelrc needs this flag for CommonJS output\n", " process.env.BABEL_ENV = 'commonjs'\n" ], "file_path": "examples/universal/webpack.config.js", "type": "add", "edit_start_line_idx": 42 }
var path = require('path') var webpack = require('webpack') module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-hot-middleware/client', './index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [ { test: /\.js$/, loaders: ['babel'], exclude: /node_modules/, include: __dirname } ] } } // When inside Redux repo, prefer src to compiled version. // You can safely delete these lines in your project. var reduxSrc = path.join(__dirname, '..', '..', 'src') var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules') var fs = require('fs') if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) { // Resolve Redux to source module.exports.resolve = { alias: { 'redux': reduxSrc } } // Compile Redux from source module.exports.module.loaders.push({ test: /\.js$/, loaders: ['babel'], include: reduxSrc }) }
examples/async/webpack.config.js
1
https://github.com/reduxjs/redux/commit/872f2314838f44da9ff6dcbd5ad09f78bec5dbd6
[ 0.9984843134880066, 0.2236570417881012, 0.0002523702569305897, 0.0025004607159644365, 0.38999342918395996 ]
{ "id": 8, "code_window": [ "var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules')\n", "var fs = require('fs')\n", "if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) {\n", " // Resolve Redux to source\n", " module.exports.resolve = { alias: { 'redux': reduxSrc } }\n", " // Compile Redux from source\n", " module.exports.module.loaders.push({\n", " test: /\\.js$/,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // Our root .babelrc needs this flag for CommonJS output\n", " process.env.BABEL_ENV = 'commonjs'\n" ], "file_path": "examples/universal/webpack.config.js", "type": "add", "edit_start_line_idx": 42 }
# Contributor Code of Conduct As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion. Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
CODE_OF_CONDUCT.md
0
https://github.com/reduxjs/redux/commit/872f2314838f44da9ff6dcbd5ad09f78bec5dbd6
[ 0.00017509509052615613, 0.00017290274263359606, 0.00017071040929295123, 0.00017290274263359606, 0.0000021923406166024506 ]
{ "id": 8, "code_window": [ "var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules')\n", "var fs = require('fs')\n", "if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) {\n", " // Resolve Redux to source\n", " module.exports.resolve = { alias: { 'redux': reduxSrc } }\n", " // Compile Redux from source\n", " module.exports.module.loaders.push({\n", " test: /\\.js$/,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // Our root .babelrc needs this flag for CommonJS output\n", " process.env.BABEL_ENV = 'commonjs'\n" ], "file_path": "examples/universal/webpack.config.js", "type": "add", "edit_start_line_idx": 42 }
# Async Flow Without [middleware](Middleware.md), Redux store only supports [synchronous data flow](../basics/DataFlow.md). This is what you get by default with [`createStore()`](../api/createStore.md). You may enhance [`createStore()`](../api/createStore.md) with [`applyMiddleware()`](../api/applyMiddleware.md). It is not required, but it lets you [express asynchronous actions in a convenient way](AsyncActions.md). Asynchronous middleware like [redux-thunk](https://github.com/gaearon/redux-thunk) or [redux-promise](https://github.com/acdlite/redux-promise) wraps the store’s [`dispatch()`](../api/Store.md#dispatch) method and allows you to dispatch something other than actions, for example, functions or Promises. Any middleware you use can then interpret anything you dispatch, and in turn, can pass actions to the next middleware in chain. For example, a Promise middleware can intercept Promises and dispatch a pair of begin/end actions asynchronously in response to each Promise. When the last middleware in the chain dispatches an action, it has to be a plain object. This is when the [synchronous Redux data flow](../basics/DataFlow.md) takes place. Check out [the full source code for the async example](ExampleRedditAPI.md). ## Next Steps Now you saw an example of what middleware can do in Redux, it’s time to learn how it actually works, and how you can create your own. Go on to the next detailed section about [Middleware](Middleware.md).
docs/advanced/AsyncFlow.md
0
https://github.com/reduxjs/redux/commit/872f2314838f44da9ff6dcbd5ad09f78bec5dbd6
[ 0.00022995637846179307, 0.00019467435777187347, 0.0001593923516338691, 0.00019467435777187347, 0.00003528201341396198 ]
{ "id": 8, "code_window": [ "var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules')\n", "var fs = require('fs')\n", "if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) {\n", " // Resolve Redux to source\n", " module.exports.resolve = { alias: { 'redux': reduxSrc } }\n", " // Compile Redux from source\n", " module.exports.module.loaders.push({\n", " test: /\\.js$/,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // Our root .babelrc needs this flag for CommonJS output\n", " process.env.BABEL_ENV = 'commonjs'\n" ], "file_path": "examples/universal/webpack.config.js", "type": "add", "edit_start_line_idx": 42 }
var webpack = require('webpack') var webpackDevMiddleware = require('webpack-dev-middleware') var webpackHotMiddleware = require('webpack-hot-middleware') var config = require('./webpack.config') var app = new (require('express'))() var port = 3000 var compiler = webpack(config) app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })) app.use(webpackHotMiddleware(compiler)) app.get("/", function(req, res) { res.sendFile(__dirname + '/index.html') }) app.listen(port, function(error) { if (error) { console.error(error) } else { console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port) } })
examples/todos/server.js
0
https://github.com/reduxjs/redux/commit/872f2314838f44da9ff6dcbd5ad09f78bec5dbd6
[ 0.00017254998965654522, 0.00016821610915940255, 0.00016434771532658488, 0.00016775060794316232, 0.0000033647031614236766 ]
{ "id": 0, "code_window": [ " data.tables.reduce<Record<string, [ReturnType<typeof fieldRequiredValidator>]>>((acc: Record<string, any>, table, tableIdx) => {\n", " acc[`tables.${tableIdx}.table_name`] = [validateTableName]\n", " hasSelectColumn.value[tableIdx] = false\n", "\n", " table.columns?.forEach((column, columnIdx) => {\n", " acc[`tables.${tableIdx}.columns.${columnIdx}.column_name`] = [\n", " fieldRequiredValidator(),\n", " fieldLengthValidator(),\n", " ]\n", " acc[`tables.${tableIdx}.columns.${columnIdx}.uidt`] = [fieldRequiredValidator()]\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " acc[`tables.${tableIdx}.columns.${columnIdx}.title`] = [\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 133 }
<script setup lang="ts"> import dayjs from 'dayjs' import utc from 'dayjs/plugin/utc' import type { ColumnType, TableType } from 'nocodb-sdk' import { UITypes, isSystemColumn, isVirtualCol } from 'nocodb-sdk' import type { CheckboxChangeEvent } from 'ant-design-vue/es/checkbox/interface' import { srcDestMappingColumns, tableColumns } from './utils' import { Empty, Form, ImportWorkerOperations, ImportWorkerResponse, MetaInj, ReloadViewDataHookInj, TabType, computed, createEventHook, extractSdkResponseErrorMsg, fieldLengthValidator, fieldRequiredValidator, getDateFormat, getDateTimeFormat, getUIDTIcon, iconMap, inject, message, nextTick, onMounted, parseStringDate, reactive, ref, storeToRefs, useBase, useI18n, useNuxtApp, useTabs, validateTableName, } from '#imports' const { quickImportType, baseTemplate, importData, importColumns, importDataOnly, maxRowsToParse, sourceId, importWorker } = defineProps<Props>() const emit = defineEmits(['import', 'error', 'change']) dayjs.extend(utc) const { t } = useI18n() interface Props { quickImportType: 'csv' | 'excel' | 'json' baseTemplate: Record<string, any> importData: Record<string, any> importColumns: any[] importDataOnly: boolean maxRowsToParse: number sourceId: string importWorker: Worker } interface Option { label: string value: string } const meta = inject(MetaInj, ref()) const columns = computed(() => meta.value?.columns || []) const reloadHook = inject(ReloadViewDataHookInj, createEventHook()) const useForm = Form.useForm const { $api } = useNuxtApp() const { addTab } = useTabs() const baseStrore = useBase() const { loadTables } = baseStrore const { sqlUis, base } = storeToRefs(baseStrore) const { openTable } = useTablesStore() const { baseTables } = storeToRefs(useTablesStore()) const sqlUi = ref(sqlUis.value[sourceId] || Object.values(sqlUis.value)[0]) const hasSelectColumn = ref<boolean[]>([]) const expansionPanel = ref<number[]>([]) const editableTn = ref<boolean[]>([]) const inputRefs = ref<HTMLInputElement[]>([]) const isImporting = ref(false) const importingTips = ref<Record<string, string>>({}) const checkAllRecord = ref<boolean[]>([]) const formError = ref() const uiTypeOptions = ref<Option[]>( (Object.keys(UITypes) as (keyof typeof UITypes)[]) .filter( (uiType) => !isVirtualCol(UITypes[uiType]) && ![UITypes.ForeignKey, UITypes.ID, UITypes.CreateTime, UITypes.LastModifiedTime, UITypes.Barcode, UITypes.Button].includes( UITypes[uiType], ), ) .map<Option>((uiType) => ({ value: uiType, label: uiType, })), ) const srcDestMapping = ref<Record<string, Record<string, any>[]>>({}) const data = reactive<{ title: string | null name: string tables: (TableType & { ref_table_name: string; columns: (ColumnType & { key: number; _disableSelect?: boolean })[] })[] }>({ title: null, name: 'Base Name', tables: [], }) const validators = computed(() => data.tables.reduce<Record<string, [ReturnType<typeof fieldRequiredValidator>]>>((acc: Record<string, any>, table, tableIdx) => { acc[`tables.${tableIdx}.table_name`] = [validateTableName] hasSelectColumn.value[tableIdx] = false table.columns?.forEach((column, columnIdx) => { acc[`tables.${tableIdx}.columns.${columnIdx}.column_name`] = [ fieldRequiredValidator(), fieldLengthValidator(), ] acc[`tables.${tableIdx}.columns.${columnIdx}.uidt`] = [fieldRequiredValidator()] if (isSelect(column)) { hasSelectColumn.value[tableIdx] = true } }) return acc }, {}), ) const { validate, validateInfos, modelRef } = useForm(data, validators) const isValid = ref(!importDataOnly) const formRef = ref() watch( () => srcDestMapping.value, () => { let res = true if (importDataOnly) { for (const tn of Object.keys(srcDestMapping.value)) { if (!atLeastOneEnabledValidation(tn)) { res = false } for (const record of srcDestMapping.value[tn]) { if (!fieldsValidation(record, tn)) { return false } } } } else { for (const [_, o] of Object.entries(validateInfos)) { if (o?.validateStatus) { if (o.validateStatus === 'error') { res = false } } } } isValid.value = res }, { deep: true }, ) const prevEditableTn = ref<string[]>([]) onMounted(() => { parseAndLoadTemplate() // used to record the previous EditableTn values // for checking the table duplication in current import // and updating the key in importData prevEditableTn.value = data.tables.map((t) => t.table_name) if (importDataOnly) { mapDefaultColumns() } nextTick(() => { inputRefs.value[0]?.focus() }) }) function filterOption(input: string, option: Option) { return option.value.toUpperCase().includes(input.toUpperCase()) } function parseAndLoadTemplate() { if (baseTemplate) { parseTemplate(baseTemplate) expansionPanel.value = Array.from({ length: data.tables.length || 0 }, (_, i) => i) hasSelectColumn.value = Array.from({ length: data.tables.length || 0 }, () => false) } } function parseTemplate({ tables = [], ...rest }: Props['baseTemplate']) { const parsedTemplate = { ...rest, tables: tables.map(({ v = [], columns = [], ...rest }) => ({ ...rest, columns: [ ...columns.map((c: any, idx: number) => { c.key = idx return c }), ...v.map((v: any) => ({ column_name: v.title, table_name: { ...v, }, })), ], })), } Object.assign(data, parsedTemplate) } function isSelect(col: ColumnType) { return col.uidt === 'MultiSelect' || col.uidt === 'SingleSelect' } function deleteTable(tableIdx: number) { data.tables.splice(tableIdx, 1) } function deleteTableColumn(tableIdx: number, columnKey: number) { const columnIdx = data.tables[tableIdx].columns.findIndex((c: ColumnType & { key: number }) => c.key === columnKey) data.tables[tableIdx].columns.splice(columnIdx, 1) } function addNewColumnRow(tableIdx: number, uidt: string) { data.tables[tableIdx].columns.push({ key: data.tables[tableIdx].columns.length, column_name: `title${data.tables[tableIdx].columns.length + 1}`, uidt, }) nextTick(() => { const input = inputRefs.value[data.tables[tableIdx].columns.length - 1] input.focus() input.select() }) } function setEditableTn(tableIdx: number, val: boolean) { editableTn.value[tableIdx] = val } function remapColNames(batchData: any[], columns: ColumnType[]) { const dateFormatMap: Record<number, string> = {} return batchData.map((data) => (columns || []).reduce((aggObj, col: Record<string, any>) => { // for excel & json, if the column name is changed in TemplateEditor, // then only col.column_name exists in data, else col.ref_column_name // for csv, col.column_name always exists in data // since it streams the data in getData() with the updated col.column_name const key = col.column_name in data ? col.column_name : col.ref_column_name let d = data[key] if (col.uidt === UITypes.Date && d) { let dateFormat if (col?.meta?.date_format) { dateFormat = col.meta.date_format dateFormatMap[col.key] = dateFormat } else if (col.key in dateFormatMap) { dateFormat = dateFormatMap[col.key] } else { dateFormat = getDateFormat(d) dateFormatMap[col.key] = dateFormat } d = parseStringDate(d, dateFormat) } else if (col.uidt === UITypes.DateTime && d) { const dateTimeFormat = getDateTimeFormat(data[key]) d = dayjs(data[key], dateTimeFormat).format('YYYY-MM-DD HH:mm') } return { ...aggObj, [col.column_name]: d, } }, {}), ) } function missingRequiredColumnsValidation(tn: string) { const missingRequiredColumns = columns.value.filter( (c: Record<string, any>) => (c.pk ? !c.ai && !c.cdf : !c.cdf && c.rqd) && !srcDestMapping.value[tn].some((r: Record<string, any>) => r.destCn === c.title), ) if (missingRequiredColumns.length) { message.error(`${t('msg.error.columnsRequired')} : ${missingRequiredColumns.map((c) => c.title).join(', ')}`) return false } return true } function atLeastOneEnabledValidation(tn: string) { if (srcDestMapping.value[tn].filter((v: Record<string, any>) => v.enabled === true).length === 0) { message.error(t('msg.error.selectAtleastOneColumn')) return false } return true } function fieldsValidation(record: Record<string, any>, tn: string) { // if it is not selected, then pass validation if (!record.enabled) { return true } if (!record.destCn) { message.error(`${t('msg.error.columnDescriptionNotFound')} ${record.srcCn}`) return false } if (srcDestMapping.value[tn].filter((v: Record<string, any>) => v.destCn === record.destCn).length > 1) { message.error(t('msg.error.duplicateMappingFound')) return false } const v = columns.value.find((c) => c.title === record.destCn) as Record<string, any> for (const tableName of Object.keys(importData)) { // check if the input contains null value for a required column if (v.pk ? !v.ai && !v.cdf : !v.cdf && v.rqd) { if ( importData[tableName] .slice(0, maxRowsToParse) .some((r: Record<string, any>) => r[record.srcCn] === null || r[record.srcCn] === undefined || r[record.srcCn] === '') ) { message.error(t('msg.error.nullValueViolatesNotNull')) } } switch (v.uidt) { case UITypes.Number: if ( importData[tableName] .slice(0, maxRowsToParse) .some( (r: Record<string, any>) => r[record.sourceCn] !== null && r[record.srcCn] !== undefined && isNaN(+r[record.srcCn]), ) ) { message.error(t('msg.error.sourceHasInvalidNumbers')) return false } break case UITypes.Checkbox: if ( importData[tableName].slice(0, maxRowsToParse).some((r: Record<string, any>) => { if (r[record.srcCn] !== null && r[record.srcCn] !== undefined) { let input = r[record.srcCn] if (typeof input === 'string') { input = input.replace(/["']/g, '').toLowerCase().trim() return !( input === 'false' || input === 'no' || input === 'n' || input === '0' || input === 'true' || input === 'yes' || input === 'y' || input === '1' ) } return input !== 1 && input !== 0 && input !== true && input !== false } return false }) ) { message.error(t('msg.error.sourceHasInvalidBoolean')) return false } break } } return true } function updateImportTips(baseName: string, tableName: string, progress: number, total: number) { importingTips.value[`${baseName}-${tableName}`] = `Importing data to ${baseName} - ${tableName}: ${progress}/${total} records` } async function importTemplate() { if (importDataOnly) { for (const table of data.tables) { // validate required columns if (!missingRequiredColumnsValidation(table.table_name)) return // validate at least one column needs to be selected if (!atLeastOneEnabledValidation(table.table_name)) return } try { isImporting.value = true const tableId = meta.value?.id const baseId = base.value.id! const table_names = data.tables.map((t: Record<string, any>) => t.table_name) await Promise.all( Object.keys(importData).map((key: string) => (async (k) => { if (!table_names.includes(k)) { return } const data = importData[k] const total = data.length for (let i = 0, progress = 0; i < total; i += maxRowsToParse) { const batchData = data.slice(i, i + maxRowsToParse).map((row: Record<string, any>) => srcDestMapping.value[k].reduce((res: Record<string, any>, col: Record<string, any>) => { if (col.enabled && col.destCn) { const v = columns.value.find((c: Record<string, any>) => c.title === col.destCn) as Record<string, any> let input = row[col.srcCn] // parse potential boolean values if (v.uidt === UITypes.Checkbox) { input = input ? input.replace(/["']/g, '').toLowerCase().trim() : 'false' if (input === 'false' || input === 'no' || input === 'n') { input = '0' } else if (input === 'true' || input === 'yes' || input === 'y') { input = '1' } } else if (v.uidt === UITypes.Number) { if (input === '') { input = null } } else if (v.uidt === UITypes.SingleSelect || v.uidt === UITypes.MultiSelect) { if (input === '') { input = null } } else if (v.uidt === UITypes.Date) { if (input) { input = parseStringDate(input, v.meta.date_format) } } res[col.destCn] = input } return res }, {}), ) await $api.dbTableRow.bulkCreate('noco', baseId, tableId!, batchData) updateImportTips(baseId, tableId!, progress, total) progress += batchData.length } })(key), ), ) // reload table reloadHook.trigger() // Successfully imported table data message.success(t('msg.success.tableDataImported')) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { isImporting.value = false } } else { // check if form is valid try { await validate() } catch (errorInfo) { isImporting.value = false throw new Error('Please fill all the required values') } try { isImporting.value = true // tab info to be used to show the tab after successful import const tab = { id: '', title: '', baseId: '', } // create tables for (const table of data.tables) { // enrich system fields if not provided // e.g. id, created_at, updated_at const systemColumns = sqlUi?.value.getNewTableColumns().filter((c: ColumnType) => c.column_name !== 'title') for (const systemColumn of systemColumns) { if (!table.columns?.some((c) => c.column_name?.toLowerCase() === systemColumn.column_name.toLowerCase())) { table.columns?.push(systemColumn) } } if (table.columns) { for (const column of table.columns) { // set pk & rqd if ID is provided if (column.column_name?.toLowerCase() === 'id' && !('pk' in column)) { column.pk = true column.rqd = true } if ( (!isSystemColumn(column) || ['created_at', 'updated_at'].includes(column.column_name!)) && column.uidt !== UITypes.SingleSelect && column.uidt !== UITypes.MultiSelect ) { // delete dtxp if the final data type is not single & multi select // e.g. import -> detect as single / multi select -> switch to SingleLineText // the correct dtxp will be generated during column creation delete column.dtxp } } } const createdTable = await $api.source.tableCreate(base.value?.id as string, (sourceId || base.value?.sources?.[0].id)!, { table_name: table.table_name, // leave title empty to get a generated one based on table_name title: '', columns: table.columns || [], }) if (process.env.NC_SANITIZE_COLUMN_NAME !== 'false') { // column_name could have been updated in tableCreate // e.g. sanitize column name to something like field_1, field_2, and etc createdTable.columns.forEach((column, i) => { table.columns[i].column_name = column.column_name }) } table.id = createdTable.id table.title = createdTable.title // open the first table after import if (tab.id === '' && tab.title === '' && tab.baseId === '') { tab.id = createdTable.id as string tab.title = createdTable.title as string tab.baseId = base.value.id as string } // set display value if (createdTable?.columns?.[0]?.id) { await $api.dbTableColumn.primaryColumnSet(createdTable.columns[0].id as string) } } // bulk insert data if (importData) { const offset = maxRowsToParse const baseName = base.value.title as string await Promise.all( data.tables.map((table: Record<string, any>) => (async (tableMeta) => { let progress = 0 let total = 0 // use ref_table_name here instead of table_name // since importData[talbeMeta.table_name] would be empty after renaming const data = importData[tableMeta.ref_table_name] if (data) { total += data.length for (let i = 0; i < data.length; i += offset) { updateImportTips(baseName, tableMeta.title, progress, total) const batchData = remapColNames(data.slice(i, i + offset), tableMeta.columns) await $api.dbTableRow.bulkCreate('noco', base.value.id, tableMeta.id, batchData) progress += batchData.length } updateImportTips(baseName, tableMeta.title, total, total) } })(table), ), ) } // reload table list await loadTables() addTab({ ...tab, type: TabType.TABLE, }) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { isImporting.value = false } } if (!data.tables?.length) return const tables = baseTables.value.get(base.value!.id!) const toBeNavigatedTable = tables?.find((t) => t.id === data.tables[0].id) if (!toBeNavigatedTable) return openTable(toBeNavigatedTable) } function mapDefaultColumns() { srcDestMapping.value = {} for (let i = 0; i < data.tables.length; i++) { for (const col of importColumns[i]) { const o = { srcCn: col.column_name, destCn: '', enabled: true } if (columns.value) { const tableColumn = columns.value.find((c) => c.column_name === col.column_name) if (tableColumn) { o.destCn = tableColumn.title as string } else { o.enabled = false } } if (!(data.tables[i].table_name in srcDestMapping.value)) { srcDestMapping.value[data.tables[i].table_name] = [] } srcDestMapping.value[data.tables[i].table_name].push(o) } } } defineExpose({ importTemplate, isValid, }) function handleEditableTnChange(idx: number) { const oldValue = prevEditableTn.value[idx] const newValue = data.tables[idx].table_name if (data.tables.filter((t) => t.table_name === newValue).length > 1) { message.warn('Duplicate Table Name') data.tables[idx].table_name = oldValue } else { prevEditableTn.value[idx] = newValue } setEditableTn(idx, false) } function isSelectDisabled(uidt: string, disableSelect = false) { return (uidt === UITypes.SingleSelect || uidt === UITypes.MultiSelect) && disableSelect } function handleCheckAllRecord(event: CheckboxChangeEvent, tableName: string) { const isChecked = event.target.checked for (const record of srcDestMapping.value[tableName]) { record.enabled = isChecked } } function handleUIDTChange(column, table) { if (!importWorker) return const handler = (e) => { const [type, payload] = e.data switch (type) { case ImportWorkerResponse.SINGLE_SELECT_OPTIONS: case ImportWorkerResponse.MULTI_SELECT_OPTIONS: importWorker.removeEventListener('message', handler, false) column.dtxp = payload break } } if (column.uidt === UITypes.SingleSelect) { importWorker.addEventListener('message', handler, false) importWorker.postMessage([ ImportWorkerOperations.GET_SINGLE_SELECT_OPTIONS, { tableName: table.ref_table_name, columnName: column.ref_column_name, }, ]) } else if (column.uidt === UITypes.MultiSelect) { importWorker.addEventListener('message', handler, false) importWorker.postMessage([ ImportWorkerOperations.GET_MULTI_SELECT_OPTIONS, { tableName: table.ref_table_name, columnName: column.ref_column_name, }, ]) } } const setErrorState = (errorsFields: any[]) => { const errorMap: any = {} for (const error of errorsFields) { errorMap[error.name] = error.errors } formError.value = errorMap } watch(formRef, () => { setTimeout(async () => { try { await validate() emit('change') formError.value = null } catch (e: any) { emit('error', e) setErrorState(e.errorFields) } }, 500) }) watch(modelRef, async () => { try { await validate() emit('change') formError.value = null } catch (e: any) { emit('error', e) setErrorState(e.errorFields) } }) </script> <template> <a-spin :spinning="isImporting" size="large"> <template #tip> <p v-for="(importingTip, idx) of importingTips" :key="idx" class="mt-[10px]"> {{ importingTip }} </p> </template> <a-card v-if="importDataOnly"> <a-form :model="data" name="import-only"> <p v-if="data.tables && quickImportType === 'excel'" class="text-center"> {{ data.tables.length }} sheet{{ data.tables.length > 1 ? 's' : '' }} available for import </p> </a-form> <a-collapse v-if="data.tables && data.tables.length" v-model:activeKey="expansionPanel" class="template-collapse" accordion> <a-collapse-panel v-for="(table, tableIdx) of data.tables" :key="tableIdx"> <template #header> <span class="font-weight-bold text-lg flex items-center gap-2 truncate"> <component :is="iconMap.table" class="text-primary" /> {{ table.table_name }} </span> </template> <template #extra> <a-tooltip bottom> <template #title> <span>{{ $t('activity.deleteTable') }}</span> </template> <component :is="iconMap.delete" v-if="data.tables.length > 1" class="text-lg mr-8" @click.stop="deleteTable(tableIdx)" /> </a-tooltip> </template> <a-table v-if="srcDestMapping" class="template-form" row-class-name="template-form-row" :data-source="srcDestMapping[table.table_name]" :columns="srcDestMappingColumns" :pagination="false" > <template #emptyText> <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noData')" /> </template> <template #headerCell="{ column }"> <span v-if="column.key === 'source_column' || column.key === 'destination_column'"> {{ column.name }} </span> <span v-if="column.key === 'action'"> <a-checkbox v-model:checked="checkAllRecord[table.table_name]" @change="handleCheckAllRecord($event, table.table_name)" /> </span> </template> <template #bodyCell="{ column, record }"> <template v-if="column.key === 'source_column'"> <span>{{ record.srcCn }}</span> </template> <template v-else-if="column.key === 'destination_column'"> <a-select v-model:value="record.destCn" class="w-52" show-search :filter-option="filterOption" dropdown-class-name="nc-dropdown-filter-field" > <a-select-option v-for="(col, i) of columns" :key="i" :value="col.title"> <div class="flex items-center"> <component :is="getUIDTIcon(col.uidt)" /> <span class="ml-2">{{ col.title }}</span> </div> </a-select-option> </a-select> </template> <template v-if="column.key === 'action'"> <a-checkbox v-model:checked="record.enabled" /> </template> </template> </a-table> </a-collapse-panel> </a-collapse> </a-card> <a-card v-else> <a-form ref="formRef" :model="data" name="template-editor-form" @keydown.enter="emit('import')"> <p v-if="data.tables && quickImportType === 'excel'" class="text-center"> {{ data.tables.length }} sheet{{ data.tables.length > 1 ? 's' : '' }} available for import </p> <a-collapse v-if="data.tables && data.tables.length" v-model:activeKey="expansionPanel" class="template-collapse" accordion > <a-collapse-panel v-for="(table, tableIdx) of data.tables" :key="tableIdx"> <template #header> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.table_name`]" no-style> <div class="flex flex-col w-full"> <a-input v-model:value="table.table_name" class="font-weight-bold text-lg" size="large" hide-details :bordered="false" @click.stop @blur="handleEditableTnChange(tableIdx)" @keydown.enter="handleEditableTnChange(tableIdx)" @dblclick="setEditableTn(tableIdx, true)" /> <div v-if="formError?.[`tables.${tableIdx}.table_name`]" class="text-red-500 ml-3"> {{ formError?.[`tables.${tableIdx}.table_name`].join('\n') }} </div> </div> </a-form-item> </template> <template #extra> <a-tooltip bottom> <template #title> <span>{{ $t('activity.deleteTable') }}</span> </template> <component :is="iconMap.delete" v-if="data.tables.length > 1" class="text-lg mr-8" @click.stop="deleteTable(tableIdx)" /> </a-tooltip> </template> <a-table v-if="table.columns && table.columns.length" class="template-form" row-class-name="template-form-row" :data-source="table.columns" :columns="tableColumns" :pagination="table.columns.length > 50 ? { defaultPageSize: 50, position: ['bottomCenter'] } : false" > <template #emptyText> <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noData')" /> </template> <template #headerCell="{ column }"> <template v-if="column.key === 'column_name'"> <span> {{ $t('labels.columnName') }} </span> </template> <template v-else-if="column.key === 'uidt'"> <span> {{ $t('labels.columnType') }} </span> </template> <template v-else-if="column.key === 'dtxp' && hasSelectColumn[tableIdx]"> <span> {{ $t('general.options') }} </span> </template> </template> <template #bodyCell="{ column, record }"> <template v-if="column.key === 'column_name'"> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]"> <a-input :ref="(el: HTMLInputElement) => (inputRefs[record.key] = el)" v-model:value="record.column_name" /> </a-form-item> </template> <template v-else-if="column.key === 'uidt'"> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]"> <a-select v-model:value="record.uidt" class="w-52" show-search :filter-option="filterOption" dropdown-class-name="nc-dropdown-template-uidt" @change="handleUIDTChange(record, table)" > <a-select-option v-for="(option, i) of uiTypeOptions" :key="i" :value="option.value"> <a-tooltip placement="right"> <template v-if="isSelectDisabled(option.label, table.columns[record.key]?._disableSelect)" #title> {{ $t('msg.tooLargeFieldEntity', { entity: option.label, }) }} </template> {{ option.label }} </a-tooltip> </a-select-option> </a-select> </a-form-item> </template> <template v-else-if="column.key === 'dtxp'"> <a-form-item v-if="isSelect(record)"> <a-input v-model:value="record.dtxp" /> </a-form-item> </template> <template v-if="column.key === 'action'"> <a-tooltip v-if="record.key === 0"> <template #title> <span>{{ $t('general.primaryValue') }}</span> </template> <div class="flex items-center float-right mr-4"> <mdi-key-star class="text-lg" /> </div> </a-tooltip> <a-tooltip v-else> <template #title> <span>{{ $t('activity.column.delete') }}</span> </template> <a-button type="text" @click="deleteTableColumn(tableIdx, record.key)"> <div class="flex items-center"> <component :is="iconMap.delete" class="text-lg" /> </div> </a-button> </a-tooltip> </template> </template> </a-table> <div class="mt-5 flex gap-2 justify-center"> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addNumber') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'Number')"> <div class="flex items-center"> <component :is="iconMap.number" class="group-hover:!text-accent flex text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addSingleLineText') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'SingleLineText')"> <div class="flex items-center"> <component :is="iconMap.text" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addLongText') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'LongText')"> <div class="flex items-center"> <component :is="iconMap.longText" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addOther') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'SingleLineText')"> <div class="flex items-center gap-1"> <component :is="iconMap.plus" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> </div> </a-collapse-panel> </a-collapse> </a-form> </a-card> </a-spin> </template> <style scoped lang="scss"> .template-collapse { @apply bg-white; } .template-form { :deep(.ant-table-thead) > tr > th { @apply bg-white; } :deep(.template-form-row) > td { @apply p-0 mb-0; .ant-form-item { @apply mb-0; } } } </style>
packages/nc-gui/components/template/Editor.vue
1
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.9979074001312256, 0.0221360195428133, 0.00016121758380904794, 0.0002978367265313864, 0.13224247097969055 ]
{ "id": 0, "code_window": [ " data.tables.reduce<Record<string, [ReturnType<typeof fieldRequiredValidator>]>>((acc: Record<string, any>, table, tableIdx) => {\n", " acc[`tables.${tableIdx}.table_name`] = [validateTableName]\n", " hasSelectColumn.value[tableIdx] = false\n", "\n", " table.columns?.forEach((column, columnIdx) => {\n", " acc[`tables.${tableIdx}.columns.${columnIdx}.column_name`] = [\n", " fieldRequiredValidator(),\n", " fieldLengthValidator(),\n", " ]\n", " acc[`tables.${tableIdx}.columns.${columnIdx}.uidt`] = [fieldRequiredValidator()]\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " acc[`tables.${tableIdx}.columns.${columnIdx}.title`] = [\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 133 }
import fs from 'fs'; import { promisify } from 'util'; import { Storage } from '@google-cloud/storage'; import axios from 'axios'; import { useAgent } from 'request-filtering-agent'; import type { IStorageAdapterV2, XcFile } from 'nc-plugin'; import type { Readable } from 'stream'; import type { StorageOptions } from '@google-cloud/storage'; import { generateTempFilePath, waitForStreamClose } from '~/utils/pluginUtils'; export default class Gcs implements IStorageAdapterV2 { private storageClient: Storage; private bucketName: string; private input: any; constructor(input: any) { this.input = input; } async fileCreate(key: string, file: XcFile): Promise<any> { const uploadResponse = await this.storageClient .bucket(this.bucketName) .upload(file.path, { destination: key, // Support for HTTP requests made with `Accept-Encoding: gzip` gzip: true, // By setting the option `destination`, you can change the name of the // object you are uploading to a bucket. metadata: { // Enable long-lived HTTP caching headers // Use only if the contents of the file will never change // (If the contents will change, use cacheControl: 'no-cache') cacheControl: 'public, max-age=31536000', }, }); return uploadResponse[0].publicUrl(); } fileDelete(_path: string): Promise<any> { return Promise.resolve(undefined); } public fileRead(key: string): Promise<any> { return new Promise((resolve, reject) => { const file = this.storageClient.bucket(this.bucketName).file(key); // Check for existence, since gcloud-node seemed to be caching the result file.exists((err, exists) => { if (exists) { file.download((downerr, data) => { if (err) { return reject(downerr); } return resolve(data); }); } else { reject(err); } }); }); } public async init(): Promise<any> { const options: StorageOptions = {}; // options.credentials = { // client_email: process.env.NC_GCS_CLIENT_EMAIL, // private_key: process.env.NC_GCS_PRIVATE_KEY // } // // this.bucketName = process.env.NC_GCS_BUCKET; options.credentials = { client_email: this.input.client_email, // replace \n with real line breaks to avoid // error:0909006C:PEM routines:get_name:no start line private_key: this.input.private_key.replace(/\\n/gm, '\n'), }; // default project ID would be used if it is not provided if (this.input.project_id) { options.projectId = this.input.project_id; } this.bucketName = this.input.bucket; this.storageClient = new Storage(options); } public async test(): Promise<boolean> { try { const tempFile = generateTempFilePath(); const createStream = fs.createWriteStream(tempFile); await waitForStreamClose(createStream); await this.fileCreate('nc-test-file.txt', { path: tempFile, mimetype: '', originalname: 'temp.txt', size: '', }); await promisify(fs.unlink)(tempFile); return true; } catch (e) { throw e; } } fileCreateByUrl(destPath: string, url: string): Promise<any> { return new Promise((resolve, reject) => { axios .get(url, { httpAgent: useAgent(url, { stopPortScanningByUrlRedirection: true }), httpsAgent: useAgent(url, { stopPortScanningByUrlRedirection: true }), // TODO - use stream instead of buffer responseType: 'arraybuffer', }) .then((response) => { this.storageClient .bucket(this.bucketName) .file(destPath) .save(response.data) .then((res) => resolve(res)) .catch(reject); }) .catch((error) => { reject(error); }); }); } // TODO - implement fileCreateByStream(_key: string, _stream: Readable): Promise<void> { return Promise.resolve(undefined); } // TODO - implement fileReadByStream(_key: string): Promise<Readable> { return Promise.resolve(undefined); } // TODO - implement getDirectoryList(_path: string): Promise<string[]> { return Promise.resolve(undefined); } }
packages/nocodb/src/plugins/gcs/Gcs.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00017663899052422494, 0.00016888273239601403, 0.00016218337987083942, 0.00016902254719752818, 0.0000034485240121284733 ]
{ "id": 0, "code_window": [ " data.tables.reduce<Record<string, [ReturnType<typeof fieldRequiredValidator>]>>((acc: Record<string, any>, table, tableIdx) => {\n", " acc[`tables.${tableIdx}.table_name`] = [validateTableName]\n", " hasSelectColumn.value[tableIdx] = false\n", "\n", " table.columns?.forEach((column, columnIdx) => {\n", " acc[`tables.${tableIdx}.columns.${columnIdx}.column_name`] = [\n", " fieldRequiredValidator(),\n", " fieldLengthValidator(),\n", " ]\n", " acc[`tables.${tableIdx}.columns.${columnIdx}.uidt`] = [fieldRequiredValidator()]\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " acc[`tables.${tableIdx}.columns.${columnIdx}.title`] = [\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 133 }
import { forwardRef, Module } from '@nestjs/common'; import { PassportModule } from '@nestjs/passport'; import { GlobalModule } from '~/modules/global/global.module'; import { UsersService } from '~/services/users/users.service'; import { UsersController } from '~/controllers/users/users.controller'; import { MetasModule } from '~/modules/metas/metas.module'; @Module({ imports: [ forwardRef(() => GlobalModule), PassportModule, forwardRef(() => MetasModule), ], controllers: [ ...(process.env.NC_WORKER_CONTAINER !== 'true' ? [UsersController] : []), ], providers: [UsersService], exports: [UsersService], }) export class UsersModule {}
packages/nocodb/src/modules/users/users.module.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0004728682106360793, 0.00027483340818434954, 0.00017341015336569399, 0.00017822184599936008, 0.0001400455366820097 ]
{ "id": 0, "code_window": [ " data.tables.reduce<Record<string, [ReturnType<typeof fieldRequiredValidator>]>>((acc: Record<string, any>, table, tableIdx) => {\n", " acc[`tables.${tableIdx}.table_name`] = [validateTableName]\n", " hasSelectColumn.value[tableIdx] = false\n", "\n", " table.columns?.forEach((column, columnIdx) => {\n", " acc[`tables.${tableIdx}.columns.${columnIdx}.column_name`] = [\n", " fieldRequiredValidator(),\n", " fieldLengthValidator(),\n", " ]\n", " acc[`tables.${tableIdx}.columns.${columnIdx}.uidt`] = [fieldRequiredValidator()]\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " acc[`tables.${tableIdx}.columns.${columnIdx}.title`] = [\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 133 }
# NocoDB SDK Available in [npm](https://www.npmjs.com/package/nocodb-sdk). Used in frontend and backend.
packages/nocodb-sdk/README.md
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00016338865680154413, 0.00016338865680154413, 0.00016338865680154413, 0.00016338865680154413, 0 ]
{ "id": 1, "code_window": [ "function addNewColumnRow(tableIdx: number, uidt: string) {\n", " data.tables[tableIdx].columns.push({\n", " key: data.tables[tableIdx].columns.length,\n", " column_name: `title${data.tables[tableIdx].columns.length + 1}`,\n", " uidt,\n", " })\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " title: `title${data.tables[tableIdx].columns.length + 1}`,\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "add", "edit_start_line_idx": 254 }
<script setup lang="ts"> import dayjs from 'dayjs' import utc from 'dayjs/plugin/utc' import type { ColumnType, TableType } from 'nocodb-sdk' import { UITypes, isSystemColumn, isVirtualCol } from 'nocodb-sdk' import type { CheckboxChangeEvent } from 'ant-design-vue/es/checkbox/interface' import { srcDestMappingColumns, tableColumns } from './utils' import { Empty, Form, ImportWorkerOperations, ImportWorkerResponse, MetaInj, ReloadViewDataHookInj, TabType, computed, createEventHook, extractSdkResponseErrorMsg, fieldLengthValidator, fieldRequiredValidator, getDateFormat, getDateTimeFormat, getUIDTIcon, iconMap, inject, message, nextTick, onMounted, parseStringDate, reactive, ref, storeToRefs, useBase, useI18n, useNuxtApp, useTabs, validateTableName, } from '#imports' const { quickImportType, baseTemplate, importData, importColumns, importDataOnly, maxRowsToParse, sourceId, importWorker } = defineProps<Props>() const emit = defineEmits(['import', 'error', 'change']) dayjs.extend(utc) const { t } = useI18n() interface Props { quickImportType: 'csv' | 'excel' | 'json' baseTemplate: Record<string, any> importData: Record<string, any> importColumns: any[] importDataOnly: boolean maxRowsToParse: number sourceId: string importWorker: Worker } interface Option { label: string value: string } const meta = inject(MetaInj, ref()) const columns = computed(() => meta.value?.columns || []) const reloadHook = inject(ReloadViewDataHookInj, createEventHook()) const useForm = Form.useForm const { $api } = useNuxtApp() const { addTab } = useTabs() const baseStrore = useBase() const { loadTables } = baseStrore const { sqlUis, base } = storeToRefs(baseStrore) const { openTable } = useTablesStore() const { baseTables } = storeToRefs(useTablesStore()) const sqlUi = ref(sqlUis.value[sourceId] || Object.values(sqlUis.value)[0]) const hasSelectColumn = ref<boolean[]>([]) const expansionPanel = ref<number[]>([]) const editableTn = ref<boolean[]>([]) const inputRefs = ref<HTMLInputElement[]>([]) const isImporting = ref(false) const importingTips = ref<Record<string, string>>({}) const checkAllRecord = ref<boolean[]>([]) const formError = ref() const uiTypeOptions = ref<Option[]>( (Object.keys(UITypes) as (keyof typeof UITypes)[]) .filter( (uiType) => !isVirtualCol(UITypes[uiType]) && ![UITypes.ForeignKey, UITypes.ID, UITypes.CreateTime, UITypes.LastModifiedTime, UITypes.Barcode, UITypes.Button].includes( UITypes[uiType], ), ) .map<Option>((uiType) => ({ value: uiType, label: uiType, })), ) const srcDestMapping = ref<Record<string, Record<string, any>[]>>({}) const data = reactive<{ title: string | null name: string tables: (TableType & { ref_table_name: string; columns: (ColumnType & { key: number; _disableSelect?: boolean })[] })[] }>({ title: null, name: 'Base Name', tables: [], }) const validators = computed(() => data.tables.reduce<Record<string, [ReturnType<typeof fieldRequiredValidator>]>>((acc: Record<string, any>, table, tableIdx) => { acc[`tables.${tableIdx}.table_name`] = [validateTableName] hasSelectColumn.value[tableIdx] = false table.columns?.forEach((column, columnIdx) => { acc[`tables.${tableIdx}.columns.${columnIdx}.column_name`] = [ fieldRequiredValidator(), fieldLengthValidator(), ] acc[`tables.${tableIdx}.columns.${columnIdx}.uidt`] = [fieldRequiredValidator()] if (isSelect(column)) { hasSelectColumn.value[tableIdx] = true } }) return acc }, {}), ) const { validate, validateInfos, modelRef } = useForm(data, validators) const isValid = ref(!importDataOnly) const formRef = ref() watch( () => srcDestMapping.value, () => { let res = true if (importDataOnly) { for (const tn of Object.keys(srcDestMapping.value)) { if (!atLeastOneEnabledValidation(tn)) { res = false } for (const record of srcDestMapping.value[tn]) { if (!fieldsValidation(record, tn)) { return false } } } } else { for (const [_, o] of Object.entries(validateInfos)) { if (o?.validateStatus) { if (o.validateStatus === 'error') { res = false } } } } isValid.value = res }, { deep: true }, ) const prevEditableTn = ref<string[]>([]) onMounted(() => { parseAndLoadTemplate() // used to record the previous EditableTn values // for checking the table duplication in current import // and updating the key in importData prevEditableTn.value = data.tables.map((t) => t.table_name) if (importDataOnly) { mapDefaultColumns() } nextTick(() => { inputRefs.value[0]?.focus() }) }) function filterOption(input: string, option: Option) { return option.value.toUpperCase().includes(input.toUpperCase()) } function parseAndLoadTemplate() { if (baseTemplate) { parseTemplate(baseTemplate) expansionPanel.value = Array.from({ length: data.tables.length || 0 }, (_, i) => i) hasSelectColumn.value = Array.from({ length: data.tables.length || 0 }, () => false) } } function parseTemplate({ tables = [], ...rest }: Props['baseTemplate']) { const parsedTemplate = { ...rest, tables: tables.map(({ v = [], columns = [], ...rest }) => ({ ...rest, columns: [ ...columns.map((c: any, idx: number) => { c.key = idx return c }), ...v.map((v: any) => ({ column_name: v.title, table_name: { ...v, }, })), ], })), } Object.assign(data, parsedTemplate) } function isSelect(col: ColumnType) { return col.uidt === 'MultiSelect' || col.uidt === 'SingleSelect' } function deleteTable(tableIdx: number) { data.tables.splice(tableIdx, 1) } function deleteTableColumn(tableIdx: number, columnKey: number) { const columnIdx = data.tables[tableIdx].columns.findIndex((c: ColumnType & { key: number }) => c.key === columnKey) data.tables[tableIdx].columns.splice(columnIdx, 1) } function addNewColumnRow(tableIdx: number, uidt: string) { data.tables[tableIdx].columns.push({ key: data.tables[tableIdx].columns.length, column_name: `title${data.tables[tableIdx].columns.length + 1}`, uidt, }) nextTick(() => { const input = inputRefs.value[data.tables[tableIdx].columns.length - 1] input.focus() input.select() }) } function setEditableTn(tableIdx: number, val: boolean) { editableTn.value[tableIdx] = val } function remapColNames(batchData: any[], columns: ColumnType[]) { const dateFormatMap: Record<number, string> = {} return batchData.map((data) => (columns || []).reduce((aggObj, col: Record<string, any>) => { // for excel & json, if the column name is changed in TemplateEditor, // then only col.column_name exists in data, else col.ref_column_name // for csv, col.column_name always exists in data // since it streams the data in getData() with the updated col.column_name const key = col.column_name in data ? col.column_name : col.ref_column_name let d = data[key] if (col.uidt === UITypes.Date && d) { let dateFormat if (col?.meta?.date_format) { dateFormat = col.meta.date_format dateFormatMap[col.key] = dateFormat } else if (col.key in dateFormatMap) { dateFormat = dateFormatMap[col.key] } else { dateFormat = getDateFormat(d) dateFormatMap[col.key] = dateFormat } d = parseStringDate(d, dateFormat) } else if (col.uidt === UITypes.DateTime && d) { const dateTimeFormat = getDateTimeFormat(data[key]) d = dayjs(data[key], dateTimeFormat).format('YYYY-MM-DD HH:mm') } return { ...aggObj, [col.column_name]: d, } }, {}), ) } function missingRequiredColumnsValidation(tn: string) { const missingRequiredColumns = columns.value.filter( (c: Record<string, any>) => (c.pk ? !c.ai && !c.cdf : !c.cdf && c.rqd) && !srcDestMapping.value[tn].some((r: Record<string, any>) => r.destCn === c.title), ) if (missingRequiredColumns.length) { message.error(`${t('msg.error.columnsRequired')} : ${missingRequiredColumns.map((c) => c.title).join(', ')}`) return false } return true } function atLeastOneEnabledValidation(tn: string) { if (srcDestMapping.value[tn].filter((v: Record<string, any>) => v.enabled === true).length === 0) { message.error(t('msg.error.selectAtleastOneColumn')) return false } return true } function fieldsValidation(record: Record<string, any>, tn: string) { // if it is not selected, then pass validation if (!record.enabled) { return true } if (!record.destCn) { message.error(`${t('msg.error.columnDescriptionNotFound')} ${record.srcCn}`) return false } if (srcDestMapping.value[tn].filter((v: Record<string, any>) => v.destCn === record.destCn).length > 1) { message.error(t('msg.error.duplicateMappingFound')) return false } const v = columns.value.find((c) => c.title === record.destCn) as Record<string, any> for (const tableName of Object.keys(importData)) { // check if the input contains null value for a required column if (v.pk ? !v.ai && !v.cdf : !v.cdf && v.rqd) { if ( importData[tableName] .slice(0, maxRowsToParse) .some((r: Record<string, any>) => r[record.srcCn] === null || r[record.srcCn] === undefined || r[record.srcCn] === '') ) { message.error(t('msg.error.nullValueViolatesNotNull')) } } switch (v.uidt) { case UITypes.Number: if ( importData[tableName] .slice(0, maxRowsToParse) .some( (r: Record<string, any>) => r[record.sourceCn] !== null && r[record.srcCn] !== undefined && isNaN(+r[record.srcCn]), ) ) { message.error(t('msg.error.sourceHasInvalidNumbers')) return false } break case UITypes.Checkbox: if ( importData[tableName].slice(0, maxRowsToParse).some((r: Record<string, any>) => { if (r[record.srcCn] !== null && r[record.srcCn] !== undefined) { let input = r[record.srcCn] if (typeof input === 'string') { input = input.replace(/["']/g, '').toLowerCase().trim() return !( input === 'false' || input === 'no' || input === 'n' || input === '0' || input === 'true' || input === 'yes' || input === 'y' || input === '1' ) } return input !== 1 && input !== 0 && input !== true && input !== false } return false }) ) { message.error(t('msg.error.sourceHasInvalidBoolean')) return false } break } } return true } function updateImportTips(baseName: string, tableName: string, progress: number, total: number) { importingTips.value[`${baseName}-${tableName}`] = `Importing data to ${baseName} - ${tableName}: ${progress}/${total} records` } async function importTemplate() { if (importDataOnly) { for (const table of data.tables) { // validate required columns if (!missingRequiredColumnsValidation(table.table_name)) return // validate at least one column needs to be selected if (!atLeastOneEnabledValidation(table.table_name)) return } try { isImporting.value = true const tableId = meta.value?.id const baseId = base.value.id! const table_names = data.tables.map((t: Record<string, any>) => t.table_name) await Promise.all( Object.keys(importData).map((key: string) => (async (k) => { if (!table_names.includes(k)) { return } const data = importData[k] const total = data.length for (let i = 0, progress = 0; i < total; i += maxRowsToParse) { const batchData = data.slice(i, i + maxRowsToParse).map((row: Record<string, any>) => srcDestMapping.value[k].reduce((res: Record<string, any>, col: Record<string, any>) => { if (col.enabled && col.destCn) { const v = columns.value.find((c: Record<string, any>) => c.title === col.destCn) as Record<string, any> let input = row[col.srcCn] // parse potential boolean values if (v.uidt === UITypes.Checkbox) { input = input ? input.replace(/["']/g, '').toLowerCase().trim() : 'false' if (input === 'false' || input === 'no' || input === 'n') { input = '0' } else if (input === 'true' || input === 'yes' || input === 'y') { input = '1' } } else if (v.uidt === UITypes.Number) { if (input === '') { input = null } } else if (v.uidt === UITypes.SingleSelect || v.uidt === UITypes.MultiSelect) { if (input === '') { input = null } } else if (v.uidt === UITypes.Date) { if (input) { input = parseStringDate(input, v.meta.date_format) } } res[col.destCn] = input } return res }, {}), ) await $api.dbTableRow.bulkCreate('noco', baseId, tableId!, batchData) updateImportTips(baseId, tableId!, progress, total) progress += batchData.length } })(key), ), ) // reload table reloadHook.trigger() // Successfully imported table data message.success(t('msg.success.tableDataImported')) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { isImporting.value = false } } else { // check if form is valid try { await validate() } catch (errorInfo) { isImporting.value = false throw new Error('Please fill all the required values') } try { isImporting.value = true // tab info to be used to show the tab after successful import const tab = { id: '', title: '', baseId: '', } // create tables for (const table of data.tables) { // enrich system fields if not provided // e.g. id, created_at, updated_at const systemColumns = sqlUi?.value.getNewTableColumns().filter((c: ColumnType) => c.column_name !== 'title') for (const systemColumn of systemColumns) { if (!table.columns?.some((c) => c.column_name?.toLowerCase() === systemColumn.column_name.toLowerCase())) { table.columns?.push(systemColumn) } } if (table.columns) { for (const column of table.columns) { // set pk & rqd if ID is provided if (column.column_name?.toLowerCase() === 'id' && !('pk' in column)) { column.pk = true column.rqd = true } if ( (!isSystemColumn(column) || ['created_at', 'updated_at'].includes(column.column_name!)) && column.uidt !== UITypes.SingleSelect && column.uidt !== UITypes.MultiSelect ) { // delete dtxp if the final data type is not single & multi select // e.g. import -> detect as single / multi select -> switch to SingleLineText // the correct dtxp will be generated during column creation delete column.dtxp } } } const createdTable = await $api.source.tableCreate(base.value?.id as string, (sourceId || base.value?.sources?.[0].id)!, { table_name: table.table_name, // leave title empty to get a generated one based on table_name title: '', columns: table.columns || [], }) if (process.env.NC_SANITIZE_COLUMN_NAME !== 'false') { // column_name could have been updated in tableCreate // e.g. sanitize column name to something like field_1, field_2, and etc createdTable.columns.forEach((column, i) => { table.columns[i].column_name = column.column_name }) } table.id = createdTable.id table.title = createdTable.title // open the first table after import if (tab.id === '' && tab.title === '' && tab.baseId === '') { tab.id = createdTable.id as string tab.title = createdTable.title as string tab.baseId = base.value.id as string } // set display value if (createdTable?.columns?.[0]?.id) { await $api.dbTableColumn.primaryColumnSet(createdTable.columns[0].id as string) } } // bulk insert data if (importData) { const offset = maxRowsToParse const baseName = base.value.title as string await Promise.all( data.tables.map((table: Record<string, any>) => (async (tableMeta) => { let progress = 0 let total = 0 // use ref_table_name here instead of table_name // since importData[talbeMeta.table_name] would be empty after renaming const data = importData[tableMeta.ref_table_name] if (data) { total += data.length for (let i = 0; i < data.length; i += offset) { updateImportTips(baseName, tableMeta.title, progress, total) const batchData = remapColNames(data.slice(i, i + offset), tableMeta.columns) await $api.dbTableRow.bulkCreate('noco', base.value.id, tableMeta.id, batchData) progress += batchData.length } updateImportTips(baseName, tableMeta.title, total, total) } })(table), ), ) } // reload table list await loadTables() addTab({ ...tab, type: TabType.TABLE, }) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { isImporting.value = false } } if (!data.tables?.length) return const tables = baseTables.value.get(base.value!.id!) const toBeNavigatedTable = tables?.find((t) => t.id === data.tables[0].id) if (!toBeNavigatedTable) return openTable(toBeNavigatedTable) } function mapDefaultColumns() { srcDestMapping.value = {} for (let i = 0; i < data.tables.length; i++) { for (const col of importColumns[i]) { const o = { srcCn: col.column_name, destCn: '', enabled: true } if (columns.value) { const tableColumn = columns.value.find((c) => c.column_name === col.column_name) if (tableColumn) { o.destCn = tableColumn.title as string } else { o.enabled = false } } if (!(data.tables[i].table_name in srcDestMapping.value)) { srcDestMapping.value[data.tables[i].table_name] = [] } srcDestMapping.value[data.tables[i].table_name].push(o) } } } defineExpose({ importTemplate, isValid, }) function handleEditableTnChange(idx: number) { const oldValue = prevEditableTn.value[idx] const newValue = data.tables[idx].table_name if (data.tables.filter((t) => t.table_name === newValue).length > 1) { message.warn('Duplicate Table Name') data.tables[idx].table_name = oldValue } else { prevEditableTn.value[idx] = newValue } setEditableTn(idx, false) } function isSelectDisabled(uidt: string, disableSelect = false) { return (uidt === UITypes.SingleSelect || uidt === UITypes.MultiSelect) && disableSelect } function handleCheckAllRecord(event: CheckboxChangeEvent, tableName: string) { const isChecked = event.target.checked for (const record of srcDestMapping.value[tableName]) { record.enabled = isChecked } } function handleUIDTChange(column, table) { if (!importWorker) return const handler = (e) => { const [type, payload] = e.data switch (type) { case ImportWorkerResponse.SINGLE_SELECT_OPTIONS: case ImportWorkerResponse.MULTI_SELECT_OPTIONS: importWorker.removeEventListener('message', handler, false) column.dtxp = payload break } } if (column.uidt === UITypes.SingleSelect) { importWorker.addEventListener('message', handler, false) importWorker.postMessage([ ImportWorkerOperations.GET_SINGLE_SELECT_OPTIONS, { tableName: table.ref_table_name, columnName: column.ref_column_name, }, ]) } else if (column.uidt === UITypes.MultiSelect) { importWorker.addEventListener('message', handler, false) importWorker.postMessage([ ImportWorkerOperations.GET_MULTI_SELECT_OPTIONS, { tableName: table.ref_table_name, columnName: column.ref_column_name, }, ]) } } const setErrorState = (errorsFields: any[]) => { const errorMap: any = {} for (const error of errorsFields) { errorMap[error.name] = error.errors } formError.value = errorMap } watch(formRef, () => { setTimeout(async () => { try { await validate() emit('change') formError.value = null } catch (e: any) { emit('error', e) setErrorState(e.errorFields) } }, 500) }) watch(modelRef, async () => { try { await validate() emit('change') formError.value = null } catch (e: any) { emit('error', e) setErrorState(e.errorFields) } }) </script> <template> <a-spin :spinning="isImporting" size="large"> <template #tip> <p v-for="(importingTip, idx) of importingTips" :key="idx" class="mt-[10px]"> {{ importingTip }} </p> </template> <a-card v-if="importDataOnly"> <a-form :model="data" name="import-only"> <p v-if="data.tables && quickImportType === 'excel'" class="text-center"> {{ data.tables.length }} sheet{{ data.tables.length > 1 ? 's' : '' }} available for import </p> </a-form> <a-collapse v-if="data.tables && data.tables.length" v-model:activeKey="expansionPanel" class="template-collapse" accordion> <a-collapse-panel v-for="(table, tableIdx) of data.tables" :key="tableIdx"> <template #header> <span class="font-weight-bold text-lg flex items-center gap-2 truncate"> <component :is="iconMap.table" class="text-primary" /> {{ table.table_name }} </span> </template> <template #extra> <a-tooltip bottom> <template #title> <span>{{ $t('activity.deleteTable') }}</span> </template> <component :is="iconMap.delete" v-if="data.tables.length > 1" class="text-lg mr-8" @click.stop="deleteTable(tableIdx)" /> </a-tooltip> </template> <a-table v-if="srcDestMapping" class="template-form" row-class-name="template-form-row" :data-source="srcDestMapping[table.table_name]" :columns="srcDestMappingColumns" :pagination="false" > <template #emptyText> <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noData')" /> </template> <template #headerCell="{ column }"> <span v-if="column.key === 'source_column' || column.key === 'destination_column'"> {{ column.name }} </span> <span v-if="column.key === 'action'"> <a-checkbox v-model:checked="checkAllRecord[table.table_name]" @change="handleCheckAllRecord($event, table.table_name)" /> </span> </template> <template #bodyCell="{ column, record }"> <template v-if="column.key === 'source_column'"> <span>{{ record.srcCn }}</span> </template> <template v-else-if="column.key === 'destination_column'"> <a-select v-model:value="record.destCn" class="w-52" show-search :filter-option="filterOption" dropdown-class-name="nc-dropdown-filter-field" > <a-select-option v-for="(col, i) of columns" :key="i" :value="col.title"> <div class="flex items-center"> <component :is="getUIDTIcon(col.uidt)" /> <span class="ml-2">{{ col.title }}</span> </div> </a-select-option> </a-select> </template> <template v-if="column.key === 'action'"> <a-checkbox v-model:checked="record.enabled" /> </template> </template> </a-table> </a-collapse-panel> </a-collapse> </a-card> <a-card v-else> <a-form ref="formRef" :model="data" name="template-editor-form" @keydown.enter="emit('import')"> <p v-if="data.tables && quickImportType === 'excel'" class="text-center"> {{ data.tables.length }} sheet{{ data.tables.length > 1 ? 's' : '' }} available for import </p> <a-collapse v-if="data.tables && data.tables.length" v-model:activeKey="expansionPanel" class="template-collapse" accordion > <a-collapse-panel v-for="(table, tableIdx) of data.tables" :key="tableIdx"> <template #header> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.table_name`]" no-style> <div class="flex flex-col w-full"> <a-input v-model:value="table.table_name" class="font-weight-bold text-lg" size="large" hide-details :bordered="false" @click.stop @blur="handleEditableTnChange(tableIdx)" @keydown.enter="handleEditableTnChange(tableIdx)" @dblclick="setEditableTn(tableIdx, true)" /> <div v-if="formError?.[`tables.${tableIdx}.table_name`]" class="text-red-500 ml-3"> {{ formError?.[`tables.${tableIdx}.table_name`].join('\n') }} </div> </div> </a-form-item> </template> <template #extra> <a-tooltip bottom> <template #title> <span>{{ $t('activity.deleteTable') }}</span> </template> <component :is="iconMap.delete" v-if="data.tables.length > 1" class="text-lg mr-8" @click.stop="deleteTable(tableIdx)" /> </a-tooltip> </template> <a-table v-if="table.columns && table.columns.length" class="template-form" row-class-name="template-form-row" :data-source="table.columns" :columns="tableColumns" :pagination="table.columns.length > 50 ? { defaultPageSize: 50, position: ['bottomCenter'] } : false" > <template #emptyText> <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noData')" /> </template> <template #headerCell="{ column }"> <template v-if="column.key === 'column_name'"> <span> {{ $t('labels.columnName') }} </span> </template> <template v-else-if="column.key === 'uidt'"> <span> {{ $t('labels.columnType') }} </span> </template> <template v-else-if="column.key === 'dtxp' && hasSelectColumn[tableIdx]"> <span> {{ $t('general.options') }} </span> </template> </template> <template #bodyCell="{ column, record }"> <template v-if="column.key === 'column_name'"> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]"> <a-input :ref="(el: HTMLInputElement) => (inputRefs[record.key] = el)" v-model:value="record.column_name" /> </a-form-item> </template> <template v-else-if="column.key === 'uidt'"> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]"> <a-select v-model:value="record.uidt" class="w-52" show-search :filter-option="filterOption" dropdown-class-name="nc-dropdown-template-uidt" @change="handleUIDTChange(record, table)" > <a-select-option v-for="(option, i) of uiTypeOptions" :key="i" :value="option.value"> <a-tooltip placement="right"> <template v-if="isSelectDisabled(option.label, table.columns[record.key]?._disableSelect)" #title> {{ $t('msg.tooLargeFieldEntity', { entity: option.label, }) }} </template> {{ option.label }} </a-tooltip> </a-select-option> </a-select> </a-form-item> </template> <template v-else-if="column.key === 'dtxp'"> <a-form-item v-if="isSelect(record)"> <a-input v-model:value="record.dtxp" /> </a-form-item> </template> <template v-if="column.key === 'action'"> <a-tooltip v-if="record.key === 0"> <template #title> <span>{{ $t('general.primaryValue') }}</span> </template> <div class="flex items-center float-right mr-4"> <mdi-key-star class="text-lg" /> </div> </a-tooltip> <a-tooltip v-else> <template #title> <span>{{ $t('activity.column.delete') }}</span> </template> <a-button type="text" @click="deleteTableColumn(tableIdx, record.key)"> <div class="flex items-center"> <component :is="iconMap.delete" class="text-lg" /> </div> </a-button> </a-tooltip> </template> </template> </a-table> <div class="mt-5 flex gap-2 justify-center"> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addNumber') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'Number')"> <div class="flex items-center"> <component :is="iconMap.number" class="group-hover:!text-accent flex text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addSingleLineText') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'SingleLineText')"> <div class="flex items-center"> <component :is="iconMap.text" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addLongText') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'LongText')"> <div class="flex items-center"> <component :is="iconMap.longText" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addOther') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'SingleLineText')"> <div class="flex items-center gap-1"> <component :is="iconMap.plus" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> </div> </a-collapse-panel> </a-collapse> </a-form> </a-card> </a-spin> </template> <style scoped lang="scss"> .template-collapse { @apply bg-white; } .template-form { :deep(.ant-table-thead) > tr > th { @apply bg-white; } :deep(.template-form-row) > td { @apply p-0 mb-0; .ant-form-item { @apply mb-0; } } } </style>
packages/nc-gui/components/template/Editor.vue
1
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.9989966750144958, 0.07328380644321442, 0.00016720716666895896, 0.00048040554975159466, 0.23610107600688934 ]
{ "id": 1, "code_window": [ "function addNewColumnRow(tableIdx: number, uidt: string) {\n", " data.tables[tableIdx].columns.push({\n", " key: data.tables[tableIdx].columns.length,\n", " column_name: `title${data.tables[tableIdx].columns.length + 1}`,\n", " uidt,\n", " })\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " title: `title${data.tables[tableIdx].columns.length + 1}`,\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "add", "edit_start_line_idx": 254 }
import { Strategy } from 'passport-local'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { extractRolesObj } from 'nocodb-sdk'; import type { AppConfig } from '~/interface/config'; import { AuthService } from '~/services/auth.service'; import { NcError } from '~/helpers/catchError'; @Injectable() export class LocalStrategy extends PassportStrategy(Strategy) { constructor( private authService: AuthService, private config: ConfigService<AppConfig>, ) { super({ usernameField: 'email', passwordField: 'password', }); } async validate(username: string, password: string): Promise<any> { if (this.config.get('auth.disableEmailAuth', { infer: true })) NcError.forbidden('Not available'); const user = await this.authService.validateUser(username, password); if (!user) { NcError.badRequest('Invalid credentials'); } user.roles = extractRolesObj(user.roles); return user; } }
packages/nocodb/src/strategies/local.strategy.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0001756088895490393, 0.00017369144188705832, 0.00017059245146811008, 0.00017428223509341478, 0.000002046627059826278 ]
{ "id": 1, "code_window": [ "function addNewColumnRow(tableIdx: number, uidt: string) {\n", " data.tables[tableIdx].columns.push({\n", " key: data.tables[tableIdx].columns.length,\n", " column_name: `title${data.tables[tableIdx].columns.length + 1}`,\n", " uidt,\n", " })\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " title: `title${data.tables[tableIdx].columns.length + 1}`,\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "add", "edit_start_line_idx": 254 }
export function sanitize(v) { if (typeof v !== 'string') return v; return v?.replace(/([^\\]|^)(\?+)/g, (_, m1, m2) => { return `${m1}${m2.split('?').join('\\?')}`; }); } export function unsanitize(v) { if (typeof v !== 'string') return v; return v?.replace(/\\[?]/g, '?'); }
packages/nocodb/src/helpers/sanitize.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.000177892463398166, 0.000172699976246804, 0.000167507489095442, 0.000172699976246804, 0.000005192487151362002 ]
{ "id": 1, "code_window": [ "function addNewColumnRow(tableIdx: number, uidt: string) {\n", " data.tables[tableIdx].columns.push({\n", " key: data.tables[tableIdx].columns.length,\n", " column_name: `title${data.tables[tableIdx].columns.length + 1}`,\n", " uidt,\n", " })\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " title: `title${data.tables[tableIdx].columns.length + 1}`,\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "add", "edit_start_line_idx": 254 }
<script lang="ts" setup> definePageMeta({ hideHeader: true, hasSidebar: true, }) const dialogOpen = ref(false) const openDialogKey = ref<string>('') const dataSourcesState = ref<string>('') const baseId = ref<string>() const basesStore = useBases() const { populateWorkspace } = useWorkspace() const { signedIn } = useGlobal() const { isUIAllowed } = useRoles() const router = useRouter() const route = router.currentRoute const { basesList } = storeToRefs(basesStore) const autoNavigateToProject = async () => { const routeName = route.value.name as string if (routeName !== 'index-typeOrId' && routeName !== 'index') { return } await basesStore.navigateToProject({ baseId: basesList.value[0].id! }) } const isSharedView = computed(() => { const routeName = (route.value.name as string) || '' // check route is not base page by route name return !routeName.startsWith('index-typeOrId-baseId-') && !['index', 'index-typeOrId'].includes(routeName) }) const isSharedFormView = computed(() => { const routeName = (route.value.name as string) || '' // check route is shared form view route return routeName.startsWith('index-typeOrId-form-viewId') }) const { sharedBaseId } = useCopySharedBase() const isDuplicateDlgOpen = ref(false) async function handleRouteTypeIdChange() { // avoid loading bases for shared views if (isSharedView.value) { return } // avoid loading bases for shared base if (route.value.params.typeOrId === 'base') { await populateWorkspace() return } if (!signedIn.value) { navigateTo('/signIn') return } // Load bases await populateWorkspace() if (!route.value.params.baseId && basesList.value.length > 0) { await autoNavigateToProject() } } watch( () => route.value.params.typeOrId, () => { handleRouteTypeIdChange() }, ) // onMounted is needed instead having this function called through // immediate watch, because if route is changed during page transition // It will error out nuxt onMounted(() => { if (route.value.query?.continueAfterSignIn) { localStorage.removeItem('continueAfterSignIn') return navigateTo(route.value.query.continueAfterSignIn as string) } else { const continueAfterSignIn = localStorage.getItem('continueAfterSignIn') localStorage.removeItem('continueAfterSignIn') if (continueAfterSignIn) { return navigateTo({ path: continueAfterSignIn, query: route.value.query, }) } } handleRouteTypeIdChange().then(() => { if (sharedBaseId.value) { if (!isUIAllowed('baseDuplicate')) { message.error('You are not allowed to create base') return } isDuplicateDlgOpen.value = true } }) }) function toggleDialog(value?: boolean, key?: string, dsState?: string, pId?: string) { dialogOpen.value = value ?? !dialogOpen.value openDialogKey.value = key || '' dataSourcesState.value = dsState || '' baseId.value = pId || '' } provide(ToggleDialogInj, toggleDialog) </script> <template> <div> <NuxtLayout v-if="isSharedFormView"> <NuxtPage /> </NuxtLayout> <NuxtLayout v-else-if="isSharedView" name="shared-view"> <NuxtPage /> </NuxtLayout> <NuxtLayout v-else name="dashboard"> <template #sidebar> <DashboardSidebar /> </template> <template #content> <NuxtPage /> </template> </NuxtLayout> <LazyDashboardSettingsModal v-model:model-value="dialogOpen" v-model:open-key="openDialogKey" v-model:data-sources-state="dataSourcesState" :base-id="baseId" /> <DlgSharedBaseDuplicate v-if="isUIAllowed('baseDuplicate')" v-model="isDuplicateDlgOpen" /> </div> </template> <style scoped></style>
packages/nc-gui/pages/index.vue
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00017611647490411997, 0.00017149544146377593, 0.00016513046284671873, 0.00017186299373861402, 0.0000034443041840859223 ]
{ "id": 2, "code_window": [ " // then only col.column_name exists in data, else col.ref_column_name\n", " // for csv, col.column_name always exists in data\n", " // since it streams the data in getData() with the updated col.column_name\n", " const key = col.column_name in data ? col.column_name : col.ref_column_name\n", " let d = data[key]\n", " if (col.uidt === UITypes.Date && d) {\n", " let dateFormat\n", " if (col?.meta?.date_format) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const key = col.title in data ? col.title : col.ref_column_name\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 277 }
import { parse } from 'papaparse' import type { UploadFile } from 'ant-design-vue' import { UITypes } from 'nocodb-sdk' import { getDateFormat, validateDateWithUnknownFormat } from '../../utils/dateTimeUtils' import { extractMultiOrSingleSelectProps, getCheckboxValue, isCheckboxType, isDecimalType, isEmailType, isMultiLineTextType, isUrlType, } from './parserHelpers' export default class CSVTemplateAdapter { config: Record<string, any> source: UploadFile[] | string detectedColumnTypes: Record<number, Record<string, number>> distinctValues: Record<number, Set<string>> headers: Record<number, string[]> tables: Record<number, any> base: { tables: Record<string, any>[] } data: Record<string, any> = {} columnValues: Record<number, []> private progressCallback?: (msg: string) => void constructor(source: UploadFile[] | string, parserConfig = {}, progressCallback?: (msg: string) => void) { this.config = parserConfig this.source = source this.base = { tables: [], } this.detectedColumnTypes = {} this.distinctValues = {} this.headers = {} this.columnValues = {} this.tables = {} this.progressCallback = progressCallback } async init() {} initTemplate(tableIdx: number, tn: string, columnNames: string[]) { const columnNameRowExist = +columnNames.every((v: any) => v === null || typeof v === 'string') const columnNamePrefixRef: Record<string, any> = { id: 0 } const tableObj: Record<string, any> = { table_name: tn, ref_table_name: tn, columns: [], } this.headers[tableIdx] = [] this.tables[tableIdx] = [] for (const [columnIdx, columnName] of columnNames.entries()) { let cn: string = ((columnNameRowExist && columnName.toString().trim()) || `field_${columnIdx + 1}`) .replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_') .trim() while (cn in columnNamePrefixRef) { cn = `${cn}${++columnNamePrefixRef[cn]}` } columnNamePrefixRef[cn] = 0 this.detectedColumnTypes[columnIdx] = {} this.distinctValues[columnIdx] = new Set<string>() this.columnValues[columnIdx] = [] tableObj.columns.push({ column_name: cn, ref_column_name: cn, meta: {}, uidt: UITypes.SingleLineText, key: columnIdx, }) this.headers[tableIdx].push(cn) this.tables[tableIdx] = tableObj } } detectInitialUidt(v: string) { if (!isNaN(Number(v)) && !isNaN(parseFloat(v))) return UITypes.Number if (validateDateWithUnknownFormat(v)) return UITypes.DateTime if (isCheckboxType(v)) return UITypes.Checkbox return UITypes.SingleLineText } detectColumnType(tableIdx: number, data: []) { for (let columnIdx = 0; columnIdx < data.length; columnIdx++) { // skip null data if (!data[columnIdx]) continue const colData: any = [data[columnIdx]] const colProps = { uidt: this.detectInitialUidt(data[columnIdx]) } // TODO(import): centralise if (isMultiLineTextType(colData)) { colProps.uidt = UITypes.LongText } else if (colProps.uidt === UITypes.SingleLineText) { if (isEmailType(colData)) { colProps.uidt = UITypes.Email } else if (isUrlType(colData)) { colProps.uidt = UITypes.URL } else if (isCheckboxType(colData)) { colProps.uidt = UITypes.Checkbox } else { if (data[columnIdx] && columnIdx < this.config.maxRowsToParse) { this.columnValues[columnIdx].push(data[columnIdx]) colProps.uidt = UITypes.SingleSelect } } } else if (colProps.uidt === UITypes.Number) { if (isDecimalType(colData)) { colProps.uidt = UITypes.Decimal } } else if (colProps.uidt === UITypes.DateTime) { if (data[columnIdx] && columnIdx < this.config.maxRowsToParse) { this.columnValues[columnIdx].push(data[columnIdx]) } } if (!(colProps.uidt in this.detectedColumnTypes[columnIdx])) { this.detectedColumnTypes[columnIdx] = { ...this.detectedColumnTypes[columnIdx], [colProps.uidt]: 0, } } this.detectedColumnTypes[columnIdx][colProps.uidt] += 1 if (data[columnIdx]) { this.distinctValues[columnIdx].add(data[columnIdx]) } } } getPossibleUidt(columnIdx: number) { const detectedColTypes = this.detectedColumnTypes[columnIdx] const len = Object.keys(detectedColTypes).length // all records are null if (len === 0) { return UITypes.SingleLineText } // handle numeric case if (len === 2 && UITypes.Number in detectedColTypes && UITypes.Decimal in detectedColTypes) { return UITypes.Decimal } // if there are multiple detected column types // then return either LongText or SingleLineText if (len > 1) { if (UITypes.LongText in detectedColTypes) { return UITypes.LongText } return UITypes.SingleLineText } // otherwise, all records have the same column type return Object.keys(detectedColTypes)[0] } updateTemplate(tableIdx: number) { for (let columnIdx = 0; columnIdx < this.headers[tableIdx].length; columnIdx++) { const uidt = this.getPossibleUidt(columnIdx) if (this.columnValues[columnIdx].length > 0) { if (uidt === UITypes.DateTime) { const dateFormat: Record<string, number> = {} if ( this.columnValues[columnIdx].slice(1, this.config.maxRowsToParse).every((v: any) => { const isDate = v.split(' ').length === 1 if (isDate) { dateFormat[getDateFormat(v)] = (dateFormat[getDateFormat(v)] || 0) + 1 } return isDate }) ) { this.tables[tableIdx].columns[columnIdx].uidt = UITypes.Date // take the date format with the max occurrence const objKeys = Object.keys(dateFormat) this.tables[tableIdx].columns[columnIdx].meta.date_format = objKeys.length ? objKeys.reduce((x, y) => (dateFormat[x] > dateFormat[y] ? x : y)) : 'YYYY/MM/DD' } else { // Datetime this.tables[tableIdx].columns[columnIdx].uidt = uidt } } else if (uidt === UITypes.SingleSelect || uidt === UITypes.MultiSelect) { // assume it is a SingleLineText first this.tables[tableIdx].columns[columnIdx].uidt = UITypes.SingleLineText // override with UITypes.SingleSelect or UITypes.MultiSelect if applicable Object.assign(this.tables[tableIdx].columns[columnIdx], extractMultiOrSingleSelectProps(this.columnValues[columnIdx])) } else { this.tables[tableIdx].columns[columnIdx].uidt = uidt } delete this.columnValues[columnIdx] } else { this.tables[tableIdx].columns[columnIdx].uidt = uidt } } } async _parseTableData(tableIdx: number, source: UploadFile | string, tn: string) { return new Promise((resolve, reject) => { const that = this let steppers = 0 if (that.config.shouldImportData) { that.progress(`Processing ${tn} data`) steppers = 0 const parseSource = (this.config.importFromURL ? (source as string) : (source as UploadFile).originFileObj)! parse(parseSource, { download: that.config.importFromURL, // worker: true, skipEmptyLines: 'greedy', step(row) { steppers += 1 if (row && steppers >= +that.config.firstRowAsHeaders + 1) { const rowData: Record<string, any> = {} for (let columnIdx = 0; columnIdx < that.headers[tableIdx].length; columnIdx++) { const column = that.tables[tableIdx].columns[columnIdx] const data = (row.data as [])[columnIdx] === '' ? null : (row.data as [])[columnIdx] if (column.uidt === UITypes.Checkbox) { rowData[column.column_name] = getCheckboxValue(data) } else if (column.uidt === UITypes.SingleSelect || column.uidt === UITypes.MultiSelect) { rowData[column.column_name] = (data || '').toString().trim() || null } else { // TODO(import): do parsing if necessary based on type rowData[column.column_name] = data } } that.data[tn].push(rowData) } if (steppers % 1000 === 0) { that.progress(`Processed ${steppers} rows of ${tn}`) } }, complete() { that.progress(`Processed ${tn} data`) resolve(true) }, error(e: Error) { reject(e) }, }) } else { resolve(true) } }) } async _parseTableMeta(tableIdx: number, source: UploadFile | string) { return new Promise((resolve, reject) => { const that = this let steppers = 0 const tn = ((this.config.importFromURL ? (source as string).split('/').pop() : (source as UploadFile).name) as string) .replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_') .trim()! this.data[tn] = [] const parseSource = (this.config.importFromURL ? (source as string) : (source as UploadFile).originFileObj)! parse(parseSource, { download: that.config.importFromURL, skipEmptyLines: 'greedy', step(row) { steppers += 1 if (row) { if (steppers === 1) { if (that.config.firstRowAsHeaders) { // row.data is header that.initTemplate(tableIdx, tn, row.data as []) } else { // use dummy column names as header that.initTemplate( tableIdx, tn, [...Array((row.data as []).length)].map((_, i) => `field_${i + 1}`), ) if (that.config.autoSelectFieldTypes) { // row.data is data that.detectColumnType(tableIdx, row.data as []) } } } else { if (that.config.autoSelectFieldTypes) { // row.data is data that.detectColumnType(tableIdx, row.data as []) } } } }, async complete() { that.updateTemplate(tableIdx) that.base.tables.push(that.tables[tableIdx]) that.progress(`Processed ${tn} metadata`) await that._parseTableData(tableIdx, source, tn) resolve(true) }, error(e: Error) { reject(e) }, }) }) } async parse() { if (this.config.importFromURL) { await this._parseTableMeta(0, this.source as string) } else { await Promise.all( (this.source as UploadFile[]).map((file: UploadFile, tableIdx: number) => (async (f, idx) => { this.progress(`Parsing ${f.name}`) await this._parseTableMeta(idx, f) })(file, tableIdx), ), ) } } getColumns() { return this.base.tables.map((t: Record<string, any>) => t.columns) } getData() { return this.data } getTemplate() { return this.base } progress(msg: string) { this.progressCallback?.(msg) } }
packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts
1
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.9985117316246033, 0.058484017848968506, 0.00015966189675964415, 0.00018157446174882352, 0.23165878653526306 ]
{ "id": 2, "code_window": [ " // then only col.column_name exists in data, else col.ref_column_name\n", " // for csv, col.column_name always exists in data\n", " // since it streams the data in getData() with the updated col.column_name\n", " const key = col.column_name in data ? col.column_name : col.ref_column_name\n", " let d = data[key]\n", " if (col.uidt === UITypes.Date && d) {\n", " let dateFormat\n", " if (col?.meta?.date_format) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const key = col.title in data ? col.title : col.ref_column_name\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 277 }
export interface IEventEmitter { emit(event: string, arg: any): void; on(event: string, listener: (arg: any) => void): () => void; removeListener(event: string, listener: (arg: any) => void): void; removeAllListeners(event?: string): void; }
packages/nocodb/src/modules/event-emitter/event-emitter.interface.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00016809228691272438, 0.00016809228691272438, 0.00016809228691272438, 0.00016809228691272438, 0 ]
{ "id": 2, "code_window": [ " // then only col.column_name exists in data, else col.ref_column_name\n", " // for csv, col.column_name always exists in data\n", " // since it streams the data in getData() with the updated col.column_name\n", " const key = col.column_name in data ? col.column_name : col.ref_column_name\n", " let d = data[key]\n", " if (col.uidt === UITypes.Date && d) {\n", " let dateFormat\n", " if (col?.meta?.date_format) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const key = col.title in data ? col.title : col.ref_column_name\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 277 }
import { test } from '@playwright/test'; import { DashboardPage } from '../../../pages/Dashboard'; import { ToolbarPage } from '../../../pages/Dashboard/common/Toolbar'; import setup, { unsetup } from '../../../setup'; test.describe('Views CRUD Operations', () => { let dashboard: DashboardPage; let context: any; let toolbar: ToolbarPage; test.beforeEach(async ({ page }) => { context = await setup({ page, isEmptyProject: false }); dashboard = new DashboardPage(page, context.base); toolbar = dashboard.grid.toolbar; }); test.afterEach(async () => { await unsetup(context); }); test('Create views, reorder and delete', async () => { await dashboard.treeView.openTable({ title: 'City' }); await dashboard.viewSidebar.createGridView({ title: 'CityGrid' }); await dashboard.viewSidebar.verifyView({ title: 'CityGrid', index: 0 }); await dashboard.viewSidebar.renameView({ title: 'CityGrid', newTitle: 'CityGrid2', }); await dashboard.viewSidebar.verifyView({ title: 'CityGrid2', index: 0, }); await dashboard.viewSidebar.createFormView({ title: 'CityForm' }); await dashboard.viewSidebar.verifyView({ title: 'CityForm', index: 1 }); await dashboard.viewSidebar.renameView({ title: 'CityForm', newTitle: 'CityForm2', }); await dashboard.viewSidebar.verifyView({ title: 'CityForm2', index: 1, }); await dashboard.viewSidebar.createGalleryView({ title: 'CityGallery' }); await dashboard.viewSidebar.verifyView({ title: 'CityGallery', index: 2 }); await dashboard.viewSidebar.renameView({ title: 'CityGallery', newTitle: 'CityGallery2', }); await dashboard.viewSidebar.verifyView({ title: 'CityGallery2', index: 2, }); await dashboard.viewSidebar.changeViewIcon({ title: 'CityGallery2', icon: 'american-football', iconDisplay: '🏈', }); // todo: Enable when view bug is fixed // await dashboard.viewSidebar.reorderViews({ // sourceView: "CityGrid", // destinationView: "CityForm", // }); // await dashboard.viewSidebar.verifyView({ title: "CityGrid", index: 2 }); // await dashboard.viewSidebar.verifyView({ title: "CityForm", index: 1 }); // await dashboard.viewSidebar.deleteView({ title: "CityForm2" }); // await dashboard.viewSidebar.verifyViewNotPresent({ // title: "CityGrid2", // index: 2, // }); await dashboard.viewSidebar.deleteView({ title: 'CityForm2' }); await dashboard.viewSidebar.verifyViewNotPresent({ title: 'CityForm2', index: 1, }); // fix index after enabling reorder test await dashboard.viewSidebar.deleteView({ title: 'CityGallery2' }); await dashboard.viewSidebar.verifyViewNotPresent({ title: 'CityGallery2', index: 0, }); }); test('Save search query for each table and view', async () => { await dashboard.treeView.openTable({ title: 'City' }); await toolbar.searchData.verify(''); await toolbar.searchData.get().fill('City-City'); await toolbar.searchData.verify('City-City'); await dashboard.viewSidebar.createGridView({ title: 'CityGrid' }); await toolbar.searchData.verify(''); await toolbar.searchData.get().fill('City-CityGrid'); await toolbar.searchData.verify('City-CityGrid'); await dashboard.viewSidebar.createGridView({ title: 'CityGrid2' }); await toolbar.searchData.verify(''); await toolbar.searchData.get().fill('City-CityGrid2'); await toolbar.searchData.verify('City-CityGrid2'); await dashboard.viewSidebar.openView({ title: 'CityGrid' }); await dashboard.rootPage.waitForTimeout(1000); await toolbar.searchData.verify('City-CityGrid'); await dashboard.treeView.openTable({ title: 'City' }); await dashboard.rootPage.waitForTimeout(1000); await toolbar.searchData.verify('City-City'); await dashboard.treeView.openTable({ title: 'Actor' }); await toolbar.searchData.verify(''); await dashboard.viewSidebar.createGridView({ title: 'ActorGrid' }); await toolbar.searchData.verify(''); await toolbar.searchData.get().fill('Actor-ActorGrid'); await toolbar.searchData.verify('Actor-ActorGrid'); await dashboard.treeView.openTable({ title: 'Actor' }); await dashboard.rootPage.waitForTimeout(1000); await toolbar.searchData.verify(''); await dashboard.treeView.openTable({ title: 'City', mode: '' }); await toolbar.searchData.verify('City-City'); }); });
tests/playwright/tests/db/general/views.spec.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00017713166016619653, 0.0001746658090269193, 0.00016599634545855224, 0.00017535440565552562, 0.0000025585620733181713 ]
{ "id": 2, "code_window": [ " // then only col.column_name exists in data, else col.ref_column_name\n", " // for csv, col.column_name always exists in data\n", " // since it streams the data in getData() with the updated col.column_name\n", " const key = col.column_name in data ? col.column_name : col.ref_column_name\n", " let d = data[key]\n", " if (col.uidt === UITypes.Date && d) {\n", " let dateFormat\n", " if (col?.meta?.date_format) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const key = col.title in data ? col.title : col.ref_column_name\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 277 }
@use 'header'; /** * Any CSS included here will be global. The classic template * bundles Infima by default. Infima is a CSS framework designed to * work well for content-centric websites. */ /* You can override the default Infima variables here. */ :root { --ifm-color-primary: #3498db; --ifm-color-primary-dark: #2980b9; --ifm-color-primary-darker: #2471a3; --ifm-color-primary-darkest: #1f618d; --ifm-color-primary-light: #5fa8d0; --ifm-color-primary-lighter: #76b9e0; --ifm-color-primary-lightest: #a5d8ff; --ifm-code-font-size: 95%; --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1); } /* For readability concerns, you should choose a lighter palette in dark mode. */ [data-theme='dark'] { --ifm-color-primary: #258cc2; --ifm-color-primary-dark: #2074a0; --ifm-color-primary-darker: #1d6a8e; --ifm-color-primary-darkest: #1a5779; --ifm-color-primary-light: #29a7d5; --ifm-color-primary-lighter: #32b9e1; --ifm-color-primary-lightest: #4fcbe9; --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.3); } .markdown img { -webkit-box-shadow: 0 0 10px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0 0 10px rgba(0, 0, 0, 0.75); box-shadow: 0 0 10px rgba(0, 0, 0, 0.75); } [data-theme='light'] .DocSearch { /* --docsearch-primary-color: var(--ifm-color-primary); */ /* --docsearch-text-color: var(--ifm-font-color-base); */ --docsearch-muted-color: var(--ifm-color-secondary-darkest); --docsearch-container-background: rgba(94, 100, 112, 0.7); /* Modal */ --docsearch-modal-background: var(--ifm-color-secondary-lighter); /* Search box */ --docsearch-searchbox-background: var(--ifm-color-secondary); --docsearch-searchbox-focus-background: var(--ifm-color-white); /* Hit */ --docsearch-hit-color: var(--ifm-font-color-base); --docsearch-hit-active-color: var(--ifm-color-white); --docsearch-hit-background: var(--ifm-color-white); /* Footer */ --docsearch-footer-background: var(--ifm-color-white); } [data-theme='dark'] .DocSearch { --docsearch-text-color: var(--ifm-font-color-base); --docsearch-muted-color: var(--ifm-color-secondary-darkest); --docsearch-container-background: rgba(47, 55, 69, 0.7); /* Modal */ --docsearch-modal-background: var(--ifm-background-color); /* Search box */ --docsearch-searchbox-background: var(--ifm-background-color); --docsearch-searchbox-focus-background: var(--ifm-color-black); /* Hit */ --docsearch-hit-color: var(--ifm-font-color-base); --docsearch-hit-active-color: var(--ifm-color-white); --docsearch-hit-background: var(--ifm-color-emphasis-100); /* Footer */ --docsearch-footer-background: var(--ifm-background-surface-color); --docsearch-key-gradient: linear-gradient( -26.5deg, var(--ifm-color-emphasis-200) 0%, var(--ifm-color-emphasis-100) 100% ); } @media screen and (min-width: 768px) { .DocSearch.DocSearch-Button{ width: 200px; position: fixed; left:50%; transform: translateX(-50%); top: 12px; } }
packages/noco-docs/src/css/custom.scss
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0002760289062280208, 0.00018293733592145145, 0.00016376908752135932, 0.00017359376943204552, 0.00003117654341622256 ]
{ "id": 3, "code_window": [ " const dateTimeFormat = getDateTimeFormat(data[key])\n", " d = dayjs(data[key], dateTimeFormat).format('YYYY-MM-DD HH:mm')\n", " }\n", " return {\n", " ...aggObj,\n", " [col.column_name]: d,\n", " }\n", " }, {}),\n", " )\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " [col.title]: d,\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 297 }
import { UITypes } from 'nocodb-sdk' import { getDateFormat } from '../../utils/dateTimeUtils' import TemplateGenerator from './TemplateGenerator' import { extractMultiOrSingleSelectProps, getCheckboxValue, isCheckboxType, isEmailType, isMultiLineTextType, isUrlType, } from './parserHelpers' const excelTypeToUidt: Record<string, UITypes> = { d: UITypes.DateTime, b: UITypes.Checkbox, n: UITypes.Number, s: UITypes.SingleLineText, } export default class ExcelTemplateAdapter extends TemplateGenerator { config: Record<string, any> excelData: any base: { tables: Record<string, any>[] } data: Record<string, any> = {} wb: any xlsx: typeof import('xlsx') constructor(data = {}, parserConfig = {}, xlsx: any = null, progressCallback?: (msg: string) => void) { super(progressCallback) this.config = parserConfig this.excelData = data this.base = { tables: [], } this.xlsx = xlsx || ({} as any) } async init() { this.progress('Initializing excel parser') this.xlsx = this.xlsx || (await import('xlsx')) const options = { cellText: true, cellDates: true, } this.wb = this.xlsx.read(new Uint8Array(this.excelData), { type: 'array', ...options, }) } async parse() { this.progress('Parsing excel file') const tableNamePrefixRef: Record<string, any> = {} await Promise.all( this.wb.SheetNames.map((sheetName: string) => (async (sheet) => { this.progress(`Parsing sheet ${sheetName}`) await new Promise((resolve) => { const columnNamePrefixRef: Record<string, any> = { id: 0 } let tn: string = (sheet || 'table').replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_').trim() while (tn in tableNamePrefixRef) { tn = `${tn}${++tableNamePrefixRef[tn]}` } tableNamePrefixRef[tn] = 0 const table = { table_name: tn, ref_table_name: tn, columns: [] as any[] } const ws: any = this.wb.Sheets[sheet] // if sheet is empty, skip it if (!ws || !ws['!ref']) { return resolve(true) } const range = this.xlsx.utils.decode_range(ws['!ref']) let rows: any = this.xlsx.utils.sheet_to_json(ws, { // header has to be 1 disregarding this.config.firstRowAsHeaders // so that it generates an array of arrays header: 1, blankrows: false, defval: null, }) // fix precision bug & timezone offset issues introduced by xlsx const basedate = new Date(1899, 11, 30, 0, 0, 0) // number of milliseconds since base date const dnthresh = basedate.getTime() + (new Date().getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000 // number of milliseconds in a day const day_ms = 24 * 60 * 60 * 1000 // handle date1904 property const fixImportedDate = (date: Date) => { const parsed = this.xlsx.SSF.parse_date_code((date.getTime() - dnthresh) / day_ms, { date1904: this.wb.Workbook.WBProps.date1904, }) return new Date(parsed.y, parsed.m, parsed.d, parsed.H, parsed.M, parsed.S) } // fix imported date rows = rows.map((r: any) => r.map((v: any) => { return v instanceof Date ? fixImportedDate(v) : v }), ) for (let col = 0; col < rows[0].length; col++) { let cn: string = ( (this.config.firstRowAsHeaders && rows[0] && rows[0][col] && rows[0][col].toString().trim()) || `field_${col + 1}` ) .replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_') .trim() while (cn in columnNamePrefixRef) { cn = `${cn}${++columnNamePrefixRef[cn]}` } columnNamePrefixRef[cn] = 0 const column: Record<string, any> = { column_name: cn, ref_column_name: cn, meta: {}, uidt: UITypes.SingleLineText, } if (this.config.autoSelectFieldTypes) { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + col, r: +this.config.firstRowAsHeaders, }) const cellProps = ws[cellId] || {} column.uidt = excelTypeToUidt[cellProps.t] || UITypes.SingleLineText if (column.uidt === UITypes.SingleLineText) { // check for long text if (isMultiLineTextType(rows, col)) { column.uidt = UITypes.LongText } else if (isEmailType(rows, col)) { column.uidt = UITypes.Email } else if (isUrlType(rows, col)) { column.uidt = UITypes.URL } else { const vals = rows .slice(+this.config.firstRowAsHeaders) .map((r: any) => r[col]) .filter((v: any) => v !== null && v !== undefined && v.toString().trim() !== '') if (isCheckboxType(vals, col)) { column.uidt = UITypes.Checkbox } else { // Single Select / Multi Select Object.assign(column, extractMultiOrSingleSelectProps(vals)) } } } else if (column.uidt === UITypes.Number) { if ( rows.slice(1, this.config.maxRowsToParse).some((v: any) => { return v && v[col] && parseInt(v[col]) !== +v[col] }) ) { column.uidt = UITypes.Decimal } if ( rows.slice(1, this.config.maxRowsToParse).every((v: any, i: any) => { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + col, r: i + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] return !cellObj || (cellObj.w && cellObj.w.startsWith('$')) }) ) { column.uidt = UITypes.Currency } if ( rows.slice(1, this.config.maxRowsToParse).some((v: any, i: any) => { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + col, r: i + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] return !cellObj || (cellObj.w && !(!isNaN(Number(cellObj.w)) && !isNaN(parseFloat(cellObj.w)))) }) ) { // fallback to SingleLineText column.uidt = UITypes.SingleLineText } } else if (column.uidt === UITypes.DateTime) { // TODO(import): centralise // hold the possible date format found in the date const dateFormat: Record<string, number> = {} if ( rows.slice(1, this.config.maxRowsToParse).every((v: any, i: any) => { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + col, r: i + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] const isDate = !cellObj || (cellObj.w && cellObj.w.split(' ').length === 1) if (isDate && cellObj) { dateFormat[getDateFormat(cellObj.w)] = (dateFormat[getDateFormat(cellObj.w)] || 0) + 1 } return isDate }) ) { column.uidt = UITypes.Date // take the date format with the max occurrence column.meta.date_format = Object.keys(dateFormat).reduce((x, y) => (dateFormat[x] > dateFormat[y] ? x : y)) || 'YYYY/MM/DD' } } } table.columns.push(column) } this.base.tables.push(table) this.data[tn] = [] if (this.config.shouldImportData) { this.progress(`Parsing data from ${tn}`) let rowIndex = 0 for (const row of rows.slice(1)) { const rowData: Record<string, any> = {} for (let i = 0; i < table.columns.length; i++) { if (!this.config.autoSelectFieldTypes) { // take raw data instead of data parsed by xlsx const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + i, r: rowIndex + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] rowData[table.columns[i].column_name] = (cellObj && cellObj.w) || row[i] } else { if (table.columns[i].uidt === UITypes.Checkbox) { rowData[table.columns[i].column_name] = getCheckboxValue(row[i]) } else if (table.columns[i].uidt === UITypes.Currency) { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + i, r: rowIndex + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] rowData[table.columns[i].column_name] = (cellObj && cellObj.w && cellObj.w.replace(/[^\d.]+/g, '')) || row[i] } else if (table.columns[i].uidt === UITypes.SingleSelect || table.columns[i].uidt === UITypes.MultiSelect) { rowData[table.columns[i].column_name] = (row[i] || '').toString().trim() || null } else if (table.columns[i].uidt === UITypes.Date) { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + i, r: rowIndex + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] rowData[table.columns[i].column_name] = (cellObj && cellObj.w) || row[i] } else if (table.columns[i].uidt === UITypes.SingleLineText || table.columns[i].uidt === UITypes.LongText) { rowData[table.columns[i].column_name] = row[i] === null || row[i] === undefined ? null : `${row[i]}` } else { // TODO: do parsing if necessary based on type rowData[table.columns[i].column_name] = row[i] } } } this.data[tn].push(rowData) rowIndex++ } } resolve(true) }) })(sheetName), ), ) } getTemplate() { return this.base } getData() { return this.data } getColumns() { return this.base.tables.map((t: Record<string, any>) => t.columns) } }
packages/nc-gui/helpers/parsers/ExcelTemplateAdapter.ts
1
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.3462079167366028, 0.016641151160001755, 0.00016429006063845009, 0.0002429504820611328, 0.06241513416171074 ]
{ "id": 3, "code_window": [ " const dateTimeFormat = getDateTimeFormat(data[key])\n", " d = dayjs(data[key], dateTimeFormat).format('YYYY-MM-DD HH:mm')\n", " }\n", " return {\n", " ...aggObj,\n", " [col.column_name]: d,\n", " }\n", " }, {}),\n", " )\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " [col.title]: d,\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 297 }
import colors from 'windicss/colors' export const theme = { light: ['#ffdce5', '#fee2d5', '#ffeab6', '#d1f7c4', '#ede2fe', '#eee', '#cfdffe', '#d0f1fd', '#c2f5e8', '#ffdaf6'], dark: [ '#f82b6099', '#ff6f2c99', '#fcb40099', '#20c93399', '#8b46ff99', '#666', '#2d7ff999', '#18bfff99', '#20d9d299', '#ff08c299', ], } export const enumColor = { light: ['#cfdffe', '#d0f1fd', '#c2f5e8', '#ffdaf6', '#ffdce5', '#fee2d5', '#ffeab6', '#d1f7c4', '#ede2fe', '#eeeeee'], dark: [ '#2d7ff999', '#18bfff99', '#20d9d299', '#ff08c299', '#f82b6099', '#ff6f2c99', '#fcb40099', '#20c93399', '#8b46ff99', '#666', ], } export const themeColors = { 'background': '#FFFFFF', 'surface': '#FFFFFF', 'primary': '#4351e8', 'primary-selected': '#EBF0FF', 'primary-selected-sidebar': '#EBF0FF', 'hover': '#E1E3E6', 'scrollbar': '#d7d7d7', 'scrollbar-hover': '#cbcbcb', 'border': '#F3F4F6', 'secondary': '#F2F4F7', 'secondary-darken-1': '#018786', 'error': '#B00020', 'info': '#2196F3', 'success': '#4CAF50', 'warning': '#FB8C00', } export const themeV2Colors = { /** Primary shades */ 'royal-blue': { 'DEFAULT': '#4351E8', '50': '#E7E8FC', '100': '#D4D8FA', '200': '#B0B6F5', '300': '#8C94F1', '400': '#6773EC', '500': '#4351E8', '600': '#1A2BD8', '700': '#1421A6', '800': '#0E1774', '900': '#080D42', }, /** Accent shades */ 'pink': colors.pink, } const isValidHex = (hex: string) => /^#([A-Fa-f0-9]{3,4}){1,2}$/.test(hex) const getChunksFromString = (st: string, chunkSize: number) => st.match(new RegExp(`.{${chunkSize}}`, 'g')) const convertHexUnitTo256 = (hexStr: string) => parseInt(hexStr.repeat(2 / hexStr.length), 16) export const hexToRGB = (hex: string) => { if (!isValidHex(hex)) { throw new Error('Invalid HEX') } const chunkSize = Math.floor((hex.length - 1) / 3) const hexArr = getChunksFromString(hex.slice(1), chunkSize)! const [r, g, b] = hexArr.map(convertHexUnitTo256) return `${r}, ${g}, ${b}` } export const baseThemeColors = [ themeV2Colors['royal-blue'].DEFAULT, '#2D7FF9', '#18BFFF', '#0C4E65', '#EC2CBD', '#F82B60', '#F57134', '#1BAF2C', '#8B46FF', '#1B51A2', '#146C8E', '#24716E', '#8A2170', '#941737', '#B94915', '#0E4C15', '#381475', '#333333', ] const designSystem = { light: [ // '#EBF0FF', // '#D6E0FF', // '#ADC2FF', // '#85A3FF', // '#5C85FF', '#3366FF', '#2952CC', '#1F3D99', '#142966', '#0A1433', // '#FCFCFC', // '#F9F9FA', // '#F4F4F5', // '#E7E7E9', // '#D5D5D9', // '#9AA2AF', // '#6A7184', '#4A5268', '#374151', '#1F293A', '#101015', // '#FFF2F1', // '#FFDBD9', // '#FFB7B2', // '#FF928C', // '#FF6E65', // '#FF4A3F', '#E8463C', '#CB3F36', '#B23830', '#7D2721', // '#FFEEFB', // '#FED8F4', // '#FEB0E8', // '#FD89DD', // '#FD61D1', '#FC3AC6', '#CA2E9E', '#972377', '#65174F', '#320C28', // '#FFF5EF', // '#FEE6D6', // '#FDCDAD', // '#FCB483', // '#FB9B5A', '#FA8231', '#E1752C', '#C86827', '#964E1D', '#4B270F', // '#F3ECFA', // '#E5D4F5', // '#CBA8EB', // '#B17DE1', // '#9751D7', '#7D26CD', '#641EA4', '#4B177B', '#320F52', '#190829', // '#EDF9FF', // '#D7F2FF', // '#AFE5FF', // '#86D9FF', // '#5ECCFF', '#36BFFF', '#2B99CC', '#207399', '#164C66', '#0B2633', // '#fffbf2', // '#fff0d1', // '#fee5b0', // '#fdd889', // '#fdcb61', // '#fcbe3a', '#ca982e', '#977223', '#654c17', '#32260c', ], dark: [], } // convert string into a unique color export const stringToColor = (input: string, colorArray = designSystem.light) => { // Calculate a numeric hash value from the input string let hash = 0 for (let i = 0; i < input.length; i++) { hash = input.charCodeAt(i) + ((hash << 5) - hash) } // Ensure the hash value is within the array length const index = Math.abs(hash) % colorArray.length // Return the selected color return colorArray[index] } // Function to convert hex color to RGB function hexToRGBObject(hexColor: string) { // Remove '#' if present in the hexColor hexColor = hexColor.replace(/^#/, '') // Split the hexColor into red, green, and blue components const r = parseInt(hexColor.substring(0, 2), 16) const g = parseInt(hexColor.substring(2, 4), 16) const b = parseInt(hexColor.substring(4, 6), 16) return { r, g, b } } export function isColorDark(hexColor: string) { const rgbColor = hexToRGBObject(hexColor) const luminance = 0.299 * rgbColor.r + 0.587 * rgbColor.g + 0.114 * rgbColor.b // Choose a luminance threshold (e.g., 0.5) to determine darkness/lightness return luminance < 128 }
packages/nc-gui/utils/colorsUtils.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00017432263121008873, 0.0001705848117126152, 0.00016434930148534477, 0.0001711820368655026, 0.000002547933718233253 ]
{ "id": 3, "code_window": [ " const dateTimeFormat = getDateTimeFormat(data[key])\n", " d = dayjs(data[key], dateTimeFormat).format('YYYY-MM-DD HH:mm')\n", " }\n", " return {\n", " ...aggObj,\n", " [col.column_name]: d,\n", " }\n", " }, {}),\n", " )\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " [col.title]: d,\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 297 }
<script setup lang="ts"> import { navigateTo, useDark, useRoute, useRouter, useSharedFormStoreOrThrow, useTheme, watch } from '#imports' const { sharedViewMeta } = useSharedFormStoreOrThrow() const isDark = useDark() const { setTheme } = useTheme() const route = useRoute() const router = useRouter() watch( () => sharedViewMeta.value.withTheme, (hasTheme) => { if (hasTheme && sharedViewMeta.value.theme) setTheme(sharedViewMeta.value.theme) }, { immediate: true }, ) const onClick = () => { isDark.value = !isDark.value } const shouldRedirect = (to: string) => { if (sharedViewMeta.value.surveyMode) { if (!to.includes('survey')) navigateTo(`/nc/form/${route.params.viewId}/survey`) } else { if (to.includes('survey')) navigateTo(`/nc/form/${route.params.viewId}`) } } shouldRedirect(route.name as string) router.afterEach((to) => shouldRedirect(to.name as string)) </script> <template> <div class="scrollbar-thin-dull overflow-y-auto overflow-x-hidden flex flex-col color-transition nc-form-view relative bg-primary bg-opacity-10 dark:(bg-slate-900) h-[100vh] min-h-[600px] py-4" > <NuxtPage /> <div class="color-transition flex items-center justify-center cursor-pointer absolute top-4 md:top-15 right-4 md:right-15 rounded-full p-2 bg-white dark:(bg-slate-600) shadow hover:(ring-1 ring-accent ring-opacity-100)" @click="onClick" > <Transition name="slide-left" duration="250" mode="out-in"> <MaterialSymbolsDarkModeOutline v-if="isDark" /> <MaterialSymbolsLightModeOutline v-else /> </Transition> </div> </div> </template> <style lang="scss"> html, body, h1, h2, h3, h4, h5, h6, p { @apply dark:text-white color-transition; } .nc-form-view { .nc-cell { @apply bg-white dark:bg-slate-500; &.nc-cell-checkbox { @apply color-transition !border-0; .nc-icon { @apply !text-2xl; } .nc-cell-hover-show { opacity: 100 !important; div { background-color: transparent !important; } } } &:not(.nc-cell-checkbox) { @apply bg-white dark:bg-slate-500; &.nc-input { @apply w-full rounded p-2 min-h-[40px] flex items-center border-solid border-1 border-gray-300 dark:border-slate-200; .duration-cell-wrapper { @apply w-full; input { @apply !outline-none; &::placeholder { @apply text-gray-400 dark:text-slate-300; } } } input, textarea, &.nc-virtual-cell, > div { @apply bg-white dark:(bg-slate-500 text-white); .ant-btn { @apply dark:(bg-slate-300); } .chip { @apply dark:(bg-slate-700 text-white); } } textarea { @apply px-4 py-2 rounded; &:focus { box-shadow: none !important; } } } } .nc-attachment-cell > div { @apply dark:(bg-slate-100); } } } .nc-form-column-label { > * { @apply dark:text-slate-300; } } </style>
packages/nc-gui/pages/index/[typeOrId]/form/[viewId]/index.vue
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0001751886011334136, 0.00017206645861733705, 0.00016802146274130791, 0.0001727691269479692, 0.0000021964510779071134 ]
{ "id": 3, "code_window": [ " const dateTimeFormat = getDateTimeFormat(data[key])\n", " d = dayjs(data[key], dateTimeFormat).format('YYYY-MM-DD HH:mm')\n", " }\n", " return {\n", " ...aggObj,\n", " [col.column_name]: d,\n", " }\n", " }, {}),\n", " )\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " [col.title]: d,\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 297 }
# http://editorconfig.org root = true [*] charset = utf-8 end_of_line = lf indent_size = 2 indent_style = space insert_final_newline = true max_line_length = 80 trim_trailing_whitespace = true [*.md] max_line_length = 0 trim_trailing_whitespace = false
packages/nc-plugin/.editorconfig
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00018186806119047105, 0.00017702931654639542, 0.00017219055735040456, 0.00017702931654639542, 0.000004838751920033246 ]
{ "id": 4, "code_window": [ " </template>\n", "\n", " <template #bodyCell=\"{ column, record }\">\n", " <template v-if=\"column.key === 'column_name'\">\n", " <a-form-item v-bind=\"validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]\">\n", " <a-input :ref=\"(el: HTMLInputElement) => (inputRefs[record.key] = el)\" v-model:value=\"record.column_name\" />\n", " </a-form-item>\n", " </template>\n", "\n", " <template v-else-if=\"column.key === 'uidt'\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a-input :ref=\"(el: HTMLInputElement) => (inputRefs[record.key] = el)\" v-model:value=\"record.title\" />\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 903 }
import { UITypes } from 'nocodb-sdk' import { getCheckboxValue, getColumnUIDTAndMetas } from './parserHelpers' import TemplateGenerator from './TemplateGenerator' const jsonTypeToUidt: Record<string, string> = { number: UITypes.Number, string: UITypes.SingleLineText, date: UITypes.DateTime, boolean: UITypes.Checkbox, object: UITypes.JSON, } const extractNestedData: any = (obj: any, path: any) => path.reduce((val: any, key: any) => val && val[key], obj) export default class JSONTemplateAdapter extends TemplateGenerator { config: Record<string, any> data: Record<string, any> _jsonData: string | Record<string, any> jsonData: Record<string, any> base: { tables: Record<string, any>[] } columns: object constructor(data: object, parserConfig = {}, progressCallback?: (msg: string) => void) { super(progressCallback) this.config = parserConfig this._jsonData = data this.base = { tables: [], } this.jsonData = [] this.data = [] this.columns = {} } async init() { this.progress('Initializing json parser') const parsedJsonData = typeof this._jsonData === 'string' ? // for json editor JSON.parse(this._jsonData) : // for file upload JSON.parse(new TextDecoder().decode(this._jsonData as BufferSource)) this.jsonData = Array.isArray(parsedJsonData) ? parsedJsonData : [parsedJsonData] } getColumns(): any { return this.columns } getData(): any { return this.data } parse(): any { this.progress('Parsing json data') const jsonData = this.jsonData const tn = 'table' const table: any = { table_name: tn, ref_table_name: tn, columns: [] } this.data[tn] = [] for (const col of Object.keys(jsonData[0])) { const columns = this._parseColumn([col], jsonData) table.columns.push(...columns) } if (this.config.shouldImportData) { this._parseTableData(table) } this.base.tables.push(table) } getTemplate() { return this.base } _parseColumn( path: any = [], jsonData = this.jsonData, firstRowVal = path.reduce((val: any, k: any) => val && val[k], this.jsonData[0]), ): any { const columns = [] // parse nested if (firstRowVal && typeof firstRowVal === 'object' && !Array.isArray(firstRowVal) && this.config.normalizeNested) { for (const key of Object.keys(firstRowVal)) { const normalizedNestedColumns = this._parseColumn([...path, key], this.jsonData, firstRowVal[key]) columns.push(...normalizedNestedColumns) } } else { const cn = path.join('_').replace(/\W/g, '_').trim() const column: Record<string, any> = { column_name: cn, ref_column_name: cn, uidt: UITypes.SingleLineText, path, } if (this.config.autoSelectFieldTypes) { column.uidt = jsonTypeToUidt[typeof firstRowVal] || UITypes.SingleLineText const colData = jsonData.map((r: any) => extractNestedData(r, path)) Object.assign(column, getColumnUIDTAndMetas(colData, column.uidt)) } columns.push(column) } return columns } _parseTableData(tableMeta: any) { for (const row of this.jsonData as any) { const rowData: any = {} for (let i = 0; i < tableMeta.columns.length; i++) { const value = extractNestedData(row, tableMeta.columns[i].path || []) if (tableMeta.columns[i].uidt === UITypes.Checkbox) { rowData[tableMeta.columns[i].ref_column_name] = getCheckboxValue(value) } else if (tableMeta.columns[i].uidt === UITypes.SingleSelect || tableMeta.columns[i].uidt === UITypes.MultiSelect) { rowData[tableMeta.columns[i].ref_column_name] = (value || '').toString().trim() || null } else if (tableMeta.columns[i].uidt === UITypes.JSON) { rowData[tableMeta.columns[i].ref_column_name] = JSON.stringify(value) } else { // toto: do parsing if necessary based on type rowData[tableMeta.columns[i].column_name] = value } } this.data[tableMeta.ref_table_name].push(rowData) } } }
packages/nc-gui/helpers/parsers/JSONTemplateAdapter.ts
1
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0019061056664213538, 0.00048464330029673874, 0.00016711201169528067, 0.0002454491041135043, 0.0004981287638656795 ]
{ "id": 4, "code_window": [ " </template>\n", "\n", " <template #bodyCell=\"{ column, record }\">\n", " <template v-if=\"column.key === 'column_name'\">\n", " <a-form-item v-bind=\"validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]\">\n", " <a-input :ref=\"(el: HTMLInputElement) => (inputRefs[record.key] = el)\" v-model:value=\"record.column_name\" />\n", " </a-form-item>\n", " </template>\n", "\n", " <template v-else-if=\"column.key === 'uidt'\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a-input :ref=\"(el: HTMLInputElement) => (inputRefs[record.key] = el)\" v-model:value=\"record.title\" />\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 903 }
--- title: 'Actions on table' description: 'Learn how to rename, duplicate, and delete a table in NocoDB.' tags: ['Tables', 'Rename', 'Duplicate', 'Delete'] keywords: ['NocoDB table', 'rename table', 'duplicate table', 'delete table'] --- ## Rename table 1. Access the contextual menu for the table by clicking on the ellipsis symbol (`...`) located in the left sidebar. 2. Click on the `Rename` option from the context menu. 3. Enter the desired new table name into the provided field. 4. To finalize the renaming process, click on the `Rename` button. ![image](/img/v2/table/table-context-menu.png) ![image](/img/v2/table/table-rename.png) ## Change table icon 1. Click on the existing table icon to the left of the table name in the left sidebar. 2. Select the desired icon from the list of available options. ![image](/img/v2/table/table-change-icon.png) ## Duplicate table 1. Access the contextual menu for the table by clicking on the ellipsis symbol (`...`) located in the left sidebar. 2. Click on the `Duplicate` option from the context menu. 3. For additional customization (Optional) a) Under `Include data`, you have the flexibility to choose whether to replicate the table with or without its data. b) Regarding `Include views` you can select whether to duplicate the table with or without its associated views. 4. Proceed by clicking the `Duplicate Table` button found in the confirmation dialog. A new table will be generated, mirroring the original table's schema and content, in accordance with the configurations specified in step 3. ![image](/img/v2/table/table-context-menu.png) ![image](/img/v2/table/table-duplicate.png) :::info - Duplicate table will be created in the same base as the original table - Duplicate table will carry suffix ` Copy` in its name. - Duplicate table option is not available for `External DB` projects ::: ## Delete table :::info **This action cannot be undone.** ::: 1. Access the contextual menu for the table by clicking on the ellipsis symbol (`...`) located in the left sidebar. 2. Click on the `Delete` option from the context menu. 3. To finalize the deletion process, click on the `Delete` button in the confirmation dialog. ![image](/img/v2/table/table-context-menu.png) ![image](/img/v2/table/table-delete.png) ## Related articles - [Create a new table](/tables/create-table) - [Create a table using a CSV, Excel or a JSON](/tables/create-table-via-import) - [Import data from Csv/Xlsx into existing table](/tables/import-data-into-existing-table) - [Rename a table](/tables/actions-on-table#rename-table) - [Duplicate a table](/tables/actions-on-table#duplicate-table) - [Delete a table](/tables/actions-on-table#delete-table)
packages/noco-docs/docs/050.tables/060.actions-on-table.md
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0005404621479101479, 0.00021415052469819784, 0.00016239260730799288, 0.00016817363211885095, 0.00012335814244579524 ]
{ "id": 4, "code_window": [ " </template>\n", "\n", " <template #bodyCell=\"{ column, record }\">\n", " <template v-if=\"column.key === 'column_name'\">\n", " <a-form-item v-bind=\"validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]\">\n", " <a-input :ref=\"(el: HTMLInputElement) => (inputRefs[record.key] = el)\" v-model:value=\"record.column_name\" />\n", " </a-form-item>\n", " </template>\n", "\n", " <template v-else-if=\"column.key === 'uidt'\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a-input :ref=\"(el: HTMLInputElement) => (inputRefs[record.key] = el)\" v-model:value=\"record.title\" />\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 903 }
import { XcActionType, XcType } from 'nocodb-sdk'; import TwilioWhatsappPlugin from './TwilioWhatsappPlugin'; import type { XcPluginConfig } from 'nc-plugin'; const config: XcPluginConfig = { builder: TwilioWhatsappPlugin, title: 'Whatsapp Twilio', version: '0.0.1', logo: 'plugins/whatsapp.png', description: 'With Twilio, unite communications and strengthen customer relationships across your business – from marketing and sales to customer service and operations.', price: 'Free', tags: 'Chat', category: 'Twilio', inputs: { title: 'Configure Twilio', items: [ { key: 'sid', label: 'Account SID', placeholder: 'Account SID', type: XcType.SingleLineText, required: true, }, { key: 'token', label: 'Auth Token', placeholder: 'Auth Token', type: XcType.Password, required: true, }, { key: 'from', label: 'From Phone Number', placeholder: 'From Phone Number', type: XcType.SingleLineText, required: true, }, ], actions: [ { label: 'Test', placeholder: 'Test', key: 'test', actionType: XcActionType.TEST, type: XcType.Button, }, { label: 'Save', placeholder: 'Save', key: 'save', actionType: XcActionType.SUBMIT, type: XcType.Button, }, ], msgOnInstall: 'Successfully installed and Whatsapp Twilio is enabled for notification.', msgOnUninstall: '', }, }; export default config;
packages/nocodb/src/plugins/twilioWhatsapp/index.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0001737398561090231, 0.00017134145309682935, 0.00016504971426911652, 0.00017260611639358103, 0.000002789913878586958 ]
{ "id": 4, "code_window": [ " </template>\n", "\n", " <template #bodyCell=\"{ column, record }\">\n", " <template v-if=\"column.key === 'column_name'\">\n", " <a-form-item v-bind=\"validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]\">\n", " <a-input :ref=\"(el: HTMLInputElement) => (inputRefs[record.key] = el)\" v-model:value=\"record.column_name\" />\n", " </a-form-item>\n", " </template>\n", "\n", " <template v-else-if=\"column.key === 'uidt'\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a-input :ref=\"(el: HTMLInputElement) => (inputRefs[record.key] = el)\" v-model:value=\"record.title\" />\n" ], "file_path": "packages/nc-gui/components/template/Editor.vue", "type": "replace", "edit_start_line_idx": 903 }
engine-strict=true shamefully-hoist=true use-node-version=18.14.0
.npmrc
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00016706388851162046, 0.00016706388851162046, 0.00016706388851162046, 0.00016706388851162046, 0 ]
{ "id": 5, "code_window": [ " this.tables[tableIdx] = []\n", "\n", " for (const [columnIdx, columnName] of columnNames.entries()) {\n", " let cn: string = ((columnNameRowExist && columnName.toString().trim()) || `field_${columnIdx + 1}`)\n", " .replace(/[` ~!@#$%^&*()_|+\\-=?;:'\",.<>\\{\\}\\[\\]\\\\\\/]/g, '_')\n", " .trim()\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " let title = ((columnNameRowExist && columnName.toString().trim()) || `Field ${columnIdx + 1}`).trim()\n" ], "file_path": "packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 60 }
<script setup lang="ts"> import dayjs from 'dayjs' import utc from 'dayjs/plugin/utc' import type { ColumnType, TableType } from 'nocodb-sdk' import { UITypes, isSystemColumn, isVirtualCol } from 'nocodb-sdk' import type { CheckboxChangeEvent } from 'ant-design-vue/es/checkbox/interface' import { srcDestMappingColumns, tableColumns } from './utils' import { Empty, Form, ImportWorkerOperations, ImportWorkerResponse, MetaInj, ReloadViewDataHookInj, TabType, computed, createEventHook, extractSdkResponseErrorMsg, fieldLengthValidator, fieldRequiredValidator, getDateFormat, getDateTimeFormat, getUIDTIcon, iconMap, inject, message, nextTick, onMounted, parseStringDate, reactive, ref, storeToRefs, useBase, useI18n, useNuxtApp, useTabs, validateTableName, } from '#imports' const { quickImportType, baseTemplate, importData, importColumns, importDataOnly, maxRowsToParse, sourceId, importWorker } = defineProps<Props>() const emit = defineEmits(['import', 'error', 'change']) dayjs.extend(utc) const { t } = useI18n() interface Props { quickImportType: 'csv' | 'excel' | 'json' baseTemplate: Record<string, any> importData: Record<string, any> importColumns: any[] importDataOnly: boolean maxRowsToParse: number sourceId: string importWorker: Worker } interface Option { label: string value: string } const meta = inject(MetaInj, ref()) const columns = computed(() => meta.value?.columns || []) const reloadHook = inject(ReloadViewDataHookInj, createEventHook()) const useForm = Form.useForm const { $api } = useNuxtApp() const { addTab } = useTabs() const baseStrore = useBase() const { loadTables } = baseStrore const { sqlUis, base } = storeToRefs(baseStrore) const { openTable } = useTablesStore() const { baseTables } = storeToRefs(useTablesStore()) const sqlUi = ref(sqlUis.value[sourceId] || Object.values(sqlUis.value)[0]) const hasSelectColumn = ref<boolean[]>([]) const expansionPanel = ref<number[]>([]) const editableTn = ref<boolean[]>([]) const inputRefs = ref<HTMLInputElement[]>([]) const isImporting = ref(false) const importingTips = ref<Record<string, string>>({}) const checkAllRecord = ref<boolean[]>([]) const formError = ref() const uiTypeOptions = ref<Option[]>( (Object.keys(UITypes) as (keyof typeof UITypes)[]) .filter( (uiType) => !isVirtualCol(UITypes[uiType]) && ![UITypes.ForeignKey, UITypes.ID, UITypes.CreateTime, UITypes.LastModifiedTime, UITypes.Barcode, UITypes.Button].includes( UITypes[uiType], ), ) .map<Option>((uiType) => ({ value: uiType, label: uiType, })), ) const srcDestMapping = ref<Record<string, Record<string, any>[]>>({}) const data = reactive<{ title: string | null name: string tables: (TableType & { ref_table_name: string; columns: (ColumnType & { key: number; _disableSelect?: boolean })[] })[] }>({ title: null, name: 'Base Name', tables: [], }) const validators = computed(() => data.tables.reduce<Record<string, [ReturnType<typeof fieldRequiredValidator>]>>((acc: Record<string, any>, table, tableIdx) => { acc[`tables.${tableIdx}.table_name`] = [validateTableName] hasSelectColumn.value[tableIdx] = false table.columns?.forEach((column, columnIdx) => { acc[`tables.${tableIdx}.columns.${columnIdx}.column_name`] = [ fieldRequiredValidator(), fieldLengthValidator(), ] acc[`tables.${tableIdx}.columns.${columnIdx}.uidt`] = [fieldRequiredValidator()] if (isSelect(column)) { hasSelectColumn.value[tableIdx] = true } }) return acc }, {}), ) const { validate, validateInfos, modelRef } = useForm(data, validators) const isValid = ref(!importDataOnly) const formRef = ref() watch( () => srcDestMapping.value, () => { let res = true if (importDataOnly) { for (const tn of Object.keys(srcDestMapping.value)) { if (!atLeastOneEnabledValidation(tn)) { res = false } for (const record of srcDestMapping.value[tn]) { if (!fieldsValidation(record, tn)) { return false } } } } else { for (const [_, o] of Object.entries(validateInfos)) { if (o?.validateStatus) { if (o.validateStatus === 'error') { res = false } } } } isValid.value = res }, { deep: true }, ) const prevEditableTn = ref<string[]>([]) onMounted(() => { parseAndLoadTemplate() // used to record the previous EditableTn values // for checking the table duplication in current import // and updating the key in importData prevEditableTn.value = data.tables.map((t) => t.table_name) if (importDataOnly) { mapDefaultColumns() } nextTick(() => { inputRefs.value[0]?.focus() }) }) function filterOption(input: string, option: Option) { return option.value.toUpperCase().includes(input.toUpperCase()) } function parseAndLoadTemplate() { if (baseTemplate) { parseTemplate(baseTemplate) expansionPanel.value = Array.from({ length: data.tables.length || 0 }, (_, i) => i) hasSelectColumn.value = Array.from({ length: data.tables.length || 0 }, () => false) } } function parseTemplate({ tables = [], ...rest }: Props['baseTemplate']) { const parsedTemplate = { ...rest, tables: tables.map(({ v = [], columns = [], ...rest }) => ({ ...rest, columns: [ ...columns.map((c: any, idx: number) => { c.key = idx return c }), ...v.map((v: any) => ({ column_name: v.title, table_name: { ...v, }, })), ], })), } Object.assign(data, parsedTemplate) } function isSelect(col: ColumnType) { return col.uidt === 'MultiSelect' || col.uidt === 'SingleSelect' } function deleteTable(tableIdx: number) { data.tables.splice(tableIdx, 1) } function deleteTableColumn(tableIdx: number, columnKey: number) { const columnIdx = data.tables[tableIdx].columns.findIndex((c: ColumnType & { key: number }) => c.key === columnKey) data.tables[tableIdx].columns.splice(columnIdx, 1) } function addNewColumnRow(tableIdx: number, uidt: string) { data.tables[tableIdx].columns.push({ key: data.tables[tableIdx].columns.length, column_name: `title${data.tables[tableIdx].columns.length + 1}`, uidt, }) nextTick(() => { const input = inputRefs.value[data.tables[tableIdx].columns.length - 1] input.focus() input.select() }) } function setEditableTn(tableIdx: number, val: boolean) { editableTn.value[tableIdx] = val } function remapColNames(batchData: any[], columns: ColumnType[]) { const dateFormatMap: Record<number, string> = {} return batchData.map((data) => (columns || []).reduce((aggObj, col: Record<string, any>) => { // for excel & json, if the column name is changed in TemplateEditor, // then only col.column_name exists in data, else col.ref_column_name // for csv, col.column_name always exists in data // since it streams the data in getData() with the updated col.column_name const key = col.column_name in data ? col.column_name : col.ref_column_name let d = data[key] if (col.uidt === UITypes.Date && d) { let dateFormat if (col?.meta?.date_format) { dateFormat = col.meta.date_format dateFormatMap[col.key] = dateFormat } else if (col.key in dateFormatMap) { dateFormat = dateFormatMap[col.key] } else { dateFormat = getDateFormat(d) dateFormatMap[col.key] = dateFormat } d = parseStringDate(d, dateFormat) } else if (col.uidt === UITypes.DateTime && d) { const dateTimeFormat = getDateTimeFormat(data[key]) d = dayjs(data[key], dateTimeFormat).format('YYYY-MM-DD HH:mm') } return { ...aggObj, [col.column_name]: d, } }, {}), ) } function missingRequiredColumnsValidation(tn: string) { const missingRequiredColumns = columns.value.filter( (c: Record<string, any>) => (c.pk ? !c.ai && !c.cdf : !c.cdf && c.rqd) && !srcDestMapping.value[tn].some((r: Record<string, any>) => r.destCn === c.title), ) if (missingRequiredColumns.length) { message.error(`${t('msg.error.columnsRequired')} : ${missingRequiredColumns.map((c) => c.title).join(', ')}`) return false } return true } function atLeastOneEnabledValidation(tn: string) { if (srcDestMapping.value[tn].filter((v: Record<string, any>) => v.enabled === true).length === 0) { message.error(t('msg.error.selectAtleastOneColumn')) return false } return true } function fieldsValidation(record: Record<string, any>, tn: string) { // if it is not selected, then pass validation if (!record.enabled) { return true } if (!record.destCn) { message.error(`${t('msg.error.columnDescriptionNotFound')} ${record.srcCn}`) return false } if (srcDestMapping.value[tn].filter((v: Record<string, any>) => v.destCn === record.destCn).length > 1) { message.error(t('msg.error.duplicateMappingFound')) return false } const v = columns.value.find((c) => c.title === record.destCn) as Record<string, any> for (const tableName of Object.keys(importData)) { // check if the input contains null value for a required column if (v.pk ? !v.ai && !v.cdf : !v.cdf && v.rqd) { if ( importData[tableName] .slice(0, maxRowsToParse) .some((r: Record<string, any>) => r[record.srcCn] === null || r[record.srcCn] === undefined || r[record.srcCn] === '') ) { message.error(t('msg.error.nullValueViolatesNotNull')) } } switch (v.uidt) { case UITypes.Number: if ( importData[tableName] .slice(0, maxRowsToParse) .some( (r: Record<string, any>) => r[record.sourceCn] !== null && r[record.srcCn] !== undefined && isNaN(+r[record.srcCn]), ) ) { message.error(t('msg.error.sourceHasInvalidNumbers')) return false } break case UITypes.Checkbox: if ( importData[tableName].slice(0, maxRowsToParse).some((r: Record<string, any>) => { if (r[record.srcCn] !== null && r[record.srcCn] !== undefined) { let input = r[record.srcCn] if (typeof input === 'string') { input = input.replace(/["']/g, '').toLowerCase().trim() return !( input === 'false' || input === 'no' || input === 'n' || input === '0' || input === 'true' || input === 'yes' || input === 'y' || input === '1' ) } return input !== 1 && input !== 0 && input !== true && input !== false } return false }) ) { message.error(t('msg.error.sourceHasInvalidBoolean')) return false } break } } return true } function updateImportTips(baseName: string, tableName: string, progress: number, total: number) { importingTips.value[`${baseName}-${tableName}`] = `Importing data to ${baseName} - ${tableName}: ${progress}/${total} records` } async function importTemplate() { if (importDataOnly) { for (const table of data.tables) { // validate required columns if (!missingRequiredColumnsValidation(table.table_name)) return // validate at least one column needs to be selected if (!atLeastOneEnabledValidation(table.table_name)) return } try { isImporting.value = true const tableId = meta.value?.id const baseId = base.value.id! const table_names = data.tables.map((t: Record<string, any>) => t.table_name) await Promise.all( Object.keys(importData).map((key: string) => (async (k) => { if (!table_names.includes(k)) { return } const data = importData[k] const total = data.length for (let i = 0, progress = 0; i < total; i += maxRowsToParse) { const batchData = data.slice(i, i + maxRowsToParse).map((row: Record<string, any>) => srcDestMapping.value[k].reduce((res: Record<string, any>, col: Record<string, any>) => { if (col.enabled && col.destCn) { const v = columns.value.find((c: Record<string, any>) => c.title === col.destCn) as Record<string, any> let input = row[col.srcCn] // parse potential boolean values if (v.uidt === UITypes.Checkbox) { input = input ? input.replace(/["']/g, '').toLowerCase().trim() : 'false' if (input === 'false' || input === 'no' || input === 'n') { input = '0' } else if (input === 'true' || input === 'yes' || input === 'y') { input = '1' } } else if (v.uidt === UITypes.Number) { if (input === '') { input = null } } else if (v.uidt === UITypes.SingleSelect || v.uidt === UITypes.MultiSelect) { if (input === '') { input = null } } else if (v.uidt === UITypes.Date) { if (input) { input = parseStringDate(input, v.meta.date_format) } } res[col.destCn] = input } return res }, {}), ) await $api.dbTableRow.bulkCreate('noco', baseId, tableId!, batchData) updateImportTips(baseId, tableId!, progress, total) progress += batchData.length } })(key), ), ) // reload table reloadHook.trigger() // Successfully imported table data message.success(t('msg.success.tableDataImported')) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { isImporting.value = false } } else { // check if form is valid try { await validate() } catch (errorInfo) { isImporting.value = false throw new Error('Please fill all the required values') } try { isImporting.value = true // tab info to be used to show the tab after successful import const tab = { id: '', title: '', baseId: '', } // create tables for (const table of data.tables) { // enrich system fields if not provided // e.g. id, created_at, updated_at const systemColumns = sqlUi?.value.getNewTableColumns().filter((c: ColumnType) => c.column_name !== 'title') for (const systemColumn of systemColumns) { if (!table.columns?.some((c) => c.column_name?.toLowerCase() === systemColumn.column_name.toLowerCase())) { table.columns?.push(systemColumn) } } if (table.columns) { for (const column of table.columns) { // set pk & rqd if ID is provided if (column.column_name?.toLowerCase() === 'id' && !('pk' in column)) { column.pk = true column.rqd = true } if ( (!isSystemColumn(column) || ['created_at', 'updated_at'].includes(column.column_name!)) && column.uidt !== UITypes.SingleSelect && column.uidt !== UITypes.MultiSelect ) { // delete dtxp if the final data type is not single & multi select // e.g. import -> detect as single / multi select -> switch to SingleLineText // the correct dtxp will be generated during column creation delete column.dtxp } } } const createdTable = await $api.source.tableCreate(base.value?.id as string, (sourceId || base.value?.sources?.[0].id)!, { table_name: table.table_name, // leave title empty to get a generated one based on table_name title: '', columns: table.columns || [], }) if (process.env.NC_SANITIZE_COLUMN_NAME !== 'false') { // column_name could have been updated in tableCreate // e.g. sanitize column name to something like field_1, field_2, and etc createdTable.columns.forEach((column, i) => { table.columns[i].column_name = column.column_name }) } table.id = createdTable.id table.title = createdTable.title // open the first table after import if (tab.id === '' && tab.title === '' && tab.baseId === '') { tab.id = createdTable.id as string tab.title = createdTable.title as string tab.baseId = base.value.id as string } // set display value if (createdTable?.columns?.[0]?.id) { await $api.dbTableColumn.primaryColumnSet(createdTable.columns[0].id as string) } } // bulk insert data if (importData) { const offset = maxRowsToParse const baseName = base.value.title as string await Promise.all( data.tables.map((table: Record<string, any>) => (async (tableMeta) => { let progress = 0 let total = 0 // use ref_table_name here instead of table_name // since importData[talbeMeta.table_name] would be empty after renaming const data = importData[tableMeta.ref_table_name] if (data) { total += data.length for (let i = 0; i < data.length; i += offset) { updateImportTips(baseName, tableMeta.title, progress, total) const batchData = remapColNames(data.slice(i, i + offset), tableMeta.columns) await $api.dbTableRow.bulkCreate('noco', base.value.id, tableMeta.id, batchData) progress += batchData.length } updateImportTips(baseName, tableMeta.title, total, total) } })(table), ), ) } // reload table list await loadTables() addTab({ ...tab, type: TabType.TABLE, }) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { isImporting.value = false } } if (!data.tables?.length) return const tables = baseTables.value.get(base.value!.id!) const toBeNavigatedTable = tables?.find((t) => t.id === data.tables[0].id) if (!toBeNavigatedTable) return openTable(toBeNavigatedTable) } function mapDefaultColumns() { srcDestMapping.value = {} for (let i = 0; i < data.tables.length; i++) { for (const col of importColumns[i]) { const o = { srcCn: col.column_name, destCn: '', enabled: true } if (columns.value) { const tableColumn = columns.value.find((c) => c.column_name === col.column_name) if (tableColumn) { o.destCn = tableColumn.title as string } else { o.enabled = false } } if (!(data.tables[i].table_name in srcDestMapping.value)) { srcDestMapping.value[data.tables[i].table_name] = [] } srcDestMapping.value[data.tables[i].table_name].push(o) } } } defineExpose({ importTemplate, isValid, }) function handleEditableTnChange(idx: number) { const oldValue = prevEditableTn.value[idx] const newValue = data.tables[idx].table_name if (data.tables.filter((t) => t.table_name === newValue).length > 1) { message.warn('Duplicate Table Name') data.tables[idx].table_name = oldValue } else { prevEditableTn.value[idx] = newValue } setEditableTn(idx, false) } function isSelectDisabled(uidt: string, disableSelect = false) { return (uidt === UITypes.SingleSelect || uidt === UITypes.MultiSelect) && disableSelect } function handleCheckAllRecord(event: CheckboxChangeEvent, tableName: string) { const isChecked = event.target.checked for (const record of srcDestMapping.value[tableName]) { record.enabled = isChecked } } function handleUIDTChange(column, table) { if (!importWorker) return const handler = (e) => { const [type, payload] = e.data switch (type) { case ImportWorkerResponse.SINGLE_SELECT_OPTIONS: case ImportWorkerResponse.MULTI_SELECT_OPTIONS: importWorker.removeEventListener('message', handler, false) column.dtxp = payload break } } if (column.uidt === UITypes.SingleSelect) { importWorker.addEventListener('message', handler, false) importWorker.postMessage([ ImportWorkerOperations.GET_SINGLE_SELECT_OPTIONS, { tableName: table.ref_table_name, columnName: column.ref_column_name, }, ]) } else if (column.uidt === UITypes.MultiSelect) { importWorker.addEventListener('message', handler, false) importWorker.postMessage([ ImportWorkerOperations.GET_MULTI_SELECT_OPTIONS, { tableName: table.ref_table_name, columnName: column.ref_column_name, }, ]) } } const setErrorState = (errorsFields: any[]) => { const errorMap: any = {} for (const error of errorsFields) { errorMap[error.name] = error.errors } formError.value = errorMap } watch(formRef, () => { setTimeout(async () => { try { await validate() emit('change') formError.value = null } catch (e: any) { emit('error', e) setErrorState(e.errorFields) } }, 500) }) watch(modelRef, async () => { try { await validate() emit('change') formError.value = null } catch (e: any) { emit('error', e) setErrorState(e.errorFields) } }) </script> <template> <a-spin :spinning="isImporting" size="large"> <template #tip> <p v-for="(importingTip, idx) of importingTips" :key="idx" class="mt-[10px]"> {{ importingTip }} </p> </template> <a-card v-if="importDataOnly"> <a-form :model="data" name="import-only"> <p v-if="data.tables && quickImportType === 'excel'" class="text-center"> {{ data.tables.length }} sheet{{ data.tables.length > 1 ? 's' : '' }} available for import </p> </a-form> <a-collapse v-if="data.tables && data.tables.length" v-model:activeKey="expansionPanel" class="template-collapse" accordion> <a-collapse-panel v-for="(table, tableIdx) of data.tables" :key="tableIdx"> <template #header> <span class="font-weight-bold text-lg flex items-center gap-2 truncate"> <component :is="iconMap.table" class="text-primary" /> {{ table.table_name }} </span> </template> <template #extra> <a-tooltip bottom> <template #title> <span>{{ $t('activity.deleteTable') }}</span> </template> <component :is="iconMap.delete" v-if="data.tables.length > 1" class="text-lg mr-8" @click.stop="deleteTable(tableIdx)" /> </a-tooltip> </template> <a-table v-if="srcDestMapping" class="template-form" row-class-name="template-form-row" :data-source="srcDestMapping[table.table_name]" :columns="srcDestMappingColumns" :pagination="false" > <template #emptyText> <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noData')" /> </template> <template #headerCell="{ column }"> <span v-if="column.key === 'source_column' || column.key === 'destination_column'"> {{ column.name }} </span> <span v-if="column.key === 'action'"> <a-checkbox v-model:checked="checkAllRecord[table.table_name]" @change="handleCheckAllRecord($event, table.table_name)" /> </span> </template> <template #bodyCell="{ column, record }"> <template v-if="column.key === 'source_column'"> <span>{{ record.srcCn }}</span> </template> <template v-else-if="column.key === 'destination_column'"> <a-select v-model:value="record.destCn" class="w-52" show-search :filter-option="filterOption" dropdown-class-name="nc-dropdown-filter-field" > <a-select-option v-for="(col, i) of columns" :key="i" :value="col.title"> <div class="flex items-center"> <component :is="getUIDTIcon(col.uidt)" /> <span class="ml-2">{{ col.title }}</span> </div> </a-select-option> </a-select> </template> <template v-if="column.key === 'action'"> <a-checkbox v-model:checked="record.enabled" /> </template> </template> </a-table> </a-collapse-panel> </a-collapse> </a-card> <a-card v-else> <a-form ref="formRef" :model="data" name="template-editor-form" @keydown.enter="emit('import')"> <p v-if="data.tables && quickImportType === 'excel'" class="text-center"> {{ data.tables.length }} sheet{{ data.tables.length > 1 ? 's' : '' }} available for import </p> <a-collapse v-if="data.tables && data.tables.length" v-model:activeKey="expansionPanel" class="template-collapse" accordion > <a-collapse-panel v-for="(table, tableIdx) of data.tables" :key="tableIdx"> <template #header> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.table_name`]" no-style> <div class="flex flex-col w-full"> <a-input v-model:value="table.table_name" class="font-weight-bold text-lg" size="large" hide-details :bordered="false" @click.stop @blur="handleEditableTnChange(tableIdx)" @keydown.enter="handleEditableTnChange(tableIdx)" @dblclick="setEditableTn(tableIdx, true)" /> <div v-if="formError?.[`tables.${tableIdx}.table_name`]" class="text-red-500 ml-3"> {{ formError?.[`tables.${tableIdx}.table_name`].join('\n') }} </div> </div> </a-form-item> </template> <template #extra> <a-tooltip bottom> <template #title> <span>{{ $t('activity.deleteTable') }}</span> </template> <component :is="iconMap.delete" v-if="data.tables.length > 1" class="text-lg mr-8" @click.stop="deleteTable(tableIdx)" /> </a-tooltip> </template> <a-table v-if="table.columns && table.columns.length" class="template-form" row-class-name="template-form-row" :data-source="table.columns" :columns="tableColumns" :pagination="table.columns.length > 50 ? { defaultPageSize: 50, position: ['bottomCenter'] } : false" > <template #emptyText> <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noData')" /> </template> <template #headerCell="{ column }"> <template v-if="column.key === 'column_name'"> <span> {{ $t('labels.columnName') }} </span> </template> <template v-else-if="column.key === 'uidt'"> <span> {{ $t('labels.columnType') }} </span> </template> <template v-else-if="column.key === 'dtxp' && hasSelectColumn[tableIdx]"> <span> {{ $t('general.options') }} </span> </template> </template> <template #bodyCell="{ column, record }"> <template v-if="column.key === 'column_name'"> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]"> <a-input :ref="(el: HTMLInputElement) => (inputRefs[record.key] = el)" v-model:value="record.column_name" /> </a-form-item> </template> <template v-else-if="column.key === 'uidt'"> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]"> <a-select v-model:value="record.uidt" class="w-52" show-search :filter-option="filterOption" dropdown-class-name="nc-dropdown-template-uidt" @change="handleUIDTChange(record, table)" > <a-select-option v-for="(option, i) of uiTypeOptions" :key="i" :value="option.value"> <a-tooltip placement="right"> <template v-if="isSelectDisabled(option.label, table.columns[record.key]?._disableSelect)" #title> {{ $t('msg.tooLargeFieldEntity', { entity: option.label, }) }} </template> {{ option.label }} </a-tooltip> </a-select-option> </a-select> </a-form-item> </template> <template v-else-if="column.key === 'dtxp'"> <a-form-item v-if="isSelect(record)"> <a-input v-model:value="record.dtxp" /> </a-form-item> </template> <template v-if="column.key === 'action'"> <a-tooltip v-if="record.key === 0"> <template #title> <span>{{ $t('general.primaryValue') }}</span> </template> <div class="flex items-center float-right mr-4"> <mdi-key-star class="text-lg" /> </div> </a-tooltip> <a-tooltip v-else> <template #title> <span>{{ $t('activity.column.delete') }}</span> </template> <a-button type="text" @click="deleteTableColumn(tableIdx, record.key)"> <div class="flex items-center"> <component :is="iconMap.delete" class="text-lg" /> </div> </a-button> </a-tooltip> </template> </template> </a-table> <div class="mt-5 flex gap-2 justify-center"> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addNumber') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'Number')"> <div class="flex items-center"> <component :is="iconMap.number" class="group-hover:!text-accent flex text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addSingleLineText') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'SingleLineText')"> <div class="flex items-center"> <component :is="iconMap.text" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addLongText') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'LongText')"> <div class="flex items-center"> <component :is="iconMap.longText" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addOther') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'SingleLineText')"> <div class="flex items-center gap-1"> <component :is="iconMap.plus" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> </div> </a-collapse-panel> </a-collapse> </a-form> </a-card> </a-spin> </template> <style scoped lang="scss"> .template-collapse { @apply bg-white; } .template-form { :deep(.ant-table-thead) > tr > th { @apply bg-white; } :deep(.template-form-row) > td { @apply p-0 mb-0; .ant-form-item { @apply mb-0; } } } </style>
packages/nc-gui/components/template/Editor.vue
1
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.9898199439048767, 0.07185259461402893, 0.00016348386998288333, 0.00020439547370187938, 0.23034027218818665 ]
{ "id": 5, "code_window": [ " this.tables[tableIdx] = []\n", "\n", " for (const [columnIdx, columnName] of columnNames.entries()) {\n", " let cn: string = ((columnNameRowExist && columnName.toString().trim()) || `field_${columnIdx + 1}`)\n", " .replace(/[` ~!@#$%^&*()_|+\\-=?;:'\",.<>\\{\\}\\[\\]\\\\\\/]/g, '_')\n", " .trim()\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " let title = ((columnNameRowExist && columnName.toString().trim()) || `Field ${columnIdx + 1}`).trim()\n" ], "file_path": "packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 60 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M9.33341 1.33333H4.00008C3.64646 1.33333 3.30732 1.4738 3.05727 1.72385C2.80722 1.9739 2.66675 2.31304 2.66675 2.66666V13.3333C2.66675 13.6869 2.80722 14.0261 3.05727 14.2761C3.30732 14.5262 3.64646 14.6667 4.00008 14.6667H12.0001C12.3537 14.6667 12.6928 14.5262 12.9429 14.2761C13.1929 14.0261 13.3334 13.6869 13.3334 13.3333V5.33333L9.33341 1.33333Z" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10.6666 11.3333H5.33325" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10.6666 8.66667H5.33325" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M6.66659 6H5.99992H5.33325" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M9.33325 1.33333V5.33333H13.3333" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> </svg>
packages/nc-gui/assets/nc-icons/file.svg
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00024305899569299072, 0.00024305899569299072, 0.00024305899569299072, 0.00024305899569299072, 0 ]
{ "id": 5, "code_window": [ " this.tables[tableIdx] = []\n", "\n", " for (const [columnIdx, columnName] of columnNames.entries()) {\n", " let cn: string = ((columnNameRowExist && columnName.toString().trim()) || `field_${columnIdx + 1}`)\n", " .replace(/[` ~!@#$%^&*()_|+\\-=?;:'\",.<>\\{\\}\\[\\]\\\\\\/]/g, '_')\n", " .trim()\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " let title = ((columnNameRowExist && columnName.toString().trim()) || `Field ${columnIdx + 1}`).trim()\n" ], "file_path": "packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 60 }
<script setup lang="ts"> import { ref, useVModel } from '#imports' interface Props { modelValue: boolean } const props = defineProps<Props>() const emits = defineEmits(['update:modelValue']) const editOrAdd = ref(false) const vModel = useVModel(props, 'modelValue', emits) const currentHook = ref<Record<string, any>>() async function editHook(hook: Record<string, any>) { editOrAdd.value = true currentHook.value = hook } async function addHook() { editOrAdd.value = true currentHook.value = undefined } </script> <template> <a-drawer v-model:visible="vModel" :closable="false" placement="right" width="700px" :body-style="{ background: 'rgba(67, 81, 232, 0.05)', padding: '0px 0px', overflow: 'hidden' }" class="nc-drawer-webhook" @keydown.esc="vModel = false" > <a-layout class="nc-drawer-webhook-body"> <a-layout-content class="px-10 py-5 scrollbar-thin-primary"> <LazyWebhookEditor v-if="editOrAdd" :hook="currentHook" @back-to-list="editOrAdd = false" /> <LazyWebhookList v-else @edit="editHook" @add="addHook" /> </a-layout-content> <a-layout-footer class="!bg-white border-t flex"> <a-button v-e="['e:hiring']" class="mx-auto mb-4 !rounded-md" href="https://angel.co/company/nocodb" target="_blank" size="large" rel="noopener noreferrer" > 🚀 {{ $t('labels.weAreHiring') }}! 🚀 </a-button> </a-layout-footer> </a-layout> </a-drawer> </template>
packages/nc-gui/components/webhook/Drawer.vue
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00017394537280779332, 0.00017224563634954393, 0.00017007580026984215, 0.00017295950965490192, 0.000001436735601600958 ]
{ "id": 5, "code_window": [ " this.tables[tableIdx] = []\n", "\n", " for (const [columnIdx, columnName] of columnNames.entries()) {\n", " let cn: string = ((columnNameRowExist && columnName.toString().trim()) || `field_${columnIdx + 1}`)\n", " .replace(/[` ~!@#$%^&*()_|+\\-=?;:'\",.<>\\{\\}\\[\\]\\\\\\/]/g, '_')\n", " .trim()\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " let title = ((columnNameRowExist && columnName.toString().trim()) || `Field ${columnIdx + 1}`).trim()\n" ], "file_path": "packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 60 }
import { test } from '@playwright/test'; import { DashboardPage } from '../../../pages/Dashboard'; import setup, { unsetup } from '../../../setup'; import { ToolbarPage } from '../../../pages/Dashboard/common/Toolbar'; import { UITypes } from 'nocodb-sdk'; import { Api } from 'nocodb-sdk'; let api: Api<any>; test.describe('Checkbox - cell, filter, sort', () => { let dashboard: DashboardPage, toolbar: ToolbarPage; let context: any; // define validateRowArray function async function validateRowArray(value: string[]) { const length = value.length; for (let i = 0; i < length; i++) { await dashboard.grid.cell.verify({ index: i, columnHeader: 'Title', value: value[i], }); } } async function verifyFilter(param: { opType: string; value?: string; result: string[] }) { await toolbar.clickFilter(); await toolbar.filter.add({ title: 'checkbox', operation: param.opType, value: param.value, locallySaved: false, dataType: 'Checkbox', }); await toolbar.clickFilter(); // verify filtered rows await validateRowArray(param.result); // Reset filter await toolbar.filter.reset(); } test.beforeEach(async ({ page }) => { context = await setup({ page, isEmptyProject: true }); dashboard = new DashboardPage(page, context.base); toolbar = dashboard.grid.toolbar; api = new Api({ baseURL: `http://localhost:8080/`, headers: { 'xc-auth': context.token, }, }); const columns = [ { column_name: 'Id', title: 'Id', uidt: UITypes.ID, }, { column_name: 'Title', title: 'Title', uidt: UITypes.SingleLineText, }, ]; try { const base = await api.base.read(context.base.id); const table = await api.source.tableCreate(context.base.id, base.sources?.[0].id, { table_name: 'Sheet-1', title: 'Sheet-1', columns: columns, }); const rowAttributes = []; for (let i = 0; i < 6; i++) { const row = { Id: i + 1, Title: `1${String.fromCharCode(97 + i)}`, }; rowAttributes.push(row); } await api.dbTableRow.bulkCreate('noco', context.base.id, table.id, rowAttributes); } catch (e) { console.error(e); } // page reload await page.reload(); }); test.afterEach(async () => { await unsetup(context); }); test('Checkbox', async () => { // close 'Team & Auth' tab await dashboard.closeTab({ title: 'Team & Auth' }); await dashboard.treeView.openTable({ title: 'Sheet-1' }); // Create Checkbox column await dashboard.grid.column.create({ title: 'checkbox', type: 'Checkbox', }); // In cell insert await dashboard.grid.cell.checkbox.click({ index: 0, columnHeader: 'checkbox' }); await dashboard.grid.cell.checkbox.click({ index: 1, columnHeader: 'checkbox' }); await dashboard.grid.cell.checkbox.click({ index: 2, columnHeader: 'checkbox' }); await dashboard.grid.cell.checkbox.click({ index: 5, columnHeader: 'checkbox' }); await dashboard.grid.cell.checkbox.click({ index: 1, columnHeader: 'checkbox' }); // verify checkbox state await dashboard.grid.cell.checkbox.verifyChecked({ index: 0, columnHeader: 'checkbox' }); await dashboard.grid.cell.checkbox.verifyChecked({ index: 2, columnHeader: 'checkbox' }); await dashboard.grid.cell.checkbox.verifyChecked({ index: 5, columnHeader: 'checkbox' }); await dashboard.grid.cell.checkbox.verifyUnchecked({ index: 1, columnHeader: 'checkbox' }); await dashboard.grid.cell.checkbox.verifyUnchecked({ index: 3, columnHeader: 'checkbox' }); await dashboard.grid.cell.checkbox.verifyUnchecked({ index: 4, columnHeader: 'checkbox' }); // column values // 1a : true // 1b : false // 1c : true // 1d : null // 1e : null // 1f : true // Filter column await verifyFilter({ opType: 'is checked', result: ['1a', '1c', '1f'] }); await verifyFilter({ opType: 'is not checked', result: ['1b', '1d', '1e'] }); // await verifyFilter({ opType: 'is equal', value: '0', result: ['1b', '1d', '1e'] }); // await verifyFilter({ opType: 'is not equal', value: '1', result: ['1b', '1d', '1e'] }); // await verifyFilter({ opType: 'is null', result: [] }); // await verifyFilter({ opType: 'is not null', result: ['1a', '1b', '1c', '1d', '1e', '1f'] }); // Sort column await toolbar.sort.add({ title: 'checkbox', ascending: true, locallySaved: false, }); for (let i = 0; i < 3; i++) { await dashboard.grid.cell.checkbox.verifyUnchecked({ index: i, columnHeader: 'checkbox' }); } for (let i = 3; i < 6; i++) { await dashboard.grid.cell.checkbox.verifyChecked({ index: i, columnHeader: 'checkbox' }); } await toolbar.sort.reset(); // sort descending & validate await toolbar.sort.add({ title: 'checkbox', ascending: false, locallySaved: false, }); for (let i = 0; i < 3; i++) { await dashboard.grid.cell.checkbox.verifyChecked({ index: i, columnHeader: 'checkbox' }); } for (let i = 3; i < 6; i++) { await dashboard.grid.cell.checkbox.verifyUnchecked({ index: i, columnHeader: 'checkbox' }); } await toolbar.sort.reset(); // TBD: Add more tests // Expanded form insert // Expanded record insert // Expanded form insert }); });
tests/playwright/tests/db/columns/columnCheckbox.spec.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.09095171838998795, 0.005242747254669666, 0.00016465861699543893, 0.00016985132242552936, 0.020787760615348816 ]
{ "id": 6, "code_window": [ " this.detectedColumnTypes[columnIdx] = {}\n", " this.distinctValues[columnIdx] = new Set<string>()\n", " this.columnValues[columnIdx] = []\n", " tableObj.columns.push({\n", " column_name: cn,\n", " ref_column_name: cn,\n", " meta: {},\n", " uidt: UITypes.SingleLineText,\n", " key: columnIdx,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " title,\n" ], "file_path": "packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 72 }
<script setup lang="ts"> import dayjs from 'dayjs' import utc from 'dayjs/plugin/utc' import type { ColumnType, TableType } from 'nocodb-sdk' import { UITypes, isSystemColumn, isVirtualCol } from 'nocodb-sdk' import type { CheckboxChangeEvent } from 'ant-design-vue/es/checkbox/interface' import { srcDestMappingColumns, tableColumns } from './utils' import { Empty, Form, ImportWorkerOperations, ImportWorkerResponse, MetaInj, ReloadViewDataHookInj, TabType, computed, createEventHook, extractSdkResponseErrorMsg, fieldLengthValidator, fieldRequiredValidator, getDateFormat, getDateTimeFormat, getUIDTIcon, iconMap, inject, message, nextTick, onMounted, parseStringDate, reactive, ref, storeToRefs, useBase, useI18n, useNuxtApp, useTabs, validateTableName, } from '#imports' const { quickImportType, baseTemplate, importData, importColumns, importDataOnly, maxRowsToParse, sourceId, importWorker } = defineProps<Props>() const emit = defineEmits(['import', 'error', 'change']) dayjs.extend(utc) const { t } = useI18n() interface Props { quickImportType: 'csv' | 'excel' | 'json' baseTemplate: Record<string, any> importData: Record<string, any> importColumns: any[] importDataOnly: boolean maxRowsToParse: number sourceId: string importWorker: Worker } interface Option { label: string value: string } const meta = inject(MetaInj, ref()) const columns = computed(() => meta.value?.columns || []) const reloadHook = inject(ReloadViewDataHookInj, createEventHook()) const useForm = Form.useForm const { $api } = useNuxtApp() const { addTab } = useTabs() const baseStrore = useBase() const { loadTables } = baseStrore const { sqlUis, base } = storeToRefs(baseStrore) const { openTable } = useTablesStore() const { baseTables } = storeToRefs(useTablesStore()) const sqlUi = ref(sqlUis.value[sourceId] || Object.values(sqlUis.value)[0]) const hasSelectColumn = ref<boolean[]>([]) const expansionPanel = ref<number[]>([]) const editableTn = ref<boolean[]>([]) const inputRefs = ref<HTMLInputElement[]>([]) const isImporting = ref(false) const importingTips = ref<Record<string, string>>({}) const checkAllRecord = ref<boolean[]>([]) const formError = ref() const uiTypeOptions = ref<Option[]>( (Object.keys(UITypes) as (keyof typeof UITypes)[]) .filter( (uiType) => !isVirtualCol(UITypes[uiType]) && ![UITypes.ForeignKey, UITypes.ID, UITypes.CreateTime, UITypes.LastModifiedTime, UITypes.Barcode, UITypes.Button].includes( UITypes[uiType], ), ) .map<Option>((uiType) => ({ value: uiType, label: uiType, })), ) const srcDestMapping = ref<Record<string, Record<string, any>[]>>({}) const data = reactive<{ title: string | null name: string tables: (TableType & { ref_table_name: string; columns: (ColumnType & { key: number; _disableSelect?: boolean })[] })[] }>({ title: null, name: 'Base Name', tables: [], }) const validators = computed(() => data.tables.reduce<Record<string, [ReturnType<typeof fieldRequiredValidator>]>>((acc: Record<string, any>, table, tableIdx) => { acc[`tables.${tableIdx}.table_name`] = [validateTableName] hasSelectColumn.value[tableIdx] = false table.columns?.forEach((column, columnIdx) => { acc[`tables.${tableIdx}.columns.${columnIdx}.column_name`] = [ fieldRequiredValidator(), fieldLengthValidator(), ] acc[`tables.${tableIdx}.columns.${columnIdx}.uidt`] = [fieldRequiredValidator()] if (isSelect(column)) { hasSelectColumn.value[tableIdx] = true } }) return acc }, {}), ) const { validate, validateInfos, modelRef } = useForm(data, validators) const isValid = ref(!importDataOnly) const formRef = ref() watch( () => srcDestMapping.value, () => { let res = true if (importDataOnly) { for (const tn of Object.keys(srcDestMapping.value)) { if (!atLeastOneEnabledValidation(tn)) { res = false } for (const record of srcDestMapping.value[tn]) { if (!fieldsValidation(record, tn)) { return false } } } } else { for (const [_, o] of Object.entries(validateInfos)) { if (o?.validateStatus) { if (o.validateStatus === 'error') { res = false } } } } isValid.value = res }, { deep: true }, ) const prevEditableTn = ref<string[]>([]) onMounted(() => { parseAndLoadTemplate() // used to record the previous EditableTn values // for checking the table duplication in current import // and updating the key in importData prevEditableTn.value = data.tables.map((t) => t.table_name) if (importDataOnly) { mapDefaultColumns() } nextTick(() => { inputRefs.value[0]?.focus() }) }) function filterOption(input: string, option: Option) { return option.value.toUpperCase().includes(input.toUpperCase()) } function parseAndLoadTemplate() { if (baseTemplate) { parseTemplate(baseTemplate) expansionPanel.value = Array.from({ length: data.tables.length || 0 }, (_, i) => i) hasSelectColumn.value = Array.from({ length: data.tables.length || 0 }, () => false) } } function parseTemplate({ tables = [], ...rest }: Props['baseTemplate']) { const parsedTemplate = { ...rest, tables: tables.map(({ v = [], columns = [], ...rest }) => ({ ...rest, columns: [ ...columns.map((c: any, idx: number) => { c.key = idx return c }), ...v.map((v: any) => ({ column_name: v.title, table_name: { ...v, }, })), ], })), } Object.assign(data, parsedTemplate) } function isSelect(col: ColumnType) { return col.uidt === 'MultiSelect' || col.uidt === 'SingleSelect' } function deleteTable(tableIdx: number) { data.tables.splice(tableIdx, 1) } function deleteTableColumn(tableIdx: number, columnKey: number) { const columnIdx = data.tables[tableIdx].columns.findIndex((c: ColumnType & { key: number }) => c.key === columnKey) data.tables[tableIdx].columns.splice(columnIdx, 1) } function addNewColumnRow(tableIdx: number, uidt: string) { data.tables[tableIdx].columns.push({ key: data.tables[tableIdx].columns.length, column_name: `title${data.tables[tableIdx].columns.length + 1}`, uidt, }) nextTick(() => { const input = inputRefs.value[data.tables[tableIdx].columns.length - 1] input.focus() input.select() }) } function setEditableTn(tableIdx: number, val: boolean) { editableTn.value[tableIdx] = val } function remapColNames(batchData: any[], columns: ColumnType[]) { const dateFormatMap: Record<number, string> = {} return batchData.map((data) => (columns || []).reduce((aggObj, col: Record<string, any>) => { // for excel & json, if the column name is changed in TemplateEditor, // then only col.column_name exists in data, else col.ref_column_name // for csv, col.column_name always exists in data // since it streams the data in getData() with the updated col.column_name const key = col.column_name in data ? col.column_name : col.ref_column_name let d = data[key] if (col.uidt === UITypes.Date && d) { let dateFormat if (col?.meta?.date_format) { dateFormat = col.meta.date_format dateFormatMap[col.key] = dateFormat } else if (col.key in dateFormatMap) { dateFormat = dateFormatMap[col.key] } else { dateFormat = getDateFormat(d) dateFormatMap[col.key] = dateFormat } d = parseStringDate(d, dateFormat) } else if (col.uidt === UITypes.DateTime && d) { const dateTimeFormat = getDateTimeFormat(data[key]) d = dayjs(data[key], dateTimeFormat).format('YYYY-MM-DD HH:mm') } return { ...aggObj, [col.column_name]: d, } }, {}), ) } function missingRequiredColumnsValidation(tn: string) { const missingRequiredColumns = columns.value.filter( (c: Record<string, any>) => (c.pk ? !c.ai && !c.cdf : !c.cdf && c.rqd) && !srcDestMapping.value[tn].some((r: Record<string, any>) => r.destCn === c.title), ) if (missingRequiredColumns.length) { message.error(`${t('msg.error.columnsRequired')} : ${missingRequiredColumns.map((c) => c.title).join(', ')}`) return false } return true } function atLeastOneEnabledValidation(tn: string) { if (srcDestMapping.value[tn].filter((v: Record<string, any>) => v.enabled === true).length === 0) { message.error(t('msg.error.selectAtleastOneColumn')) return false } return true } function fieldsValidation(record: Record<string, any>, tn: string) { // if it is not selected, then pass validation if (!record.enabled) { return true } if (!record.destCn) { message.error(`${t('msg.error.columnDescriptionNotFound')} ${record.srcCn}`) return false } if (srcDestMapping.value[tn].filter((v: Record<string, any>) => v.destCn === record.destCn).length > 1) { message.error(t('msg.error.duplicateMappingFound')) return false } const v = columns.value.find((c) => c.title === record.destCn) as Record<string, any> for (const tableName of Object.keys(importData)) { // check if the input contains null value for a required column if (v.pk ? !v.ai && !v.cdf : !v.cdf && v.rqd) { if ( importData[tableName] .slice(0, maxRowsToParse) .some((r: Record<string, any>) => r[record.srcCn] === null || r[record.srcCn] === undefined || r[record.srcCn] === '') ) { message.error(t('msg.error.nullValueViolatesNotNull')) } } switch (v.uidt) { case UITypes.Number: if ( importData[tableName] .slice(0, maxRowsToParse) .some( (r: Record<string, any>) => r[record.sourceCn] !== null && r[record.srcCn] !== undefined && isNaN(+r[record.srcCn]), ) ) { message.error(t('msg.error.sourceHasInvalidNumbers')) return false } break case UITypes.Checkbox: if ( importData[tableName].slice(0, maxRowsToParse).some((r: Record<string, any>) => { if (r[record.srcCn] !== null && r[record.srcCn] !== undefined) { let input = r[record.srcCn] if (typeof input === 'string') { input = input.replace(/["']/g, '').toLowerCase().trim() return !( input === 'false' || input === 'no' || input === 'n' || input === '0' || input === 'true' || input === 'yes' || input === 'y' || input === '1' ) } return input !== 1 && input !== 0 && input !== true && input !== false } return false }) ) { message.error(t('msg.error.sourceHasInvalidBoolean')) return false } break } } return true } function updateImportTips(baseName: string, tableName: string, progress: number, total: number) { importingTips.value[`${baseName}-${tableName}`] = `Importing data to ${baseName} - ${tableName}: ${progress}/${total} records` } async function importTemplate() { if (importDataOnly) { for (const table of data.tables) { // validate required columns if (!missingRequiredColumnsValidation(table.table_name)) return // validate at least one column needs to be selected if (!atLeastOneEnabledValidation(table.table_name)) return } try { isImporting.value = true const tableId = meta.value?.id const baseId = base.value.id! const table_names = data.tables.map((t: Record<string, any>) => t.table_name) await Promise.all( Object.keys(importData).map((key: string) => (async (k) => { if (!table_names.includes(k)) { return } const data = importData[k] const total = data.length for (let i = 0, progress = 0; i < total; i += maxRowsToParse) { const batchData = data.slice(i, i + maxRowsToParse).map((row: Record<string, any>) => srcDestMapping.value[k].reduce((res: Record<string, any>, col: Record<string, any>) => { if (col.enabled && col.destCn) { const v = columns.value.find((c: Record<string, any>) => c.title === col.destCn) as Record<string, any> let input = row[col.srcCn] // parse potential boolean values if (v.uidt === UITypes.Checkbox) { input = input ? input.replace(/["']/g, '').toLowerCase().trim() : 'false' if (input === 'false' || input === 'no' || input === 'n') { input = '0' } else if (input === 'true' || input === 'yes' || input === 'y') { input = '1' } } else if (v.uidt === UITypes.Number) { if (input === '') { input = null } } else if (v.uidt === UITypes.SingleSelect || v.uidt === UITypes.MultiSelect) { if (input === '') { input = null } } else if (v.uidt === UITypes.Date) { if (input) { input = parseStringDate(input, v.meta.date_format) } } res[col.destCn] = input } return res }, {}), ) await $api.dbTableRow.bulkCreate('noco', baseId, tableId!, batchData) updateImportTips(baseId, tableId!, progress, total) progress += batchData.length } })(key), ), ) // reload table reloadHook.trigger() // Successfully imported table data message.success(t('msg.success.tableDataImported')) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { isImporting.value = false } } else { // check if form is valid try { await validate() } catch (errorInfo) { isImporting.value = false throw new Error('Please fill all the required values') } try { isImporting.value = true // tab info to be used to show the tab after successful import const tab = { id: '', title: '', baseId: '', } // create tables for (const table of data.tables) { // enrich system fields if not provided // e.g. id, created_at, updated_at const systemColumns = sqlUi?.value.getNewTableColumns().filter((c: ColumnType) => c.column_name !== 'title') for (const systemColumn of systemColumns) { if (!table.columns?.some((c) => c.column_name?.toLowerCase() === systemColumn.column_name.toLowerCase())) { table.columns?.push(systemColumn) } } if (table.columns) { for (const column of table.columns) { // set pk & rqd if ID is provided if (column.column_name?.toLowerCase() === 'id' && !('pk' in column)) { column.pk = true column.rqd = true } if ( (!isSystemColumn(column) || ['created_at', 'updated_at'].includes(column.column_name!)) && column.uidt !== UITypes.SingleSelect && column.uidt !== UITypes.MultiSelect ) { // delete dtxp if the final data type is not single & multi select // e.g. import -> detect as single / multi select -> switch to SingleLineText // the correct dtxp will be generated during column creation delete column.dtxp } } } const createdTable = await $api.source.tableCreate(base.value?.id as string, (sourceId || base.value?.sources?.[0].id)!, { table_name: table.table_name, // leave title empty to get a generated one based on table_name title: '', columns: table.columns || [], }) if (process.env.NC_SANITIZE_COLUMN_NAME !== 'false') { // column_name could have been updated in tableCreate // e.g. sanitize column name to something like field_1, field_2, and etc createdTable.columns.forEach((column, i) => { table.columns[i].column_name = column.column_name }) } table.id = createdTable.id table.title = createdTable.title // open the first table after import if (tab.id === '' && tab.title === '' && tab.baseId === '') { tab.id = createdTable.id as string tab.title = createdTable.title as string tab.baseId = base.value.id as string } // set display value if (createdTable?.columns?.[0]?.id) { await $api.dbTableColumn.primaryColumnSet(createdTable.columns[0].id as string) } } // bulk insert data if (importData) { const offset = maxRowsToParse const baseName = base.value.title as string await Promise.all( data.tables.map((table: Record<string, any>) => (async (tableMeta) => { let progress = 0 let total = 0 // use ref_table_name here instead of table_name // since importData[talbeMeta.table_name] would be empty after renaming const data = importData[tableMeta.ref_table_name] if (data) { total += data.length for (let i = 0; i < data.length; i += offset) { updateImportTips(baseName, tableMeta.title, progress, total) const batchData = remapColNames(data.slice(i, i + offset), tableMeta.columns) await $api.dbTableRow.bulkCreate('noco', base.value.id, tableMeta.id, batchData) progress += batchData.length } updateImportTips(baseName, tableMeta.title, total, total) } })(table), ), ) } // reload table list await loadTables() addTab({ ...tab, type: TabType.TABLE, }) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { isImporting.value = false } } if (!data.tables?.length) return const tables = baseTables.value.get(base.value!.id!) const toBeNavigatedTable = tables?.find((t) => t.id === data.tables[0].id) if (!toBeNavigatedTable) return openTable(toBeNavigatedTable) } function mapDefaultColumns() { srcDestMapping.value = {} for (let i = 0; i < data.tables.length; i++) { for (const col of importColumns[i]) { const o = { srcCn: col.column_name, destCn: '', enabled: true } if (columns.value) { const tableColumn = columns.value.find((c) => c.column_name === col.column_name) if (tableColumn) { o.destCn = tableColumn.title as string } else { o.enabled = false } } if (!(data.tables[i].table_name in srcDestMapping.value)) { srcDestMapping.value[data.tables[i].table_name] = [] } srcDestMapping.value[data.tables[i].table_name].push(o) } } } defineExpose({ importTemplate, isValid, }) function handleEditableTnChange(idx: number) { const oldValue = prevEditableTn.value[idx] const newValue = data.tables[idx].table_name if (data.tables.filter((t) => t.table_name === newValue).length > 1) { message.warn('Duplicate Table Name') data.tables[idx].table_name = oldValue } else { prevEditableTn.value[idx] = newValue } setEditableTn(idx, false) } function isSelectDisabled(uidt: string, disableSelect = false) { return (uidt === UITypes.SingleSelect || uidt === UITypes.MultiSelect) && disableSelect } function handleCheckAllRecord(event: CheckboxChangeEvent, tableName: string) { const isChecked = event.target.checked for (const record of srcDestMapping.value[tableName]) { record.enabled = isChecked } } function handleUIDTChange(column, table) { if (!importWorker) return const handler = (e) => { const [type, payload] = e.data switch (type) { case ImportWorkerResponse.SINGLE_SELECT_OPTIONS: case ImportWorkerResponse.MULTI_SELECT_OPTIONS: importWorker.removeEventListener('message', handler, false) column.dtxp = payload break } } if (column.uidt === UITypes.SingleSelect) { importWorker.addEventListener('message', handler, false) importWorker.postMessage([ ImportWorkerOperations.GET_SINGLE_SELECT_OPTIONS, { tableName: table.ref_table_name, columnName: column.ref_column_name, }, ]) } else if (column.uidt === UITypes.MultiSelect) { importWorker.addEventListener('message', handler, false) importWorker.postMessage([ ImportWorkerOperations.GET_MULTI_SELECT_OPTIONS, { tableName: table.ref_table_name, columnName: column.ref_column_name, }, ]) } } const setErrorState = (errorsFields: any[]) => { const errorMap: any = {} for (const error of errorsFields) { errorMap[error.name] = error.errors } formError.value = errorMap } watch(formRef, () => { setTimeout(async () => { try { await validate() emit('change') formError.value = null } catch (e: any) { emit('error', e) setErrorState(e.errorFields) } }, 500) }) watch(modelRef, async () => { try { await validate() emit('change') formError.value = null } catch (e: any) { emit('error', e) setErrorState(e.errorFields) } }) </script> <template> <a-spin :spinning="isImporting" size="large"> <template #tip> <p v-for="(importingTip, idx) of importingTips" :key="idx" class="mt-[10px]"> {{ importingTip }} </p> </template> <a-card v-if="importDataOnly"> <a-form :model="data" name="import-only"> <p v-if="data.tables && quickImportType === 'excel'" class="text-center"> {{ data.tables.length }} sheet{{ data.tables.length > 1 ? 's' : '' }} available for import </p> </a-form> <a-collapse v-if="data.tables && data.tables.length" v-model:activeKey="expansionPanel" class="template-collapse" accordion> <a-collapse-panel v-for="(table, tableIdx) of data.tables" :key="tableIdx"> <template #header> <span class="font-weight-bold text-lg flex items-center gap-2 truncate"> <component :is="iconMap.table" class="text-primary" /> {{ table.table_name }} </span> </template> <template #extra> <a-tooltip bottom> <template #title> <span>{{ $t('activity.deleteTable') }}</span> </template> <component :is="iconMap.delete" v-if="data.tables.length > 1" class="text-lg mr-8" @click.stop="deleteTable(tableIdx)" /> </a-tooltip> </template> <a-table v-if="srcDestMapping" class="template-form" row-class-name="template-form-row" :data-source="srcDestMapping[table.table_name]" :columns="srcDestMappingColumns" :pagination="false" > <template #emptyText> <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noData')" /> </template> <template #headerCell="{ column }"> <span v-if="column.key === 'source_column' || column.key === 'destination_column'"> {{ column.name }} </span> <span v-if="column.key === 'action'"> <a-checkbox v-model:checked="checkAllRecord[table.table_name]" @change="handleCheckAllRecord($event, table.table_name)" /> </span> </template> <template #bodyCell="{ column, record }"> <template v-if="column.key === 'source_column'"> <span>{{ record.srcCn }}</span> </template> <template v-else-if="column.key === 'destination_column'"> <a-select v-model:value="record.destCn" class="w-52" show-search :filter-option="filterOption" dropdown-class-name="nc-dropdown-filter-field" > <a-select-option v-for="(col, i) of columns" :key="i" :value="col.title"> <div class="flex items-center"> <component :is="getUIDTIcon(col.uidt)" /> <span class="ml-2">{{ col.title }}</span> </div> </a-select-option> </a-select> </template> <template v-if="column.key === 'action'"> <a-checkbox v-model:checked="record.enabled" /> </template> </template> </a-table> </a-collapse-panel> </a-collapse> </a-card> <a-card v-else> <a-form ref="formRef" :model="data" name="template-editor-form" @keydown.enter="emit('import')"> <p v-if="data.tables && quickImportType === 'excel'" class="text-center"> {{ data.tables.length }} sheet{{ data.tables.length > 1 ? 's' : '' }} available for import </p> <a-collapse v-if="data.tables && data.tables.length" v-model:activeKey="expansionPanel" class="template-collapse" accordion > <a-collapse-panel v-for="(table, tableIdx) of data.tables" :key="tableIdx"> <template #header> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.table_name`]" no-style> <div class="flex flex-col w-full"> <a-input v-model:value="table.table_name" class="font-weight-bold text-lg" size="large" hide-details :bordered="false" @click.stop @blur="handleEditableTnChange(tableIdx)" @keydown.enter="handleEditableTnChange(tableIdx)" @dblclick="setEditableTn(tableIdx, true)" /> <div v-if="formError?.[`tables.${tableIdx}.table_name`]" class="text-red-500 ml-3"> {{ formError?.[`tables.${tableIdx}.table_name`].join('\n') }} </div> </div> </a-form-item> </template> <template #extra> <a-tooltip bottom> <template #title> <span>{{ $t('activity.deleteTable') }}</span> </template> <component :is="iconMap.delete" v-if="data.tables.length > 1" class="text-lg mr-8" @click.stop="deleteTable(tableIdx)" /> </a-tooltip> </template> <a-table v-if="table.columns && table.columns.length" class="template-form" row-class-name="template-form-row" :data-source="table.columns" :columns="tableColumns" :pagination="table.columns.length > 50 ? { defaultPageSize: 50, position: ['bottomCenter'] } : false" > <template #emptyText> <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noData')" /> </template> <template #headerCell="{ column }"> <template v-if="column.key === 'column_name'"> <span> {{ $t('labels.columnName') }} </span> </template> <template v-else-if="column.key === 'uidt'"> <span> {{ $t('labels.columnType') }} </span> </template> <template v-else-if="column.key === 'dtxp' && hasSelectColumn[tableIdx]"> <span> {{ $t('general.options') }} </span> </template> </template> <template #bodyCell="{ column, record }"> <template v-if="column.key === 'column_name'"> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]"> <a-input :ref="(el: HTMLInputElement) => (inputRefs[record.key] = el)" v-model:value="record.column_name" /> </a-form-item> </template> <template v-else-if="column.key === 'uidt'"> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]"> <a-select v-model:value="record.uidt" class="w-52" show-search :filter-option="filterOption" dropdown-class-name="nc-dropdown-template-uidt" @change="handleUIDTChange(record, table)" > <a-select-option v-for="(option, i) of uiTypeOptions" :key="i" :value="option.value"> <a-tooltip placement="right"> <template v-if="isSelectDisabled(option.label, table.columns[record.key]?._disableSelect)" #title> {{ $t('msg.tooLargeFieldEntity', { entity: option.label, }) }} </template> {{ option.label }} </a-tooltip> </a-select-option> </a-select> </a-form-item> </template> <template v-else-if="column.key === 'dtxp'"> <a-form-item v-if="isSelect(record)"> <a-input v-model:value="record.dtxp" /> </a-form-item> </template> <template v-if="column.key === 'action'"> <a-tooltip v-if="record.key === 0"> <template #title> <span>{{ $t('general.primaryValue') }}</span> </template> <div class="flex items-center float-right mr-4"> <mdi-key-star class="text-lg" /> </div> </a-tooltip> <a-tooltip v-else> <template #title> <span>{{ $t('activity.column.delete') }}</span> </template> <a-button type="text" @click="deleteTableColumn(tableIdx, record.key)"> <div class="flex items-center"> <component :is="iconMap.delete" class="text-lg" /> </div> </a-button> </a-tooltip> </template> </template> </a-table> <div class="mt-5 flex gap-2 justify-center"> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addNumber') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'Number')"> <div class="flex items-center"> <component :is="iconMap.number" class="group-hover:!text-accent flex text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addSingleLineText') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'SingleLineText')"> <div class="flex items-center"> <component :is="iconMap.text" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addLongText') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'LongText')"> <div class="flex items-center"> <component :is="iconMap.longText" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addOther') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'SingleLineText')"> <div class="flex items-center gap-1"> <component :is="iconMap.plus" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> </div> </a-collapse-panel> </a-collapse> </a-form> </a-card> </a-spin> </template> <style scoped lang="scss"> .template-collapse { @apply bg-white; } .template-form { :deep(.ant-table-thead) > tr > th { @apply bg-white; } :deep(.template-form-row) > td { @apply p-0 mb-0; .ant-form-item { @apply mb-0; } } } </style>
packages/nc-gui/components/template/Editor.vue
1
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.1173541396856308, 0.0021441541612148285, 0.00016279087867587805, 0.00017516968364361674, 0.012117298319935799 ]
{ "id": 6, "code_window": [ " this.detectedColumnTypes[columnIdx] = {}\n", " this.distinctValues[columnIdx] = new Set<string>()\n", " this.columnValues[columnIdx] = []\n", " tableObj.columns.push({\n", " column_name: cn,\n", " ref_column_name: cn,\n", " meta: {},\n", " uidt: UITypes.SingleLineText,\n", " key: columnIdx,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " title,\n" ], "file_path": "packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 72 }
<% const { utils, config, routes, modelTypes } = it; const { _, classNameCase } = utils; const dataContracts = config.modular ? _.map(modelTypes, "name") : []; %> <% if (dataContracts.length) { %> import { <%~ dataContracts.join(", ") %> } from "./<%~ config.fileNames.dataContracts %>" <% } %> <% /* TODO: outOfModule, combined should be attributes of route, which will allow to avoid duplication of code */ %> <% routes.outOfModule && routes.outOfModule.forEach(({ routes = [] }) => { %> <% routes.forEach((route) => { %> <%~ includeFile('@base/route-type.eta', { ...it, route }) %> <% }) %> <% }) %> <% routes.combined && routes.combined.forEach(({ routes = [], moduleName }) => { %> export namespace <%~ classNameCase(moduleName) %> { <% routes.forEach((route) => { %> <%~ includeFile('@base/route-type.eta', { ...it, route }) %> <% }) %> } <% }) %>
scripts/sdk/templates/route-types.eta
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00016975095786619931, 0.00016960129141807556, 0.00016935146413743496, 0.00016970143769867718, 1.778041962552379e-7 ]
{ "id": 6, "code_window": [ " this.detectedColumnTypes[columnIdx] = {}\n", " this.distinctValues[columnIdx] = new Set<string>()\n", " this.columnValues[columnIdx] = []\n", " tableObj.columns.push({\n", " column_name: cn,\n", " ref_column_name: cn,\n", " meta: {},\n", " uidt: UITypes.SingleLineText,\n", " key: columnIdx,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " title,\n" ], "file_path": "packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 72 }
import axios from 'axios'; import { useAgent } from 'request-filtering-agent'; import type { IWebhookNotificationAdapter } from 'nc-plugin'; export default class Mattermost implements IWebhookNotificationAdapter { public init(): Promise<any> { return Promise.resolve(undefined); } public async sendMessage(text: string, payload: any): Promise<any> { for (const { webhook_url } of payload?.channels || []) { try { return await axios.post(webhook_url, { text, httpAgent: useAgent(webhook_url, { stopPortScanningByUrlRedirection: true, }), httpsAgent: useAgent(webhook_url, { stopPortScanningByUrlRedirection: true, }), }); } catch (e) { console.log(e); throw e; } } } }
packages/nocodb/src/plugins/mattermost/Mattermost.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00017311096598859876, 0.00017068006854970008, 0.00016729600611142814, 0.00017163323354907334, 0.0000024677697183506098 ]
{ "id": 6, "code_window": [ " this.detectedColumnTypes[columnIdx] = {}\n", " this.distinctValues[columnIdx] = new Set<string>()\n", " this.columnValues[columnIdx] = []\n", " tableObj.columns.push({\n", " column_name: cn,\n", " ref_column_name: cn,\n", " meta: {},\n", " uidt: UITypes.SingleLineText,\n", " key: columnIdx,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " title,\n" ], "file_path": "packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 72 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M9.33341 1.33333H4.00008C3.64646 1.33333 3.30732 1.4738 3.05727 1.72385C2.80722 1.9739 2.66675 2.31304 2.66675 2.66666V13.3333C2.66675 13.6869 2.80722 14.0261 3.05727 14.2761C3.30732 14.5262 3.64646 14.6667 4.00008 14.6667H12.0001C12.3537 14.6667 12.6928 14.5262 12.9429 14.2761C13.1929 14.0261 13.3334 13.6869 13.3334 13.3333V5.33333L9.33341 1.33333Z" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10.6666 11.3333H5.33325" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10.6666 8.66667H5.33325" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M6.66659 6H5.99992H5.33325" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M9.33325 1.33333V5.33333H13.3333" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> </svg>
packages/nc-gui/assets/nc-icons/file.svg
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00016624853014945984, 0.00016624853014945984, 0.00016624853014945984, 0.00016624853014945984, 0 ]
{ "id": 7, "code_window": [ " }\n", "\n", " getTemplate() {\n", " return this.base\n", " }\n", "\n", " progress(msg: string) {\n", " this.progressCallback?.(msg)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " console.log(this)\n" ], "file_path": "packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 327 }
<script setup lang="ts"> import dayjs from 'dayjs' import utc from 'dayjs/plugin/utc' import type { ColumnType, TableType } from 'nocodb-sdk' import { UITypes, isSystemColumn, isVirtualCol } from 'nocodb-sdk' import type { CheckboxChangeEvent } from 'ant-design-vue/es/checkbox/interface' import { srcDestMappingColumns, tableColumns } from './utils' import { Empty, Form, ImportWorkerOperations, ImportWorkerResponse, MetaInj, ReloadViewDataHookInj, TabType, computed, createEventHook, extractSdkResponseErrorMsg, fieldLengthValidator, fieldRequiredValidator, getDateFormat, getDateTimeFormat, getUIDTIcon, iconMap, inject, message, nextTick, onMounted, parseStringDate, reactive, ref, storeToRefs, useBase, useI18n, useNuxtApp, useTabs, validateTableName, } from '#imports' const { quickImportType, baseTemplate, importData, importColumns, importDataOnly, maxRowsToParse, sourceId, importWorker } = defineProps<Props>() const emit = defineEmits(['import', 'error', 'change']) dayjs.extend(utc) const { t } = useI18n() interface Props { quickImportType: 'csv' | 'excel' | 'json' baseTemplate: Record<string, any> importData: Record<string, any> importColumns: any[] importDataOnly: boolean maxRowsToParse: number sourceId: string importWorker: Worker } interface Option { label: string value: string } const meta = inject(MetaInj, ref()) const columns = computed(() => meta.value?.columns || []) const reloadHook = inject(ReloadViewDataHookInj, createEventHook()) const useForm = Form.useForm const { $api } = useNuxtApp() const { addTab } = useTabs() const baseStrore = useBase() const { loadTables } = baseStrore const { sqlUis, base } = storeToRefs(baseStrore) const { openTable } = useTablesStore() const { baseTables } = storeToRefs(useTablesStore()) const sqlUi = ref(sqlUis.value[sourceId] || Object.values(sqlUis.value)[0]) const hasSelectColumn = ref<boolean[]>([]) const expansionPanel = ref<number[]>([]) const editableTn = ref<boolean[]>([]) const inputRefs = ref<HTMLInputElement[]>([]) const isImporting = ref(false) const importingTips = ref<Record<string, string>>({}) const checkAllRecord = ref<boolean[]>([]) const formError = ref() const uiTypeOptions = ref<Option[]>( (Object.keys(UITypes) as (keyof typeof UITypes)[]) .filter( (uiType) => !isVirtualCol(UITypes[uiType]) && ![UITypes.ForeignKey, UITypes.ID, UITypes.CreateTime, UITypes.LastModifiedTime, UITypes.Barcode, UITypes.Button].includes( UITypes[uiType], ), ) .map<Option>((uiType) => ({ value: uiType, label: uiType, })), ) const srcDestMapping = ref<Record<string, Record<string, any>[]>>({}) const data = reactive<{ title: string | null name: string tables: (TableType & { ref_table_name: string; columns: (ColumnType & { key: number; _disableSelect?: boolean })[] })[] }>({ title: null, name: 'Base Name', tables: [], }) const validators = computed(() => data.tables.reduce<Record<string, [ReturnType<typeof fieldRequiredValidator>]>>((acc: Record<string, any>, table, tableIdx) => { acc[`tables.${tableIdx}.table_name`] = [validateTableName] hasSelectColumn.value[tableIdx] = false table.columns?.forEach((column, columnIdx) => { acc[`tables.${tableIdx}.columns.${columnIdx}.column_name`] = [ fieldRequiredValidator(), fieldLengthValidator(), ] acc[`tables.${tableIdx}.columns.${columnIdx}.uidt`] = [fieldRequiredValidator()] if (isSelect(column)) { hasSelectColumn.value[tableIdx] = true } }) return acc }, {}), ) const { validate, validateInfos, modelRef } = useForm(data, validators) const isValid = ref(!importDataOnly) const formRef = ref() watch( () => srcDestMapping.value, () => { let res = true if (importDataOnly) { for (const tn of Object.keys(srcDestMapping.value)) { if (!atLeastOneEnabledValidation(tn)) { res = false } for (const record of srcDestMapping.value[tn]) { if (!fieldsValidation(record, tn)) { return false } } } } else { for (const [_, o] of Object.entries(validateInfos)) { if (o?.validateStatus) { if (o.validateStatus === 'error') { res = false } } } } isValid.value = res }, { deep: true }, ) const prevEditableTn = ref<string[]>([]) onMounted(() => { parseAndLoadTemplate() // used to record the previous EditableTn values // for checking the table duplication in current import // and updating the key in importData prevEditableTn.value = data.tables.map((t) => t.table_name) if (importDataOnly) { mapDefaultColumns() } nextTick(() => { inputRefs.value[0]?.focus() }) }) function filterOption(input: string, option: Option) { return option.value.toUpperCase().includes(input.toUpperCase()) } function parseAndLoadTemplate() { if (baseTemplate) { parseTemplate(baseTemplate) expansionPanel.value = Array.from({ length: data.tables.length || 0 }, (_, i) => i) hasSelectColumn.value = Array.from({ length: data.tables.length || 0 }, () => false) } } function parseTemplate({ tables = [], ...rest }: Props['baseTemplate']) { const parsedTemplate = { ...rest, tables: tables.map(({ v = [], columns = [], ...rest }) => ({ ...rest, columns: [ ...columns.map((c: any, idx: number) => { c.key = idx return c }), ...v.map((v: any) => ({ column_name: v.title, table_name: { ...v, }, })), ], })), } Object.assign(data, parsedTemplate) } function isSelect(col: ColumnType) { return col.uidt === 'MultiSelect' || col.uidt === 'SingleSelect' } function deleteTable(tableIdx: number) { data.tables.splice(tableIdx, 1) } function deleteTableColumn(tableIdx: number, columnKey: number) { const columnIdx = data.tables[tableIdx].columns.findIndex((c: ColumnType & { key: number }) => c.key === columnKey) data.tables[tableIdx].columns.splice(columnIdx, 1) } function addNewColumnRow(tableIdx: number, uidt: string) { data.tables[tableIdx].columns.push({ key: data.tables[tableIdx].columns.length, column_name: `title${data.tables[tableIdx].columns.length + 1}`, uidt, }) nextTick(() => { const input = inputRefs.value[data.tables[tableIdx].columns.length - 1] input.focus() input.select() }) } function setEditableTn(tableIdx: number, val: boolean) { editableTn.value[tableIdx] = val } function remapColNames(batchData: any[], columns: ColumnType[]) { const dateFormatMap: Record<number, string> = {} return batchData.map((data) => (columns || []).reduce((aggObj, col: Record<string, any>) => { // for excel & json, if the column name is changed in TemplateEditor, // then only col.column_name exists in data, else col.ref_column_name // for csv, col.column_name always exists in data // since it streams the data in getData() with the updated col.column_name const key = col.column_name in data ? col.column_name : col.ref_column_name let d = data[key] if (col.uidt === UITypes.Date && d) { let dateFormat if (col?.meta?.date_format) { dateFormat = col.meta.date_format dateFormatMap[col.key] = dateFormat } else if (col.key in dateFormatMap) { dateFormat = dateFormatMap[col.key] } else { dateFormat = getDateFormat(d) dateFormatMap[col.key] = dateFormat } d = parseStringDate(d, dateFormat) } else if (col.uidt === UITypes.DateTime && d) { const dateTimeFormat = getDateTimeFormat(data[key]) d = dayjs(data[key], dateTimeFormat).format('YYYY-MM-DD HH:mm') } return { ...aggObj, [col.column_name]: d, } }, {}), ) } function missingRequiredColumnsValidation(tn: string) { const missingRequiredColumns = columns.value.filter( (c: Record<string, any>) => (c.pk ? !c.ai && !c.cdf : !c.cdf && c.rqd) && !srcDestMapping.value[tn].some((r: Record<string, any>) => r.destCn === c.title), ) if (missingRequiredColumns.length) { message.error(`${t('msg.error.columnsRequired')} : ${missingRequiredColumns.map((c) => c.title).join(', ')}`) return false } return true } function atLeastOneEnabledValidation(tn: string) { if (srcDestMapping.value[tn].filter((v: Record<string, any>) => v.enabled === true).length === 0) { message.error(t('msg.error.selectAtleastOneColumn')) return false } return true } function fieldsValidation(record: Record<string, any>, tn: string) { // if it is not selected, then pass validation if (!record.enabled) { return true } if (!record.destCn) { message.error(`${t('msg.error.columnDescriptionNotFound')} ${record.srcCn}`) return false } if (srcDestMapping.value[tn].filter((v: Record<string, any>) => v.destCn === record.destCn).length > 1) { message.error(t('msg.error.duplicateMappingFound')) return false } const v = columns.value.find((c) => c.title === record.destCn) as Record<string, any> for (const tableName of Object.keys(importData)) { // check if the input contains null value for a required column if (v.pk ? !v.ai && !v.cdf : !v.cdf && v.rqd) { if ( importData[tableName] .slice(0, maxRowsToParse) .some((r: Record<string, any>) => r[record.srcCn] === null || r[record.srcCn] === undefined || r[record.srcCn] === '') ) { message.error(t('msg.error.nullValueViolatesNotNull')) } } switch (v.uidt) { case UITypes.Number: if ( importData[tableName] .slice(0, maxRowsToParse) .some( (r: Record<string, any>) => r[record.sourceCn] !== null && r[record.srcCn] !== undefined && isNaN(+r[record.srcCn]), ) ) { message.error(t('msg.error.sourceHasInvalidNumbers')) return false } break case UITypes.Checkbox: if ( importData[tableName].slice(0, maxRowsToParse).some((r: Record<string, any>) => { if (r[record.srcCn] !== null && r[record.srcCn] !== undefined) { let input = r[record.srcCn] if (typeof input === 'string') { input = input.replace(/["']/g, '').toLowerCase().trim() return !( input === 'false' || input === 'no' || input === 'n' || input === '0' || input === 'true' || input === 'yes' || input === 'y' || input === '1' ) } return input !== 1 && input !== 0 && input !== true && input !== false } return false }) ) { message.error(t('msg.error.sourceHasInvalidBoolean')) return false } break } } return true } function updateImportTips(baseName: string, tableName: string, progress: number, total: number) { importingTips.value[`${baseName}-${tableName}`] = `Importing data to ${baseName} - ${tableName}: ${progress}/${total} records` } async function importTemplate() { if (importDataOnly) { for (const table of data.tables) { // validate required columns if (!missingRequiredColumnsValidation(table.table_name)) return // validate at least one column needs to be selected if (!atLeastOneEnabledValidation(table.table_name)) return } try { isImporting.value = true const tableId = meta.value?.id const baseId = base.value.id! const table_names = data.tables.map((t: Record<string, any>) => t.table_name) await Promise.all( Object.keys(importData).map((key: string) => (async (k) => { if (!table_names.includes(k)) { return } const data = importData[k] const total = data.length for (let i = 0, progress = 0; i < total; i += maxRowsToParse) { const batchData = data.slice(i, i + maxRowsToParse).map((row: Record<string, any>) => srcDestMapping.value[k].reduce((res: Record<string, any>, col: Record<string, any>) => { if (col.enabled && col.destCn) { const v = columns.value.find((c: Record<string, any>) => c.title === col.destCn) as Record<string, any> let input = row[col.srcCn] // parse potential boolean values if (v.uidt === UITypes.Checkbox) { input = input ? input.replace(/["']/g, '').toLowerCase().trim() : 'false' if (input === 'false' || input === 'no' || input === 'n') { input = '0' } else if (input === 'true' || input === 'yes' || input === 'y') { input = '1' } } else if (v.uidt === UITypes.Number) { if (input === '') { input = null } } else if (v.uidt === UITypes.SingleSelect || v.uidt === UITypes.MultiSelect) { if (input === '') { input = null } } else if (v.uidt === UITypes.Date) { if (input) { input = parseStringDate(input, v.meta.date_format) } } res[col.destCn] = input } return res }, {}), ) await $api.dbTableRow.bulkCreate('noco', baseId, tableId!, batchData) updateImportTips(baseId, tableId!, progress, total) progress += batchData.length } })(key), ), ) // reload table reloadHook.trigger() // Successfully imported table data message.success(t('msg.success.tableDataImported')) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { isImporting.value = false } } else { // check if form is valid try { await validate() } catch (errorInfo) { isImporting.value = false throw new Error('Please fill all the required values') } try { isImporting.value = true // tab info to be used to show the tab after successful import const tab = { id: '', title: '', baseId: '', } // create tables for (const table of data.tables) { // enrich system fields if not provided // e.g. id, created_at, updated_at const systemColumns = sqlUi?.value.getNewTableColumns().filter((c: ColumnType) => c.column_name !== 'title') for (const systemColumn of systemColumns) { if (!table.columns?.some((c) => c.column_name?.toLowerCase() === systemColumn.column_name.toLowerCase())) { table.columns?.push(systemColumn) } } if (table.columns) { for (const column of table.columns) { // set pk & rqd if ID is provided if (column.column_name?.toLowerCase() === 'id' && !('pk' in column)) { column.pk = true column.rqd = true } if ( (!isSystemColumn(column) || ['created_at', 'updated_at'].includes(column.column_name!)) && column.uidt !== UITypes.SingleSelect && column.uidt !== UITypes.MultiSelect ) { // delete dtxp if the final data type is not single & multi select // e.g. import -> detect as single / multi select -> switch to SingleLineText // the correct dtxp will be generated during column creation delete column.dtxp } } } const createdTable = await $api.source.tableCreate(base.value?.id as string, (sourceId || base.value?.sources?.[0].id)!, { table_name: table.table_name, // leave title empty to get a generated one based on table_name title: '', columns: table.columns || [], }) if (process.env.NC_SANITIZE_COLUMN_NAME !== 'false') { // column_name could have been updated in tableCreate // e.g. sanitize column name to something like field_1, field_2, and etc createdTable.columns.forEach((column, i) => { table.columns[i].column_name = column.column_name }) } table.id = createdTable.id table.title = createdTable.title // open the first table after import if (tab.id === '' && tab.title === '' && tab.baseId === '') { tab.id = createdTable.id as string tab.title = createdTable.title as string tab.baseId = base.value.id as string } // set display value if (createdTable?.columns?.[0]?.id) { await $api.dbTableColumn.primaryColumnSet(createdTable.columns[0].id as string) } } // bulk insert data if (importData) { const offset = maxRowsToParse const baseName = base.value.title as string await Promise.all( data.tables.map((table: Record<string, any>) => (async (tableMeta) => { let progress = 0 let total = 0 // use ref_table_name here instead of table_name // since importData[talbeMeta.table_name] would be empty after renaming const data = importData[tableMeta.ref_table_name] if (data) { total += data.length for (let i = 0; i < data.length; i += offset) { updateImportTips(baseName, tableMeta.title, progress, total) const batchData = remapColNames(data.slice(i, i + offset), tableMeta.columns) await $api.dbTableRow.bulkCreate('noco', base.value.id, tableMeta.id, batchData) progress += batchData.length } updateImportTips(baseName, tableMeta.title, total, total) } })(table), ), ) } // reload table list await loadTables() addTab({ ...tab, type: TabType.TABLE, }) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { isImporting.value = false } } if (!data.tables?.length) return const tables = baseTables.value.get(base.value!.id!) const toBeNavigatedTable = tables?.find((t) => t.id === data.tables[0].id) if (!toBeNavigatedTable) return openTable(toBeNavigatedTable) } function mapDefaultColumns() { srcDestMapping.value = {} for (let i = 0; i < data.tables.length; i++) { for (const col of importColumns[i]) { const o = { srcCn: col.column_name, destCn: '', enabled: true } if (columns.value) { const tableColumn = columns.value.find((c) => c.column_name === col.column_name) if (tableColumn) { o.destCn = tableColumn.title as string } else { o.enabled = false } } if (!(data.tables[i].table_name in srcDestMapping.value)) { srcDestMapping.value[data.tables[i].table_name] = [] } srcDestMapping.value[data.tables[i].table_name].push(o) } } } defineExpose({ importTemplate, isValid, }) function handleEditableTnChange(idx: number) { const oldValue = prevEditableTn.value[idx] const newValue = data.tables[idx].table_name if (data.tables.filter((t) => t.table_name === newValue).length > 1) { message.warn('Duplicate Table Name') data.tables[idx].table_name = oldValue } else { prevEditableTn.value[idx] = newValue } setEditableTn(idx, false) } function isSelectDisabled(uidt: string, disableSelect = false) { return (uidt === UITypes.SingleSelect || uidt === UITypes.MultiSelect) && disableSelect } function handleCheckAllRecord(event: CheckboxChangeEvent, tableName: string) { const isChecked = event.target.checked for (const record of srcDestMapping.value[tableName]) { record.enabled = isChecked } } function handleUIDTChange(column, table) { if (!importWorker) return const handler = (e) => { const [type, payload] = e.data switch (type) { case ImportWorkerResponse.SINGLE_SELECT_OPTIONS: case ImportWorkerResponse.MULTI_SELECT_OPTIONS: importWorker.removeEventListener('message', handler, false) column.dtxp = payload break } } if (column.uidt === UITypes.SingleSelect) { importWorker.addEventListener('message', handler, false) importWorker.postMessage([ ImportWorkerOperations.GET_SINGLE_SELECT_OPTIONS, { tableName: table.ref_table_name, columnName: column.ref_column_name, }, ]) } else if (column.uidt === UITypes.MultiSelect) { importWorker.addEventListener('message', handler, false) importWorker.postMessage([ ImportWorkerOperations.GET_MULTI_SELECT_OPTIONS, { tableName: table.ref_table_name, columnName: column.ref_column_name, }, ]) } } const setErrorState = (errorsFields: any[]) => { const errorMap: any = {} for (const error of errorsFields) { errorMap[error.name] = error.errors } formError.value = errorMap } watch(formRef, () => { setTimeout(async () => { try { await validate() emit('change') formError.value = null } catch (e: any) { emit('error', e) setErrorState(e.errorFields) } }, 500) }) watch(modelRef, async () => { try { await validate() emit('change') formError.value = null } catch (e: any) { emit('error', e) setErrorState(e.errorFields) } }) </script> <template> <a-spin :spinning="isImporting" size="large"> <template #tip> <p v-for="(importingTip, idx) of importingTips" :key="idx" class="mt-[10px]"> {{ importingTip }} </p> </template> <a-card v-if="importDataOnly"> <a-form :model="data" name="import-only"> <p v-if="data.tables && quickImportType === 'excel'" class="text-center"> {{ data.tables.length }} sheet{{ data.tables.length > 1 ? 's' : '' }} available for import </p> </a-form> <a-collapse v-if="data.tables && data.tables.length" v-model:activeKey="expansionPanel" class="template-collapse" accordion> <a-collapse-panel v-for="(table, tableIdx) of data.tables" :key="tableIdx"> <template #header> <span class="font-weight-bold text-lg flex items-center gap-2 truncate"> <component :is="iconMap.table" class="text-primary" /> {{ table.table_name }} </span> </template> <template #extra> <a-tooltip bottom> <template #title> <span>{{ $t('activity.deleteTable') }}</span> </template> <component :is="iconMap.delete" v-if="data.tables.length > 1" class="text-lg mr-8" @click.stop="deleteTable(tableIdx)" /> </a-tooltip> </template> <a-table v-if="srcDestMapping" class="template-form" row-class-name="template-form-row" :data-source="srcDestMapping[table.table_name]" :columns="srcDestMappingColumns" :pagination="false" > <template #emptyText> <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noData')" /> </template> <template #headerCell="{ column }"> <span v-if="column.key === 'source_column' || column.key === 'destination_column'"> {{ column.name }} </span> <span v-if="column.key === 'action'"> <a-checkbox v-model:checked="checkAllRecord[table.table_name]" @change="handleCheckAllRecord($event, table.table_name)" /> </span> </template> <template #bodyCell="{ column, record }"> <template v-if="column.key === 'source_column'"> <span>{{ record.srcCn }}</span> </template> <template v-else-if="column.key === 'destination_column'"> <a-select v-model:value="record.destCn" class="w-52" show-search :filter-option="filterOption" dropdown-class-name="nc-dropdown-filter-field" > <a-select-option v-for="(col, i) of columns" :key="i" :value="col.title"> <div class="flex items-center"> <component :is="getUIDTIcon(col.uidt)" /> <span class="ml-2">{{ col.title }}</span> </div> </a-select-option> </a-select> </template> <template v-if="column.key === 'action'"> <a-checkbox v-model:checked="record.enabled" /> </template> </template> </a-table> </a-collapse-panel> </a-collapse> </a-card> <a-card v-else> <a-form ref="formRef" :model="data" name="template-editor-form" @keydown.enter="emit('import')"> <p v-if="data.tables && quickImportType === 'excel'" class="text-center"> {{ data.tables.length }} sheet{{ data.tables.length > 1 ? 's' : '' }} available for import </p> <a-collapse v-if="data.tables && data.tables.length" v-model:activeKey="expansionPanel" class="template-collapse" accordion > <a-collapse-panel v-for="(table, tableIdx) of data.tables" :key="tableIdx"> <template #header> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.table_name`]" no-style> <div class="flex flex-col w-full"> <a-input v-model:value="table.table_name" class="font-weight-bold text-lg" size="large" hide-details :bordered="false" @click.stop @blur="handleEditableTnChange(tableIdx)" @keydown.enter="handleEditableTnChange(tableIdx)" @dblclick="setEditableTn(tableIdx, true)" /> <div v-if="formError?.[`tables.${tableIdx}.table_name`]" class="text-red-500 ml-3"> {{ formError?.[`tables.${tableIdx}.table_name`].join('\n') }} </div> </div> </a-form-item> </template> <template #extra> <a-tooltip bottom> <template #title> <span>{{ $t('activity.deleteTable') }}</span> </template> <component :is="iconMap.delete" v-if="data.tables.length > 1" class="text-lg mr-8" @click.stop="deleteTable(tableIdx)" /> </a-tooltip> </template> <a-table v-if="table.columns && table.columns.length" class="template-form" row-class-name="template-form-row" :data-source="table.columns" :columns="tableColumns" :pagination="table.columns.length > 50 ? { defaultPageSize: 50, position: ['bottomCenter'] } : false" > <template #emptyText> <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noData')" /> </template> <template #headerCell="{ column }"> <template v-if="column.key === 'column_name'"> <span> {{ $t('labels.columnName') }} </span> </template> <template v-else-if="column.key === 'uidt'"> <span> {{ $t('labels.columnType') }} </span> </template> <template v-else-if="column.key === 'dtxp' && hasSelectColumn[tableIdx]"> <span> {{ $t('general.options') }} </span> </template> </template> <template #bodyCell="{ column, record }"> <template v-if="column.key === 'column_name'"> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]"> <a-input :ref="(el: HTMLInputElement) => (inputRefs[record.key] = el)" v-model:value="record.column_name" /> </a-form-item> </template> <template v-else-if="column.key === 'uidt'"> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]"> <a-select v-model:value="record.uidt" class="w-52" show-search :filter-option="filterOption" dropdown-class-name="nc-dropdown-template-uidt" @change="handleUIDTChange(record, table)" > <a-select-option v-for="(option, i) of uiTypeOptions" :key="i" :value="option.value"> <a-tooltip placement="right"> <template v-if="isSelectDisabled(option.label, table.columns[record.key]?._disableSelect)" #title> {{ $t('msg.tooLargeFieldEntity', { entity: option.label, }) }} </template> {{ option.label }} </a-tooltip> </a-select-option> </a-select> </a-form-item> </template> <template v-else-if="column.key === 'dtxp'"> <a-form-item v-if="isSelect(record)"> <a-input v-model:value="record.dtxp" /> </a-form-item> </template> <template v-if="column.key === 'action'"> <a-tooltip v-if="record.key === 0"> <template #title> <span>{{ $t('general.primaryValue') }}</span> </template> <div class="flex items-center float-right mr-4"> <mdi-key-star class="text-lg" /> </div> </a-tooltip> <a-tooltip v-else> <template #title> <span>{{ $t('activity.column.delete') }}</span> </template> <a-button type="text" @click="deleteTableColumn(tableIdx, record.key)"> <div class="flex items-center"> <component :is="iconMap.delete" class="text-lg" /> </div> </a-button> </a-tooltip> </template> </template> </a-table> <div class="mt-5 flex gap-2 justify-center"> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addNumber') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'Number')"> <div class="flex items-center"> <component :is="iconMap.number" class="group-hover:!text-accent flex text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addSingleLineText') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'SingleLineText')"> <div class="flex items-center"> <component :is="iconMap.text" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addLongText') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'LongText')"> <div class="flex items-center"> <component :is="iconMap.longText" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addOther') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'SingleLineText')"> <div class="flex items-center gap-1"> <component :is="iconMap.plus" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> </div> </a-collapse-panel> </a-collapse> </a-form> </a-card> </a-spin> </template> <style scoped lang="scss"> .template-collapse { @apply bg-white; } .template-form { :deep(.ant-table-thead) > tr > th { @apply bg-white; } :deep(.template-form-row) > td { @apply p-0 mb-0; .ant-form-item { @apply mb-0; } } } </style>
packages/nc-gui/components/template/Editor.vue
1
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.9980863332748413, 0.024420082569122314, 0.00016518683696631342, 0.00017006476991809905, 0.14306241273880005 ]
{ "id": 7, "code_window": [ " }\n", "\n", " getTemplate() {\n", " return this.base\n", " }\n", "\n", " progress(msg: string) {\n", " this.progressCallback?.(msg)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " console.log(this)\n" ], "file_path": "packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 327 }
<script setup lang="ts"> import type { VNodeRef } from '@vue/runtime-core' import type { InputPassword } from 'ant-design-vue' import { extractSdkResponseErrorMsg, message, ref, useRoute, useSharedView, useVModel } from '#imports' const props = defineProps<{ modelValue: boolean }>() const emit = defineEmits(['update:modelValue']) const vModel = useVModel(props, 'modelValue', emit) const route = useRoute() const { loadSharedView } = useSharedView() const formState = ref({ password: undefined }) const onFinish = async () => { try { await loadSharedView(route.params.viewId as string, formState.value.password) vModel.value = false } catch (e: any) { console.error(e) message.error(await extractSdkResponseErrorMsg(e)) } } const focus: VNodeRef = (el: typeof InputPassword) => el?.$el?.querySelector('input').focus() </script> <template> <NcModal v-model:visible="vModel" c size="small" :class="{ active: vModel }" :mask-closable="false"> <template #header> <div class="flex flex-row items-center gap-x-2"> <GeneralIcon icon="key" /> {{ $t('msg.thisSharedViewIsProtected') }} </div> </template> <div class="mt-2"> <a-form ref="formRef" :model="formState" name="create-new-table-form" @finish="onFinish"> <a-form-item name="password" :rules="[{ required: true, message: $t('msg.error.signUpRules.passwdRequired') }]"> <a-input-password ref="focus" v-model:value="formState.password" class="nc-input-md" hide-details size="large" :placeholder="$t('msg.enterPassword')" /> </a-form-item> </a-form> <div class="flex flex-row justify-end gap-x-2 mt-6"> <NcButton type="primary" html-type="submit" @click="onFinish" >{{ $t('general.unlock') }} <template #loading> {{ $t('msg.verifyingPassword') }}</template> </NcButton> </div> </div> </NcModal> </template>
packages/nc-gui/components/shared-view/AskPassword.vue
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00017514418868813664, 0.00017011808813549578, 0.00016740482533350587, 0.00016927496471907943, 0.0000025842189188551856 ]
{ "id": 7, "code_window": [ " }\n", "\n", " getTemplate() {\n", " return this.base\n", " }\n", "\n", " progress(msg: string) {\n", " this.progressCallback?.(msg)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " console.log(this)\n" ], "file_path": "packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 327 }
import { Injectable } from '@nestjs/common'; import Redis from 'ioredis'; import { InstanceTypes } from '~/interface/Jobs'; @Injectable() export class JobsRedisService { private redisClient: Redis; private redisSubscriber: Redis; private unsubscribeCallbacks: { [key: string]: () => void } = {}; public primaryCallbacks: { [key: string]: () => void } = {}; public workerCallbacks: { [key: string]: () => void } = {}; constructor() { this.redisClient = new Redis(process.env.NC_REDIS_JOB_URL); this.redisSubscriber = new Redis(process.env.NC_REDIS_JOB_URL); if (process.env.NC_WORKER_CONTAINER === 'true') { this.redisSubscriber.subscribe(InstanceTypes.WORKER); } else { this.redisSubscriber.subscribe(InstanceTypes.PRIMARY); } const onMessage = (channel, message) => { if (channel === InstanceTypes.WORKER) { this.workerCallbacks[message] && this.workerCallbacks[message](); } else if (channel === InstanceTypes.PRIMARY) { this.primaryCallbacks[message] && this.primaryCallbacks[message](); } }; this.redisSubscriber.on('message', onMessage); } publish(channel: string, message: string | any) { if (typeof message === 'string') { this.redisClient.publish(channel, message); } else { try { this.redisClient.publish(channel, JSON.stringify(message)); } catch (e) { console.error(e); } } } subscribe(channel: string, callback: (message: any) => void) { this.redisSubscriber.subscribe(channel); const onMessage = (_channel, message) => { try { message = JSON.parse(message); } catch (e) {} callback(message); }; this.redisSubscriber.on('message', onMessage); this.unsubscribeCallbacks[channel] = () => { this.redisSubscriber.unsubscribe(channel); this.redisSubscriber.off('message', onMessage); }; } unsubscribe(channel: string) { if (this.unsubscribeCallbacks[channel]) { this.unsubscribeCallbacks[channel](); delete this.unsubscribeCallbacks[channel]; } } workerCount(): Promise<number> { return new Promise((resolve, reject) => { this.redisClient.publish( InstanceTypes.WORKER, 'count', (error, numberOfSubscribers) => { if (error) { reject(0); } else { resolve(numberOfSubscribers); } }, ); }); } }
packages/nocodb/src/modules/jobs/redis/jobs-redis.service.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00020220867008902133, 0.0001713876990834251, 0.00016519991913810372, 0.0001676276297075674, 0.000010956840014841873 ]
{ "id": 7, "code_window": [ " }\n", "\n", " getTemplate() {\n", " return this.base\n", " }\n", "\n", " progress(msg: string) {\n", " this.progressCallback?.(msg)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " console.log(this)\n" ], "file_path": "packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 327 }
import { Test } from '@nestjs/testing'; import { HooksService } from './hooks.service'; import type { TestingModule } from '@nestjs/testing'; describe('HooksService', () => { let service: HooksService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [HooksService], }).compile(); service = module.get<HooksService>(HooksService); }); it('should be defined', () => { expect(service).toBeDefined(); }); });
packages/nocodb/src/services/hooks.service.spec.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0001740683219395578, 0.00017310300609096885, 0.00017213770479429513, 0.00017310300609096885, 9.653085726313293e-7 ]
{ "id": 8, "code_window": [ " )\n", "\n", " for (let col = 0; col < rows[0].length; col++) {\n", " let cn: string = (\n", " (this.config.firstRowAsHeaders && rows[0] && rows[0][col] && rows[0][col].toString().trim()) ||\n", " `field_${col + 1}`\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const title = (\n", " (this.config.firstRowAsHeaders && rows[0] && rows[0][col] && rows[0][col].toString().trim()) ||\n", " `Field ${col + 1}`\n", " ).trim()\n" ], "file_path": "packages/nc-gui/helpers/parsers/ExcelTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 115 }
import { UITypes } from 'nocodb-sdk' import { getDateFormat } from '../../utils/dateTimeUtils' import TemplateGenerator from './TemplateGenerator' import { extractMultiOrSingleSelectProps, getCheckboxValue, isCheckboxType, isEmailType, isMultiLineTextType, isUrlType, } from './parserHelpers' const excelTypeToUidt: Record<string, UITypes> = { d: UITypes.DateTime, b: UITypes.Checkbox, n: UITypes.Number, s: UITypes.SingleLineText, } export default class ExcelTemplateAdapter extends TemplateGenerator { config: Record<string, any> excelData: any base: { tables: Record<string, any>[] } data: Record<string, any> = {} wb: any xlsx: typeof import('xlsx') constructor(data = {}, parserConfig = {}, xlsx: any = null, progressCallback?: (msg: string) => void) { super(progressCallback) this.config = parserConfig this.excelData = data this.base = { tables: [], } this.xlsx = xlsx || ({} as any) } async init() { this.progress('Initializing excel parser') this.xlsx = this.xlsx || (await import('xlsx')) const options = { cellText: true, cellDates: true, } this.wb = this.xlsx.read(new Uint8Array(this.excelData), { type: 'array', ...options, }) } async parse() { this.progress('Parsing excel file') const tableNamePrefixRef: Record<string, any> = {} await Promise.all( this.wb.SheetNames.map((sheetName: string) => (async (sheet) => { this.progress(`Parsing sheet ${sheetName}`) await new Promise((resolve) => { const columnNamePrefixRef: Record<string, any> = { id: 0 } let tn: string = (sheet || 'table').replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_').trim() while (tn in tableNamePrefixRef) { tn = `${tn}${++tableNamePrefixRef[tn]}` } tableNamePrefixRef[tn] = 0 const table = { table_name: tn, ref_table_name: tn, columns: [] as any[] } const ws: any = this.wb.Sheets[sheet] // if sheet is empty, skip it if (!ws || !ws['!ref']) { return resolve(true) } const range = this.xlsx.utils.decode_range(ws['!ref']) let rows: any = this.xlsx.utils.sheet_to_json(ws, { // header has to be 1 disregarding this.config.firstRowAsHeaders // so that it generates an array of arrays header: 1, blankrows: false, defval: null, }) // fix precision bug & timezone offset issues introduced by xlsx const basedate = new Date(1899, 11, 30, 0, 0, 0) // number of milliseconds since base date const dnthresh = basedate.getTime() + (new Date().getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000 // number of milliseconds in a day const day_ms = 24 * 60 * 60 * 1000 // handle date1904 property const fixImportedDate = (date: Date) => { const parsed = this.xlsx.SSF.parse_date_code((date.getTime() - dnthresh) / day_ms, { date1904: this.wb.Workbook.WBProps.date1904, }) return new Date(parsed.y, parsed.m, parsed.d, parsed.H, parsed.M, parsed.S) } // fix imported date rows = rows.map((r: any) => r.map((v: any) => { return v instanceof Date ? fixImportedDate(v) : v }), ) for (let col = 0; col < rows[0].length; col++) { let cn: string = ( (this.config.firstRowAsHeaders && rows[0] && rows[0][col] && rows[0][col].toString().trim()) || `field_${col + 1}` ) .replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_') .trim() while (cn in columnNamePrefixRef) { cn = `${cn}${++columnNamePrefixRef[cn]}` } columnNamePrefixRef[cn] = 0 const column: Record<string, any> = { column_name: cn, ref_column_name: cn, meta: {}, uidt: UITypes.SingleLineText, } if (this.config.autoSelectFieldTypes) { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + col, r: +this.config.firstRowAsHeaders, }) const cellProps = ws[cellId] || {} column.uidt = excelTypeToUidt[cellProps.t] || UITypes.SingleLineText if (column.uidt === UITypes.SingleLineText) { // check for long text if (isMultiLineTextType(rows, col)) { column.uidt = UITypes.LongText } else if (isEmailType(rows, col)) { column.uidt = UITypes.Email } else if (isUrlType(rows, col)) { column.uidt = UITypes.URL } else { const vals = rows .slice(+this.config.firstRowAsHeaders) .map((r: any) => r[col]) .filter((v: any) => v !== null && v !== undefined && v.toString().trim() !== '') if (isCheckboxType(vals, col)) { column.uidt = UITypes.Checkbox } else { // Single Select / Multi Select Object.assign(column, extractMultiOrSingleSelectProps(vals)) } } } else if (column.uidt === UITypes.Number) { if ( rows.slice(1, this.config.maxRowsToParse).some((v: any) => { return v && v[col] && parseInt(v[col]) !== +v[col] }) ) { column.uidt = UITypes.Decimal } if ( rows.slice(1, this.config.maxRowsToParse).every((v: any, i: any) => { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + col, r: i + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] return !cellObj || (cellObj.w && cellObj.w.startsWith('$')) }) ) { column.uidt = UITypes.Currency } if ( rows.slice(1, this.config.maxRowsToParse).some((v: any, i: any) => { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + col, r: i + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] return !cellObj || (cellObj.w && !(!isNaN(Number(cellObj.w)) && !isNaN(parseFloat(cellObj.w)))) }) ) { // fallback to SingleLineText column.uidt = UITypes.SingleLineText } } else if (column.uidt === UITypes.DateTime) { // TODO(import): centralise // hold the possible date format found in the date const dateFormat: Record<string, number> = {} if ( rows.slice(1, this.config.maxRowsToParse).every((v: any, i: any) => { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + col, r: i + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] const isDate = !cellObj || (cellObj.w && cellObj.w.split(' ').length === 1) if (isDate && cellObj) { dateFormat[getDateFormat(cellObj.w)] = (dateFormat[getDateFormat(cellObj.w)] || 0) + 1 } return isDate }) ) { column.uidt = UITypes.Date // take the date format with the max occurrence column.meta.date_format = Object.keys(dateFormat).reduce((x, y) => (dateFormat[x] > dateFormat[y] ? x : y)) || 'YYYY/MM/DD' } } } table.columns.push(column) } this.base.tables.push(table) this.data[tn] = [] if (this.config.shouldImportData) { this.progress(`Parsing data from ${tn}`) let rowIndex = 0 for (const row of rows.slice(1)) { const rowData: Record<string, any> = {} for (let i = 0; i < table.columns.length; i++) { if (!this.config.autoSelectFieldTypes) { // take raw data instead of data parsed by xlsx const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + i, r: rowIndex + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] rowData[table.columns[i].column_name] = (cellObj && cellObj.w) || row[i] } else { if (table.columns[i].uidt === UITypes.Checkbox) { rowData[table.columns[i].column_name] = getCheckboxValue(row[i]) } else if (table.columns[i].uidt === UITypes.Currency) { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + i, r: rowIndex + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] rowData[table.columns[i].column_name] = (cellObj && cellObj.w && cellObj.w.replace(/[^\d.]+/g, '')) || row[i] } else if (table.columns[i].uidt === UITypes.SingleSelect || table.columns[i].uidt === UITypes.MultiSelect) { rowData[table.columns[i].column_name] = (row[i] || '').toString().trim() || null } else if (table.columns[i].uidt === UITypes.Date) { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + i, r: rowIndex + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] rowData[table.columns[i].column_name] = (cellObj && cellObj.w) || row[i] } else if (table.columns[i].uidt === UITypes.SingleLineText || table.columns[i].uidt === UITypes.LongText) { rowData[table.columns[i].column_name] = row[i] === null || row[i] === undefined ? null : `${row[i]}` } else { // TODO: do parsing if necessary based on type rowData[table.columns[i].column_name] = row[i] } } } this.data[tn].push(rowData) rowIndex++ } } resolve(true) }) })(sheetName), ), ) } getTemplate() { return this.base } getData() { return this.data } getColumns() { return this.base.tables.map((t: Record<string, any>) => t.columns) } }
packages/nc-gui/helpers/parsers/ExcelTemplateAdapter.ts
1
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.9989662170410156, 0.3464912176132202, 0.000166219673701562, 0.004515173379331827, 0.46192818880081177 ]
{ "id": 8, "code_window": [ " )\n", "\n", " for (let col = 0; col < rows[0].length; col++) {\n", " let cn: string = (\n", " (this.config.firstRowAsHeaders && rows[0] && rows[0][col] && rows[0][col].toString().trim()) ||\n", " `field_${col + 1}`\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const title = (\n", " (this.config.firstRowAsHeaders && rows[0] && rows[0][col] && rows[0][col].toString().trim()) ||\n", " `Field ${col + 1}`\n", " ).trim()\n" ], "file_path": "packages/nc-gui/helpers/parsers/ExcelTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 115 }
<script lang="ts" setup> import { LoadingOutlined } from '@ant-design/icons-vue' const props = defineProps<{ size?: 'small' | 'medium' | 'large' | 'xlarge' loaderClass?: string }>() function getFontSize() { const { size = 'medium' } = props switch (size) { case 'small': return 'text-xs' case 'medium': return 'text-sm' case 'large': return 'text-xl' case 'xlarge': return 'text-3xl' } } const indicator = h(LoadingOutlined, { class: `!${getFontSize()} flex flex-row items-center !bg-inherit !hover:bg-inherit !text-inherit ${props.loaderClass}}`, spin: true, }) </script> <template> <a-spin class="nc-loader flex flex-row items-center" :indicator="indicator" /> </template> <style lang="scss" scoped> :deep(.anticon-spin) { @apply flex; } </style>
packages/nc-gui/components/general/Loader.vue
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00017459991795476526, 0.00017112528439611197, 0.0001666745520196855, 0.00017161334108095616, 0.0000029980265026097186 ]
{ "id": 8, "code_window": [ " )\n", "\n", " for (let col = 0; col < rows[0].length; col++) {\n", " let cn: string = (\n", " (this.config.firstRowAsHeaders && rows[0] && rows[0][col] && rows[0][col].toString().trim()) ||\n", " `field_${col + 1}`\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const title = (\n", " (this.config.firstRowAsHeaders && rows[0] && rows[0][col] && rows[0][col].toString().trim()) ||\n", " `Field ${col + 1}`\n", " ).trim()\n" ], "file_path": "packages/nc-gui/helpers/parsers/ExcelTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 115 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M9.33341 1.33333H4.00008C3.64646 1.33333 3.30732 1.4738 3.05727 1.72385C2.80722 1.9739 2.66675 2.31304 2.66675 2.66666V13.3333C2.66675 13.6869 2.80722 14.0261 3.05727 14.2761C3.30732 14.5262 3.64646 14.6667 4.00008 14.6667H12.0001C12.3537 14.6667 12.6928 14.5262 12.9429 14.2761C13.1929 14.0261 13.3334 13.6869 13.3334 13.3333V5.33333L9.33341 1.33333Z" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10.6666 11.3333H5.33325" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M10.6666 8.66667H5.33325" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M6.66659 6H5.99992H5.33325" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> <path d="M9.33325 1.33333V5.33333H13.3333" stroke="#4A5268" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> </svg>
packages/nc-gui/assets/nc-icons/file.svg
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00018706309492699802, 0.00018706309492699802, 0.00018706309492699802, 0.00018706309492699802, 0 ]
{ "id": 8, "code_window": [ " )\n", "\n", " for (let col = 0; col < rows[0].length; col++) {\n", " let cn: string = (\n", " (this.config.firstRowAsHeaders && rows[0] && rows[0][col] && rows[0][col].toString().trim()) ||\n", " `field_${col + 1}`\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const title = (\n", " (this.config.firstRowAsHeaders && rows[0] && rows[0][col] && rows[0][col].toString().trim()) ||\n", " `Field ${col + 1}`\n", " ).trim()\n" ], "file_path": "packages/nc-gui/helpers/parsers/ExcelTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 115 }
--- title: 'URL' description: 'This article explains how to create & work with an URL field.' tags: ['Fields', 'Field types', 'Text based types', 'URL'] keywords: ['Fields', 'Field types', 'Text based types', 'URL', 'Create URL field'] --- `URL` field is text based field custom-built for storing URLs. It is a special type of `Single line text` field with - Optional validation for URL - Cell display as clickable link ## Create an `URL` field 1. Click on `+` icon to the right of `Fields header` 2. On the dropdown modal, enter the field name (Optional). 3. Select the field type as `URL` from the dropdown. 4. Enable validation by toggling the `Validate URL` checkbox (Optional). 5. Set default value for the field (Optional). 6. Click on `Save Field` button. ![image](/img/v2/fields/types/url.png) :::note - Specify default value without quotes. - Validation only ensures that the value entered is a valid URL. It does not check if the URL exists. ::: ## Similar text based fields Following are the other text based fields available in NocoDB, custom-built for specific use cases. - [Single line text](010.single-line-text.md) - [Long text](020.long-text.md) - [Email](030.email.md) - [Phone](040.phonenumber.md)
packages/noco-docs/docs/070.fields/040.field-types/010.text-based/050.url.md
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0001671413192525506, 0.0001645387092139572, 0.00016317007248289883, 0.00016392172256018966, 0.0000015338696357503068 ]
{ "id": 9, "code_window": [ " cn = `${cn}${++columnNamePrefixRef[cn]}`\n", " }\n", " columnNamePrefixRef[cn] = 0\n", "\n", " const column: Record<string, any> = {\n", " column_name: cn,\n", " ref_column_name: cn,\n", " meta: {},\n", " uidt: UITypes.SingleLineText,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " title,\n" ], "file_path": "packages/nc-gui/helpers/parsers/ExcelTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 128 }
<script setup lang="ts"> import dayjs from 'dayjs' import utc from 'dayjs/plugin/utc' import type { ColumnType, TableType } from 'nocodb-sdk' import { UITypes, isSystemColumn, isVirtualCol } from 'nocodb-sdk' import type { CheckboxChangeEvent } from 'ant-design-vue/es/checkbox/interface' import { srcDestMappingColumns, tableColumns } from './utils' import { Empty, Form, ImportWorkerOperations, ImportWorkerResponse, MetaInj, ReloadViewDataHookInj, TabType, computed, createEventHook, extractSdkResponseErrorMsg, fieldLengthValidator, fieldRequiredValidator, getDateFormat, getDateTimeFormat, getUIDTIcon, iconMap, inject, message, nextTick, onMounted, parseStringDate, reactive, ref, storeToRefs, useBase, useI18n, useNuxtApp, useTabs, validateTableName, } from '#imports' const { quickImportType, baseTemplate, importData, importColumns, importDataOnly, maxRowsToParse, sourceId, importWorker } = defineProps<Props>() const emit = defineEmits(['import', 'error', 'change']) dayjs.extend(utc) const { t } = useI18n() interface Props { quickImportType: 'csv' | 'excel' | 'json' baseTemplate: Record<string, any> importData: Record<string, any> importColumns: any[] importDataOnly: boolean maxRowsToParse: number sourceId: string importWorker: Worker } interface Option { label: string value: string } const meta = inject(MetaInj, ref()) const columns = computed(() => meta.value?.columns || []) const reloadHook = inject(ReloadViewDataHookInj, createEventHook()) const useForm = Form.useForm const { $api } = useNuxtApp() const { addTab } = useTabs() const baseStrore = useBase() const { loadTables } = baseStrore const { sqlUis, base } = storeToRefs(baseStrore) const { openTable } = useTablesStore() const { baseTables } = storeToRefs(useTablesStore()) const sqlUi = ref(sqlUis.value[sourceId] || Object.values(sqlUis.value)[0]) const hasSelectColumn = ref<boolean[]>([]) const expansionPanel = ref<number[]>([]) const editableTn = ref<boolean[]>([]) const inputRefs = ref<HTMLInputElement[]>([]) const isImporting = ref(false) const importingTips = ref<Record<string, string>>({}) const checkAllRecord = ref<boolean[]>([]) const formError = ref() const uiTypeOptions = ref<Option[]>( (Object.keys(UITypes) as (keyof typeof UITypes)[]) .filter( (uiType) => !isVirtualCol(UITypes[uiType]) && ![UITypes.ForeignKey, UITypes.ID, UITypes.CreateTime, UITypes.LastModifiedTime, UITypes.Barcode, UITypes.Button].includes( UITypes[uiType], ), ) .map<Option>((uiType) => ({ value: uiType, label: uiType, })), ) const srcDestMapping = ref<Record<string, Record<string, any>[]>>({}) const data = reactive<{ title: string | null name: string tables: (TableType & { ref_table_name: string; columns: (ColumnType & { key: number; _disableSelect?: boolean })[] })[] }>({ title: null, name: 'Base Name', tables: [], }) const validators = computed(() => data.tables.reduce<Record<string, [ReturnType<typeof fieldRequiredValidator>]>>((acc: Record<string, any>, table, tableIdx) => { acc[`tables.${tableIdx}.table_name`] = [validateTableName] hasSelectColumn.value[tableIdx] = false table.columns?.forEach((column, columnIdx) => { acc[`tables.${tableIdx}.columns.${columnIdx}.column_name`] = [ fieldRequiredValidator(), fieldLengthValidator(), ] acc[`tables.${tableIdx}.columns.${columnIdx}.uidt`] = [fieldRequiredValidator()] if (isSelect(column)) { hasSelectColumn.value[tableIdx] = true } }) return acc }, {}), ) const { validate, validateInfos, modelRef } = useForm(data, validators) const isValid = ref(!importDataOnly) const formRef = ref() watch( () => srcDestMapping.value, () => { let res = true if (importDataOnly) { for (const tn of Object.keys(srcDestMapping.value)) { if (!atLeastOneEnabledValidation(tn)) { res = false } for (const record of srcDestMapping.value[tn]) { if (!fieldsValidation(record, tn)) { return false } } } } else { for (const [_, o] of Object.entries(validateInfos)) { if (o?.validateStatus) { if (o.validateStatus === 'error') { res = false } } } } isValid.value = res }, { deep: true }, ) const prevEditableTn = ref<string[]>([]) onMounted(() => { parseAndLoadTemplate() // used to record the previous EditableTn values // for checking the table duplication in current import // and updating the key in importData prevEditableTn.value = data.tables.map((t) => t.table_name) if (importDataOnly) { mapDefaultColumns() } nextTick(() => { inputRefs.value[0]?.focus() }) }) function filterOption(input: string, option: Option) { return option.value.toUpperCase().includes(input.toUpperCase()) } function parseAndLoadTemplate() { if (baseTemplate) { parseTemplate(baseTemplate) expansionPanel.value = Array.from({ length: data.tables.length || 0 }, (_, i) => i) hasSelectColumn.value = Array.from({ length: data.tables.length || 0 }, () => false) } } function parseTemplate({ tables = [], ...rest }: Props['baseTemplate']) { const parsedTemplate = { ...rest, tables: tables.map(({ v = [], columns = [], ...rest }) => ({ ...rest, columns: [ ...columns.map((c: any, idx: number) => { c.key = idx return c }), ...v.map((v: any) => ({ column_name: v.title, table_name: { ...v, }, })), ], })), } Object.assign(data, parsedTemplate) } function isSelect(col: ColumnType) { return col.uidt === 'MultiSelect' || col.uidt === 'SingleSelect' } function deleteTable(tableIdx: number) { data.tables.splice(tableIdx, 1) } function deleteTableColumn(tableIdx: number, columnKey: number) { const columnIdx = data.tables[tableIdx].columns.findIndex((c: ColumnType & { key: number }) => c.key === columnKey) data.tables[tableIdx].columns.splice(columnIdx, 1) } function addNewColumnRow(tableIdx: number, uidt: string) { data.tables[tableIdx].columns.push({ key: data.tables[tableIdx].columns.length, column_name: `title${data.tables[tableIdx].columns.length + 1}`, uidt, }) nextTick(() => { const input = inputRefs.value[data.tables[tableIdx].columns.length - 1] input.focus() input.select() }) } function setEditableTn(tableIdx: number, val: boolean) { editableTn.value[tableIdx] = val } function remapColNames(batchData: any[], columns: ColumnType[]) { const dateFormatMap: Record<number, string> = {} return batchData.map((data) => (columns || []).reduce((aggObj, col: Record<string, any>) => { // for excel & json, if the column name is changed in TemplateEditor, // then only col.column_name exists in data, else col.ref_column_name // for csv, col.column_name always exists in data // since it streams the data in getData() with the updated col.column_name const key = col.column_name in data ? col.column_name : col.ref_column_name let d = data[key] if (col.uidt === UITypes.Date && d) { let dateFormat if (col?.meta?.date_format) { dateFormat = col.meta.date_format dateFormatMap[col.key] = dateFormat } else if (col.key in dateFormatMap) { dateFormat = dateFormatMap[col.key] } else { dateFormat = getDateFormat(d) dateFormatMap[col.key] = dateFormat } d = parseStringDate(d, dateFormat) } else if (col.uidt === UITypes.DateTime && d) { const dateTimeFormat = getDateTimeFormat(data[key]) d = dayjs(data[key], dateTimeFormat).format('YYYY-MM-DD HH:mm') } return { ...aggObj, [col.column_name]: d, } }, {}), ) } function missingRequiredColumnsValidation(tn: string) { const missingRequiredColumns = columns.value.filter( (c: Record<string, any>) => (c.pk ? !c.ai && !c.cdf : !c.cdf && c.rqd) && !srcDestMapping.value[tn].some((r: Record<string, any>) => r.destCn === c.title), ) if (missingRequiredColumns.length) { message.error(`${t('msg.error.columnsRequired')} : ${missingRequiredColumns.map((c) => c.title).join(', ')}`) return false } return true } function atLeastOneEnabledValidation(tn: string) { if (srcDestMapping.value[tn].filter((v: Record<string, any>) => v.enabled === true).length === 0) { message.error(t('msg.error.selectAtleastOneColumn')) return false } return true } function fieldsValidation(record: Record<string, any>, tn: string) { // if it is not selected, then pass validation if (!record.enabled) { return true } if (!record.destCn) { message.error(`${t('msg.error.columnDescriptionNotFound')} ${record.srcCn}`) return false } if (srcDestMapping.value[tn].filter((v: Record<string, any>) => v.destCn === record.destCn).length > 1) { message.error(t('msg.error.duplicateMappingFound')) return false } const v = columns.value.find((c) => c.title === record.destCn) as Record<string, any> for (const tableName of Object.keys(importData)) { // check if the input contains null value for a required column if (v.pk ? !v.ai && !v.cdf : !v.cdf && v.rqd) { if ( importData[tableName] .slice(0, maxRowsToParse) .some((r: Record<string, any>) => r[record.srcCn] === null || r[record.srcCn] === undefined || r[record.srcCn] === '') ) { message.error(t('msg.error.nullValueViolatesNotNull')) } } switch (v.uidt) { case UITypes.Number: if ( importData[tableName] .slice(0, maxRowsToParse) .some( (r: Record<string, any>) => r[record.sourceCn] !== null && r[record.srcCn] !== undefined && isNaN(+r[record.srcCn]), ) ) { message.error(t('msg.error.sourceHasInvalidNumbers')) return false } break case UITypes.Checkbox: if ( importData[tableName].slice(0, maxRowsToParse).some((r: Record<string, any>) => { if (r[record.srcCn] !== null && r[record.srcCn] !== undefined) { let input = r[record.srcCn] if (typeof input === 'string') { input = input.replace(/["']/g, '').toLowerCase().trim() return !( input === 'false' || input === 'no' || input === 'n' || input === '0' || input === 'true' || input === 'yes' || input === 'y' || input === '1' ) } return input !== 1 && input !== 0 && input !== true && input !== false } return false }) ) { message.error(t('msg.error.sourceHasInvalidBoolean')) return false } break } } return true } function updateImportTips(baseName: string, tableName: string, progress: number, total: number) { importingTips.value[`${baseName}-${tableName}`] = `Importing data to ${baseName} - ${tableName}: ${progress}/${total} records` } async function importTemplate() { if (importDataOnly) { for (const table of data.tables) { // validate required columns if (!missingRequiredColumnsValidation(table.table_name)) return // validate at least one column needs to be selected if (!atLeastOneEnabledValidation(table.table_name)) return } try { isImporting.value = true const tableId = meta.value?.id const baseId = base.value.id! const table_names = data.tables.map((t: Record<string, any>) => t.table_name) await Promise.all( Object.keys(importData).map((key: string) => (async (k) => { if (!table_names.includes(k)) { return } const data = importData[k] const total = data.length for (let i = 0, progress = 0; i < total; i += maxRowsToParse) { const batchData = data.slice(i, i + maxRowsToParse).map((row: Record<string, any>) => srcDestMapping.value[k].reduce((res: Record<string, any>, col: Record<string, any>) => { if (col.enabled && col.destCn) { const v = columns.value.find((c: Record<string, any>) => c.title === col.destCn) as Record<string, any> let input = row[col.srcCn] // parse potential boolean values if (v.uidt === UITypes.Checkbox) { input = input ? input.replace(/["']/g, '').toLowerCase().trim() : 'false' if (input === 'false' || input === 'no' || input === 'n') { input = '0' } else if (input === 'true' || input === 'yes' || input === 'y') { input = '1' } } else if (v.uidt === UITypes.Number) { if (input === '') { input = null } } else if (v.uidt === UITypes.SingleSelect || v.uidt === UITypes.MultiSelect) { if (input === '') { input = null } } else if (v.uidt === UITypes.Date) { if (input) { input = parseStringDate(input, v.meta.date_format) } } res[col.destCn] = input } return res }, {}), ) await $api.dbTableRow.bulkCreate('noco', baseId, tableId!, batchData) updateImportTips(baseId, tableId!, progress, total) progress += batchData.length } })(key), ), ) // reload table reloadHook.trigger() // Successfully imported table data message.success(t('msg.success.tableDataImported')) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { isImporting.value = false } } else { // check if form is valid try { await validate() } catch (errorInfo) { isImporting.value = false throw new Error('Please fill all the required values') } try { isImporting.value = true // tab info to be used to show the tab after successful import const tab = { id: '', title: '', baseId: '', } // create tables for (const table of data.tables) { // enrich system fields if not provided // e.g. id, created_at, updated_at const systemColumns = sqlUi?.value.getNewTableColumns().filter((c: ColumnType) => c.column_name !== 'title') for (const systemColumn of systemColumns) { if (!table.columns?.some((c) => c.column_name?.toLowerCase() === systemColumn.column_name.toLowerCase())) { table.columns?.push(systemColumn) } } if (table.columns) { for (const column of table.columns) { // set pk & rqd if ID is provided if (column.column_name?.toLowerCase() === 'id' && !('pk' in column)) { column.pk = true column.rqd = true } if ( (!isSystemColumn(column) || ['created_at', 'updated_at'].includes(column.column_name!)) && column.uidt !== UITypes.SingleSelect && column.uidt !== UITypes.MultiSelect ) { // delete dtxp if the final data type is not single & multi select // e.g. import -> detect as single / multi select -> switch to SingleLineText // the correct dtxp will be generated during column creation delete column.dtxp } } } const createdTable = await $api.source.tableCreate(base.value?.id as string, (sourceId || base.value?.sources?.[0].id)!, { table_name: table.table_name, // leave title empty to get a generated one based on table_name title: '', columns: table.columns || [], }) if (process.env.NC_SANITIZE_COLUMN_NAME !== 'false') { // column_name could have been updated in tableCreate // e.g. sanitize column name to something like field_1, field_2, and etc createdTable.columns.forEach((column, i) => { table.columns[i].column_name = column.column_name }) } table.id = createdTable.id table.title = createdTable.title // open the first table after import if (tab.id === '' && tab.title === '' && tab.baseId === '') { tab.id = createdTable.id as string tab.title = createdTable.title as string tab.baseId = base.value.id as string } // set display value if (createdTable?.columns?.[0]?.id) { await $api.dbTableColumn.primaryColumnSet(createdTable.columns[0].id as string) } } // bulk insert data if (importData) { const offset = maxRowsToParse const baseName = base.value.title as string await Promise.all( data.tables.map((table: Record<string, any>) => (async (tableMeta) => { let progress = 0 let total = 0 // use ref_table_name here instead of table_name // since importData[talbeMeta.table_name] would be empty after renaming const data = importData[tableMeta.ref_table_name] if (data) { total += data.length for (let i = 0; i < data.length; i += offset) { updateImportTips(baseName, tableMeta.title, progress, total) const batchData = remapColNames(data.slice(i, i + offset), tableMeta.columns) await $api.dbTableRow.bulkCreate('noco', base.value.id, tableMeta.id, batchData) progress += batchData.length } updateImportTips(baseName, tableMeta.title, total, total) } })(table), ), ) } // reload table list await loadTables() addTab({ ...tab, type: TabType.TABLE, }) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { isImporting.value = false } } if (!data.tables?.length) return const tables = baseTables.value.get(base.value!.id!) const toBeNavigatedTable = tables?.find((t) => t.id === data.tables[0].id) if (!toBeNavigatedTable) return openTable(toBeNavigatedTable) } function mapDefaultColumns() { srcDestMapping.value = {} for (let i = 0; i < data.tables.length; i++) { for (const col of importColumns[i]) { const o = { srcCn: col.column_name, destCn: '', enabled: true } if (columns.value) { const tableColumn = columns.value.find((c) => c.column_name === col.column_name) if (tableColumn) { o.destCn = tableColumn.title as string } else { o.enabled = false } } if (!(data.tables[i].table_name in srcDestMapping.value)) { srcDestMapping.value[data.tables[i].table_name] = [] } srcDestMapping.value[data.tables[i].table_name].push(o) } } } defineExpose({ importTemplate, isValid, }) function handleEditableTnChange(idx: number) { const oldValue = prevEditableTn.value[idx] const newValue = data.tables[idx].table_name if (data.tables.filter((t) => t.table_name === newValue).length > 1) { message.warn('Duplicate Table Name') data.tables[idx].table_name = oldValue } else { prevEditableTn.value[idx] = newValue } setEditableTn(idx, false) } function isSelectDisabled(uidt: string, disableSelect = false) { return (uidt === UITypes.SingleSelect || uidt === UITypes.MultiSelect) && disableSelect } function handleCheckAllRecord(event: CheckboxChangeEvent, tableName: string) { const isChecked = event.target.checked for (const record of srcDestMapping.value[tableName]) { record.enabled = isChecked } } function handleUIDTChange(column, table) { if (!importWorker) return const handler = (e) => { const [type, payload] = e.data switch (type) { case ImportWorkerResponse.SINGLE_SELECT_OPTIONS: case ImportWorkerResponse.MULTI_SELECT_OPTIONS: importWorker.removeEventListener('message', handler, false) column.dtxp = payload break } } if (column.uidt === UITypes.SingleSelect) { importWorker.addEventListener('message', handler, false) importWorker.postMessage([ ImportWorkerOperations.GET_SINGLE_SELECT_OPTIONS, { tableName: table.ref_table_name, columnName: column.ref_column_name, }, ]) } else if (column.uidt === UITypes.MultiSelect) { importWorker.addEventListener('message', handler, false) importWorker.postMessage([ ImportWorkerOperations.GET_MULTI_SELECT_OPTIONS, { tableName: table.ref_table_name, columnName: column.ref_column_name, }, ]) } } const setErrorState = (errorsFields: any[]) => { const errorMap: any = {} for (const error of errorsFields) { errorMap[error.name] = error.errors } formError.value = errorMap } watch(formRef, () => { setTimeout(async () => { try { await validate() emit('change') formError.value = null } catch (e: any) { emit('error', e) setErrorState(e.errorFields) } }, 500) }) watch(modelRef, async () => { try { await validate() emit('change') formError.value = null } catch (e: any) { emit('error', e) setErrorState(e.errorFields) } }) </script> <template> <a-spin :spinning="isImporting" size="large"> <template #tip> <p v-for="(importingTip, idx) of importingTips" :key="idx" class="mt-[10px]"> {{ importingTip }} </p> </template> <a-card v-if="importDataOnly"> <a-form :model="data" name="import-only"> <p v-if="data.tables && quickImportType === 'excel'" class="text-center"> {{ data.tables.length }} sheet{{ data.tables.length > 1 ? 's' : '' }} available for import </p> </a-form> <a-collapse v-if="data.tables && data.tables.length" v-model:activeKey="expansionPanel" class="template-collapse" accordion> <a-collapse-panel v-for="(table, tableIdx) of data.tables" :key="tableIdx"> <template #header> <span class="font-weight-bold text-lg flex items-center gap-2 truncate"> <component :is="iconMap.table" class="text-primary" /> {{ table.table_name }} </span> </template> <template #extra> <a-tooltip bottom> <template #title> <span>{{ $t('activity.deleteTable') }}</span> </template> <component :is="iconMap.delete" v-if="data.tables.length > 1" class="text-lg mr-8" @click.stop="deleteTable(tableIdx)" /> </a-tooltip> </template> <a-table v-if="srcDestMapping" class="template-form" row-class-name="template-form-row" :data-source="srcDestMapping[table.table_name]" :columns="srcDestMappingColumns" :pagination="false" > <template #emptyText> <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noData')" /> </template> <template #headerCell="{ column }"> <span v-if="column.key === 'source_column' || column.key === 'destination_column'"> {{ column.name }} </span> <span v-if="column.key === 'action'"> <a-checkbox v-model:checked="checkAllRecord[table.table_name]" @change="handleCheckAllRecord($event, table.table_name)" /> </span> </template> <template #bodyCell="{ column, record }"> <template v-if="column.key === 'source_column'"> <span>{{ record.srcCn }}</span> </template> <template v-else-if="column.key === 'destination_column'"> <a-select v-model:value="record.destCn" class="w-52" show-search :filter-option="filterOption" dropdown-class-name="nc-dropdown-filter-field" > <a-select-option v-for="(col, i) of columns" :key="i" :value="col.title"> <div class="flex items-center"> <component :is="getUIDTIcon(col.uidt)" /> <span class="ml-2">{{ col.title }}</span> </div> </a-select-option> </a-select> </template> <template v-if="column.key === 'action'"> <a-checkbox v-model:checked="record.enabled" /> </template> </template> </a-table> </a-collapse-panel> </a-collapse> </a-card> <a-card v-else> <a-form ref="formRef" :model="data" name="template-editor-form" @keydown.enter="emit('import')"> <p v-if="data.tables && quickImportType === 'excel'" class="text-center"> {{ data.tables.length }} sheet{{ data.tables.length > 1 ? 's' : '' }} available for import </p> <a-collapse v-if="data.tables && data.tables.length" v-model:activeKey="expansionPanel" class="template-collapse" accordion > <a-collapse-panel v-for="(table, tableIdx) of data.tables" :key="tableIdx"> <template #header> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.table_name`]" no-style> <div class="flex flex-col w-full"> <a-input v-model:value="table.table_name" class="font-weight-bold text-lg" size="large" hide-details :bordered="false" @click.stop @blur="handleEditableTnChange(tableIdx)" @keydown.enter="handleEditableTnChange(tableIdx)" @dblclick="setEditableTn(tableIdx, true)" /> <div v-if="formError?.[`tables.${tableIdx}.table_name`]" class="text-red-500 ml-3"> {{ formError?.[`tables.${tableIdx}.table_name`].join('\n') }} </div> </div> </a-form-item> </template> <template #extra> <a-tooltip bottom> <template #title> <span>{{ $t('activity.deleteTable') }}</span> </template> <component :is="iconMap.delete" v-if="data.tables.length > 1" class="text-lg mr-8" @click.stop="deleteTable(tableIdx)" /> </a-tooltip> </template> <a-table v-if="table.columns && table.columns.length" class="template-form" row-class-name="template-form-row" :data-source="table.columns" :columns="tableColumns" :pagination="table.columns.length > 50 ? { defaultPageSize: 50, position: ['bottomCenter'] } : false" > <template #emptyText> <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noData')" /> </template> <template #headerCell="{ column }"> <template v-if="column.key === 'column_name'"> <span> {{ $t('labels.columnName') }} </span> </template> <template v-else-if="column.key === 'uidt'"> <span> {{ $t('labels.columnType') }} </span> </template> <template v-else-if="column.key === 'dtxp' && hasSelectColumn[tableIdx]"> <span> {{ $t('general.options') }} </span> </template> </template> <template #bodyCell="{ column, record }"> <template v-if="column.key === 'column_name'"> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]"> <a-input :ref="(el: HTMLInputElement) => (inputRefs[record.key] = el)" v-model:value="record.column_name" /> </a-form-item> </template> <template v-else-if="column.key === 'uidt'"> <a-form-item v-bind="validateInfos[`tables.${tableIdx}.columns.${record.key}.${column.key}`]"> <a-select v-model:value="record.uidt" class="w-52" show-search :filter-option="filterOption" dropdown-class-name="nc-dropdown-template-uidt" @change="handleUIDTChange(record, table)" > <a-select-option v-for="(option, i) of uiTypeOptions" :key="i" :value="option.value"> <a-tooltip placement="right"> <template v-if="isSelectDisabled(option.label, table.columns[record.key]?._disableSelect)" #title> {{ $t('msg.tooLargeFieldEntity', { entity: option.label, }) }} </template> {{ option.label }} </a-tooltip> </a-select-option> </a-select> </a-form-item> </template> <template v-else-if="column.key === 'dtxp'"> <a-form-item v-if="isSelect(record)"> <a-input v-model:value="record.dtxp" /> </a-form-item> </template> <template v-if="column.key === 'action'"> <a-tooltip v-if="record.key === 0"> <template #title> <span>{{ $t('general.primaryValue') }}</span> </template> <div class="flex items-center float-right mr-4"> <mdi-key-star class="text-lg" /> </div> </a-tooltip> <a-tooltip v-else> <template #title> <span>{{ $t('activity.column.delete') }}</span> </template> <a-button type="text" @click="deleteTableColumn(tableIdx, record.key)"> <div class="flex items-center"> <component :is="iconMap.delete" class="text-lg" /> </div> </a-button> </a-tooltip> </template> </template> </a-table> <div class="mt-5 flex gap-2 justify-center"> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addNumber') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'Number')"> <div class="flex items-center"> <component :is="iconMap.number" class="group-hover:!text-accent flex text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addSingleLineText') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'SingleLineText')"> <div class="flex items-center"> <component :is="iconMap.text" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addLongText') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'LongText')"> <div class="flex items-center"> <component :is="iconMap.longText" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> <a-tooltip bottom> <template #title> <span>{{ $t('activity.column.addOther') }}</span> </template> <a-button class="group" @click="addNewColumnRow(tableIdx, 'SingleLineText')"> <div class="flex items-center gap-1"> <component :is="iconMap.plus" class="group-hover:!text-accent text-lg" /> </div> </a-button> </a-tooltip> </div> </a-collapse-panel> </a-collapse> </a-form> </a-card> </a-spin> </template> <style scoped lang="scss"> .template-collapse { @apply bg-white; } .template-form { :deep(.ant-table-thead) > tr > th { @apply bg-white; } :deep(.template-form-row) > td { @apply p-0 mb-0; .ant-form-item { @apply mb-0; } } } </style>
packages/nc-gui/components/template/Editor.vue
1
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.9963074922561646, 0.0889497622847557, 0.00016325160686392337, 0.00017648277571424842, 0.27281850576400757 ]
{ "id": 9, "code_window": [ " cn = `${cn}${++columnNamePrefixRef[cn]}`\n", " }\n", " columnNamePrefixRef[cn] = 0\n", "\n", " const column: Record<string, any> = {\n", " column_name: cn,\n", " ref_column_name: cn,\n", " meta: {},\n", " uidt: UITypes.SingleLineText,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " title,\n" ], "file_path": "packages/nc-gui/helpers/parsers/ExcelTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 128 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M14.6668 2H1.3335L6.66683 8.30667V12.6667L9.3335 14V8.30667L14.6668 2Z" stroke="currentColor" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/> </svg>
packages/nc-gui/assets/nc-icons/filter.svg
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00017343230138067156, 0.00017343230138067156, 0.00017343230138067156, 0.00017343230138067156, 0 ]
{ "id": 9, "code_window": [ " cn = `${cn}${++columnNamePrefixRef[cn]}`\n", " }\n", " columnNamePrefixRef[cn] = 0\n", "\n", " const column: Record<string, any> = {\n", " column_name: cn,\n", " ref_column_name: cn,\n", " meta: {},\n", " uidt: UITypes.SingleLineText,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " title,\n" ], "file_path": "packages/nc-gui/helpers/parsers/ExcelTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 128 }
import { Injectable } from '@nestjs/common'; import { AppEvents } from 'nocodb-sdk'; import type { GridColumnReqType } from 'nocodb-sdk'; import type { NcRequest } from '~/interface/config'; import { AppHooksService } from '~/services/app-hooks/app-hooks.service'; import { validatePayload } from '~/helpers'; import { GridViewColumn } from '~/models'; @Injectable() export class GridColumnsService { constructor(private readonly appHooksService: AppHooksService) {} async columnList(param: { gridViewId: string }) { return await GridViewColumn.list(param.gridViewId); } async gridColumnUpdate(param: { gridViewColumnId: string; grid: GridColumnReqType; req: NcRequest; }) { validatePayload( 'swagger.json#/components/schemas/GridColumnReq', param.grid, ); const res = await GridViewColumn.update(param.gridViewColumnId, param.grid); this.appHooksService.emit(AppEvents.GRID_COLUMN_UPDATE, { req: param.req, }); return res; } }
packages/nocodb/src/services/grid-columns.service.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0001751723902998492, 0.0001712274388410151, 0.00016606030112598091, 0.0001718385610729456, 0.000003962913069699425 ]
{ "id": 9, "code_window": [ " cn = `${cn}${++columnNamePrefixRef[cn]}`\n", " }\n", " columnNamePrefixRef[cn] = 0\n", "\n", " const column: Record<string, any> = {\n", " column_name: cn,\n", " ref_column_name: cn,\n", " meta: {},\n", " uidt: UITypes.SingleLineText,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " title,\n" ], "file_path": "packages/nc-gui/helpers/parsers/ExcelTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 128 }
import { Test } from '@nestjs/testing'; import { PluginsService } from '../services/plugins.service'; import { PluginsController } from './plugins.controller'; import type { TestingModule } from '@nestjs/testing'; describe('PluginsController', () => { let controller: PluginsController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [PluginsController], providers: [PluginsService], }).compile(); controller = module.get<PluginsController>(PluginsController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); });
packages/nocodb/src/controllers/plugins.controller.spec.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0001754980767145753, 0.00017268575902562588, 0.00017038224905263633, 0.0001721769367577508, 0.000002119291593771777 ]
{ "id": 10, "code_window": [ " for (const key of Object.keys(firstRowVal)) {\n", " const normalizedNestedColumns = this._parseColumn([...path, key], this.jsonData, firstRowVal[key])\n", " columns.push(...normalizedNestedColumns)\n", " }\n", " } else {\n", " const cn = path.join('_').replace(/\\W/g, '_').trim()\n", " const column: Record<string, any> = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const title = path.join(' ').trim()\n" ], "file_path": "packages/nc-gui/helpers/parsers/JSONTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 92 }
import { UITypes } from 'nocodb-sdk' import { getDateFormat } from '../../utils/dateTimeUtils' import TemplateGenerator from './TemplateGenerator' import { extractMultiOrSingleSelectProps, getCheckboxValue, isCheckboxType, isEmailType, isMultiLineTextType, isUrlType, } from './parserHelpers' const excelTypeToUidt: Record<string, UITypes> = { d: UITypes.DateTime, b: UITypes.Checkbox, n: UITypes.Number, s: UITypes.SingleLineText, } export default class ExcelTemplateAdapter extends TemplateGenerator { config: Record<string, any> excelData: any base: { tables: Record<string, any>[] } data: Record<string, any> = {} wb: any xlsx: typeof import('xlsx') constructor(data = {}, parserConfig = {}, xlsx: any = null, progressCallback?: (msg: string) => void) { super(progressCallback) this.config = parserConfig this.excelData = data this.base = { tables: [], } this.xlsx = xlsx || ({} as any) } async init() { this.progress('Initializing excel parser') this.xlsx = this.xlsx || (await import('xlsx')) const options = { cellText: true, cellDates: true, } this.wb = this.xlsx.read(new Uint8Array(this.excelData), { type: 'array', ...options, }) } async parse() { this.progress('Parsing excel file') const tableNamePrefixRef: Record<string, any> = {} await Promise.all( this.wb.SheetNames.map((sheetName: string) => (async (sheet) => { this.progress(`Parsing sheet ${sheetName}`) await new Promise((resolve) => { const columnNamePrefixRef: Record<string, any> = { id: 0 } let tn: string = (sheet || 'table').replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_').trim() while (tn in tableNamePrefixRef) { tn = `${tn}${++tableNamePrefixRef[tn]}` } tableNamePrefixRef[tn] = 0 const table = { table_name: tn, ref_table_name: tn, columns: [] as any[] } const ws: any = this.wb.Sheets[sheet] // if sheet is empty, skip it if (!ws || !ws['!ref']) { return resolve(true) } const range = this.xlsx.utils.decode_range(ws['!ref']) let rows: any = this.xlsx.utils.sheet_to_json(ws, { // header has to be 1 disregarding this.config.firstRowAsHeaders // so that it generates an array of arrays header: 1, blankrows: false, defval: null, }) // fix precision bug & timezone offset issues introduced by xlsx const basedate = new Date(1899, 11, 30, 0, 0, 0) // number of milliseconds since base date const dnthresh = basedate.getTime() + (new Date().getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000 // number of milliseconds in a day const day_ms = 24 * 60 * 60 * 1000 // handle date1904 property const fixImportedDate = (date: Date) => { const parsed = this.xlsx.SSF.parse_date_code((date.getTime() - dnthresh) / day_ms, { date1904: this.wb.Workbook.WBProps.date1904, }) return new Date(parsed.y, parsed.m, parsed.d, parsed.H, parsed.M, parsed.S) } // fix imported date rows = rows.map((r: any) => r.map((v: any) => { return v instanceof Date ? fixImportedDate(v) : v }), ) for (let col = 0; col < rows[0].length; col++) { let cn: string = ( (this.config.firstRowAsHeaders && rows[0] && rows[0][col] && rows[0][col].toString().trim()) || `field_${col + 1}` ) .replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_') .trim() while (cn in columnNamePrefixRef) { cn = `${cn}${++columnNamePrefixRef[cn]}` } columnNamePrefixRef[cn] = 0 const column: Record<string, any> = { column_name: cn, ref_column_name: cn, meta: {}, uidt: UITypes.SingleLineText, } if (this.config.autoSelectFieldTypes) { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + col, r: +this.config.firstRowAsHeaders, }) const cellProps = ws[cellId] || {} column.uidt = excelTypeToUidt[cellProps.t] || UITypes.SingleLineText if (column.uidt === UITypes.SingleLineText) { // check for long text if (isMultiLineTextType(rows, col)) { column.uidt = UITypes.LongText } else if (isEmailType(rows, col)) { column.uidt = UITypes.Email } else if (isUrlType(rows, col)) { column.uidt = UITypes.URL } else { const vals = rows .slice(+this.config.firstRowAsHeaders) .map((r: any) => r[col]) .filter((v: any) => v !== null && v !== undefined && v.toString().trim() !== '') if (isCheckboxType(vals, col)) { column.uidt = UITypes.Checkbox } else { // Single Select / Multi Select Object.assign(column, extractMultiOrSingleSelectProps(vals)) } } } else if (column.uidt === UITypes.Number) { if ( rows.slice(1, this.config.maxRowsToParse).some((v: any) => { return v && v[col] && parseInt(v[col]) !== +v[col] }) ) { column.uidt = UITypes.Decimal } if ( rows.slice(1, this.config.maxRowsToParse).every((v: any, i: any) => { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + col, r: i + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] return !cellObj || (cellObj.w && cellObj.w.startsWith('$')) }) ) { column.uidt = UITypes.Currency } if ( rows.slice(1, this.config.maxRowsToParse).some((v: any, i: any) => { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + col, r: i + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] return !cellObj || (cellObj.w && !(!isNaN(Number(cellObj.w)) && !isNaN(parseFloat(cellObj.w)))) }) ) { // fallback to SingleLineText column.uidt = UITypes.SingleLineText } } else if (column.uidt === UITypes.DateTime) { // TODO(import): centralise // hold the possible date format found in the date const dateFormat: Record<string, number> = {} if ( rows.slice(1, this.config.maxRowsToParse).every((v: any, i: any) => { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + col, r: i + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] const isDate = !cellObj || (cellObj.w && cellObj.w.split(' ').length === 1) if (isDate && cellObj) { dateFormat[getDateFormat(cellObj.w)] = (dateFormat[getDateFormat(cellObj.w)] || 0) + 1 } return isDate }) ) { column.uidt = UITypes.Date // take the date format with the max occurrence column.meta.date_format = Object.keys(dateFormat).reduce((x, y) => (dateFormat[x] > dateFormat[y] ? x : y)) || 'YYYY/MM/DD' } } } table.columns.push(column) } this.base.tables.push(table) this.data[tn] = [] if (this.config.shouldImportData) { this.progress(`Parsing data from ${tn}`) let rowIndex = 0 for (const row of rows.slice(1)) { const rowData: Record<string, any> = {} for (let i = 0; i < table.columns.length; i++) { if (!this.config.autoSelectFieldTypes) { // take raw data instead of data parsed by xlsx const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + i, r: rowIndex + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] rowData[table.columns[i].column_name] = (cellObj && cellObj.w) || row[i] } else { if (table.columns[i].uidt === UITypes.Checkbox) { rowData[table.columns[i].column_name] = getCheckboxValue(row[i]) } else if (table.columns[i].uidt === UITypes.Currency) { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + i, r: rowIndex + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] rowData[table.columns[i].column_name] = (cellObj && cellObj.w && cellObj.w.replace(/[^\d.]+/g, '')) || row[i] } else if (table.columns[i].uidt === UITypes.SingleSelect || table.columns[i].uidt === UITypes.MultiSelect) { rowData[table.columns[i].column_name] = (row[i] || '').toString().trim() || null } else if (table.columns[i].uidt === UITypes.Date) { const cellId = this.xlsx.utils.encode_cell({ c: range.s.c + i, r: rowIndex + +this.config.firstRowAsHeaders, }) const cellObj = ws[cellId] rowData[table.columns[i].column_name] = (cellObj && cellObj.w) || row[i] } else if (table.columns[i].uidt === UITypes.SingleLineText || table.columns[i].uidt === UITypes.LongText) { rowData[table.columns[i].column_name] = row[i] === null || row[i] === undefined ? null : `${row[i]}` } else { // TODO: do parsing if necessary based on type rowData[table.columns[i].column_name] = row[i] } } } this.data[tn].push(rowData) rowIndex++ } } resolve(true) }) })(sheetName), ), ) } getTemplate() { return this.base } getData() { return this.data } getColumns() { return this.base.tables.map((t: Record<string, any>) => t.columns) } }
packages/nc-gui/helpers/parsers/ExcelTemplateAdapter.ts
1
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.9972796440124512, 0.2637401521205902, 0.00016555185720790178, 0.0015452385414391756, 0.4300784170627594 ]
{ "id": 10, "code_window": [ " for (const key of Object.keys(firstRowVal)) {\n", " const normalizedNestedColumns = this._parseColumn([...path, key], this.jsonData, firstRowVal[key])\n", " columns.push(...normalizedNestedColumns)\n", " }\n", " } else {\n", " const cn = path.join('_').replace(/\\W/g, '_').trim()\n", " const column: Record<string, any> = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const title = path.join(' ').trim()\n" ], "file_path": "packages/nc-gui/helpers/parsers/JSONTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 92 }
import { isLinksOrLTAR, ModelTypes } from 'nocodb-sdk'; import { columnNameParam, columnNameQueryParam, csvExportOffsetParam, exportTypeParam, fieldsParam, getNestedParams, limitParam, offsetParam, referencedRowIdParam, relationTypeParam, rowIdParam, shuffleParam, sortParam, whereParam, } from './params'; import { csvExportResponseHeader } from './headers'; import type { SwaggerColumn } from '../getSwaggerColumnMetas'; export const getModelPaths = async (ctx: { tableName: string; orgs: string; type: ModelTypes; columns: SwaggerColumn[]; baseName: string; }): Promise<{ [path: string]: any }> => ({ [`/api/v1/db/data/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}`]: { get: { summary: `${ctx.tableName} list`, operationId: `${ctx.tableName.toLowerCase()}-db-table-row-list`, description: `List of all rows from ${ctx.tableName} ${ctx.type} and response data fields can be filtered based on query params.`, tags: [ctx.tableName], parameters: [ fieldsParam, sortParam, whereParam, limitParam, shuffleParam, offsetParam, ...(await getNestedParams(ctx.columns)), ], responses: { '200': { description: 'OK', content: { 'application/json': { schema: getPaginatedResponseType(`${ctx.tableName}Response`), }, }, }, }, }, ...(ctx.type === ModelTypes.TABLE ? { post: { summary: `${ctx.tableName} create`, description: 'Insert a new row in table by providing a key value pair object where key refers to the column alias. All the required fields should be included with payload excluding `autoincrement` and column with default value.', operationId: `${ctx.tableName.toLowerCase()}-create`, responses: { '200': { description: 'OK', content: { 'application/json': { schema: { $ref: `#/components/schemas/${ctx.tableName}Response`, }, }, }, }, }, tags: [ctx.tableName], requestBody: { content: { 'application/json': { schema: { $ref: `#/components/schemas/${ctx.tableName}Request`, }, }, }, }, }, } : {}), }, [`/api/v1/db/data/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}/{rowId}`]: { parameters: [rowIdParam], ...(ctx.type === ModelTypes.TABLE ? { get: { parameters: [fieldsParam], summary: `${ctx.tableName} read`, description: 'Read a row data by using the **primary key** column value.', operationId: `${ctx.tableName.toLowerCase()}-read`, responses: { '201': { description: 'Created', content: { 'application/json': { schema: { $ref: `#/components/schemas/${ctx.tableName}Response`, }, }, }, }, }, tags: [ctx.tableName], }, patch: { summary: `${ctx.tableName} update`, operationId: `${ctx.tableName.toLowerCase()}-update`, description: 'Partial update row in table by providing a key value pair object where key refers to the column alias. You need to only include columns which you want to update.', responses: { '200': { description: 'OK', content: { 'application/json': { schema: { $ref: `#/components/schemas/${ctx.tableName}Request`, }, }, }, }, }, tags: [ctx.tableName], requestBody: { content: { 'application/json': { schema: {}, }, }, }, }, delete: { summary: `${ctx.tableName} delete`, operationId: `${ctx.tableName.toLowerCase()}-delete`, responses: { '200': { description: 'OK', }, }, tags: [ctx.tableName], description: 'Delete a row by using the **primary key** column value.', }, } : {}), }, [`/api/v1/db/data/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}/count`]: { get: { summary: `${ctx.tableName} count`, operationId: `${ctx.tableName.toLowerCase()}-count`, description: 'Get rows count of a table by applying optional filters.', tags: [ctx.tableName], parameters: [whereParam], responses: { '200': { description: 'OK', content: { 'application/json': { schema: {}, }, }, }, }, }, }, [`/api/v1/db/data/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}/find-one`]: { get: { summary: `${ctx.tableName} find-one`, operationId: `${ctx.tableName.toLowerCase()}-db-table-row-find-one`, description: `Find first record matching the conditions.`, tags: [ctx.tableName], parameters: [fieldsParam, whereParam, sortParam], responses: { '200': { description: 'OK', content: { 'application/json': { schema: { $ref: `#/components/schemas/${ctx.tableName}Response`, }, }, }, }, }, }, }, [`/api/v1/db/data/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}/groupby`]: { get: { summary: `${ctx.tableName} groupby`, operationId: `${ctx.tableName.toLowerCase()}-groupby`, description: 'Group by a column.', tags: [ctx.tableName], parameters: [ columnNameQueryParam, sortParam, whereParam, limitParam, offsetParam, shuffleParam, ], responses: { '200': { description: 'OK', content: { 'application/json': { schema: { type: 'object', properties: { list: { type: 'array', items: { $ref: `#/components/schemas/Groupby`, }, }, PageInfo: { $ref: `#/components/schemas/Paginated`, }, }, }, }, }, }, }, }, }, ...(ctx.type === ModelTypes.TABLE ? { [`/api/v1/db/data/bulk/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}`]: { post: { summary: `${ctx.tableName} bulk insert`, description: "To insert large amount of data in a single api call you can use this api. It's similar to insert method but here you can pass array of objects to insert into table. Array object will be key value paired column name and value.", operationId: `${ctx.tableName.toLowerCase()}-bulk-create`, responses: { '200': { description: 'OK', content: { 'application/json': { schema: {}, }, }, }, }, tags: [ctx.tableName], requestBody: { content: { 'application/json': { schema: {}, }, }, }, }, patch: { summary: `${ctx.tableName} bulk update`, description: "To update multiple records using it's primary key you can use this api. Bulk updated api accepts array object in which each object should contain it's primary columns value mapped to corresponding alias. In addition to primary key you can include the fields which you want to update", operationId: `${ctx.tableName.toLowerCase()}-bulk-update`, responses: { '200': { description: 'OK', content: { 'application/json': { schema: {}, }, }, }, }, tags: [ctx.tableName], requestBody: { content: { 'application/json': { schema: {}, }, }, }, }, delete: { summary: `${ctx.tableName} bulk delete by IDs`, description: "To delete multiple records using it's primary key you can use this api. Bulk delete api accepts array object in which each object should contain it's primary columns value mapped to corresponding alias.", operationId: `${ctx.tableName.toLowerCase()}-bulk-delete`, responses: { '200': { description: 'OK', content: { 'application/json': { schema: {}, }, }, }, }, tags: [ctx.tableName], requestBody: { content: { 'application/json': { schema: {}, }, }, }, }, }, [`/api/v1/db/data/bulk/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}/all`]: { parameters: [whereParam], patch: { summary: `${ctx.tableName} Bulk update with conditions`, description: "This api helps you update multiple table rows in a single api call. You don't have to pass the record id instead you can filter records and apply the changes to filtered records. Payload is similar as normal update in which you can pass any partial row data to be updated.", operationId: `${ctx.tableName.toLowerCase()}-bulk-update-all`, responses: { '200': { description: 'OK', content: { 'application/json': { schema: {}, }, }, }, }, tags: [ctx.tableName], requestBody: { content: { 'application/json': { schema: {}, }, }, }, }, delete: { summary: 'Bulk delete with conditions', description: "This api helps you delete multiple table rows in a single api call. You don't have to pass the record id instead you can filter records and delete filtered records.", operationId: `${ctx.tableName.toLowerCase()}-bulk-delete-all`, responses: { '200': { description: 'OK', content: { 'application/json': { schema: {}, }, }, }, }, tags: [ctx.tableName], }, }, ...(isRelationExist(ctx.columns) ? { [`/api/v1/db/data/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}/{rowId}/{relationType}/{columnName}`]: { parameters: [ rowIdParam, relationTypeParam, columnNameParam(ctx.columns), ], get: { summary: 'Relation row list', operationId: `${ctx.tableName.toLowerCase()}-nested-list`, responses: { '200': { description: 'OK', content: { 'application/json': { schema: {}, }, }, }, }, tags: [ctx.tableName], parameters: [limitParam, offsetParam], }, }, [`/api/v1/db/data/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}/{rowId}/{relationType}/{columnName}/{refRowId}`]: { parameters: [ rowIdParam, relationTypeParam, columnNameParam(ctx.columns), referencedRowIdParam, ], post: { summary: 'Relation row add', operationId: `${ctx.tableName.toLowerCase()}-nested-add`, responses: { '200': { description: 'OK', content: { 'application/json': { schema: {}, }, }, }, }, tags: [ctx.tableName], parameters: [limitParam, shuffleParam, offsetParam], description: '', }, delete: { summary: 'Relation row remove', operationId: `${ctx.tableName.toLowerCase()}-nested-remove`, responses: { '200': { description: 'OK', content: { 'application/json': { schema: {}, }, }, }, }, tags: [ctx.tableName], }, }, [`/api/v1/db/data/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}/{rowId}/{relationType}/{columnName}/exclude`]: { parameters: [ rowIdParam, relationTypeParam, columnNameParam(ctx.columns), ], get: { summary: 'Referenced tables rows excluding current records children/parent', operationId: `${ctx.tableName.toLowerCase()}-nested-children-excluded-list`, responses: { '200': { description: 'OK', content: { 'application/json': { schema: {}, }, }, }, }, tags: [ctx.tableName], parameters: [limitParam, shuffleParam, offsetParam], }, }, } : {}), } : {}), [`/api/v1/db/data/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}/export/{type}`]: { parameters: [exportTypeParam], get: { summary: 'Rows export', operationId: `${ctx.tableName.toLowerCase()}-csv-export`, description: 'Export all the records from a table.Currently we are only supports `csv` export.', tags: [ctx.tableName], responses: { '200': { description: 'OK', content: { 'application/octet-stream': { schema: {}, }, }, headers: csvExportResponseHeader, }, }, parameters: [csvExportOffsetParam], }, }, }); export const getViewPaths = async (ctx: { tableName: string; viewName: string; type: ModelTypes; orgs: string; baseName: string; columns: SwaggerColumn[]; }): Promise<any> => ({ [`/api/v1/db/data/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}/views/${ctx.viewName}`]: { get: { summary: `${ctx.viewName} list`, operationId: `${ctx.tableName}-${ctx.viewName}-row-list`, description: `List of all rows from ${ctx.viewName} grid view and data of fields can be filtered based on query params. Data and fields in a grid view will be filtered and sorted by default based on the applied options in Dashboard.`, tags: [`${ctx.viewName} ( ${ctx.tableName} grid )`], parameters: [ fieldsParam, sortParam, whereParam, ...(await getNestedParams(ctx.columns)), ], responses: { '200': { description: 'OK', content: { 'application/json': { schema: getPaginatedResponseType( `${ctx.tableName}${ctx.viewName}GridResponse`, ), }, }, }, }, }, ...(ctx.type === ModelTypes.TABLE ? { post: { summary: `${ctx.viewName} create`, description: 'Insert a new row in table by providing a key value pair object where key refers to the column alias. All the required fields should be included with payload excluding `autoincrement` and column with default value.', operationId: `${ctx.tableName}-${ctx.viewName}-row-create`, responses: { '200': { description: 'OK', content: { 'application/json': { schema: {}, }, }, }, }, tags: [`${ctx.viewName} ( ${ctx.tableName} grid )`], requestBody: { content: { 'application/json': { schema: { $ref: `#/components/schemas/${ctx.tableName}${ctx.viewName}GridRequest`, }, }, }, }, }, } : {}), }, [`/api/v1/db/data/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}/views/${ctx.viewName}/count`]: { get: { summary: `${ctx.viewName} count`, operationId: `${ctx.tableName}-${ctx.viewName}-row-count`, description: '', tags: [`${ctx.viewName} ( ${ctx.tableName} grid )`], parameters: [whereParam], responses: { '200': { description: 'OK', content: { 'application/json': { schema: { type: 'object', properties: { count: { type: 'number' }, }, }, }, }, }, }, }, }, ...(ctx.type === ModelTypes.TABLE ? { [`/api/v1/db/data/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}/views/${ctx.viewName}/{rowId}`]: { parameters: [rowIdParam], get: { summary: `${ctx.viewName} read`, description: 'Read a row data by using the **primary key** column value.', operationId: `${ctx.tableName}-${ctx.viewName}-row-read`, responses: { '200': { description: 'Created', content: { 'application/json': { schema: { $ref: `#/components/schemas/${ctx.tableName}${ctx.viewName}GridResponse`, }, }, }, }, }, tags: [`${ctx.viewName} ( ${ctx.tableName} grid )`], }, patch: { summary: `${ctx.viewName} update`, description: 'Partial update row in table by providing a key value pair object where key refers to the column alias. You need to only include columns which you want to update.', operationId: `${ctx.tableName}-${ctx.viewName}-row-update`, responses: { '200': { description: 'OK', content: { 'application/json': { schema: {}, }, }, }, }, tags: [`${ctx.viewName} ( ${ctx.tableName} grid )`], requestBody: { content: { 'application/json': { schema: { $ref: `#/components/schemas/${ctx.tableName}${ctx.viewName}GridRequest`, }, }, }, }, }, delete: { summary: `${ctx.viewName} delete`, operationId: `${ctx.tableName}-${ctx.viewName}-row-delete`, responses: { '200': { description: 'OK', }, }, tags: [`${ctx.viewName} ( ${ctx.tableName} grid )`], description: 'Delete a row by using the **primary key** column value.', }, }, } : {}), [`/api/v1/db/data/${ctx.orgs}/${ctx.baseName}/${ctx.tableName}/views/${ctx.viewName}/export/{type}`]: { parameters: [exportTypeParam], get: { summary: `${ctx.viewName} export`, operationId: `${ctx.tableName}-${ctx.viewName}-row-export`, description: 'Export all the records from a table view. Currently we are only supports `csv` export.', tags: [`${ctx.viewName} ( ${ctx.tableName} grid )`], responses: { '200': { description: 'OK', content: { 'application/octet-stream': { schema: {}, }, }, headers: csvExportResponseHeader, }, }, parameters: [], }, }, }); function getPaginatedResponseType(type: string) { return { type: 'object', properties: { list: { type: 'array', items: { $ref: `#/components/schemas/${type}`, }, }, PageInfo: { $ref: `#/components/schemas/Paginated`, }, }, }; } export function isRelationExist(columns: SwaggerColumn[]) { return columns.some((c) => isLinksOrLTAR(c.column) && !c.column.system); }
packages/nocodb/src/services/api-docs/swagger/templates/paths.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0034739146940410137, 0.00023835130559746176, 0.0001621826086193323, 0.00016961750225163996, 0.00040978618199005723 ]
{ "id": 10, "code_window": [ " for (const key of Object.keys(firstRowVal)) {\n", " const normalizedNestedColumns = this._parseColumn([...path, key], this.jsonData, firstRowVal[key])\n", " columns.push(...normalizedNestedColumns)\n", " }\n", " } else {\n", " const cn = path.join('_').replace(/\\W/g, '_').trim()\n", " const column: Record<string, any> = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const title = path.join(' ').trim()\n" ], "file_path": "packages/nc-gui/helpers/parsers/JSONTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 92 }
import type { BaseType, BoolType, MetaType } from 'nocodb-sdk'; import type { DB_TYPES } from '~/utils/globals'; import Source from '~/models/Source'; import { BaseUser } from '~/models'; import Noco from '~/Noco'; import { CacheDelDirection, CacheGetType, CacheScope, MetaTable, } from '~/utils/globals'; import { extractProps } from '~/helpers/extractProps'; import NocoCache from '~/cache/NocoCache'; import { parseMetaProp, stringifyMetaProp } from '~/utils/modelUtils'; import NcConnectionMgrv2 from '~/utils/common/NcConnectionMgrv2'; export default class Base implements BaseType { public id: string; public title: string; public prefix: string; public status: string; public description: string; public meta: MetaType; public color: string; public deleted: BoolType; public order: number; public is_meta = false; public sources?: Source[]; public linked_db_projects?: Base[]; // shared base props uuid?: string; password?: string; roles?: string; constructor(base: Partial<Base>) { Object.assign(this, base); } public static castType(base: Base): Base { return base && new Base(base); } public static async createProject( base: Partial<BaseType>, ncMeta = Noco.ncMeta, ): Promise<Base> { const insertObj = extractProps(base, [ 'id', 'title', 'prefix', 'description', 'is_meta', 'status', 'meta', 'color', ]); const { id: baseId } = await ncMeta.metaInsert2( null, null, MetaTable.PROJECT, insertObj, ); await NocoCache.appendToList( CacheScope.PROJECT, [], `${CacheScope.PROJECT}:${baseId}`, ); for (const source of base.sources) { await Source.createBase( { type: source.config?.client as (typeof DB_TYPES)[number], ...source, baseId, }, ncMeta, ); } await NocoCache.del(CacheScope.INSTANCE_META); return this.getWithInfo(baseId, ncMeta); } static async list( // @ts-ignore param, ncMeta = Noco.ncMeta, ): Promise<Base[]> { // todo: pagination const cachedList = await NocoCache.getList(CacheScope.PROJECT, []); let { list: baseList } = cachedList; const { isNoneList } = cachedList; if (!isNoneList && !baseList.length) { baseList = await ncMeta.metaList2(null, null, MetaTable.PROJECT, { xcCondition: { _or: [ { deleted: { eq: false, }, }, { deleted: { eq: null, }, }, ], }, }); await NocoCache.setList(CacheScope.PROJECT, [], baseList); } baseList = baseList.filter( (p) => p.deleted === 0 || p.deleted === false || p.deleted === null, ); const castedProjectList = baseList.map((m) => this.castType(m)); await Promise.all(castedProjectList.map((base) => base.getBases(ncMeta))); return castedProjectList; } // @ts-ignore static async get(baseId: string, ncMeta = Noco.ncMeta): Promise<Base> { let baseData = baseId && (await NocoCache.get( `${CacheScope.PROJECT}:${baseId}`, CacheGetType.TYPE_OBJECT, )); if (!baseData) { baseData = await ncMeta.metaGet2(null, null, MetaTable.PROJECT, { id: baseId, deleted: false, }); if (baseData) { baseData.meta = parseMetaProp(baseData); await NocoCache.set(`${CacheScope.PROJECT}:${baseId}`, baseData); } } else { if (baseData.deleted) { baseData = null; } } return this.castType(baseData); } async getBases(ncMeta = Noco.ncMeta): Promise<Source[]> { return (this.sources = await Source.list({ baseId: this.id }, ncMeta)); } // todo: hide credentials // @ts-ignore static async getWithInfo( baseId: string, ncMeta = Noco.ncMeta, ): Promise<Base> { let baseData = baseId && (await NocoCache.get( `${CacheScope.PROJECT}:${baseId}`, CacheGetType.TYPE_OBJECT, )); if (!baseData) { baseData = await ncMeta.metaGet2(null, null, MetaTable.PROJECT, { id: baseId, deleted: false, }); if (baseData) { baseData.meta = parseMetaProp(baseData); await NocoCache.set(`${CacheScope.PROJECT}:${baseId}`, baseData); } if (baseData?.uuid) { await NocoCache.set(`${CacheScope.PROJECT}:${baseData.uuid}`, baseId); } } else { if (baseData?.deleted) { baseData = null; } } if (baseData) { const base = new Base(baseData); await base.getBases(ncMeta); return this.castType(base); } return null; } // @ts-ignore static async softDelete(baseId: string, ncMeta = Noco.ncMeta): Promise<any> { await this.clearConnectionPool(baseId, ncMeta); // get existing cache const key = `${CacheScope.PROJECT}:${baseId}`; const o = await NocoCache.get(key, CacheGetType.TYPE_OBJECT); if (o) { // delete <scope>:<id> await NocoCache.del(`${CacheScope.PROJECT}:${baseId}`); // delete <scope>:<title> await NocoCache.del(`${CacheScope.PROJECT}:${o.title}`); // delete <scope>:<uuid> await NocoCache.del(`${CacheScope.PROJECT}:${o.uuid}`); // delete <scope>:ref:<titleOfId> await NocoCache.del(`${CacheScope.PROJECT}:ref:${o.title}`); await NocoCache.del(`${CacheScope.PROJECT}:ref:${o.id}`); } await NocoCache.delAll(CacheScope.USER_PROJECT, '*'); await NocoCache.del(CacheScope.INSTANCE_META); // remove item in cache list await NocoCache.deepDel( CacheScope.PROJECT, `${CacheScope.PROJECT}:${baseId}`, CacheDelDirection.CHILD_TO_PARENT, ); // set meta return await ncMeta.metaUpdate( null, null, MetaTable.PROJECT, { deleted: true }, baseId, ); } // @ts-ignore static async update( baseId: string, base: Partial<Base>, ncMeta = Noco.ncMeta, ): Promise<any> { const updateObj = extractProps(base, [ 'title', 'prefix', 'status', 'description', 'meta', 'color', 'deleted', 'order', 'sources', 'uuid', 'password', 'roles', ]); // get existing cache const key = `${CacheScope.PROJECT}:${baseId}`; let o = await NocoCache.get(key, CacheGetType.TYPE_OBJECT); if (o) { // update data // new uuid is generated if (o.uuid && updateObj.uuid && o.uuid !== updateObj.uuid) { await NocoCache.del(`${CacheScope.PROJECT}:${o.uuid}`); await NocoCache.set(`${CacheScope.PROJECT}:${updateObj.uuid}`, baseId); } // disable shared base if (o.uuid && updateObj.uuid === null) { await NocoCache.del(`${CacheScope.PROJECT}:${o.uuid}`); } if (o.title && updateObj.title && o.title !== updateObj.title) { await NocoCache.del(`${CacheScope.PROJECT}:${o.title}`); await NocoCache.set(`${CacheScope.PROJECT}:${updateObj.title}`, baseId); } o = { ...o, ...updateObj }; await NocoCache.del(CacheScope.INSTANCE_META); // set cache await NocoCache.set(key, o); } // stringify meta if (updateObj.meta) { updateObj.meta = stringifyMetaProp(updateObj); } // set meta return await ncMeta.metaUpdate( null, null, MetaTable.PROJECT, updateObj, baseId, ); } // Todo: Remove the base entry from the connection pool in NcConnectionMgrv2 static async delete(baseId, ncMeta = Noco.ncMeta): Promise<any> { let base = await this.get(baseId); const users = await BaseUser.getUsersList({ base_id: baseId, offset: 0, limit: 1000, }); for (const user of users) { await BaseUser.delete(baseId, user.id); } const sources = await Source.list({ baseId }); for (const source of sources) { await source.delete(ncMeta); } base = await this.get(baseId); if (base) { // delete <scope>:<uuid> await NocoCache.del(`${CacheScope.PROJECT}:${base.uuid}`); // delete <scope>:<title> await NocoCache.del(`${CacheScope.PROJECT}:${base.title}`); // delete <scope>:ref:<titleOfId> await NocoCache.del(`${CacheScope.PROJECT}:ref:${base.title}`); await NocoCache.del(`${CacheScope.PROJECT}:ref:${base.id}`); } await NocoCache.delAll(CacheScope.USER_PROJECT, '*'); await NocoCache.deepDel( CacheScope.PROJECT, `${CacheScope.PROJECT}:${baseId}`, CacheDelDirection.CHILD_TO_PARENT, ); await ncMeta.metaDelete(null, null, MetaTable.AUDIT, { base_id: baseId, }); return await ncMeta.metaDelete(null, null, MetaTable.PROJECT, baseId); } static async getByUuid(uuid, ncMeta = Noco.ncMeta) { const baseId = uuid && (await NocoCache.get( `${CacheScope.PROJECT}:${uuid}`, CacheGetType.TYPE_OBJECT, )); let baseData = null; if (!baseId) { baseData = await Noco.ncMeta.metaGet2(null, null, MetaTable.PROJECT, { uuid, }); if (baseData) { baseData.meta = parseMetaProp(baseData); await NocoCache.set(`${CacheScope.PROJECT}:${uuid}`, baseData?.id); } } else { return this.get(baseId); } return baseData?.id && this.get(baseData?.id, ncMeta); } static async getWithInfoByTitle(title: string, ncMeta = Noco.ncMeta) { const base = await this.getByTitle(title, ncMeta); if (base) await base.getBases(ncMeta); return base; } static async getByTitle(title: string, ncMeta = Noco.ncMeta) { const baseId = title && (await NocoCache.get( `${CacheScope.PROJECT}:${title}`, CacheGetType.TYPE_OBJECT, )); let baseData = null; if (!baseId) { baseData = await Noco.ncMeta.metaGet2(null, null, MetaTable.PROJECT, { title, deleted: false, }); if (baseData) { baseData.meta = parseMetaProp(baseData); await NocoCache.set(`${CacheScope.PROJECT}:${title}`, baseData?.id); } } else { return this.get(baseId); } return baseData?.id && this.get(baseData?.id, ncMeta); } static async getByTitleOrId(titleOrId: string, ncMeta = Noco.ncMeta) { const baseId = titleOrId && (await NocoCache.get( `${CacheScope.PROJECT}:ref:${titleOrId}`, CacheGetType.TYPE_OBJECT, )); let baseData = null; if (!baseId) { baseData = await Noco.ncMeta.metaGet2( null, null, MetaTable.PROJECT, { deleted: false, }, null, { _or: [ { id: { eq: titleOrId, }, }, { title: { eq: titleOrId, }, }, ], }, ); if (baseData) { // parse meta baseData.meta = parseMetaProp(baseData); await NocoCache.set( `${CacheScope.PROJECT}:ref:${titleOrId}`, baseData?.id, ); } } else { return this.get(baseId); } return baseData?.id && this.get(baseData?.id, ncMeta); } static async getWithInfoByTitleOrId(titleOrId: string, ncMeta = Noco.ncMeta) { const base = await this.getByTitleOrId(titleOrId, ncMeta); // parse meta base.meta = parseMetaProp(base); if (base) await base.getBases(ncMeta); return base; } static async clearConnectionPool(baseId: string, ncMeta = Noco.ncMeta) { const base = await this.get(baseId, ncMeta); if (base) { const sources = await base.getBases(ncMeta); for (const source of sources) { await NcConnectionMgrv2.deleteAwait(source); } } } }
packages/nocodb/src/models/Base.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00017794675659388304, 0.00017273514822591096, 0.00015981878095772117, 0.0001733239332679659, 0.0000035632770050142426 ]
{ "id": 10, "code_window": [ " for (const key of Object.keys(firstRowVal)) {\n", " const normalizedNestedColumns = this._parseColumn([...path, key], this.jsonData, firstRowVal[key])\n", " columns.push(...normalizedNestedColumns)\n", " }\n", " } else {\n", " const cn = path.join('_').replace(/\\W/g, '_').trim()\n", " const column: Record<string, any> = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const title = path.join(' ').trim()\n" ], "file_path": "packages/nc-gui/helpers/parsers/JSONTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 92 }
import BaseRender from '../../BaseRender'; class ExpressXcTsRoutes extends BaseRender { /** * * @param dir * @param filename * @param ct * @param ctx.tn * @param ctx.columns * @param ctx.relations */ constructor({ dir, filename, ctx }: any) { super({ dir, filename, ctx }); } /** * Prepare variables used in code template */ prepare() { let data: any = {}; /* run of simple variable */ data = this.ctx; return data; } getObject() { const ejsData: any = this.prepare(); const routes = [ { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}`, type: 'get', handler: ['list'], acl: { admin: true, user: true, guest: true, }, functions: [ ` async function(req, res){ const data = await req.model.list(req.query); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/findOne`, type: 'get', handler: ['findOne'], acl: { admin: true, user: true, guest: true, }, functions: [ ` async function(req, res){ const data = await req.model.findOne(req.query); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/m2mNotChildren/:assoc/:pid`, type: 'get', handler: ['m2mNotChildren'], acl: { admin: true, user: true, guest: true, }, functions: [ ` `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/groupby/:column_name`, type: 'get', handler: ['groupby'], acl: { admin: true, user: true, guest: true, }, functions: [ ` async function(req, res){ const data = await req.model.groupBy({ ...req.params, ...req.query }); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/count`, type: 'get', handler: ['count'], acl: { admin: true, user: true, guest: true, }, functions: [ ` async function(req, res){ const data = await req.model.countByPk({ ...req.query }); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/bulk`, type: 'post', handler: ['bulkInsert'], acl: { admin: true, user: true, guest: false, }, functions: [ ` async function(req, res){ const data = await req.model.insertb(req.body); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/bulk`, type: 'put', handler: ['bulkUpdate'], acl: { admin: true, user: true, guest: false, }, functions: [ ` async function(req, res){ const data = await req.model.updateb(req.body); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/bulk`, type: 'delete', handler: ['bulkDelete'], acl: { admin: true, user: true, guest: false, }, functions: [ ` async function(req, res){ const data = await req.model.delb(req.body) res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/:id/exists`, type: 'get', handler: ['exists'], acl: { admin: true, user: true, guest: false, }, functions: [ ` async function(req, res){ const data = await req.model.exists(req.params.id); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/distinct`, type: 'get', handler: ['distinct'], acl: { admin: true, user: true, guest: true, }, functions: [ ` async function(req, res){ const data = await req.model.distinct({ ...req.query }); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/distribute`, type: 'get', handler: ['distribute'], acl: { admin: true, user: true, guest: true, }, functions: [ ` async function(req, res){ const data = await req.model.distribution({ ...req.query }); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/aggregate`, type: 'get', handler: ['aggregate'], acl: { admin: true, user: true, guest: true, }, functions: [ ` async function(req, res){ const data = await req.model.aggregate({ ...req.params, ...req.query }); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/groupby`, type: 'get', handler: ['groupby'], acl: { admin: true, user: true, guest: true, }, functions: [ ` async function(req, res){ const data = await req.model.groupBy({ ...req.params, ...req.query }); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/:id`, type: 'get', handler: ['get'], acl: { admin: true, user: true, guest: true, }, functions: [ ` async function(req, res){ const data = await req.model.readByPk(req.params.id); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}`, type: 'post', handler: ['create'], acl: { admin: true, user: true, guest: false, }, functions: [ ` async function(req, res){ const data = await req.model.insert(req.body, null, req); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/:id`, type: 'put', handler: ['update'], acl: { admin: true, user: true, guest: false, }, functions: [ ` async function(req, res){ const data = await req.model.updateByPk(req.params.id, req.body, null, req); res.json(data); } `, ], }, { path: `/api/${this.ctx.routeVersionLetter}/${ejsData._tn}/:id`, type: 'delete', handler: ['delete'], acl: { admin: true, user: true, guest: false, }, functions: [ ` async function(req, res){ const data = await req.model.delByPk(req.params.id, null, req); res.json(data); } `, ], }, ]; if (this.ctx.type === 'view') { return routes.filter( ({ type, handler }) => type === 'get' && !handler.includes('exists') && !handler.includes('get'), ); } return routes; } getObjectWithoutFunctions() { return this.getObject().map(({ functions, ...rest }) => rest); } } export default ExpressXcTsRoutes;
packages/nocodb/src/db/sql-mgr/code/routes/xc-ts/ExpressXcTsRoutes.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0001832330453908071, 0.00017032808682415634, 0.0001652088831178844, 0.00016998047067318112, 0.000003473446895441157 ]
{ "id": 11, "code_window": [ " const cn = path.join('_').replace(/\\W/g, '_').trim()\n", " const column: Record<string, any> = {\n", " column_name: cn,\n", " ref_column_name: cn,\n", " uidt: UITypes.SingleLineText,\n", " path,\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " title,\n" ], "file_path": "packages/nc-gui/helpers/parsers/JSONTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 94 }
import { parse } from 'papaparse' import type { UploadFile } from 'ant-design-vue' import { UITypes } from 'nocodb-sdk' import { getDateFormat, validateDateWithUnknownFormat } from '../../utils/dateTimeUtils' import { extractMultiOrSingleSelectProps, getCheckboxValue, isCheckboxType, isDecimalType, isEmailType, isMultiLineTextType, isUrlType, } from './parserHelpers' export default class CSVTemplateAdapter { config: Record<string, any> source: UploadFile[] | string detectedColumnTypes: Record<number, Record<string, number>> distinctValues: Record<number, Set<string>> headers: Record<number, string[]> tables: Record<number, any> base: { tables: Record<string, any>[] } data: Record<string, any> = {} columnValues: Record<number, []> private progressCallback?: (msg: string) => void constructor(source: UploadFile[] | string, parserConfig = {}, progressCallback?: (msg: string) => void) { this.config = parserConfig this.source = source this.base = { tables: [], } this.detectedColumnTypes = {} this.distinctValues = {} this.headers = {} this.columnValues = {} this.tables = {} this.progressCallback = progressCallback } async init() {} initTemplate(tableIdx: number, tn: string, columnNames: string[]) { const columnNameRowExist = +columnNames.every((v: any) => v === null || typeof v === 'string') const columnNamePrefixRef: Record<string, any> = { id: 0 } const tableObj: Record<string, any> = { table_name: tn, ref_table_name: tn, columns: [], } this.headers[tableIdx] = [] this.tables[tableIdx] = [] for (const [columnIdx, columnName] of columnNames.entries()) { let cn: string = ((columnNameRowExist && columnName.toString().trim()) || `field_${columnIdx + 1}`) .replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_') .trim() while (cn in columnNamePrefixRef) { cn = `${cn}${++columnNamePrefixRef[cn]}` } columnNamePrefixRef[cn] = 0 this.detectedColumnTypes[columnIdx] = {} this.distinctValues[columnIdx] = new Set<string>() this.columnValues[columnIdx] = [] tableObj.columns.push({ column_name: cn, ref_column_name: cn, meta: {}, uidt: UITypes.SingleLineText, key: columnIdx, }) this.headers[tableIdx].push(cn) this.tables[tableIdx] = tableObj } } detectInitialUidt(v: string) { if (!isNaN(Number(v)) && !isNaN(parseFloat(v))) return UITypes.Number if (validateDateWithUnknownFormat(v)) return UITypes.DateTime if (isCheckboxType(v)) return UITypes.Checkbox return UITypes.SingleLineText } detectColumnType(tableIdx: number, data: []) { for (let columnIdx = 0; columnIdx < data.length; columnIdx++) { // skip null data if (!data[columnIdx]) continue const colData: any = [data[columnIdx]] const colProps = { uidt: this.detectInitialUidt(data[columnIdx]) } // TODO(import): centralise if (isMultiLineTextType(colData)) { colProps.uidt = UITypes.LongText } else if (colProps.uidt === UITypes.SingleLineText) { if (isEmailType(colData)) { colProps.uidt = UITypes.Email } else if (isUrlType(colData)) { colProps.uidt = UITypes.URL } else if (isCheckboxType(colData)) { colProps.uidt = UITypes.Checkbox } else { if (data[columnIdx] && columnIdx < this.config.maxRowsToParse) { this.columnValues[columnIdx].push(data[columnIdx]) colProps.uidt = UITypes.SingleSelect } } } else if (colProps.uidt === UITypes.Number) { if (isDecimalType(colData)) { colProps.uidt = UITypes.Decimal } } else if (colProps.uidt === UITypes.DateTime) { if (data[columnIdx] && columnIdx < this.config.maxRowsToParse) { this.columnValues[columnIdx].push(data[columnIdx]) } } if (!(colProps.uidt in this.detectedColumnTypes[columnIdx])) { this.detectedColumnTypes[columnIdx] = { ...this.detectedColumnTypes[columnIdx], [colProps.uidt]: 0, } } this.detectedColumnTypes[columnIdx][colProps.uidt] += 1 if (data[columnIdx]) { this.distinctValues[columnIdx].add(data[columnIdx]) } } } getPossibleUidt(columnIdx: number) { const detectedColTypes = this.detectedColumnTypes[columnIdx] const len = Object.keys(detectedColTypes).length // all records are null if (len === 0) { return UITypes.SingleLineText } // handle numeric case if (len === 2 && UITypes.Number in detectedColTypes && UITypes.Decimal in detectedColTypes) { return UITypes.Decimal } // if there are multiple detected column types // then return either LongText or SingleLineText if (len > 1) { if (UITypes.LongText in detectedColTypes) { return UITypes.LongText } return UITypes.SingleLineText } // otherwise, all records have the same column type return Object.keys(detectedColTypes)[0] } updateTemplate(tableIdx: number) { for (let columnIdx = 0; columnIdx < this.headers[tableIdx].length; columnIdx++) { const uidt = this.getPossibleUidt(columnIdx) if (this.columnValues[columnIdx].length > 0) { if (uidt === UITypes.DateTime) { const dateFormat: Record<string, number> = {} if ( this.columnValues[columnIdx].slice(1, this.config.maxRowsToParse).every((v: any) => { const isDate = v.split(' ').length === 1 if (isDate) { dateFormat[getDateFormat(v)] = (dateFormat[getDateFormat(v)] || 0) + 1 } return isDate }) ) { this.tables[tableIdx].columns[columnIdx].uidt = UITypes.Date // take the date format with the max occurrence const objKeys = Object.keys(dateFormat) this.tables[tableIdx].columns[columnIdx].meta.date_format = objKeys.length ? objKeys.reduce((x, y) => (dateFormat[x] > dateFormat[y] ? x : y)) : 'YYYY/MM/DD' } else { // Datetime this.tables[tableIdx].columns[columnIdx].uidt = uidt } } else if (uidt === UITypes.SingleSelect || uidt === UITypes.MultiSelect) { // assume it is a SingleLineText first this.tables[tableIdx].columns[columnIdx].uidt = UITypes.SingleLineText // override with UITypes.SingleSelect or UITypes.MultiSelect if applicable Object.assign(this.tables[tableIdx].columns[columnIdx], extractMultiOrSingleSelectProps(this.columnValues[columnIdx])) } else { this.tables[tableIdx].columns[columnIdx].uidt = uidt } delete this.columnValues[columnIdx] } else { this.tables[tableIdx].columns[columnIdx].uidt = uidt } } } async _parseTableData(tableIdx: number, source: UploadFile | string, tn: string) { return new Promise((resolve, reject) => { const that = this let steppers = 0 if (that.config.shouldImportData) { that.progress(`Processing ${tn} data`) steppers = 0 const parseSource = (this.config.importFromURL ? (source as string) : (source as UploadFile).originFileObj)! parse(parseSource, { download: that.config.importFromURL, // worker: true, skipEmptyLines: 'greedy', step(row) { steppers += 1 if (row && steppers >= +that.config.firstRowAsHeaders + 1) { const rowData: Record<string, any> = {} for (let columnIdx = 0; columnIdx < that.headers[tableIdx].length; columnIdx++) { const column = that.tables[tableIdx].columns[columnIdx] const data = (row.data as [])[columnIdx] === '' ? null : (row.data as [])[columnIdx] if (column.uidt === UITypes.Checkbox) { rowData[column.column_name] = getCheckboxValue(data) } else if (column.uidt === UITypes.SingleSelect || column.uidt === UITypes.MultiSelect) { rowData[column.column_name] = (data || '').toString().trim() || null } else { // TODO(import): do parsing if necessary based on type rowData[column.column_name] = data } } that.data[tn].push(rowData) } if (steppers % 1000 === 0) { that.progress(`Processed ${steppers} rows of ${tn}`) } }, complete() { that.progress(`Processed ${tn} data`) resolve(true) }, error(e: Error) { reject(e) }, }) } else { resolve(true) } }) } async _parseTableMeta(tableIdx: number, source: UploadFile | string) { return new Promise((resolve, reject) => { const that = this let steppers = 0 const tn = ((this.config.importFromURL ? (source as string).split('/').pop() : (source as UploadFile).name) as string) .replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/g, '_') .trim()! this.data[tn] = [] const parseSource = (this.config.importFromURL ? (source as string) : (source as UploadFile).originFileObj)! parse(parseSource, { download: that.config.importFromURL, skipEmptyLines: 'greedy', step(row) { steppers += 1 if (row) { if (steppers === 1) { if (that.config.firstRowAsHeaders) { // row.data is header that.initTemplate(tableIdx, tn, row.data as []) } else { // use dummy column names as header that.initTemplate( tableIdx, tn, [...Array((row.data as []).length)].map((_, i) => `field_${i + 1}`), ) if (that.config.autoSelectFieldTypes) { // row.data is data that.detectColumnType(tableIdx, row.data as []) } } } else { if (that.config.autoSelectFieldTypes) { // row.data is data that.detectColumnType(tableIdx, row.data as []) } } } }, async complete() { that.updateTemplate(tableIdx) that.base.tables.push(that.tables[tableIdx]) that.progress(`Processed ${tn} metadata`) await that._parseTableData(tableIdx, source, tn) resolve(true) }, error(e: Error) { reject(e) }, }) }) } async parse() { if (this.config.importFromURL) { await this._parseTableMeta(0, this.source as string) } else { await Promise.all( (this.source as UploadFile[]).map((file: UploadFile, tableIdx: number) => (async (f, idx) => { this.progress(`Parsing ${f.name}`) await this._parseTableMeta(idx, f) })(file, tableIdx), ), ) } } getColumns() { return this.base.tables.map((t: Record<string, any>) => t.columns) } getData() { return this.data } getTemplate() { return this.base } progress(msg: string) { this.progressCallback?.(msg) } }
packages/nc-gui/helpers/parsers/CSVTemplateAdapter.ts
1
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.9983744621276855, 0.12831147015094757, 0.00016475410666316748, 0.0002623947220854461, 0.3159788250923157 ]
{ "id": 11, "code_window": [ " const cn = path.join('_').replace(/\\W/g, '_').trim()\n", " const column: Record<string, any> = {\n", " column_name: cn,\n", " ref_column_name: cn,\n", " uidt: UITypes.SingleLineText,\n", " path,\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " title,\n" ], "file_path": "packages/nc-gui/helpers/parsers/JSONTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 94 }
<script lang="ts" setup> import type { VNodeRef } from '@vue/runtime-core' import { message } from 'ant-design-vue' import type { ApiTokenType, RequestParams } from 'nocodb-sdk' import { extractSdkResponseErrorMsg, isEeUI, ref, useApi, useCopy, useNuxtApp } from '#imports' const { api, isLoading } = useApi() const { $e } = useNuxtApp() const { copy } = useCopy() const { t } = useI18n() interface IApiTokenInfo extends ApiTokenType { created_by: string } const tokens = ref<IApiTokenInfo[]>([]) const selectedToken = reactive({ isShow: false, id: '', }) const currentPage = ref(1) const showNewTokenModal = ref(false) const currentLimit = ref(10) const defaultTokenName = t('labels.untitledToken') const selectedTokenData = ref<ApiTokenType>({ description: defaultTokenName, }) const searchText = ref<string>('') const pagination = reactive({ total: 0, pageSize: 10, }) const hideOrShowToken = (tokenId: string) => { if (selectedToken.isShow && selectedToken.id === tokenId) { selectedToken.isShow = false selectedToken.id = '' } else { selectedToken.isShow = true selectedToken.id = tokenId } } const loadTokens = async (page = currentPage.value, limit = currentLimit.value) => { currentPage.value = page try { const response: any = await api.orgTokens.list({ query: { limit, offset: searchText.value.length === 0 ? (page - 1) * limit : 0, }, } as RequestParams) if (!response) return pagination.total = response.pageInfo.totalRows ?? 0 pagination.pageSize = 10 tokens.value = response.list as IApiTokenInfo[] } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } } loadTokens() const isModalOpen = ref(false) const tokenDesc = ref('') const tokenToCopy = ref('') const isValidTokenName = ref(false) const deleteToken = async (token: string): Promise<void> => { try { await api.orgTokens.delete(token) // message.success(t('msg.success.tokenDeleted')) await loadTokens() if (!tokens.value.length && currentPage.value !== 1) { currentPage.value-- loadTokens(currentPage.value) } } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } $e('a:account:token:delete') isModalOpen.value = false tokenToCopy.value = '' tokenDesc.value = '' } const validateTokenName = (tokenName: string | undefined) => { if (!tokenName) return false return tokenName.length < 255 } const generateToken = async () => { isValidTokenName.value = validateTokenName(selectedTokenData.value.description) if (!isValidTokenName.value) return try { await api.orgTokens.create(selectedTokenData.value) showNewTokenModal.value = false // Token generated successfully // message.success(t('msg.success.tokenGenerated')) selectedTokenData.value = {} await loadTokens() } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } finally { selectedTokenData.value.description = defaultTokenName $e('a:api-token:generate') } } const copyToken = async (token: string | undefined) => { if (!token) return try { await copy(token) // Copied to clipboard message.info(t('msg.info.copiedToClipboard')) $e('c:api-token:copy') } catch (e: any) { message.error(e.message) } } const triggerDeleteModal = (tokenToDelete: string, tokenDescription: string) => { tokenToCopy.value = tokenToDelete tokenDesc.value = tokenDescription isModalOpen.value = true } const selectInputOnMount: VNodeRef = (el) => selectedTokenData.value.description === defaultTokenName && (el as HTMLInputElement)?.select() const errorMessage = computed(() => { const tokenLength = selectedTokenData.value.description?.length if (!tokenLength) { return t('msg.info.tokenNameNotEmpty') } else if (tokenLength > 255) { return t('msg.info.tokenNameMaxLength') } }) const handleCancel = () => { showNewTokenModal.value = false isValidTokenName.value = false } </script> <template> <div class="h-full pt-2"> <div class="max-w-202 mx-auto px-4 h-full" data-testid="nc-token-list"> <div class="py-2 flex gap-4 items-baseline justify-between"> <h6 class="text-2xl text-left font-bold" data-rec="true">{{ $t('title.apiTokens') }}</h6> <NcTooltip :disabled="!(isEeUI && tokens.length)"> <template #title>{{ $t('labels.tokenLimit') }}</template> <NcButton :disabled="showNewTokenModal || (isEeUI && tokens.length)" class="!rounded-md" data-testid="nc-token-create" size="middle" type="primary" tooltip="bottom" @click="showNewTokenModal = true" > <span class="hidden md:block" data-rec="true"> {{ $t('title.addNewToken') }} </span> <span class="flex items-center justify-center md:hidden" data-rec="true"> <component :is="iconMap.plus" /> </span> </NcButton> </NcTooltip> </div> <span data-rec="true">{{ $t('msg.apiTokenCreate') }}</span> <div class="mt-5 h-[calc(100%-13rem)]"> <div class="h-full w-full !overflow-hidden rounded-md"> <div class="flex w-full pl-5 bg-gray-50 border-1 rounded-t-md"> <span class="py-3.5 text-gray-500 font-medium text-3.5 w-2/9" data-rec="true">{{ $t('title.tokenName') }}</span> <span class="py-3.5 text-gray-500 font-medium text-3.5 w-2/9 text-start" data-rec="true">{{ $t('title.creator') }}</span> <span class="py-3.5 text-gray-500 font-medium text-3.5 w-3/9 text-start" data-rec="true">{{ $t('labels.token') }}</span> <span class="py-3.5 pl-19 text-gray-500 font-medium text-3.5 w-2/9 text-start" data-rec="true">{{ $t('labels.actions') }}</span> </div> <div class="nc-scrollbar-md !overflow-y-auto flex flex-col h-[calc(100%-5rem)]"> <div v-if="showNewTokenModal"> <div class="flex gap-5 px-3 py-2.5 text-gray-500 font-medium text-3.5 w-full nc-token-generate border-b-1 border-l-1 border-r-1" :class="{ 'rounded-b-md': !tokens.length, }" > <div class="flex w-full"> <a-input :ref="selectInputOnMount" v-model:value="selectedTokenData.description" :default-value="defaultTokenName" type="text" class="!rounded-lg !py-1" placeholder="Token Name" data-testid="nc-token-input" @press-enter="generateToken" /> <span v-if="!isValidTokenName" class="text-red-500 text-xs font-light mt-1.5 ml-1" data-rec="true" >{{ errorMessage }} </span> </div> <div class="flex gap-2 justify-start"> <NcButton v-if="!isLoading" type="secondary" size="small" @click="handleCancel"> {{ $t('general.cancel') }} </NcButton> <NcButton type="primary" size="sm" :is-loading="isLoading" data-testid="nc-token-save-btn" @click="generateToken" > {{ $t('general.save') }} </NcButton> </div> </div> </div> <div v-if="!tokens.length && !showNewTokenModal" class="border-l-1 border-r-1 border-b-1 rounded-b-md justify-center flex items-center" > <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noToken')" /> </div> <div v-for="el of tokens" :key="el.id" data-testid="nc-token-list" class="flex pl-5 py-3 justify-between token items-center border-l-1 border-r-1 border-b-1" > <span class="text-black font-bold text-3.5 text-start w-2/9"> <GeneralTruncateText placement="top" length="20"> {{ el.description }} </GeneralTruncateText> </span> <span class="text-gray-500 font-medium text-3.5 text-start w-2/9"> <GeneralTruncateText placement="top" length="20"> {{ el.created_by }} </GeneralTruncateText> </span> <span class="text-gray-500 font-medium text-3.5 text-start w-3/9"> <GeneralTruncateText v-if="el.token === selectedToken.id && selectedToken.isShow" placement="top" length="29"> {{ el.token }} </GeneralTruncateText> <span v-else>************************************</span> </span> <!-- ACTIONS --> <div class="flex justify-end items-center gap-3 pr-5 text-gray-500 font-medium text-3.5 w-2/9"> <NcTooltip placement="top"> <template #title>{{ $t('labels.showOrHide') }}</template> <component :is="iconMap.eye" class="nc-toggle-token-visibility hover::cursor-pointer w-h-4 mb-[1.8px]" @click="hideOrShowToken(el.token as string)" /> </NcTooltip> <NcTooltip placement="top" class="h-4"> <template #title>{{ $t('general.copy') }}</template> <component :is="iconMap.copy" class="hover::cursor-pointer w-4 h-4 text-gray-600 mt-0.25" @click="copyToken(el.token)" /> </NcTooltip> <NcTooltip placement="top" class="mb-0.5"> <template #title>{{ $t('general.delete') }}</template> <component :is="iconMap.delete" data-testid="nc-token-row-action-icon" class="nc-delete-icon hover::cursor-pointer w-4 h-4" @click="triggerDeleteModal(el.token as string, el.description as string)" /> </NcTooltip> </div> </div> </div> </div> </div> <div v-if="pagination.total > 10" class="flex items-center justify-center mt-5"> <a-pagination v-model:current="currentPage" :total="pagination.total" show-less-items @change="loadTokens(currentPage, currentLimit)" /> </div> </div> <GeneralDeleteModal v-model:visible="isModalOpen" :entity-name="$t('labels.token')" :on-delete="() => deleteToken(tokenToCopy)" > <template #entity-preview> <span> <div class="flex flex-row items-center py-2.25 px-2.5 bg-gray-50 rounded-lg text-gray-700 mb-4"> <GeneralIcon icon="key" class="nc-view-icon"></GeneralIcon> <div class="capitalize text-ellipsis overflow-hidden select-none w-full pl-1.75" :style="{ wordBreak: 'keep-all', whiteSpace: 'nowrap', display: 'inline' }" > {{ tokenDesc }} </div> </div> </span> </template> </GeneralDeleteModal> </div> </template> <style> .token:last-child { @apply border-b-1 rounded-b-md; } </style>
packages/nc-gui/components/account/Token.vue
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.7129856944084167, 0.0211541336029768, 0.00016795947158243507, 0.00017266126815229654, 0.12043245881795883 ]
{ "id": 11, "code_window": [ " const cn = path.join('_').replace(/\\W/g, '_').trim()\n", " const column: Record<string, any> = {\n", " column_name: cn,\n", " ref_column_name: cn,\n", " uidt: UITypes.SingleLineText,\n", " path,\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " title,\n" ], "file_path": "packages/nc-gui/helpers/parsers/JSONTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 94 }
// import VueQrcodeReader from 'vue-qrcode-reader' import { defineNuxtPlugin } from 'nuxt/app' export default defineNuxtPlugin((_nuxtApp) => { // nuxtApp.vueApp.use(VueQrcodeReader) })
packages/nc-gui/plugins/vue-qr-code-scanner.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.0001748810027493164, 0.0001748810027493164, 0.0001748810027493164, 0.0001748810027493164, 0 ]
{ "id": 11, "code_window": [ " const cn = path.join('_').replace(/\\W/g, '_').trim()\n", " const column: Record<string, any> = {\n", " column_name: cn,\n", " ref_column_name: cn,\n", " uidt: UITypes.SingleLineText,\n", " path,\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " title,\n" ], "file_path": "packages/nc-gui/helpers/parsers/JSONTemplateAdapter.ts", "type": "add", "edit_start_line_idx": 94 }
import { XcActionType, XcType } from 'nocodb-sdk'; import MattermostPlugin from './MattermostPlugin'; import type { XcPluginConfig } from 'nc-plugin'; const config: XcPluginConfig = { builder: MattermostPlugin, title: 'Mattermost', version: '0.0.1', logo: 'plugins/mattermost.png', description: 'Mattermost brings all your team communication into one place, making it searchable and accessible anywhere.', price: 'Free', tags: 'Chat', category: 'Chat', inputs: { title: 'Configure Mattermost', array: true, items: [ { key: 'channel', label: 'Channel Name', placeholder: 'Channel Name', type: XcType.SingleLineText, required: true, }, { key: 'webhook_url', label: 'Webhook URL', placeholder: 'Webhook URL', type: XcType.Password, required: true, }, ], actions: [ { label: 'Test', placeholder: 'Test', key: 'test', actionType: XcActionType.TEST, type: XcType.Button, }, { label: 'Save', placeholder: 'Save', key: 'save', actionType: XcActionType.SUBMIT, type: XcType.Button, }, ], msgOnInstall: 'Successfully installed and Mattermost is enabled for notification.', msgOnUninstall: '', }, }; export default config;
packages/nocodb/src/plugins/mattermost/index.ts
0
https://github.com/nocodb/nocodb/commit/1340bd0806a8aaf80ca5fc5a7d6aecc6db914c6b
[ 0.00017646577907726169, 0.00017295409634243697, 0.0001652199134696275, 0.00017456195200793445, 0.000004110490408493206 ]
{ "id": 0, "code_window": [ " 'https://site.com',\n", " );\n", " expect(mockUseBaseUrl('/hello/foo', {absolute: true})).toBe(\n", " 'https://docusaurus.io/docusaurus/hello/foo',\n", " );\n", " expect(mockUseBaseUrl('/docusaurus/')).toBe('/docusaurus/');\n", " expect(mockUseBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello');\n", " expect(mockUseBaseUrl('#hello')).toBe('#hello');\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(mockUseBaseUrl('/docusaurus')).toBe('/docusaurus/');\n" ], "file_path": "packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx", "type": "add", "edit_start_line_idx": 79 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import {renderHook} from '@testing-library/react-hooks'; import useBaseUrl, {useBaseUrlUtils} from '../useBaseUrl'; import {Context} from '../../docusaurusContext'; import type {DocusaurusContext} from '@docusaurus/types'; import type {BaseUrlOptions} from '@docusaurus/useBaseUrl'; const forcePrepend = {forcePrependBaseUrl: true}; describe('useBaseUrl', () => { const createUseBaseUrlMock = (context: DocusaurusContext) => (url: string, options?: BaseUrlOptions) => renderHook(() => useBaseUrl(url, options), { wrapper: ({children}) => ( <Context.Provider value={context}>{children}</Context.Provider> ), }).result.current; it('works with empty base URL', () => { const mockUseBaseUrl = createUseBaseUrlMock({ siteConfig: { baseUrl: '/', url: 'https://docusaurus.io', }, }); expect(mockUseBaseUrl('hello')).toBe('/hello'); expect(mockUseBaseUrl('/hello')).toBe('/hello'); expect(mockUseBaseUrl('hello/')).toBe('/hello/'); expect(mockUseBaseUrl('/hello/')).toBe('/hello/'); expect(mockUseBaseUrl('hello/foo')).toBe('/hello/foo'); expect(mockUseBaseUrl('/hello/foo')).toBe('/hello/foo'); expect(mockUseBaseUrl('hello/foo/')).toBe('/hello/foo/'); expect(mockUseBaseUrl('/hello/foo/')).toBe('/hello/foo/'); expect(mockUseBaseUrl('https://github.com')).toBe('https://github.com'); expect(mockUseBaseUrl('//reactjs.org')).toBe('//reactjs.org'); expect(mockUseBaseUrl('//reactjs.org', forcePrepend)).toBe('//reactjs.org'); expect(mockUseBaseUrl('https://site.com', forcePrepend)).toBe( 'https://site.com', ); expect(mockUseBaseUrl('/hello/foo', {absolute: true})).toBe( 'https://docusaurus.io/hello/foo', ); expect(mockUseBaseUrl('#hello')).toBe('#hello'); }); it('works with non-empty base URL', () => { const mockUseBaseUrl = createUseBaseUrlMock({ siteConfig: { baseUrl: '/docusaurus/', url: 'https://docusaurus.io', }, }); expect(mockUseBaseUrl('')).toBe(''); expect(mockUseBaseUrl('hello')).toBe('/docusaurus/hello'); expect(mockUseBaseUrl('/hello')).toBe('/docusaurus/hello'); expect(mockUseBaseUrl('hello/')).toBe('/docusaurus/hello/'); expect(mockUseBaseUrl('/hello/')).toBe('/docusaurus/hello/'); expect(mockUseBaseUrl('hello/foo')).toBe('/docusaurus/hello/foo'); expect(mockUseBaseUrl('/hello/foo')).toBe('/docusaurus/hello/foo'); expect(mockUseBaseUrl('hello/foo/')).toBe('/docusaurus/hello/foo/'); expect(mockUseBaseUrl('/hello/foo/')).toBe('/docusaurus/hello/foo/'); expect(mockUseBaseUrl('https://github.com')).toBe('https://github.com'); expect(mockUseBaseUrl('//reactjs.org')).toBe('//reactjs.org'); expect(mockUseBaseUrl('//reactjs.org', forcePrepend)).toBe('//reactjs.org'); expect(mockUseBaseUrl('/hello', forcePrepend)).toBe('/docusaurus/hello'); expect(mockUseBaseUrl('https://site.com', forcePrepend)).toBe( 'https://site.com', ); expect(mockUseBaseUrl('/hello/foo', {absolute: true})).toBe( 'https://docusaurus.io/docusaurus/hello/foo', ); expect(mockUseBaseUrl('/docusaurus/')).toBe('/docusaurus/'); expect(mockUseBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello'); expect(mockUseBaseUrl('#hello')).toBe('#hello'); }); }); describe('useBaseUrlUtils().withBaseUrl()', () => { const mockUseBaseUrlUtils = (context: DocusaurusContext) => renderHook(() => useBaseUrlUtils(), { wrapper: ({children}) => ( <Context.Provider value={context}>{children}</Context.Provider> ), }).result.current; it('empty base URL', () => { const {withBaseUrl} = mockUseBaseUrlUtils({ siteConfig: { baseUrl: '/', url: 'https://docusaurus.io', }, }); expect(withBaseUrl('hello')).toBe('/hello'); expect(withBaseUrl('/hello')).toBe('/hello'); expect(withBaseUrl('hello/')).toBe('/hello/'); expect(withBaseUrl('/hello/')).toBe('/hello/'); expect(withBaseUrl('hello/foo')).toBe('/hello/foo'); expect(withBaseUrl('/hello/foo')).toBe('/hello/foo'); expect(withBaseUrl('hello/foo/')).toBe('/hello/foo/'); expect(withBaseUrl('/hello/foo/')).toBe('/hello/foo/'); expect(withBaseUrl('https://github.com')).toBe('https://github.com'); expect(withBaseUrl('//reactjs.org')).toBe('//reactjs.org'); expect(withBaseUrl('//reactjs.org', forcePrepend)).toBe('//reactjs.org'); expect(withBaseUrl('https://site.com', forcePrepend)).toBe( 'https://site.com', ); expect(withBaseUrl('/hello/foo', {absolute: true})).toBe( 'https://docusaurus.io/hello/foo', ); expect(withBaseUrl('#hello')).toBe('#hello'); }); it('non-empty base URL', () => { const {withBaseUrl} = mockUseBaseUrlUtils({ siteConfig: { baseUrl: '/docusaurus/', url: 'https://docusaurus.io', }, }); expect(withBaseUrl('hello')).toBe('/docusaurus/hello'); expect(withBaseUrl('/hello')).toBe('/docusaurus/hello'); expect(withBaseUrl('hello/')).toBe('/docusaurus/hello/'); expect(withBaseUrl('/hello/')).toBe('/docusaurus/hello/'); expect(withBaseUrl('hello/foo')).toBe('/docusaurus/hello/foo'); expect(withBaseUrl('/hello/foo')).toBe('/docusaurus/hello/foo'); expect(withBaseUrl('hello/foo/')).toBe('/docusaurus/hello/foo/'); expect(withBaseUrl('/hello/foo/')).toBe('/docusaurus/hello/foo/'); expect(withBaseUrl('https://github.com')).toBe('https://github.com'); expect(withBaseUrl('//reactjs.org')).toBe('//reactjs.org'); expect(withBaseUrl('//reactjs.org', forcePrepend)).toBe('//reactjs.org'); expect(withBaseUrl('https://site.com', forcePrepend)).toBe( 'https://site.com', ); expect(withBaseUrl('/hello/foo', {absolute: true})).toBe( 'https://docusaurus.io/docusaurus/hello/foo', ); expect(withBaseUrl('/docusaurus/')).toBe('/docusaurus/'); expect(withBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello'); expect(withBaseUrl('#hello')).toBe('#hello'); }); });
packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx
1
https://github.com/facebook/docusaurus/commit/e8800b9d494193f5641a9eed9894c40526f74ce5
[ 0.9362491369247437, 0.14424064755439758, 0.0001755415869411081, 0.014570723287761211, 0.27754396200180054 ]
{ "id": 0, "code_window": [ " 'https://site.com',\n", " );\n", " expect(mockUseBaseUrl('/hello/foo', {absolute: true})).toBe(\n", " 'https://docusaurus.io/docusaurus/hello/foo',\n", " );\n", " expect(mockUseBaseUrl('/docusaurus/')).toBe('/docusaurus/');\n", " expect(mockUseBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello');\n", " expect(mockUseBaseUrl('#hello')).toBe('#hello');\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(mockUseBaseUrl('/docusaurus')).toBe('/docusaurus/');\n" ], "file_path": "packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx", "type": "add", "edit_start_line_idx": 79 }
# Docusaurus 2 Website ## Installation 1. `yarn install` in the root of the repo (one level above this directory). 1. In this directory, do `yarn start`. 1. A browser window will open up, pointing to the docs.
website/README.md
0
https://github.com/facebook/docusaurus/commit/e8800b9d494193f5641a9eed9894c40526f74ce5
[ 0.0001666122698225081, 0.0001666122698225081, 0.0001666122698225081, 0.0001666122698225081, 0 ]
{ "id": 0, "code_window": [ " 'https://site.com',\n", " );\n", " expect(mockUseBaseUrl('/hello/foo', {absolute: true})).toBe(\n", " 'https://docusaurus.io/docusaurus/hello/foo',\n", " );\n", " expect(mockUseBaseUrl('/docusaurus/')).toBe('/docusaurus/');\n", " expect(mockUseBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello');\n", " expect(mockUseBaseUrl('#hello')).toBe('#hello');\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(mockUseBaseUrl('/docusaurus')).toBe('/docusaurus/');\n" ], "file_path": "packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx", "type": "add", "edit_start_line_idx": 79 }
--- id: multi-instance title: Docs Multi-instance description: Use multiple docs plugin instances on a single Docusaurus site. slug: /docs-multi-instance --- The `@docusaurus/plugin-content-docs` plugin can support [multi-instance](../../using-plugins.md#multi-instance-plugins-and-plugin-ids). :::note This feature is only useful for [versioned documentation](./versioning.md). It is recommended to be familiar with docs versioning before reading this page. If you just want [multiple sidebars](./sidebar/multiple-sidebars.md), you can do so within one plugin. ::: ## Use-cases {#use-cases} Sometimes you want a Docusaurus site to host 2 distinct sets of documentation (or more). These documentations may even have different versioning/release lifecycles. ### Mobile SDKs documentation {#mobile-sdks-documentation} If you build a cross-platform mobile SDK, you may have 2 documentations: - Android SDK documentation (`v1.0`, `v1.1`) - iOS SDK documentation (`v1.0`, `v2.0`) In this case, you can use a distinct docs plugin instance per mobile SDK documentation. :::caution If each documentation instance is very large, you should rather create 2 distinct Docusaurus sites. If someone edits the iOS documentation, is it really useful to rebuild everything, including the whole Android documentation that did not change? ::: ### Versioned and unversioned doc {#versioned-and-unversioned-doc} Sometimes, you want some documents to be versioned, while other documents are more "global", and it feels useless to version them. We use this pattern on the Docusaurus website itself: - The [/docs/\*](/docs) section is versioned - The [/community/\*](/community/support) section is unversioned ## Setup {#setup} Suppose you have 2 documentations: - Product: some versioned doc about your product - Community: some unversioned doc about the community around your product In this case, you should use the same plugin twice in your site configuration. :::caution `@docusaurus/preset-classic` already includes a docs plugin instance for you! ::: When using the preset: ```js title="docusaurus.config.js" module.exports = { presets: [ [ '@docusaurus/preset-classic', { docs: { // highlight-start // id: 'product', // omitted => default instance // highlight-end path: 'product', routeBasePath: 'product', sidebarPath: require.resolve('./sidebarsProduct.js'), // ... other options }, }, ], ], plugins: [ [ '@docusaurus/plugin-content-docs', { // highlight-start id: 'community', // highlight-end path: 'community', routeBasePath: 'community', sidebarPath: require.resolve('./sidebarsCommunity.js'), // ... other options }, ], ], }; ``` When not using the preset: ```js title="docusaurus.config.js" module.exports = { plugins: [ [ '@docusaurus/plugin-content-docs', { // highlight-start // id: 'product', // omitted => default instance // highlight-end path: 'product', routeBasePath: 'product', sidebarPath: require.resolve('./sidebarsProduct.js'), // ... other options }, ], [ '@docusaurus/plugin-content-docs', { // highlight-start id: 'community', // highlight-end path: 'community', routeBasePath: 'community', sidebarPath: require.resolve('./sidebarsCommunity.js'), // ... other options }, ], ], }; ``` Don't forget to assign a unique `id` attribute to plugin instances. :::note We consider that the `product` instance is the most important one, and make it the "default" instance by not assigning any id. ::: ## Versioned paths {#versioned-paths} Each plugin instance will store versioned docs in a distinct folder. The default plugin instance will use these paths: - `website/versions.json` - `website/versioned_docs` - `website/versioned_sidebars` The other plugin instances (with an `id` attribute) will use these paths: - `website/[pluginId]_versions.json` - `website/[pluginId]_versioned_docs` - `website/[pluginId]_versioned_sidebars` :::tip You can omit the `id` attribute (defaults to `default`) for one of the docs plugin instances. The instance paths will be simpler, and retro-compatible with a single-instance setup. ::: ## Tagging new versions {#tagging-new-versions} Each plugin instance will have its own cli command to tag a new version. They will be displayed if you run: ```bash npm2yarn npm run docusaurus -- --help ``` To version the product/default docs plugin instance: ```bash npm2yarn npm run docusaurus docs:version 1.0.0 ``` To version the non-default/community docs plugin instance: ```bash npm2yarn npm run docusaurus docs:version:community 1.0.0 ``` ## Docs navbar items {#docs-navbar-items} Each docs-related [theme navbar items](../../api/themes/theme-configuration.md#navbar) take an optional `docsPluginId` attribute. For example, if you want to have one version dropdown for each mobile SDK (iOS and Android), you could do: ```js title="docusaurus.config.js" module.exports = { themeConfig: { navbar: { items: [ { type: 'docsVersionDropdown', // highlight-start docsPluginId: 'ios', // highlight-end }, { type: 'docsVersionDropdown', // highlight-start docsPluginId: 'android', // highlight-end }, ], }, }, }; ```
website/versioned_docs/version-2.0.0-beta.17/guides/docs/docs-multi-instance.mdx
0
https://github.com/facebook/docusaurus/commit/e8800b9d494193f5641a9eed9894c40526f74ce5
[ 0.00017792097060009837, 0.00016800792946014553, 0.00015823692956473678, 0.0001661896676523611, 0.0000054376982916437555 ]
{ "id": 0, "code_window": [ " 'https://site.com',\n", " );\n", " expect(mockUseBaseUrl('/hello/foo', {absolute: true})).toBe(\n", " 'https://docusaurus.io/docusaurus/hello/foo',\n", " );\n", " expect(mockUseBaseUrl('/docusaurus/')).toBe('/docusaurus/');\n", " expect(mockUseBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello');\n", " expect(mockUseBaseUrl('#hello')).toBe('#hello');\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(mockUseBaseUrl('/docusaurus')).toBe('/docusaurus/');\n" ], "file_path": "packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx", "type": "add", "edit_start_line_idx": 79 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /// <reference types="@docusaurus/plugin-ideal-image" />
website/src/types.d.ts
0
https://github.com/facebook/docusaurus/commit/e8800b9d494193f5641a9eed9894c40526f74ce5
[ 0.0001739558210829273, 0.0001739558210829273, 0.0001739558210829273, 0.0001739558210829273, 0 ]
{ "id": 1, "code_window": [ " expect(withBaseUrl('/hello/foo', {absolute: true})).toBe(\n", " 'https://docusaurus.io/docusaurus/hello/foo',\n", " );\n", " expect(withBaseUrl('/docusaurus/')).toBe('/docusaurus/');\n", " expect(withBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello');\n", " expect(withBaseUrl('#hello')).toBe('#hello');\n", " });\n", "});" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(withBaseUrl('/docusaurus')).toBe('/docusaurus/');\n" ], "file_path": "packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx", "type": "add", "edit_start_line_idx": 145 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import useDocusaurusContext from './useDocusaurusContext'; import {hasProtocol} from './isInternalUrl'; import type {BaseUrlOptions, BaseUrlUtils} from '@docusaurus/useBaseUrl'; function addBaseUrl( siteUrl: string | undefined, baseUrl: string, url: string, {forcePrependBaseUrl = false, absolute = false}: BaseUrlOptions = {}, ): string { if (!url) { return url; } // it never makes sense to add a base url to a local anchor url if (url.startsWith('#')) { return url; } // it never makes sense to add a base url to an url with a protocol if (hasProtocol(url)) { return url; } if (forcePrependBaseUrl) { return baseUrl + url.replace(/^\//, ''); } // We should avoid adding the baseurl twice if it's already there const shouldAddBaseUrl = !url.startsWith(baseUrl); const basePath = shouldAddBaseUrl ? baseUrl + url.replace(/^\//, '') : url; return absolute ? siteUrl + basePath : basePath; } export function useBaseUrlUtils(): BaseUrlUtils { const { siteConfig: {baseUrl, url: siteUrl}, } = useDocusaurusContext(); return { withBaseUrl: (url, options) => addBaseUrl(siteUrl, baseUrl, url, options), }; } export default function useBaseUrl( url: string, options: BaseUrlOptions = {}, ): string { const {withBaseUrl} = useBaseUrlUtils(); return withBaseUrl(url, options); }
packages/docusaurus/src/client/exports/useBaseUrl.ts
1
https://github.com/facebook/docusaurus/commit/e8800b9d494193f5641a9eed9894c40526f74ce5
[ 0.001610630308277905, 0.0007493094890378416, 0.00016253635112661868, 0.0006033451645635068, 0.0006060354062356055 ]
{ "id": 1, "code_window": [ " expect(withBaseUrl('/hello/foo', {absolute: true})).toBe(\n", " 'https://docusaurus.io/docusaurus/hello/foo',\n", " );\n", " expect(withBaseUrl('/docusaurus/')).toBe('/docusaurus/');\n", " expect(withBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello');\n", " expect(withBaseUrl('#hello')).toBe('#hello');\n", " });\n", "});" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(withBaseUrl('/docusaurus')).toBe('/docusaurus/');\n" ], "file_path": "packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx", "type": "add", "edit_start_line_idx": 145 }
# Sample doc Lorem Ipsum
website/_dogfooding/_docs tests/tests/category-links/with-category-name-doc/sample-doc.md
0
https://github.com/facebook/docusaurus/commit/e8800b9d494193f5641a9eed9894c40526f74ce5
[ 0.00017182627925649285, 0.00017182627925649285, 0.00017182627925649285, 0.00017182627925649285, 0 ]
{ "id": 1, "code_window": [ " expect(withBaseUrl('/hello/foo', {absolute: true})).toBe(\n", " 'https://docusaurus.io/docusaurus/hello/foo',\n", " );\n", " expect(withBaseUrl('/docusaurus/')).toBe('/docusaurus/');\n", " expect(withBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello');\n", " expect(withBaseUrl('#hello')).toBe('#hello');\n", " });\n", "});" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(withBaseUrl('/docusaurus')).toBe('/docusaurus/');\n" ], "file_path": "packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx", "type": "add", "edit_start_line_idx": 145 }
name: 💅 Feature design / RFC description: Submit a detailed feature request with a concrete proposal, including an exhaustive API / UI design labels: [feature, 'status: needs triage'] body: - type: markdown attributes: value: | Important things: - We expect you to submit a feature request including a real design (API / UI...), not just a basic idea. - The design does not have to be perfect, we'll discuss it and fix it if needed. - For a more "casual" feature request, consider using Canny instead: https://docusaurus.io/feature-requests. - type: checkboxes attributes: label: Have you read the Contributing Guidelines on issues? options: - label: I have read the [Contributing Guidelines on issues](https://github.com/facebook/docusaurus/blob/main/CONTRIBUTING.md#reporting-new-issues). required: true - type: textarea attributes: label: Description description: A clear and concise description of what the feature is. validations: required: true - type: input attributes: label: Has this been requested on Canny? description: Please post the [Canny](https://docusaurus.io/feature-requests) link, it is helpful to see how much interest there is for this feature. - type: textarea attributes: label: Motivation description: Please outline the motivation for the proposal and why it should be implemented. Has this been requested by a lot of users? validations: required: true - type: textarea attributes: label: API design description: | Please describe how Docusaurus users will enable and configure this feature, and what it will look like. Please explain in an exhaustive way what are the config/plugin options and their respective effects. For visual elements, please send us some screenshots/mockups of what it should look like. You can use https://excalidraw.com to create simple mockups. > **What happens if you skip this step?** This issue may be closed without any in-depth discussion. Your feature request is just an idea for now, please use Canny for that: https://docusaurus.io/feature-requests. - type: textarea attributes: label: Have you tried building it? description: | Please explain how you tried to build the feature by yourself, and how successful it was. Docusaurus 2 has a plugin system and theming support. Quite often, this gives you the opportunity to build the feature you need by yourself. We expect you to put your own work in this feature, particularly if it is not requested by a lot of users. If we see it in action on your own site, it is easier to understand its value, and how it should work. If you can't build it yourself for technical reasons, please explain why. We are willing to help you, and eventually providing new APIs to make it possible. > **What happens if you skip this step?** This issue may be closed without any in-depth discussion. Your feature request is just an idea for now, please use Canny for that: https://docusaurus.io/feature-requests. - type: checkboxes attributes: label: Self-service description: | If you answered the question above as "no" because you feel like you could contribute directly to our repo, please check the box below. This would tell us and other people looking for contributions that someone's working on it. If you do check this box, please send a pull request within 7 days after a maintainer's approval so we can still delegate this to someone else. Note that for feature issues, we still require you to fully fill out this form and reach consensus with the maintainers on API design before rushing to implement it, so that you don't waste your time. options: - label: I'd be willing to contribute this feature to Docusaurus myself.
.github/ISSUE_TEMPLATE/feature.yml
0
https://github.com/facebook/docusaurus/commit/e8800b9d494193f5641a9eed9894c40526f74ce5
[ 0.00028235343052074313, 0.00020901078823953867, 0.00016421520558651537, 0.00019317639817018062, 0.00004204878132441081 ]
{ "id": 1, "code_window": [ " expect(withBaseUrl('/hello/foo', {absolute: true})).toBe(\n", " 'https://docusaurus.io/docusaurus/hello/foo',\n", " );\n", " expect(withBaseUrl('/docusaurus/')).toBe('/docusaurus/');\n", " expect(withBaseUrl('/docusaurus/hello')).toBe('/docusaurus/hello');\n", " expect(withBaseUrl('#hello')).toBe('#hello');\n", " });\n", "});" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(withBaseUrl('/docusaurus')).toBe('/docusaurus/');\n" ], "file_path": "packages/docusaurus/src/client/exports/__tests__/useBaseUrl.test.tsx", "type": "add", "edit_start_line_idx": 145 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {useEffect} from 'react'; import {useHistory} from '@docusaurus/router'; import {useDynamicCallback} from './reactUtils'; import type {Location, Action} from 'history'; type HistoryBlockHandler = (location: Location, action: Action) => void | false; /** * Permits to register a handler that will be called on history actions (pop, * push, replace). If the handler returns `false`, the navigation transition * will be blocked/cancelled. */ function useHistoryActionHandler(handler: HistoryBlockHandler): void { const {block} = useHistory(); const stableHandler = useDynamicCallback(handler); useEffect( // See https://github.com/remix-run/history/blob/main/docs/blocking-transitions.md () => block((location, action) => stableHandler(location, action)), [block, stableHandler], ); } /** * Permits to register a handler that will be called on history pop navigation * (backward/forward). If the handler returns `false`, the backward/forward * transition will be blocked. Unfortunately there's no good way to detect the * "direction" (backward/forward) of the POP event. */ export function useHistoryPopHandler(handler: HistoryBlockHandler): void { useHistoryActionHandler((location, action) => { if (action === 'POP') { // Maybe block navigation if handler returns false return handler(location, action); } // Don't block other navigation actions return undefined; }); }
packages/docusaurus-theme-common/src/utils/historyUtils.ts
0
https://github.com/facebook/docusaurus/commit/e8800b9d494193f5641a9eed9894c40526f74ce5
[ 0.00017675102571956813, 0.00017239840235561132, 0.000169038976309821, 0.00017129103071056306, 0.0000031775864499650197 ]
{ "id": 2, "code_window": [ " if (forcePrependBaseUrl) {\n", " return baseUrl + url.replace(/^\\//, '');\n", " }\n", "\n", " // We should avoid adding the baseurl twice if it's already there\n", " const shouldAddBaseUrl = !url.startsWith(baseUrl);\n", "\n", " const basePath = shouldAddBaseUrl ? baseUrl + url.replace(/^\\//, '') : url;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " // /baseUrl -> /baseUrl/\n", " // https://github.com/facebook/docusaurus/issues/6315\n", " if (url === baseUrl.replace(/\\/$/, '')) {\n", " return baseUrl;\n", " }\n", "\n" ], "file_path": "packages/docusaurus/src/client/exports/useBaseUrl.ts", "type": "add", "edit_start_line_idx": 35 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import useDocusaurusContext from './useDocusaurusContext'; import {hasProtocol} from './isInternalUrl'; import type {BaseUrlOptions, BaseUrlUtils} from '@docusaurus/useBaseUrl'; function addBaseUrl( siteUrl: string | undefined, baseUrl: string, url: string, {forcePrependBaseUrl = false, absolute = false}: BaseUrlOptions = {}, ): string { if (!url) { return url; } // it never makes sense to add a base url to a local anchor url if (url.startsWith('#')) { return url; } // it never makes sense to add a base url to an url with a protocol if (hasProtocol(url)) { return url; } if (forcePrependBaseUrl) { return baseUrl + url.replace(/^\//, ''); } // We should avoid adding the baseurl twice if it's already there const shouldAddBaseUrl = !url.startsWith(baseUrl); const basePath = shouldAddBaseUrl ? baseUrl + url.replace(/^\//, '') : url; return absolute ? siteUrl + basePath : basePath; } export function useBaseUrlUtils(): BaseUrlUtils { const { siteConfig: {baseUrl, url: siteUrl}, } = useDocusaurusContext(); return { withBaseUrl: (url, options) => addBaseUrl(siteUrl, baseUrl, url, options), }; } export default function useBaseUrl( url: string, options: BaseUrlOptions = {}, ): string { const {withBaseUrl} = useBaseUrlUtils(); return withBaseUrl(url, options); }
packages/docusaurus/src/client/exports/useBaseUrl.ts
1
https://github.com/facebook/docusaurus/commit/e8800b9d494193f5641a9eed9894c40526f74ce5
[ 0.9984726309776306, 0.33340486884117126, 0.00017556837701704353, 0.0033755768090486526, 0.4689638316631317 ]
{ "id": 2, "code_window": [ " if (forcePrependBaseUrl) {\n", " return baseUrl + url.replace(/^\\//, '');\n", " }\n", "\n", " // We should avoid adding the baseurl twice if it's already there\n", " const shouldAddBaseUrl = !url.startsWith(baseUrl);\n", "\n", " const basePath = shouldAddBaseUrl ? baseUrl + url.replace(/^\\//, '') : url;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " // /baseUrl -> /baseUrl/\n", " // https://github.com/facebook/docusaurus/issues/6315\n", " if (url === baseUrl.replace(/\\/$/, '')) {\n", " return baseUrl;\n", " }\n", "\n" ], "file_path": "packages/docusaurus/src/client/exports/useBaseUrl.ts", "type": "add", "edit_start_line_idx": 35 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {toGlobalDataVersion} from '../globalData'; describe('toGlobalDataVersion', () => { it('generates the right docs, sidebars, and metadata', () => { expect( toGlobalDataVersion({ versionName: 'current', versionLabel: 'Label', isLast: true, versionPath: '/current', mainDocId: 'main', docs: [ { unversionedId: 'main', permalink: '/current/main', sidebar: 'tutorial', }, { unversionedId: 'doc', permalink: '/current/doc', sidebar: 'tutorial', }, ], sidebars: { another: [ { type: 'category', label: 'Generated', link: { type: 'generated-index', permalink: '/current/generated', }, items: [ { type: 'doc', id: 'doc', }, ], }, ], tutorial: [ { type: 'doc', id: 'main', }, { type: 'category', label: 'Generated', link: { type: 'generated-index', permalink: '/current/generated', }, items: [ { type: 'doc', id: 'doc', }, ], }, ], links: [ { type: 'link', href: 'foo', label: 'Foo', }, { type: 'link', href: 'bar', label: 'Bar', }, ], }, categoryGeneratedIndices: [ { title: 'Generated', slug: '/current/generated', permalink: '/current/generated', sidebar: 'tutorial', }, ], versionBanner: 'unreleased', versionBadge: true, versionClassName: 'current-cls', tagsPath: '/current/tags', contentPath: '', contentPathLocalized: '', sidebarFilePath: '', routePriority: 0.5, }), ).toMatchSnapshot(); }); });
packages/docusaurus-plugin-content-docs/src/__tests__/globalData.test.ts
0
https://github.com/facebook/docusaurus/commit/e8800b9d494193f5641a9eed9894c40526f74ce5
[ 0.00017693500558380038, 0.0001732123491819948, 0.00017058366211131215, 0.00017230141384061426, 0.0000018262854837303166 ]
{ "id": 2, "code_window": [ " if (forcePrependBaseUrl) {\n", " return baseUrl + url.replace(/^\\//, '');\n", " }\n", "\n", " // We should avoid adding the baseurl twice if it's already there\n", " const shouldAddBaseUrl = !url.startsWith(baseUrl);\n", "\n", " const basePath = shouldAddBaseUrl ? baseUrl + url.replace(/^\\//, '') : url;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " // /baseUrl -> /baseUrl/\n", " // https://github.com/facebook/docusaurus/issues/6315\n", " if (url === baseUrl.replace(/\\/$/, '')) {\n", " return baseUrl;\n", " }\n", "\n" ], "file_path": "packages/docusaurus/src/client/exports/useBaseUrl.ts", "type": "add", "edit_start_line_idx": 35 }
--- sidebar_position: 0 id: themes-overview title: 'Docusaurus themes' sidebar_label: Themes overview slug: '/api/themes' --- We provide official Docusaurus themes. ## Main themes {#main-themes} The main themes implement the user interface for the [docs](../plugins/plugin-content-docs.md), [blog](../plugins/plugin-content-blog.md) and [pages](../plugins/plugin-content-pages.md) plugins. - [@docusaurus/theme-classic](./theme-classic.md) - 🚧 other themes are planned :::caution The goal is to have all themes share the exact same features, user-experience and configuration. Only the UI design and underlying styling framework should change, and you should be able to change theme easily. We are not there yet: only the classic theme is production ready. ::: ## Enhancement themes {#enhancement-themes} These themes will enhance the existing main themes with additional user-interface related features. - [@docusaurus/theme-live-codeblock](./theme-live-codeblock.md) - [@docusaurus/theme-search-algolia](./theme-search-algolia.md)
website/versioned_docs/version-2.0.0-beta.17/api/themes/overview.md
0
https://github.com/facebook/docusaurus/commit/e8800b9d494193f5641a9eed9894c40526f74ce5
[ 0.00016947036783676594, 0.00016663467977195978, 0.0001614182983757928, 0.00016782501188572496, 0.0000031120914627535967 ]
{ "id": 2, "code_window": [ " if (forcePrependBaseUrl) {\n", " return baseUrl + url.replace(/^\\//, '');\n", " }\n", "\n", " // We should avoid adding the baseurl twice if it's already there\n", " const shouldAddBaseUrl = !url.startsWith(baseUrl);\n", "\n", " const basePath = shouldAddBaseUrl ? baseUrl + url.replace(/^\\//, '') : url;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " // /baseUrl -> /baseUrl/\n", " // https://github.com/facebook/docusaurus/issues/6315\n", " if (url === baseUrl.replace(/\\/$/, '')) {\n", " return baseUrl;\n", " }\n", "\n" ], "file_path": "packages/docusaurus/src/client/exports/useBaseUrl.ts", "type": "add", "edit_start_line_idx": 35 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ export default (): null => null;
packages/docusaurus/src/client/exports/Noop.ts
0
https://github.com/facebook/docusaurus/commit/e8800b9d494193f5641a9eed9894c40526f74ce5
[ 0.00016784004401415586, 0.00016784004401415586, 0.00016784004401415586, 0.00016784004401415586, 0 ]
{ "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 { Database, Statement } from 'vscode-sqlite3';\n", "import { Event } from 'vs/base/common/event';\n", "import { timeout } from 'vs/base/common/async';\n", "import { mapToString, setToString } from 'vs/base/common/map';\n", "import { basename } from 'vs/base/common/path';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import type { Database, Statement } from 'vscode-sqlite3';\n" ], "file_path": "src/vs/base/parts/storage/node/storage.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 { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { isWindows, isLinux } from 'vs/base/common/platform'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { Registry } from 'vs/platform/registry/common/platform'; import { AccessibilityService } from 'vs/platform/accessibility/common/accessibilityService'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IJSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditing'; import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-browser/environmentService'; interface AccessibilityMetrics { enabled: boolean; } type AccessibilityMetricsClassification = { enabled: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; }; export class NativeAccessibilityService extends AccessibilityService implements IAccessibilityService { declare readonly _serviceBrand: undefined; private didSendTelemetry = false; constructor( @IWorkbenchEnvironmentService environmentService: INativeWorkbenchEnvironmentService, @IContextKeyService contextKeyService: IContextKeyService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private readonly _telemetryService: ITelemetryService ) { super(contextKeyService, configurationService); this.setAccessibilitySupport(environmentService.configuration.accessibilitySupport ? AccessibilitySupport.Enabled : AccessibilitySupport.Disabled); } alwaysUnderlineAccessKeys(): Promise<boolean> { if (!isWindows) { return Promise.resolve(false); } return new Promise<boolean>(async (resolve) => { const Registry = await import('vscode-windows-registry'); let value; try { value = Registry.GetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\Accessibility\\Keyboard Preference', 'On'); } catch { resolve(false); } resolve(value === '1'); }); } setAccessibilitySupport(accessibilitySupport: AccessibilitySupport): void { super.setAccessibilitySupport(accessibilitySupport); if (!this.didSendTelemetry && accessibilitySupport === AccessibilitySupport.Enabled) { this._telemetryService.publicLog2<AccessibilityMetrics, AccessibilityMetricsClassification>('accessibility', { enabled: true }); this.didSendTelemetry = true; } } } registerSingleton(IAccessibilityService, NativeAccessibilityService, true); // On linux we do not automatically detect that a screen reader is detected, thus we have to implicitly notify the renderer to enable accessibility when user configures it in settings class LinuxAccessibilityContribution implements IWorkbenchContribution { constructor( @IJSONEditingService jsonEditingService: IJSONEditingService, @IAccessibilityService accessibilityService: AccessibilityService, @IEnvironmentService environmentService: IEnvironmentService ) { const forceRendererAccessibility = () => { if (accessibilityService.isScreenReaderOptimized()) { jsonEditingService.write(environmentService.argvResource, [{ path: ['force-renderer-accessibility'], value: true }], true); } }; forceRendererAccessibility(); accessibilityService.onDidChangeScreenReaderOptimized(forceRendererAccessibility); } } if (isLinux) { Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(LinuxAccessibilityContribution, LifecyclePhase.Ready); }
src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts
1
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017426595150027424, 0.00017076065705623478, 0.00016529350250493735, 0.00017164755263365805, 0.000002584974254205008 ]
{ "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 { Database, Statement } from 'vscode-sqlite3';\n", "import { Event } from 'vs/base/common/event';\n", "import { timeout } from 'vs/base/common/async';\n", "import { mapToString, setToString } from 'vs/base/common/map';\n", "import { basename } from 'vs/base/common/path';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import type { Database, Statement } from 'vscode-sqlite3';\n" ], "file_path": "src/vs/base/parts/storage/node/storage.ts", "type": "replace", "edit_start_line_idx": 5 }
{ "name": "grunt", "publisher": "vscode", "description": "Extension to add Grunt capabilities to VS Code.", "displayName": "Grunt support for VS Code", "version": "1.0.0", "icon": "images/grunt.png", "license": "MIT", "engines": { "vscode": "*" }, "categories": [ "Other" ], "scripts": { "compile": "gulp compile-extension:grunt", "watch": "gulp watch-extension:grunt" }, "dependencies": { "vscode-nls": "^4.0.0" }, "devDependencies": { "@types/node": "^12.11.7" }, "main": "./out/main", "activationEvents": [ "onCommand:workbench.action.tasks.runTask" ], "contributes": { "configuration": { "id": "grunt", "type": "object", "title": "Grunt", "properties": { "grunt.autoDetect": { "scope": "resource", "type": "string", "enum": [ "off", "on" ], "default": "on", "description": "%config.grunt.autoDetect%" } } }, "taskDefinitions": [ { "type": "grunt", "required": [ "task" ], "properties": { "task": { "type": "string", "description": "%grunt.taskDefinition.type.description%" }, "args": { "type": "array", "description": "%grunt.taskDefinition.args.description%" }, "file": { "type": "string", "description": "%grunt.taskDefinition.file.description%" } } } ] } }
extensions/grunt/package.json
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017499245586805046, 0.00017298906459473073, 0.00016858828894328326, 0.0001734268298605457, 0.000002003063855227083 ]
{ "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 { Database, Statement } from 'vscode-sqlite3';\n", "import { Event } from 'vs/base/common/event';\n", "import { timeout } from 'vs/base/common/async';\n", "import { mapToString, setToString } from 'vs/base/common/map';\n", "import { basename } from 'vs/base/common/path';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import type { Database, Statement } from 'vscode-sqlite3';\n" ], "file_path": "src/vs/base/parts/storage/node/storage.ts", "type": "replace", "edit_start_line_idx": 5 }
{ "configuration.suggest.basic": "Controls whether the built-in PHP language suggestions are enabled. The support suggests PHP globals and variables.", "configuration.validate.enable": "Enable/disable built-in PHP validation.", "configuration.validate.executablePath": "Points to the PHP executable.", "configuration.validate.run": "Whether the linter is run on save or on type.", "configuration.title": "PHP", "commands.categroy.php": "PHP", "command.untrustValidationExecutable": "Disallow PHP validation executable (defined as workspace setting)", "displayName": "PHP Language Features", "description": "Provides rich language support for PHP files." }
extensions/php-language-features/package.nls.json
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017281246255151927, 0.0001715362013783306, 0.00017025995475705713, 0.0001715362013783306, 0.0000012762538972310722 ]
{ "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 { Database, Statement } from 'vscode-sqlite3';\n", "import { Event } from 'vs/base/common/event';\n", "import { timeout } from 'vs/base/common/async';\n", "import { mapToString, setToString } from 'vs/base/common/map';\n", "import { basename } from 'vs/base/common/path';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import type { Database, Statement } from 'vscode-sqlite3';\n" ], "file_path": "src/vs/base/parts/storage/node/storage.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 * as nls from 'vs/nls'; import { URI } from 'vs/base/common/uri'; import { ITextFileService, ITextFileStreamContent, ITextFileContent, IResourceEncodings, IReadTextFileOptions, IWriteTextFileOptions, toBufferOrReadable, TextFileOperationError, TextFileOperationResult, ITextFileSaveOptions, ITextFileEditorModelManager, IResourceEncoding, stringToSnapshot } from 'vs/workbench/services/textfile/common/textfiles'; import { IRevertOptions, IEncodingSupport } from 'vs/workbench/common/editor'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IFileService, FileOperationError, FileOperationResult, IFileStatWithMetadata, ICreateFileOptions, IFileStreamContent } from 'vs/platform/files/common/files'; import { Disposable } from 'vs/base/common/lifecycle'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IUntitledTextEditorService, IUntitledTextEditorModelManager } from 'vs/workbench/services/untitled/common/untitledTextEditorService'; import { UntitledTextEditorModel } from 'vs/workbench/services/untitled/common/untitledTextEditorModel'; import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { Schemas } from 'vs/base/common/network'; import { createTextBufferFactoryFromSnapshot, createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel'; import { IModelService } from 'vs/editor/common/services/modelService'; import { joinPath, dirname, basename, toLocalResource, extUri, extname } from 'vs/base/common/resources'; import { IDialogService, IFileDialogService, IConfirmation } from 'vs/platform/dialogs/common/dialogs'; import { VSBuffer, VSBufferReadable, bufferToStream } from 'vs/base/common/buffer'; import { ITextSnapshot, ITextModel } from 'vs/editor/common/model'; import { ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfigurationService'; import { PLAINTEXT_MODE_ID } from 'vs/editor/common/modes/modesRegistry'; import { IFilesConfigurationService } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService'; import { ITextModelService, IResolvedTextEditorModel } from 'vs/editor/common/services/resolverService'; import { BaseTextEditorModel } from 'vs/workbench/common/editor/textEditorModel'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { IPathService } from 'vs/workbench/services/path/common/pathService'; import { isValidBasename } from 'vs/base/common/extpath'; import { IWorkingCopyFileService } from 'vs/workbench/services/workingCopy/common/workingCopyFileService'; import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { WORKSPACE_EXTENSION } from 'vs/platform/workspaces/common/workspaces'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { UTF8, UTF8_with_bom, UTF16be, UTF16le, encodingExists, UTF8_BOM, detectEncodingByBOMFromBuffer, toEncodeReadable, toDecodeStream, IDecodeStreamResult } from 'vs/workbench/services/textfile/common/encoding'; import { consumeStream } from 'vs/base/common/stream'; import { IModeService } from 'vs/editor/common/services/modeService'; /** * The workbench file service implementation implements the raw file service spec and adds additional methods on top. */ export abstract class AbstractTextFileService extends Disposable implements ITextFileService { declare readonly _serviceBrand: undefined; readonly files: ITextFileEditorModelManager = this._register(this.instantiationService.createInstance(TextFileEditorModelManager)); readonly untitled: IUntitledTextEditorModelManager = this.untitledTextEditorService; constructor( @IFileService protected readonly fileService: IFileService, @IUntitledTextEditorService private untitledTextEditorService: IUntitledTextEditorService, @ILifecycleService protected readonly lifecycleService: ILifecycleService, @IInstantiationService protected readonly instantiationService: IInstantiationService, @IModelService private readonly modelService: IModelService, @IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService, @IDialogService private readonly dialogService: IDialogService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @ITextResourceConfigurationService protected readonly textResourceConfigurationService: ITextResourceConfigurationService, @IFilesConfigurationService protected readonly filesConfigurationService: IFilesConfigurationService, @ITextModelService private readonly textModelService: ITextModelService, @ICodeEditorService private readonly codeEditorService: ICodeEditorService, @IPathService private readonly pathService: IPathService, @IWorkingCopyFileService private readonly workingCopyFileService: IWorkingCopyFileService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService, @IModeService private readonly modeService: IModeService ) { super(); this.registerListeners(); } protected registerListeners(): void { // Lifecycle this.lifecycleService.onShutdown(this.dispose, this); } //#region text file read / write / create private _encoding: EncodingOracle | undefined; get encoding(): EncodingOracle { if (!this._encoding) { this._encoding = this._register(this.instantiationService.createInstance(EncodingOracle)); } return this._encoding; } async read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent> { const [bufferStream, decoder] = await this.doRead(resource, { ...options, // optimization: since we know that the caller does not // care about buffering, we indicate this to the reader. // this reduces all the overhead the buffered reading // has (open, read, close) if the provider supports // unbuffered reading. preferUnbuffered: true }); return { ...bufferStream, encoding: decoder.detected.encoding || UTF8, value: await consumeStream(decoder.stream, strings => strings.join('')) }; } async readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent> { const [bufferStream, decoder] = await this.doRead(resource, options); return { ...bufferStream, encoding: decoder.detected.encoding || UTF8, value: await createTextBufferFactoryFromStream(decoder.stream) }; } private async doRead(resource: URI, options?: IReadTextFileOptions & { preferUnbuffered?: boolean }): Promise<[IFileStreamContent, IDecodeStreamResult]> { // read stream raw (either buffered or unbuffered) let bufferStream: IFileStreamContent; if (options?.preferUnbuffered) { const content = await this.fileService.readFile(resource, options); bufferStream = { ...content, value: bufferToStream(content.value) }; } else { bufferStream = await this.fileService.readFileStream(resource, options); } // read through encoding library const decoder = await toDecodeStream(bufferStream.value, { guessEncoding: options?.autoGuessEncoding || this.textResourceConfigurationService.getValue(resource, 'files.autoGuessEncoding'), overwriteEncoding: detectedEncoding => this.encoding.getReadEncoding(resource, options, detectedEncoding) }); // validate binary if (options?.acceptTextOnly && decoder.detected.seemsBinary) { throw new TextFileOperationError(nls.localize('fileBinaryError', "File seems to be binary and cannot be opened as text"), TextFileOperationResult.FILE_IS_BINARY, options); } return [bufferStream, decoder]; } async create(resource: URI, value?: string | ITextSnapshot, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> { const readable = await this.getEncodedReadable(resource, value); return this.workingCopyFileService.create(resource, readable, options); } async write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata> { const readable = await this.getEncodedReadable(resource, value, options); return this.fileService.writeFile(resource, readable, options); } private async getEncodedReadable(resource: URI, value?: string | ITextSnapshot): Promise<VSBuffer | VSBufferReadable | undefined>; private async getEncodedReadable(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<VSBuffer | VSBufferReadable>; private async getEncodedReadable(resource: URI, value?: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<VSBuffer | VSBufferReadable | undefined> { // check for encoding const { encoding, addBOM } = await this.encoding.getWriteEncoding(resource, options); // when encoding is standard skip encoding step if (encoding === UTF8 && !addBOM) { return typeof value === 'undefined' ? undefined : toBufferOrReadable(value); } // otherwise create encoded readable value = value || ''; const snapshot = typeof value === 'string' ? stringToSnapshot(value) : value; return toEncodeReadable(snapshot, encoding, { addBOM }); } //#endregion //#region save async save(resource: URI, options?: ITextFileSaveOptions): Promise<URI | undefined> { // Untitled if (resource.scheme === Schemas.untitled) { const model = this.untitled.get(resource); if (model) { let targetUri: URI | undefined; // Untitled with associated file path don't need to prompt if (model.hasAssociatedFilePath) { targetUri = await this.suggestSavePath(resource); } // Otherwise ask user else { targetUri = await this.fileDialogService.pickFileToSave(await this.suggestSavePath(resource), options?.availableFileSystems); } // Save as if target provided if (targetUri) { return this.saveAs(resource, targetUri, options); } } } // File else { const model = this.files.get(resource); if (model) { return await model.save(options) ? resource : undefined; } } return undefined; } async saveAs(source: URI, target?: URI, options?: ITextFileSaveOptions): Promise<URI | undefined> { // Get to target resource if (!target) { target = await this.fileDialogService.pickFileToSave(await this.suggestSavePath(source), options?.availableFileSystems); } if (!target) { return; // user canceled } // Just save if target is same as models own resource if (extUri.isEqual(source, target)) { return this.save(source, { ...options, force: true /* force to save, even if not dirty (https://github.com/microsoft/vscode/issues/99619) */ }); } // If the target is different but of same identity, we // move the source to the target, knowing that the // underlying file system cannot have both and then save. // However, this will only work if the source exists // and is not orphaned, so we need to check that too. if (this.fileService.canHandleResource(source) && this.uriIdentityService.extUri.isEqual(source, target) && (await this.fileService.exists(source))) { await this.workingCopyFileService.move([{ source, target }]); return this.save(target, options); } // Do it return this.doSaveAs(source, target, options); } private async doSaveAs(source: URI, target: URI, options?: ITextFileSaveOptions): Promise<URI> { let success = false; // If the source is an existing text file model, we can directly // use that model to copy the contents to the target destination const textFileModel = this.files.get(source); if (textFileModel && textFileModel.isResolved()) { success = await this.doSaveAsTextFile(textFileModel, source, target, options); } // Otherwise if the source can be handled by the file service // we can simply invoke the copy() function to save as else if (this.fileService.canHandleResource(source)) { await this.fileService.copy(source, target); success = true; } // Next, if the source does not seem to be a file, we try to // resolve a text model from the resource to get at the // contents and additional meta data (e.g. encoding). else if (this.textModelService.canHandleResource(source)) { const modelReference = await this.textModelService.createModelReference(source); try { success = await this.doSaveAsTextFile(modelReference.object, source, target, options); } finally { modelReference.dispose(); // free up our use of the reference } } // Finally we simply check if we can find a editor model that // would give us access to the contents. else { const textModel = this.modelService.getModel(source); if (textModel) { success = await this.doSaveAsTextFile(textModel, source, target, options); } } // Revert the source if result is success if (success) { await this.revert(source); } return target; } private async doSaveAsTextFile(sourceModel: IResolvedTextEditorModel | ITextModel, source: URI, target: URI, options?: ITextFileSaveOptions): Promise<boolean> { // Find source encoding if any let sourceModelEncoding: string | undefined = undefined; const sourceModelWithEncodingSupport = (sourceModel as unknown as IEncodingSupport); if (typeof sourceModelWithEncodingSupport.getEncoding === 'function') { sourceModelEncoding = sourceModelWithEncodingSupport.getEncoding(); } // Prefer an existing model if it is already loaded for the given target resource let targetExists: boolean = false; let targetModel = this.files.get(target); if (targetModel?.isResolved()) { targetExists = true; } // Otherwise create the target file empty if it does not exist already and resolve it from there else { targetExists = await this.fileService.exists(target); // create target file adhoc if it does not exist yet if (!targetExists) { await this.create(target, ''); } try { targetModel = await this.files.resolve(target, { encoding: sourceModelEncoding }); } catch (error) { // if the target already exists and was not created by us, it is possible // that we cannot load the target as text model if it is binary or too // large. in that case we have to delete the target file first and then // re-run the operation. if (targetExists) { if ( (<TextFileOperationError>error).textFileOperationResult === TextFileOperationResult.FILE_IS_BINARY || (<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_TOO_LARGE ) { await this.fileService.del(target); return this.doSaveAsTextFile(sourceModel, source, target, options); } } throw error; } } // Confirm to overwrite if we have an untitled file with associated file where // the file actually exists on disk and we are instructed to save to that file // path. This can happen if the file was created after the untitled file was opened. // See https://github.com/Microsoft/vscode/issues/67946 let write: boolean; if (sourceModel instanceof UntitledTextEditorModel && sourceModel.hasAssociatedFilePath && targetExists && this.uriIdentityService.extUri.isEqual(target, toLocalResource(sourceModel.resource, this.environmentService.configuration.remoteAuthority))) { write = await this.confirmOverwrite(target); } else { write = true; } if (!write) { return false; } let sourceTextModel: ITextModel | undefined = undefined; if (sourceModel instanceof BaseTextEditorModel) { if (sourceModel.isResolved()) { sourceTextModel = sourceModel.textEditorModel; } } else { sourceTextModel = sourceModel as ITextModel; } let targetTextModel: ITextModel | undefined = undefined; if (targetModel.isResolved()) { targetTextModel = targetModel.textEditorModel; } // take over model value, encoding and mode (only if more specific) from source model if (sourceTextModel && targetTextModel) { // encoding targetModel.updatePreferredEncoding(sourceModelEncoding); // content this.modelService.updateModel(targetTextModel, createTextBufferFactoryFromSnapshot(sourceTextModel.createSnapshot())); // mode const sourceMode = sourceTextModel.getLanguageIdentifier(); const targetMode = targetTextModel.getLanguageIdentifier(); if (sourceMode.language !== PLAINTEXT_MODE_ID && targetMode.language === PLAINTEXT_MODE_ID) { targetTextModel.setMode(sourceMode); // only use if more specific than plain/text } // transient properties const sourceTransientProperties = this.codeEditorService.getTransientModelProperties(sourceTextModel); if (sourceTransientProperties) { for (const [key, value] of sourceTransientProperties) { this.codeEditorService.setTransientModelProperty(targetTextModel, key, value); } } } // save model return await targetModel.save(options); } private async confirmOverwrite(resource: URI): Promise<boolean> { const confirm: IConfirmation = { message: nls.localize('confirmOverwrite', "'{0}' already exists. Do you want to replace it?", basename(resource)), detail: nls.localize('irreversible', "A file or folder with the name '{0}' already exists in the folder '{1}'. Replacing it will overwrite its current contents.", basename(resource), basename(dirname(resource))), primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"), type: 'warning' }; return (await this.dialogService.confirm(confirm)).confirmed; } private async suggestSavePath(resource: URI): Promise<URI> { // Just take the resource as is if the file service can handle it if (this.fileService.canHandleResource(resource)) { return resource; } const remoteAuthority = this.environmentService.configuration.remoteAuthority; // Otherwise try to suggest a path that can be saved let suggestedFilename: string | undefined = undefined; if (resource.scheme === Schemas.untitled) { const model = this.untitledTextEditorService.get(resource); if (model) { // Untitled with associated file path if (model.hasAssociatedFilePath) { return toLocalResource(resource, remoteAuthority); } // Untitled without associated file path: use name // of untitled model if it is a valid path name let untitledName = model.name; if (!isValidBasename(untitledName)) { untitledName = basename(resource); } // Add mode file extension if specified const mode = model.getMode(); if (mode && mode !== PLAINTEXT_MODE_ID) { suggestedFilename = this.suggestFilename(mode, untitledName); } else { suggestedFilename = untitledName; } } } // Fallback to basename of resource if (!suggestedFilename) { suggestedFilename = basename(resource); } // Try to place where last active file was if any // Otherwise fallback to user home return joinPath(this.fileDialogService.defaultFilePath() || (await this.pathService.userHome()), suggestedFilename); } suggestFilename(mode: string, untitledName: string) { const languageName = this.modeService.getLanguageName(mode); if (!languageName) { return untitledName; } const extension = this.modeService.getExtensions(languageName)[0]; if (extension) { if (!untitledName.endsWith(extension)) { return untitledName + extension; } } const filename = this.modeService.getFilenames(languageName)[0]; return filename || untitledName; } //#endregion //#region revert async revert(resource: URI, options?: IRevertOptions): Promise<void> { // Untitled if (resource.scheme === Schemas.untitled) { const model = this.untitled.get(resource); if (model) { return model.revert(options); } } // File else { const model = this.files.get(resource); if (model && (model.isDirty() || options?.force)) { return model.revert(options); } } } //#endregion //#region dirty isDirty(resource: URI): boolean { const model = resource.scheme === Schemas.untitled ? this.untitled.get(resource) : this.files.get(resource); if (model) { return model.isDirty(); } return false; } //#endregion } export interface IEncodingOverride { parent?: URI; extension?: string; encoding: string; } export class EncodingOracle extends Disposable implements IResourceEncodings { private _encodingOverrides: IEncodingOverride[]; protected get encodingOverrides(): IEncodingOverride[] { return this._encodingOverrides; } protected set encodingOverrides(value: IEncodingOverride[]) { this._encodingOverrides = value; } constructor( @ITextResourceConfigurationService private textResourceConfigurationService: ITextResourceConfigurationService, @IEnvironmentService private environmentService: IEnvironmentService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IFileService private fileService: IFileService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService ) { super(); this._encodingOverrides = this.getDefaultEncodingOverrides(); this.registerListeners(); } private registerListeners(): void { // Workspace Folder Change this._register(this.contextService.onDidChangeWorkspaceFolders(() => this.encodingOverrides = this.getDefaultEncodingOverrides())); } private getDefaultEncodingOverrides(): IEncodingOverride[] { const defaultEncodingOverrides: IEncodingOverride[] = []; // Global settings defaultEncodingOverrides.push({ parent: this.environmentService.userRoamingDataHome, encoding: UTF8 }); // Workspace files (via extension and via untitled workspaces location) defaultEncodingOverrides.push({ extension: WORKSPACE_EXTENSION, encoding: UTF8 }); defaultEncodingOverrides.push({ parent: this.environmentService.untitledWorkspacesHome, encoding: UTF8 }); // Folder Settings this.contextService.getWorkspace().folders.forEach(folder => { defaultEncodingOverrides.push({ parent: joinPath(folder.uri, '.vscode'), encoding: UTF8 }); }); return defaultEncodingOverrides; } async getWriteEncoding(resource: URI, options?: IWriteTextFileOptions): Promise<{ encoding: string, addBOM: boolean }> { const { encoding, hasBOM } = await this.getPreferredWriteEncoding(resource, options ? options.encoding : undefined); // Some encodings come with a BOM automatically if (hasBOM) { return { encoding, addBOM: true }; } // Ensure that we preserve an existing BOM if found for UTF8 // unless we are instructed to overwrite the encoding const overwriteEncoding = options?.overwriteEncoding; if (!overwriteEncoding && encoding === UTF8) { try { const buffer = (await this.fileService.readFile(resource, { length: UTF8_BOM.length })).value; if (detectEncodingByBOMFromBuffer(buffer, buffer.byteLength) === UTF8_with_bom) { return { encoding, addBOM: true }; } } catch (error) { // ignore - file might not exist } } return { encoding, addBOM: false }; } async getPreferredWriteEncoding(resource: URI, preferredEncoding?: string): Promise<IResourceEncoding> { const resourceEncoding = await this.getEncodingForResource(resource, preferredEncoding); return { encoding: resourceEncoding, hasBOM: resourceEncoding === UTF16be || resourceEncoding === UTF16le || resourceEncoding === UTF8_with_bom // enforce BOM for certain encodings }; } getReadEncoding(resource: URI, options: IReadTextFileOptions | undefined, detectedEncoding: string | null): Promise<string> { let preferredEncoding: string | undefined; // Encoding passed in as option if (options?.encoding) { if (detectedEncoding === UTF8_with_bom && options.encoding === UTF8) { preferredEncoding = UTF8_with_bom; // indicate the file has BOM if we are to resolve with UTF 8 } else { preferredEncoding = options.encoding; // give passed in encoding highest priority } } // Encoding detected else if (detectedEncoding) { preferredEncoding = detectedEncoding; } // Encoding configured else if (this.textResourceConfigurationService.getValue(resource, 'files.encoding') === UTF8_with_bom) { preferredEncoding = UTF8; // if we did not detect UTF 8 BOM before, this can only be UTF 8 then } return this.getEncodingForResource(resource, preferredEncoding); } private async getEncodingForResource(resource: URI, preferredEncoding?: string): Promise<string> { let fileEncoding: string; const override = this.getEncodingOverride(resource); if (override) { fileEncoding = override; // encoding override always wins } else if (preferredEncoding) { fileEncoding = preferredEncoding; // preferred encoding comes second } else { fileEncoding = this.textResourceConfigurationService.getValue(resource, 'files.encoding'); // and last we check for settings } if (fileEncoding !== UTF8) { if (!fileEncoding || !(await encodingExists(fileEncoding))) { fileEncoding = UTF8; // the default is UTF-8 } } return fileEncoding; } private getEncodingOverride(resource: URI): string | undefined { if (this.encodingOverrides && this.encodingOverrides.length) { for (const override of this.encodingOverrides) { // check if the resource is child of encoding override path if (override.parent && this.uriIdentityService.extUri.isEqualOrParent(resource, override.parent)) { return override.encoding; } // check if the resource extension is equal to encoding override if (override.extension && extname(resource) === `.${override.extension}`) { return override.encoding; } } } return undefined; } }
src/vs/workbench/services/textfile/browser/textFileService.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017568525800015777, 0.00017196577391587198, 0.00016366901400033385, 0.0001727823109831661, 0.0000028682775337074418 ]
{ "id": 1, "code_window": [ "\t\tassert.ok(processTree && typeof processTree.getProcessTree === 'function', 'Unable to load windows-process-tree dependency.');\n", "\t});\n", "\n", "\ttest('vscode-windows-ca-certs', async () => {\n", "\t\tconst windowsCerts = await new Promise<any>((resolve, reject) => {\n", "\t\t\trequire(['vscode-windows-ca-certs'], resolve, reject);\n", "\t\t});\n", "\t\tassert.ok(windowsCerts, 'Unable to load vscode-windows-ca-certs dependency.');\n", "\t});\n", "\n", "\ttest('vscode-windows-registry', async () => {\n", "\t\tconst windowsRegistry = await import('vscode-windows-registry');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// @ts-ignore Windows only\n", "\t\tconst windowsCerts = await import('vscode-windows-ca-certs');\n" ], "file_path": "src/vs/code/test/electron-main/nativeHelpers.test.ts", "type": "replace", "edit_start_line_idx": 30 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { isWindows, isLinux } from 'vs/base/common/platform'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { Registry } from 'vs/platform/registry/common/platform'; import { AccessibilityService } from 'vs/platform/accessibility/common/accessibilityService'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IJSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditing'; import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-browser/environmentService'; interface AccessibilityMetrics { enabled: boolean; } type AccessibilityMetricsClassification = { enabled: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; }; export class NativeAccessibilityService extends AccessibilityService implements IAccessibilityService { declare readonly _serviceBrand: undefined; private didSendTelemetry = false; constructor( @IWorkbenchEnvironmentService environmentService: INativeWorkbenchEnvironmentService, @IContextKeyService contextKeyService: IContextKeyService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private readonly _telemetryService: ITelemetryService ) { super(contextKeyService, configurationService); this.setAccessibilitySupport(environmentService.configuration.accessibilitySupport ? AccessibilitySupport.Enabled : AccessibilitySupport.Disabled); } alwaysUnderlineAccessKeys(): Promise<boolean> { if (!isWindows) { return Promise.resolve(false); } return new Promise<boolean>(async (resolve) => { const Registry = await import('vscode-windows-registry'); let value; try { value = Registry.GetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\Accessibility\\Keyboard Preference', 'On'); } catch { resolve(false); } resolve(value === '1'); }); } setAccessibilitySupport(accessibilitySupport: AccessibilitySupport): void { super.setAccessibilitySupport(accessibilitySupport); if (!this.didSendTelemetry && accessibilitySupport === AccessibilitySupport.Enabled) { this._telemetryService.publicLog2<AccessibilityMetrics, AccessibilityMetricsClassification>('accessibility', { enabled: true }); this.didSendTelemetry = true; } } } registerSingleton(IAccessibilityService, NativeAccessibilityService, true); // On linux we do not automatically detect that a screen reader is detected, thus we have to implicitly notify the renderer to enable accessibility when user configures it in settings class LinuxAccessibilityContribution implements IWorkbenchContribution { constructor( @IJSONEditingService jsonEditingService: IJSONEditingService, @IAccessibilityService accessibilityService: AccessibilityService, @IEnvironmentService environmentService: IEnvironmentService ) { const forceRendererAccessibility = () => { if (accessibilityService.isScreenReaderOptimized()) { jsonEditingService.write(environmentService.argvResource, [{ path: ['force-renderer-accessibility'], value: true }], true); } }; forceRendererAccessibility(); accessibilityService.onDidChangeScreenReaderOptimized(forceRendererAccessibility); } } if (isLinux) { Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(LinuxAccessibilityContribution, LifecyclePhase.Ready); }
src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts
1
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00048819047515280545, 0.00020336065790615976, 0.00016675086226314306, 0.00017252506222575903, 0.00009497322025708854 ]
{ "id": 1, "code_window": [ "\t\tassert.ok(processTree && typeof processTree.getProcessTree === 'function', 'Unable to load windows-process-tree dependency.');\n", "\t});\n", "\n", "\ttest('vscode-windows-ca-certs', async () => {\n", "\t\tconst windowsCerts = await new Promise<any>((resolve, reject) => {\n", "\t\t\trequire(['vscode-windows-ca-certs'], resolve, reject);\n", "\t\t});\n", "\t\tassert.ok(windowsCerts, 'Unable to load vscode-windows-ca-certs dependency.');\n", "\t});\n", "\n", "\ttest('vscode-windows-registry', async () => {\n", "\t\tconst windowsRegistry = await import('vscode-windows-registry');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// @ts-ignore Windows only\n", "\t\tconst windowsCerts = await import('vscode-windows-ca-certs');\n" ], "file_path": "src/vs/code/test/electron-main/nativeHelpers.test.ts", "type": "replace", "edit_start_line_idx": 30 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as os from 'os'; import * as path from 'vs/base/common/path'; import { getRandomTestPath } from 'vs/base/test/node/testUtils'; import { FileStorage } from 'vs/platform/state/node/stateService'; import { mkdirp, rimraf, RimRafMode, writeFileSync } from 'vs/base/node/pfs'; suite('StateService', () => { const parentDir = getRandomTestPath(os.tmpdir(), 'vsctests', 'stateservice'); const storageFile = path.join(parentDir, 'storage.json'); teardown(async () => { await rimraf(parentDir, RimRafMode.MOVE); }); test('Basics', async () => { await mkdirp(parentDir); writeFileSync(storageFile, ''); let service = new FileStorage(storageFile, () => null); service.setItem('some.key', 'some.value'); assert.equal(service.getItem('some.key'), 'some.value'); service.removeItem('some.key'); assert.equal(service.getItem('some.key', 'some.default'), 'some.default'); assert.ok(!service.getItem('some.unknonw.key')); service.setItem('some.other.key', 'some.other.value'); service = new FileStorage(storageFile, () => null); assert.equal(service.getItem('some.other.key'), 'some.other.value'); service.setItem('some.other.key', 'some.other.value'); assert.equal(service.getItem('some.other.key'), 'some.other.value'); service.setItem('some.undefined.key', undefined); assert.equal(service.getItem('some.undefined.key', 'some.default'), 'some.default'); service.setItem('some.null.key', null); assert.equal(service.getItem('some.null.key', 'some.default'), 'some.default'); }); });
src/vs/platform/state/test/node/state.test.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.0001766243512975052, 0.0001716712722554803, 0.00016581917589064687, 0.00017228882643394172, 0.000003518549647196778 ]
{ "id": 1, "code_window": [ "\t\tassert.ok(processTree && typeof processTree.getProcessTree === 'function', 'Unable to load windows-process-tree dependency.');\n", "\t});\n", "\n", "\ttest('vscode-windows-ca-certs', async () => {\n", "\t\tconst windowsCerts = await new Promise<any>((resolve, reject) => {\n", "\t\t\trequire(['vscode-windows-ca-certs'], resolve, reject);\n", "\t\t});\n", "\t\tassert.ok(windowsCerts, 'Unable to load vscode-windows-ca-certs dependency.');\n", "\t});\n", "\n", "\ttest('vscode-windows-registry', async () => {\n", "\t\tconst windowsRegistry = await import('vscode-windows-registry');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// @ts-ignore Windows only\n", "\t\tconst windowsCerts = await import('vscode-windows-ca-certs');\n" ], "file_path": "src/vs/code/test/electron-main/nativeHelpers.test.ts", "type": "replace", "edit_start_line_idx": 30 }
#!/usr/bin/env node /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ require("../out/jsonServerMain");
extensions/json-language-features/server/bin/vscode-json-languageserver
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017247910727746785, 0.00017247910727746785, 0.00017247910727746785, 0.00017247910727746785, 0 ]
{ "id": 1, "code_window": [ "\t\tassert.ok(processTree && typeof processTree.getProcessTree === 'function', 'Unable to load windows-process-tree dependency.');\n", "\t});\n", "\n", "\ttest('vscode-windows-ca-certs', async () => {\n", "\t\tconst windowsCerts = await new Promise<any>((resolve, reject) => {\n", "\t\t\trequire(['vscode-windows-ca-certs'], resolve, reject);\n", "\t\t});\n", "\t\tassert.ok(windowsCerts, 'Unable to load vscode-windows-ca-certs dependency.');\n", "\t});\n", "\n", "\ttest('vscode-windows-registry', async () => {\n", "\t\tconst windowsRegistry = await import('vscode-windows-registry');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// @ts-ignore Windows only\n", "\t\tconst windowsCerts = await import('vscode-windows-ca-certs');\n" ], "file_path": "src/vs/code/test/electron-main/nativeHelpers.test.ts", "type": "replace", "edit_start_line_idx": 30 }
This is the summary line. It can't be too long. After I can write a much more detailed description without quite the same restrictions on length. # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. # On branch master # Your branch is up-to-date with 'origin/master'. # # Changes to be committed: # deleted: README.md # modified: index.less # new file: spec/COMMIT_EDITMSG #
extensions/git/test/colorize-fixtures/COMMIT_EDITMSG
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017319450853392482, 0.00017280515749007463, 0.00017241580644622445, 0.00017280515749007463, 3.893510438501835e-7 ]
{ "id": 2, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { ICredentialsService } from 'vs/platform/credentials/common/credentials';\n", "import { IdleValue } from 'vs/base/common/async';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import type * as keytar from 'keytar';\n" ], "file_path": "src/vs/platform/credentials/node/credentialsService.ts", "type": "add", "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 { ICredentialsService } from 'vs/platform/credentials/common/credentials'; import { IdleValue } from 'vs/base/common/async'; type KeytarModule = typeof import('keytar'); export class KeytarCredentialsService implements ICredentialsService { declare readonly _serviceBrand: undefined; private readonly _keytar = new IdleValue<Promise<KeytarModule>>(() => import('keytar')); async getPassword(service: string, account: string): Promise<string | null> { const keytar = await this._keytar.value; return keytar.getPassword(service, account); } async setPassword(service: string, account: string, password: string): Promise<void> { const keytar = await this._keytar.value; return keytar.setPassword(service, account, password); } async deletePassword(service: string, account: string): Promise<boolean> { const keytar = await this._keytar.value; return keytar.deletePassword(service, account); } async findPassword(service: string): Promise<string | null> { const keytar = await this._keytar.value; return keytar.findPassword(service); } async findCredentials(service: string): Promise<Array<{ account: string, password: string }>> { const keytar = await this._keytar.value; return keytar.findCredentials(service); } }
src/vs/platform/credentials/node/credentialsService.ts
1
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.0005684384959749877, 0.0002532749786041677, 0.0001673886872595176, 0.0001769005903042853, 0.00015762711700517684 ]
{ "id": 2, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { ICredentialsService } from 'vs/platform/credentials/common/credentials';\n", "import { IdleValue } from 'vs/base/common/async';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import type * as keytar from 'keytar';\n" ], "file_path": "src/vs/platform/credentials/node/credentialsService.ts", "type": "add", "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 * as eslint from 'eslint'; import { TSESTree, AST_NODE_TYPES } from '@typescript-eslint/experimental-utils'; export = new class ApiEventNaming implements eslint.Rule.RuleModule { private static _nameRegExp = /on(Did|Will)([A-Z][a-z]+)([A-Z][a-z]+)?/; readonly meta: eslint.Rule.RuleMetaData = { docs: { url: 'https://github.com/microsoft/vscode/wiki/Extension-API-guidelines#event-naming' }, messages: { naming: 'Event names must follow this patten: `on[Did|Will]<Verb><Subject>`', verb: 'Unknown verb \'{{verb}}\' - is this really a verb? Iff so, then add this verb to the configuration', subject: 'Unknown subject \'{{subject}}\' - This subject has not been used before but it should refer to something in the API', unknown: 'UNKNOWN event declaration, lint-rule needs tweaking' } }; create(context: eslint.Rule.RuleContext): eslint.Rule.RuleListener { const config = <{ allowed: string[], verbs: string[] }>context.options[0]; const allowed = new Set(config.allowed); const verbs = new Set(config.verbs); return { ['TSTypeAnnotation TSTypeReference Identifier[name="Event"]']: (node: any) => { const def = (<TSESTree.Identifier>node).parent?.parent?.parent; const ident = this.getIdent(def); if (!ident) { // event on unknown structure... return context.report({ node, message: 'unknown' }); } if (allowed.has(ident.name)) { // configured exception return; } const match = ApiEventNaming._nameRegExp.exec(ident.name); if (!match) { context.report({ node: ident, messageId: 'naming' }); return; } // check that <verb> is spelled out (configured) as verb if (!verbs.has(match[2].toLowerCase())) { context.report({ node: ident, messageId: 'verb', data: { verb: match[2] } }); } // check that a subject (if present) has occurred if (match[3]) { const regex = new RegExp(match[3], 'ig'); const parts = context.getSourceCode().getText().split(regex); if (parts.length < 3) { context.report({ node: ident, messageId: 'subject', data: { subject: match[3] } }); } } } }; } private getIdent(def: TSESTree.Node | undefined): TSESTree.Identifier | undefined { if (!def) { return; } if (def.type === AST_NODE_TYPES.Identifier) { return def; } else if ((def.type === AST_NODE_TYPES.TSPropertySignature || def.type === AST_NODE_TYPES.ClassProperty) && def.key.type === AST_NODE_TYPES.Identifier) { return def.key; } return this.getIdent(def.parent); } };
build/lib/eslint/vscode-dts-event-naming.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.0001771500683389604, 0.00017341137572657317, 0.00016616357606835663, 0.00017468762234784663, 0.000003586068260119646 ]
{ "id": 2, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { ICredentialsService } from 'vs/platform/credentials/common/credentials';\n", "import { IdleValue } from 'vs/base/common/async';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import type * as keytar from 'keytar';\n" ], "file_path": "src/vs/platform/credentials/node/credentialsService.ts", "type": "add", "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 { Terminal, IMarker, ITerminalAddon } from 'xterm'; import { ICommandTracker } from 'vs/workbench/contrib/terminal/common/terminal'; /** * The minimum size of the prompt in which to assume the line is a command. */ const MINIMUM_PROMPT_LENGTH = 2; enum Boundary { Top, Bottom } export const enum ScrollPosition { Top, Middle } export class CommandTrackerAddon implements ICommandTracker, ITerminalAddon { private _currentMarker: IMarker | Boundary = Boundary.Bottom; private _selectionStart: IMarker | Boundary | null = null; private _isDisposable: boolean = false; private _terminal: Terminal | undefined; public activate(terminal: Terminal): void { this._terminal = terminal; terminal.onKey(e => this._onKey(e.key)); } public dispose(): void { } private _onKey(key: string): void { if (key === '\x0d') { this._onEnter(); } // Clear the current marker so successive focus/selection actions are performed from the // bottom of the buffer this._currentMarker = Boundary.Bottom; this._selectionStart = null; } private _onEnter(): void { if (!this._terminal) { return; } if (this._terminal.buffer.active.cursorX >= MINIMUM_PROMPT_LENGTH) { this._terminal.registerMarker(0); } } public scrollToPreviousCommand(scrollPosition: ScrollPosition = ScrollPosition.Top, retainSelection: boolean = false): void { if (!this._terminal) { return; } if (!retainSelection) { this._selectionStart = null; } let markerIndex; const currentLineY = Math.min(this._getLine(this._terminal, this._currentMarker), this._terminal.buffer.active.baseY); const viewportY = this._terminal.buffer.active.viewportY; if (!retainSelection && currentLineY !== viewportY) { // The user has scrolled, find the line based on the current scroll position. This only // works when not retaining selection const markersBelowViewport = this._terminal.markers.filter(e => e.line >= viewportY).length; // -1 will scroll to the top markerIndex = this._terminal.markers.length - markersBelowViewport - 1; } else if (this._currentMarker === Boundary.Bottom) { markerIndex = this._terminal.markers.length - 1; } else if (this._currentMarker === Boundary.Top) { markerIndex = -1; } else if (this._isDisposable) { markerIndex = this._findPreviousCommand(this._terminal); this._currentMarker.dispose(); this._isDisposable = false; } else { markerIndex = this._terminal.markers.indexOf(this._currentMarker) - 1; } if (markerIndex < 0) { this._currentMarker = Boundary.Top; this._terminal.scrollToTop(); return; } this._currentMarker = this._terminal.markers[markerIndex]; this._scrollToMarker(this._currentMarker, scrollPosition); } public scrollToNextCommand(scrollPosition: ScrollPosition = ScrollPosition.Top, retainSelection: boolean = false): void { if (!this._terminal) { return; } if (!retainSelection) { this._selectionStart = null; } let markerIndex; const currentLineY = Math.min(this._getLine(this._terminal, this._currentMarker), this._terminal.buffer.active.baseY); const viewportY = this._terminal.buffer.active.viewportY; if (!retainSelection && currentLineY !== viewportY) { // The user has scrolled, find the line based on the current scroll position. This only // works when not retaining selection const markersAboveViewport = this._terminal.markers.filter(e => e.line <= viewportY).length; // markers.length will scroll to the bottom markerIndex = markersAboveViewport; } else if (this._currentMarker === Boundary.Bottom) { markerIndex = this._terminal.markers.length; } else if (this._currentMarker === Boundary.Top) { markerIndex = 0; } else if (this._isDisposable) { markerIndex = this._findNextCommand(this._terminal); this._currentMarker.dispose(); this._isDisposable = false; } else { markerIndex = this._terminal.markers.indexOf(this._currentMarker) + 1; } if (markerIndex >= this._terminal.markers.length) { this._currentMarker = Boundary.Bottom; this._terminal.scrollToBottom(); return; } this._currentMarker = this._terminal.markers[markerIndex]; this._scrollToMarker(this._currentMarker, scrollPosition); } private _scrollToMarker(marker: IMarker, position: ScrollPosition): void { if (!this._terminal) { return; } let line = marker.line; if (position === ScrollPosition.Middle) { line = Math.max(line - Math.floor(this._terminal.rows / 2), 0); } this._terminal.scrollToLine(line); } public selectToPreviousCommand(): void { if (!this._terminal) { return; } if (this._selectionStart === null) { this._selectionStart = this._currentMarker; } this.scrollToPreviousCommand(ScrollPosition.Middle, true); this._selectLines(this._terminal, this._currentMarker, this._selectionStart); } public selectToNextCommand(): void { if (!this._terminal) { return; } if (this._selectionStart === null) { this._selectionStart = this._currentMarker; } this.scrollToNextCommand(ScrollPosition.Middle, true); this._selectLines(this._terminal, this._currentMarker, this._selectionStart); } public selectToPreviousLine(): void { if (!this._terminal) { return; } if (this._selectionStart === null) { this._selectionStart = this._currentMarker; } this.scrollToPreviousLine(this._terminal, ScrollPosition.Middle, true); this._selectLines(this._terminal, this._currentMarker, this._selectionStart); } public selectToNextLine(): void { if (!this._terminal) { return; } if (this._selectionStart === null) { this._selectionStart = this._currentMarker; } this.scrollToNextLine(this._terminal, ScrollPosition.Middle, true); this._selectLines(this._terminal, this._currentMarker, this._selectionStart); } private _selectLines(xterm: Terminal, start: IMarker | Boundary, end: IMarker | Boundary | null): void { if (end === null) { end = Boundary.Bottom; } let startLine = this._getLine(xterm, start); let endLine = this._getLine(xterm, end); if (startLine > endLine) { const temp = startLine; startLine = endLine; endLine = temp; } // Subtract a line as the marker is on the line the command run, we do not want the next // command in the selection for the current command endLine -= 1; xterm.selectLines(startLine, endLine); } private _getLine(xterm: Terminal, marker: IMarker | Boundary): number { // Use the _second last_ row as the last row is likely the prompt if (marker === Boundary.Bottom) { return xterm.buffer.active.baseY + xterm.rows - 1; } if (marker === Boundary.Top) { return 0; } return marker.line; } public scrollToPreviousLine(xterm: Terminal, scrollPosition: ScrollPosition = ScrollPosition.Top, retainSelection: boolean = false): void { if (!retainSelection) { this._selectionStart = null; } if (this._currentMarker === Boundary.Top) { xterm.scrollToTop(); return; } if (this._currentMarker === Boundary.Bottom) { this._currentMarker = this._addMarkerOrThrow(xterm, this._getOffset(xterm) - 1); } else { const offset = this._getOffset(xterm); if (this._isDisposable) { this._currentMarker.dispose(); } this._currentMarker = this._addMarkerOrThrow(xterm, offset - 1); } this._isDisposable = true; this._scrollToMarker(this._currentMarker, scrollPosition); } public scrollToNextLine(xterm: Terminal, scrollPosition: ScrollPosition = ScrollPosition.Top, retainSelection: boolean = false): void { if (!retainSelection) { this._selectionStart = null; } if (this._currentMarker === Boundary.Bottom) { xterm.scrollToBottom(); return; } if (this._currentMarker === Boundary.Top) { this._currentMarker = this._addMarkerOrThrow(xterm, this._getOffset(xterm) + 1); } else { const offset = this._getOffset(xterm); if (this._isDisposable) { this._currentMarker.dispose(); } this._currentMarker = this._addMarkerOrThrow(xterm, offset + 1); } this._isDisposable = true; this._scrollToMarker(this._currentMarker, scrollPosition); } private _addMarkerOrThrow(xterm: Terminal, cursorYOffset: number): IMarker { const marker = xterm.addMarker(cursorYOffset); if (!marker) { throw new Error(`Could not create marker for ${cursorYOffset}`); } return marker; } private _getOffset(xterm: Terminal): number { if (this._currentMarker === Boundary.Bottom) { return 0; } else if (this._currentMarker === Boundary.Top) { return 0 - (xterm.buffer.active.baseY + xterm.buffer.active.cursorY); } else { let offset = this._getLine(xterm, this._currentMarker); offset -= xterm.buffer.active.baseY + xterm.buffer.active.cursorY; return offset; } } private _findPreviousCommand(xterm: Terminal): number { if (this._currentMarker === Boundary.Top) { return 0; } else if (this._currentMarker === Boundary.Bottom) { return xterm.markers.length - 1; } let i; for (i = xterm.markers.length - 1; i >= 0; i--) { if (xterm.markers[i].line < this._currentMarker.line) { return i; } } return -1; } private _findNextCommand(xterm: Terminal): number { if (this._currentMarker === Boundary.Top) { return 0; } else if (this._currentMarker === Boundary.Bottom) { return xterm.markers.length - 1; } let i; for (i = 0; i < xterm.markers.length; i++) { if (xterm.markers[i].line > this._currentMarker.line) { return i; } } return xterm.markers.length; } }
src/vs/workbench/contrib/terminal/browser/addons/commandTrackerAddon.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017794675659388304, 0.00017400787328369915, 0.00016461608174722642, 0.00017474766355007887, 0.0000028486390419857344 ]
{ "id": 2, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { ICredentialsService } from 'vs/platform/credentials/common/credentials';\n", "import { IdleValue } from 'vs/base/common/async';\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import type * as keytar from 'keytar';\n" ], "file_path": "src/vs/platform/credentials/node/credentialsService.ts", "type": "add", "edit_start_line_idx": 5 }
{ "$schema": "http://json-schema.org/draft-07/schema#", "description": "Configures an attached to container", "allowComments": true, "allowTrailingCommas": true, "type": "object", "definitions": { "attachContainer": { "type": "object", "properties": { "workspaceFolder": { "type": "string", "description": "The path of the workspace folder inside the container." }, "forwardPorts": { "type": "array", "description": "Ports that are forwarded from the container to the local machine.", "items": { "type": "integer" } }, "settings": { "$ref": "vscode://schemas/settings/machine", "description": "Machine specific settings that should be copied into the container." }, "remoteEnv": { "type": "object", "additionalProperties": { "type": [ "string", "null" ] }, "description": "Remote environment variables." }, "remoteUser": { "type": "string", "description": "The user VS Code Server will be started with. The default is the same user as the container." }, "extensions": { "type": "array", "description": "An array of extensions that should be installed into the container.", "items": { "type": "string", "pattern": "^([a-z0-9A-Z][a-z0-9\\-A-Z]*)\\.([a-z0-9A-Z][a-z0-9\\-A-Z]*)(@(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?)?$", "errorMessage": "Expected format: '${publisher}.${name}' or '${publisher}.${name}@${version}'. Example: 'ms-dotnettools.csharp'." } }, "userEnvProbe": { "type": "string", "enum": [ "none", "loginInteractiveShell", "interactiveShell" ], "description": "User environment probe to run. The default is none." }, "postAttachCommand": { "type": [ "string", "array" ], "description": "A command to run after attaching to the container. If this is a single string, it will be run in a shell. If this is an array of strings, it will be run as a single command without shell.", "items": { "type": "string" } } } } }, "allOf": [ { "$ref": "#/definitions/attachContainer" } ] }
extensions/configuration-editing/schemas/attachContainer.schema.json
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017452635802328587, 0.00017182697774842381, 0.000168425845913589, 0.00017208867939189076, 0.0000021542059585044626 ]
{ "id": 3, "code_window": [ "import { ICredentialsService } from 'vs/platform/credentials/common/credentials';\n", "import { IdleValue } from 'vs/base/common/async';\n", "\n", "type KeytarModule = typeof import('keytar');\n", "export class KeytarCredentialsService implements ICredentialsService {\n", "\n", "\tdeclare readonly _serviceBrand: undefined;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/credentials/node/credentialsService.ts", "type": "replace", "edit_start_line_idx": 8 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { isWindows, isLinux } from 'vs/base/common/platform'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { Registry } from 'vs/platform/registry/common/platform'; import { AccessibilityService } from 'vs/platform/accessibility/common/accessibilityService'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IJSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditing'; import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-browser/environmentService'; interface AccessibilityMetrics { enabled: boolean; } type AccessibilityMetricsClassification = { enabled: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; }; export class NativeAccessibilityService extends AccessibilityService implements IAccessibilityService { declare readonly _serviceBrand: undefined; private didSendTelemetry = false; constructor( @IWorkbenchEnvironmentService environmentService: INativeWorkbenchEnvironmentService, @IContextKeyService contextKeyService: IContextKeyService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private readonly _telemetryService: ITelemetryService ) { super(contextKeyService, configurationService); this.setAccessibilitySupport(environmentService.configuration.accessibilitySupport ? AccessibilitySupport.Enabled : AccessibilitySupport.Disabled); } alwaysUnderlineAccessKeys(): Promise<boolean> { if (!isWindows) { return Promise.resolve(false); } return new Promise<boolean>(async (resolve) => { const Registry = await import('vscode-windows-registry'); let value; try { value = Registry.GetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\Accessibility\\Keyboard Preference', 'On'); } catch { resolve(false); } resolve(value === '1'); }); } setAccessibilitySupport(accessibilitySupport: AccessibilitySupport): void { super.setAccessibilitySupport(accessibilitySupport); if (!this.didSendTelemetry && accessibilitySupport === AccessibilitySupport.Enabled) { this._telemetryService.publicLog2<AccessibilityMetrics, AccessibilityMetricsClassification>('accessibility', { enabled: true }); this.didSendTelemetry = true; } } } registerSingleton(IAccessibilityService, NativeAccessibilityService, true); // On linux we do not automatically detect that a screen reader is detected, thus we have to implicitly notify the renderer to enable accessibility when user configures it in settings class LinuxAccessibilityContribution implements IWorkbenchContribution { constructor( @IJSONEditingService jsonEditingService: IJSONEditingService, @IAccessibilityService accessibilityService: AccessibilityService, @IEnvironmentService environmentService: IEnvironmentService ) { const forceRendererAccessibility = () => { if (accessibilityService.isScreenReaderOptimized()) { jsonEditingService.write(environmentService.argvResource, [{ path: ['force-renderer-accessibility'], value: true }], true); } }; forceRendererAccessibility(); accessibilityService.onDidChangeScreenReaderOptimized(forceRendererAccessibility); } } if (isLinux) { Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(LinuxAccessibilityContribution, LifecyclePhase.Ready); }
src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts
1
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00032989721512421966, 0.00018403943977318704, 0.0001642496499698609, 0.00016736512770876288, 0.00004872438876191154 ]
{ "id": 3, "code_window": [ "import { ICredentialsService } from 'vs/platform/credentials/common/credentials';\n", "import { IdleValue } from 'vs/base/common/async';\n", "\n", "type KeytarModule = typeof import('keytar');\n", "export class KeytarCredentialsService implements ICredentialsService {\n", "\n", "\tdeclare readonly _serviceBrand: undefined;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/credentials/node/credentialsService.ts", "type": "replace", "edit_start_line_idx": 8 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IThemeService, Themable } from 'vs/platform/theme/common/themeService'; import { localize } from 'vs/nls'; import { registerColor, contrastBorder } from 'vs/platform/theme/common/colorRegistry'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { IDebugService, State, IDebugSession } from 'vs/workbench/contrib/debug/common/debug'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { STATUS_BAR_NO_FOLDER_BACKGROUND, STATUS_BAR_NO_FOLDER_FOREGROUND, STATUS_BAR_BACKGROUND, STATUS_BAR_FOREGROUND, STATUS_BAR_NO_FOLDER_BORDER, STATUS_BAR_BORDER } from 'vs/workbench/common/theme'; import { addClass, removeClass, createStyleSheet } from 'vs/base/browser/dom'; import { assertIsDefined } from 'vs/base/common/types'; // colors for theming export const STATUS_BAR_DEBUGGING_BACKGROUND = registerColor('statusBar.debuggingBackground', { dark: '#CC6633', light: '#CC6633', hc: '#CC6633' }, localize('statusBarDebuggingBackground', "Status bar background color when a program is being debugged. The status bar is shown in the bottom of the window")); export const STATUS_BAR_DEBUGGING_FOREGROUND = registerColor('statusBar.debuggingForeground', { dark: STATUS_BAR_FOREGROUND, light: STATUS_BAR_FOREGROUND, hc: STATUS_BAR_FOREGROUND }, localize('statusBarDebuggingForeground', "Status bar foreground color when a program is being debugged. The status bar is shown in the bottom of the window")); export const STATUS_BAR_DEBUGGING_BORDER = registerColor('statusBar.debuggingBorder', { dark: STATUS_BAR_BORDER, light: STATUS_BAR_BORDER, hc: STATUS_BAR_BORDER }, localize('statusBarDebuggingBorder', "Status bar border color separating to the sidebar and editor when a program is being debugged. The status bar is shown in the bottom of the window")); export class StatusBarColorProvider extends Themable implements IWorkbenchContribution { private styleElement: HTMLStyleElement | undefined; constructor( @IThemeService themeService: IThemeService, @IDebugService private readonly debugService: IDebugService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService ) { super(themeService); this.registerListeners(); this.updateStyles(); } private registerListeners(): void { this._register(this.debugService.onDidChangeState(state => this.updateStyles())); this._register(this.contextService.onDidChangeWorkbenchState(state => this.updateStyles())); } protected updateStyles(): void { super.updateStyles(); const container = assertIsDefined(this.layoutService.getContainer(Parts.STATUSBAR_PART)); if (isStatusbarInDebugMode(this.debugService.state, this.debugService.getViewModel().focusedSession)) { addClass(container, 'debugging'); } else { removeClass(container, 'debugging'); } // Container Colors const backgroundColor = this.getColor(this.getColorKey(STATUS_BAR_NO_FOLDER_BACKGROUND, STATUS_BAR_DEBUGGING_BACKGROUND, STATUS_BAR_BACKGROUND)); container.style.backgroundColor = backgroundColor || ''; container.style.color = this.getColor(this.getColorKey(STATUS_BAR_NO_FOLDER_FOREGROUND, STATUS_BAR_DEBUGGING_FOREGROUND, STATUS_BAR_FOREGROUND)) || ''; // Border Color const borderColor = this.getColor(this.getColorKey(STATUS_BAR_NO_FOLDER_BORDER, STATUS_BAR_DEBUGGING_BORDER, STATUS_BAR_BORDER)) || this.getColor(contrastBorder); if (borderColor) { addClass(container, 'status-border-top'); container.style.setProperty('--status-border-top-color', borderColor.toString()); } else { removeClass(container, 'status-border-top'); container.style.removeProperty('--status-border-top-color'); } // Notification Beak if (!this.styleElement) { this.styleElement = createStyleSheet(container); } this.styleElement.innerHTML = `.monaco-workbench .part.statusbar > .items-container > .statusbar-item.has-beak:before { border-bottom-color: ${backgroundColor} !important; }`; } private getColorKey(noFolderColor: string, debuggingColor: string, normalColor: string): string { // Not debugging if (!isStatusbarInDebugMode(this.debugService.state, this.debugService.getViewModel().focusedSession)) { if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY) { return normalColor; } return noFolderColor; } // Debugging return debuggingColor; } } export function isStatusbarInDebugMode(state: State, session: IDebugSession | undefined): boolean { if (state === State.Inactive || state === State.Initializing) { return false; } const isRunningWithoutDebug = session?.configuration?.noDebug; if (isRunningWithoutDebug) { return false; } return true; }
src/vs/workbench/contrib/debug/browser/statusbarColorProvider.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00025037481100298464, 0.00017729536921251565, 0.00016635778592899442, 0.0001713488600216806, 0.00002216719076386653 ]
{ "id": 3, "code_window": [ "import { ICredentialsService } from 'vs/platform/credentials/common/credentials';\n", "import { IdleValue } from 'vs/base/common/async';\n", "\n", "type KeytarModule = typeof import('keytar');\n", "export class KeytarCredentialsService implements ICredentialsService {\n", "\n", "\tdeclare readonly _serviceBrand: undefined;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/credentials/node/credentialsService.ts", "type": "replace", "edit_start_line_idx": 8 }
{ "version": "0.1.0", // List of configurations. Add new configurations or edit existing ones. "configurations": [ { "name": "Attach", "type": "node", "request": "attach", "port": 6045, "protocol": "inspector", "sourceMaps": true, "outFiles": ["${workspaceFolder}/out/**/*.js"] }, { "name": "Unit Tests", "type": "node", "request": "launch", "program": "${workspaceFolder}/../../../node_modules/mocha/bin/_mocha", "stopOnEntry": false, "args": [ "--timeout", "999999", "--colors" ], "cwd": "${workspaceFolder}", "runtimeExecutable": null, "runtimeArgs": [], "env": {}, "sourceMaps": true, "outFiles": ["${workspaceFolder}/out/**/*.js"] } ] }
extensions/html-language-features/server/.vscode/launch.json
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017377480980940163, 0.00017246043717022985, 0.00017041880346368998, 0.00017282406042795628, 0.000001328962980551296 ]
{ "id": 3, "code_window": [ "import { ICredentialsService } from 'vs/platform/credentials/common/credentials';\n", "import { IdleValue } from 'vs/base/common/async';\n", "\n", "type KeytarModule = typeof import('keytar');\n", "export class KeytarCredentialsService implements ICredentialsService {\n", "\n", "\tdeclare readonly _serviceBrand: undefined;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/credentials/node/credentialsService.ts", "type": "replace", "edit_start_line_idx": 8 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable } from 'vs/base/common/lifecycle'; import { ILocalExtension } from 'vs/platform/extensionManagement/common/extensionManagement'; import { ILogService } from 'vs/platform/log/common/log'; import { fork, ChildProcess } from 'child_process'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { join } from 'vs/base/common/path'; import { Limiter } from 'vs/base/common/async'; import { Event } from 'vs/base/common/event'; import { Schemas } from 'vs/base/common/network'; import { INativeEnvironmentService } from 'vs/platform/environment/node/environmentService'; import { rimraf } from 'vs/base/node/pfs'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; export class ExtensionsLifecycle extends Disposable { private processesLimiter: Limiter<void> = new Limiter(5); // Run max 5 processes in parallel constructor( @IEnvironmentService private environmentService: INativeEnvironmentService, @ILogService private readonly logService: ILogService ) { super(); } async postUninstall(extension: ILocalExtension): Promise<void> { const script = this.parseScript(extension, 'uninstall'); if (script) { this.logService.info(extension.identifier.id, extension.manifest.version, `Running post uninstall script`); await this.processesLimiter.queue(() => this.runLifecycleHook(script.script, 'uninstall', script.args, true, extension) .then(() => this.logService.info(extension.identifier.id, extension.manifest.version, `Finished running post uninstall script`), err => this.logService.error(extension.identifier.id, extension.manifest.version, `Failed to run post uninstall script: ${err}`))); } return rimraf(this.getExtensionStoragePath(extension)).then(undefined, e => this.logService.error('Error while removing extension storage path', e)); } private parseScript(extension: ILocalExtension, type: string): { script: string, args: string[] } | null { const scriptKey = `vscode:${type}`; if (extension.location.scheme === Schemas.file && extension.manifest && extension.manifest['scripts'] && typeof extension.manifest['scripts'][scriptKey] === 'string') { const script = (<string>extension.manifest['scripts'][scriptKey]).split(' '); if (script.length < 2 || script[0] !== 'node' || !script[1]) { this.logService.warn(extension.identifier.id, extension.manifest.version, `${scriptKey} should be a node script`); return null; } return { script: join(extension.location.fsPath, script[1]), args: script.slice(2) || [] }; } return null; } private runLifecycleHook(lifecycleHook: string, lifecycleType: string, args: string[], timeout: boolean, extension: ILocalExtension): Promise<void> { return new Promise<void>((c, e) => { const extensionLifecycleProcess = this.start(lifecycleHook, lifecycleType, args, extension); let timeoutHandler: any; const onexit = (error?: string) => { if (timeoutHandler) { clearTimeout(timeoutHandler); timeoutHandler = null; } if (error) { e(error); } else { c(undefined); } }; // on error extensionLifecycleProcess.on('error', (err) => { onexit(toErrorMessage(err) || 'Unknown'); }); // on exit extensionLifecycleProcess.on('exit', (code: number, signal: string) => { onexit(code ? `post-${lifecycleType} process exited with code ${code}` : undefined); }); if (timeout) { // timeout: kill process after waiting for 5s timeoutHandler = setTimeout(() => { timeoutHandler = null; extensionLifecycleProcess.kill(); e('timed out'); }, 5000); } }); } private start(uninstallHook: string, lifecycleType: string, args: string[], extension: ILocalExtension): ChildProcess { const opts = { silent: true, execArgv: undefined }; const extensionUninstallProcess = fork(uninstallHook, [`--type=extension-post-${lifecycleType}`, ...args], opts); // Catch all output coming from the process type Output = { data: string, format: string[] }; extensionUninstallProcess.stdout!.setEncoding('utf8'); extensionUninstallProcess.stderr!.setEncoding('utf8'); const onStdout = Event.fromNodeEventEmitter<string>(extensionUninstallProcess.stdout!, 'data'); const onStderr = Event.fromNodeEventEmitter<string>(extensionUninstallProcess.stderr!, 'data'); // Log output onStdout(data => this.logService.info(extension.identifier.id, extension.manifest.version, `post-${lifecycleType}`, data)); onStderr(data => this.logService.error(extension.identifier.id, extension.manifest.version, `post-${lifecycleType}`, data)); const onOutput = Event.any( Event.map(onStdout, o => ({ data: `%c${o}`, format: [''] })), Event.map(onStderr, o => ({ data: `%c${o}`, format: ['color: red'] })) ); // Debounce all output, so we can render it in the Chrome console as a group const onDebouncedOutput = Event.debounce<Output>(onOutput, (r, o) => { return r ? { data: r.data + o.data, format: [...r.format, ...o.format] } : { data: o.data, format: o.format }; }, 100); // Print out output onDebouncedOutput(data => { console.group(extension.identifier.id); console.log(data.data, ...data.format); console.groupEnd(); }); return extensionUninstallProcess; } private getExtensionStoragePath(extension: ILocalExtension): string { return join(this.environmentService.globalStorageHome.fsPath, extension.identifier.id.toLowerCase()); } }
src/vs/platform/extensionManagement/node/extensionLifecycle.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.0001776439748937264, 0.00017286914226133376, 0.00016516936011612415, 0.00017226627096533775, 0.0000033856085792649537 ]
{ "id": 4, "code_window": [ "export class KeytarCredentialsService implements ICredentialsService {\n", "\n", "\tdeclare readonly _serviceBrand: undefined;\n", "\n", "\tprivate readonly _keytar = new IdleValue<Promise<KeytarModule>>(() => import('keytar'));\n", "\n", "\tasync getPassword(service: string, account: string): Promise<string | null> {\n", "\t\tconst keytar = await this._keytar.value;\n", "\t\treturn keytar.getPassword(service, account);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly _keytar = new IdleValue<Promise<typeof keytar>>(() => import('keytar'));\n" ], "file_path": "src/vs/platform/credentials/node/credentialsService.ts", "type": "replace", "edit_start_line_idx": 13 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as http from 'http'; import * as https from 'https'; import * as tls from 'tls'; import * as nodeurl from 'url'; import * as os from 'os'; import * as fs from 'fs'; import * as cp from 'child_process'; import { assign } from 'vs/base/common/objects'; import { endsWith } from 'vs/base/common/strings'; import { IExtHostWorkspaceProvider } from 'vs/workbench/api/common/extHostWorkspace'; import { ExtHostConfigProvider } from 'vs/workbench/api/common/extHostConfiguration'; import { ProxyAgent } from 'vscode-proxy-agent'; import { MainThreadTelemetryShape, IInitData } from 'vs/workbench/api/common/extHost.protocol'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { ExtHostExtensionService } from 'vs/workbench/api/node/extHostExtensionService'; import { URI } from 'vs/base/common/uri'; import { promisify } from 'util'; import { ILogService } from 'vs/platform/log/common/log'; import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; interface ConnectionResult { proxy: string; connection: string; code: string; count: number; } export function connectProxyResolver( extHostWorkspace: IExtHostWorkspaceProvider, configProvider: ExtHostConfigProvider, extensionService: ExtHostExtensionService, extHostLogService: ILogService, mainThreadTelemetry: MainThreadTelemetryShape, initData: IInitData, ) { const resolveProxy = setupProxyResolution(extHostWorkspace, configProvider, extHostLogService, mainThreadTelemetry, initData); const lookup = createPatchedModules(configProvider, resolveProxy); return configureModuleLoading(extensionService, lookup); } const maxCacheEntries = 5000; // Cache can grow twice that much due to 'oldCache'. function setupProxyResolution( extHostWorkspace: IExtHostWorkspaceProvider, configProvider: ExtHostConfigProvider, extHostLogService: ILogService, mainThreadTelemetry: MainThreadTelemetryShape, initData: IInitData, ) { const env = process.env; let settingsProxy = proxyFromConfigURL(configProvider.getConfiguration('http') .get<string>('proxy')); configProvider.onDidChangeConfiguration(e => { settingsProxy = proxyFromConfigURL(configProvider.getConfiguration('http') .get<string>('proxy')); }); let envProxy = proxyFromConfigURL(env.https_proxy || env.HTTPS_PROXY || env.http_proxy || env.HTTP_PROXY); // Not standardized. let envNoProxy = noProxyFromEnv(env.no_proxy || env.NO_PROXY); // Not standardized. let cacheRolls = 0; let oldCache = new Map<string, string>(); let cache = new Map<string, string>(); function getCacheKey(url: nodeurl.UrlWithStringQuery) { // Expecting proxies to usually be the same per scheme://host:port. Assuming that for performance. return nodeurl.format({ ...url, ...{ pathname: undefined, search: undefined, hash: undefined } }); } function getCachedProxy(key: string) { let proxy = cache.get(key); if (proxy) { return proxy; } proxy = oldCache.get(key); if (proxy) { oldCache.delete(key); cacheProxy(key, proxy); } return proxy; } function cacheProxy(key: string, proxy: string) { cache.set(key, proxy); if (cache.size >= maxCacheEntries) { oldCache = cache; cache = new Map(); cacheRolls++; extHostLogService.trace('ProxyResolver#cacheProxy cacheRolls', cacheRolls); } } let timeout: NodeJS.Timer | undefined; let count = 0; let duration = 0; let errorCount = 0; let cacheCount = 0; let envCount = 0; let settingsCount = 0; let localhostCount = 0; let envNoProxyCount = 0; let results: ConnectionResult[] = []; function logEvent() { timeout = undefined; type ResolveProxyClassification = { count: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; duration: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; errorCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheSize: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; cacheRolls: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; envCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; settingsCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; localhostCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; envNoProxyCount: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', isMeasurement: true }; results: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth' }; }; type ResolveProxyEvent = { count: number; duration: number; errorCount: number; cacheCount: number; cacheSize: number; cacheRolls: number; envCount: number; settingsCount: number; localhostCount: number; envNoProxyCount: number; results: ConnectionResult[]; }; mainThreadTelemetry.$publicLog2<ResolveProxyEvent, ResolveProxyClassification>('resolveProxy', { count, duration, errorCount, cacheCount, cacheSize: cache.size, cacheRolls, envCount, settingsCount, localhostCount, envNoProxyCount, results }); count = duration = errorCount = cacheCount = envCount = settingsCount = localhostCount = envNoProxyCount = 0; results = []; } function resolveProxy(flags: { useProxySettings: boolean, useSystemCertificates: boolean }, req: http.ClientRequest, opts: http.RequestOptions, url: string, callback: (proxy?: string) => void) { if (!timeout) { timeout = setTimeout(logEvent, 10 * 60 * 1000); } const useHostProxy = initData.environment.useHostProxy; const doUseHostProxy = typeof useHostProxy === 'boolean' ? useHostProxy : !initData.remote.isRemote; useSystemCertificates(extHostLogService, flags.useSystemCertificates, opts, () => { useProxySettings(doUseHostProxy, flags.useProxySettings, req, opts, url, callback); }); } function useProxySettings(useHostProxy: boolean, useProxySettings: boolean, req: http.ClientRequest, opts: http.RequestOptions, url: string, callback: (proxy?: string) => void) { if (!useProxySettings) { callback('DIRECT'); return; } const parsedUrl = nodeurl.parse(url); // Coming from Node's URL, sticking with that. const hostname = parsedUrl.hostname; if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' || hostname === '::ffff:127.0.0.1') { localhostCount++; callback('DIRECT'); extHostLogService.trace('ProxyResolver#resolveProxy localhost', url, 'DIRECT'); return; } if (typeof hostname === 'string' && envNoProxy(hostname, String(parsedUrl.port || (<any>opts.agent).defaultPort))) { envNoProxyCount++; callback('DIRECT'); extHostLogService.trace('ProxyResolver#resolveProxy envNoProxy', url, 'DIRECT'); return; } if (settingsProxy) { settingsCount++; callback(settingsProxy); extHostLogService.trace('ProxyResolver#resolveProxy settings', url, settingsProxy); return; } if (envProxy) { envCount++; callback(envProxy); extHostLogService.trace('ProxyResolver#resolveProxy env', url, envProxy); return; } const key = getCacheKey(parsedUrl); const proxy = getCachedProxy(key); if (proxy) { cacheCount++; collectResult(results, proxy, parsedUrl.protocol === 'https:' ? 'HTTPS' : 'HTTP', req); callback(proxy); extHostLogService.trace('ProxyResolver#resolveProxy cached', url, proxy); return; } if (!useHostProxy) { callback('DIRECT'); extHostLogService.trace('ProxyResolver#resolveProxy unconfigured', url, 'DIRECT'); return; } const start = Date.now(); extHostWorkspace.resolveProxy(url) // Use full URL to ensure it is an actually used one. .then(proxy => { if (proxy) { cacheProxy(key, proxy); collectResult(results, proxy, parsedUrl.protocol === 'https:' ? 'HTTPS' : 'HTTP', req); } callback(proxy); extHostLogService.debug('ProxyResolver#resolveProxy', url, proxy); }).then(() => { count++; duration = Date.now() - start + duration; }, err => { errorCount++; callback(); extHostLogService.error('ProxyResolver#resolveProxy', toErrorMessage(err)); }); } return resolveProxy; } function collectResult(results: ConnectionResult[], resolveProxy: string, connection: string, req: http.ClientRequest) { const proxy = resolveProxy ? String(resolveProxy).trim().split(/\s+/, 1)[0] : 'EMPTY'; req.on('response', res => { const code = `HTTP_${res.statusCode}`; const result = findOrCreateResult(results, proxy, connection, code); result.count++; }); req.on('error', err => { const code = err && typeof (<any>err).code === 'string' && (<any>err).code || 'UNKNOWN_ERROR'; const result = findOrCreateResult(results, proxy, connection, code); result.count++; }); } function findOrCreateResult(results: ConnectionResult[], proxy: string, connection: string, code: string): ConnectionResult { for (const result of results) { if (result.proxy === proxy && result.connection === connection && result.code === code) { return result; } } const result = { proxy, connection, code, count: 0 }; results.push(result); return result; } function proxyFromConfigURL(configURL: string | undefined) { const url = (configURL || '').trim(); const i = url.indexOf('://'); if (i === -1) { return undefined; } const scheme = url.substr(0, i).toLowerCase(); const proxy = url.substr(i + 3); if (scheme === 'http') { return 'PROXY ' + proxy; } else if (scheme === 'https') { return 'HTTPS ' + proxy; } else if (scheme === 'socks') { return 'SOCKS ' + proxy; } return undefined; } function noProxyFromEnv(envValue?: string) { const value = (envValue || '') .trim() .toLowerCase(); if (value === '*') { return () => true; } const filters = value .split(',') .map(s => s.trim().split(':', 2)) .map(([name, port]) => ({ name, port })) .filter(filter => !!filter.name) .map(({ name, port }) => { const domain = name[0] === '.' ? name : `.${name}`; return { domain, port }; }); if (!filters.length) { return () => false; } return (hostname: string, port: string) => filters.some(({ domain, port: filterPort }) => { return endsWith(`.${hostname.toLowerCase()}`, domain) && (!filterPort || port === filterPort); }); } function createPatchedModules(configProvider: ExtHostConfigProvider, resolveProxy: ReturnType<typeof setupProxyResolution>) { const proxySetting = { config: configProvider.getConfiguration('http') .get<string>('proxySupport') || 'off' }; configProvider.onDidChangeConfiguration(e => { proxySetting.config = configProvider.getConfiguration('http') .get<string>('proxySupport') || 'off'; }); const certSetting = { config: !!configProvider.getConfiguration('http') .get<boolean>('systemCertificates') }; configProvider.onDidChangeConfiguration(e => { certSetting.config = !!configProvider.getConfiguration('http') .get<boolean>('systemCertificates'); }); return { http: { off: assign({}, http, patches(http, resolveProxy, { config: 'off' }, certSetting, true)), on: assign({}, http, patches(http, resolveProxy, { config: 'on' }, certSetting, true)), override: assign({}, http, patches(http, resolveProxy, { config: 'override' }, certSetting, true)), onRequest: assign({}, http, patches(http, resolveProxy, proxySetting, certSetting, true)), default: assign(http, patches(http, resolveProxy, proxySetting, certSetting, false)) // run last } as Record<string, typeof http>, https: { off: assign({}, https, patches(https, resolveProxy, { config: 'off' }, certSetting, true)), on: assign({}, https, patches(https, resolveProxy, { config: 'on' }, certSetting, true)), override: assign({}, https, patches(https, resolveProxy, { config: 'override' }, certSetting, true)), onRequest: assign({}, https, patches(https, resolveProxy, proxySetting, certSetting, true)), default: assign(https, patches(https, resolveProxy, proxySetting, certSetting, false)) // run last } as Record<string, typeof https>, tls: assign(tls, tlsPatches(tls)) }; } function patches(originals: typeof http | typeof https, resolveProxy: ReturnType<typeof setupProxyResolution>, proxySetting: { config: string }, certSetting: { config: boolean }, onRequest: boolean) { return { get: patch(originals.get), request: patch(originals.request) }; function patch(original: typeof http.get) { function patched(url?: string | URL | null, options?: http.RequestOptions | null, callback?: (res: http.IncomingMessage) => void): http.ClientRequest { if (typeof url !== 'string' && !(url && (<any>url).searchParams)) { callback = <any>options; options = url; url = null; } if (typeof options === 'function') { callback = options; options = null; } options = options || {}; if (options.socketPath) { return original.apply(null, arguments as any); } const originalAgent = options.agent; if (originalAgent === true) { throw new Error('Unexpected agent option: true'); } const optionsPatched = originalAgent instanceof ProxyAgent; const config = onRequest && ((<any>options)._vscodeProxySupport || /* LS */ (<any>options)._vscodeSystemProxy) || proxySetting.config; const useProxySettings = !optionsPatched && (config === 'override' || config === 'on' && originalAgent === undefined); const useSystemCertificates = !optionsPatched && certSetting.config && originals === https && !(options as https.RequestOptions).ca; if (useProxySettings || useSystemCertificates) { if (url) { const parsed = typeof url === 'string' ? new nodeurl.URL(url) : url; const urlOptions = { protocol: parsed.protocol, hostname: parsed.hostname.lastIndexOf('[', 0) === 0 ? parsed.hostname.slice(1, -1) : parsed.hostname, port: parsed.port, path: `${parsed.pathname}${parsed.search}` }; if (parsed.username || parsed.password) { options.auth = `${parsed.username}:${parsed.password}`; } options = { ...urlOptions, ...options }; } else { options = { ...options }; } options.agent = new ProxyAgent({ resolveProxy: resolveProxy.bind(undefined, { useProxySettings, useSystemCertificates }), defaultPort: originals === https ? 443 : 80, originalAgent }); return original(options, callback); } return original.apply(null, arguments as any); } return patched; } } function tlsPatches(originals: typeof tls) { return { createSecureContext: patch(originals.createSecureContext) }; function patch(original: typeof tls.createSecureContext): typeof tls.createSecureContext { return function (details: tls.SecureContextOptions): ReturnType<typeof tls.createSecureContext> { const context = original.apply(null, arguments as any); const certs = (details as any)._vscodeAdditionalCaCerts; if (certs) { for (const cert of certs) { context.context.addCACert(cert); } } return context; }; } } const modulesCache = new Map<IExtensionDescription | undefined, { http?: typeof http, https?: typeof https }>(); function configureModuleLoading(extensionService: ExtHostExtensionService, lookup: ReturnType<typeof createPatchedModules>): Promise<void> { return extensionService.getExtensionPathIndex() .then(extensionPaths => { const node_module = <any>require.__$__nodeRequire('module'); const original = node_module._load; node_module._load = function load(request: string, parent: any, isMain: any) { if (request === 'tls') { return lookup.tls; } if (request !== 'http' && request !== 'https') { return original.apply(this, arguments); } const modules = lookup[request]; const ext = extensionPaths.findSubstr(URI.file(parent.filename).fsPath); let cache = modulesCache.get(ext); if (!cache) { modulesCache.set(ext, cache = {}); } if (!cache[request]) { let mod = modules.default; if (ext && ext.enableProposedApi) { mod = (modules as any)[(<any>ext).proxySupport] || modules.onRequest; } cache[request] = <any>{ ...mod }; // Copy to work around #93167. } return cache[request]; }; }); } function useSystemCertificates(extHostLogService: ILogService, useSystemCertificates: boolean, opts: http.RequestOptions, callback: () => void) { if (useSystemCertificates) { getCaCertificates(extHostLogService) .then(caCertificates => { if (caCertificates) { if (caCertificates.append) { (opts as any)._vscodeAdditionalCaCerts = caCertificates.certs; } else { (opts as https.RequestOptions).ca = caCertificates.certs; } } callback(); }) .catch(err => { extHostLogService.error('ProxyResolver#useSystemCertificates', toErrorMessage(err)); }); } else { callback(); } } let _caCertificates: ReturnType<typeof readCaCertificates> | Promise<undefined>; async function getCaCertificates(extHostLogService: ILogService) { if (!_caCertificates) { _caCertificates = readCaCertificates() .then(res => res && res.certs.length ? res : undefined) .catch(err => { extHostLogService.error('ProxyResolver#getCertificates', toErrorMessage(err)); return undefined; }); } return _caCertificates; } async function readCaCertificates() { if (process.platform === 'win32') { return readWindowsCaCertificates(); } if (process.platform === 'darwin') { return readMacCaCertificates(); } if (process.platform === 'linux') { return readLinuxCaCertificates(); } return undefined; } async function readWindowsCaCertificates() { const winCA = await new Promise<any>((resolve, reject) => { require(['vscode-windows-ca-certs'], resolve, reject); }); let ders: any[] = []; const store = winCA(); try { let der: any; while (der = store.next()) { ders.push(der); } } finally { store.done(); } const certs = new Set(ders.map(derToPem)); return { certs: Array.from(certs), append: true }; } async function readMacCaCertificates() { const stdout = await new Promise<string>((resolve, reject) => { const child = cp.spawn('/usr/bin/security', ['find-certificate', '-a', '-p']); const stdout: string[] = []; child.stdout.setEncoding('utf8'); child.stdout.on('data', str => stdout.push(str)); child.on('error', reject); child.on('exit', code => code ? reject(code) : resolve(stdout.join(''))); }); const certs = new Set(stdout.split(/(?=-----BEGIN CERTIFICATE-----)/g) .filter(pem => !!pem.length)); return { certs: Array.from(certs), append: true }; } const linuxCaCertificatePaths = [ '/etc/ssl/certs/ca-certificates.crt', '/etc/ssl/certs/ca-bundle.crt', ]; async function readLinuxCaCertificates() { for (const certPath of linuxCaCertificatePaths) { try { const content = await promisify(fs.readFile)(certPath, { encoding: 'utf8' }); const certs = new Set(content.split(/(?=-----BEGIN CERTIFICATE-----)/g) .filter(pem => !!pem.length)); return { certs: Array.from(certs), append: false }; } catch (err) { if (err.code !== 'ENOENT') { throw err; } } } return undefined; } function derToPem(blob: Buffer) { const lines = ['-----BEGIN CERTIFICATE-----']; const der = blob.toString('base64'); for (let i = 0; i < der.length; i += 64) { lines.push(der.substr(i, 64)); } lines.push('-----END CERTIFICATE-----', ''); return lines.join(os.EOL); }
src/vs/workbench/services/extensions/node/proxyResolver.ts
1
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00022202903346624225, 0.00017217562708538026, 0.0001650563208386302, 0.0001707654446363449, 0.000007298056061699754 ]
{ "id": 4, "code_window": [ "export class KeytarCredentialsService implements ICredentialsService {\n", "\n", "\tdeclare readonly _serviceBrand: undefined;\n", "\n", "\tprivate readonly _keytar = new IdleValue<Promise<KeytarModule>>(() => import('keytar'));\n", "\n", "\tasync getPassword(service: string, account: string): Promise<string | null> {\n", "\t\tconst keytar = await this._keytar.value;\n", "\t\treturn keytar.getPassword(service, account);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly _keytar = new IdleValue<Promise<typeof keytar>>(() => import('keytar'));\n" ], "file_path": "src/vs/platform/credentials/node/credentialsService.ts", "type": "replace", "edit_start_line_idx": 13 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Position } from 'vs/editor/common/core/position'; import { Selection } from 'vs/editor/common/core/selection'; /** * Describes the reason the cursor has changed its position. */ export const enum CursorChangeReason { /** * Unknown or not set. */ NotSet = 0, /** * A `model.setValue()` was called. */ ContentFlush = 1, /** * The `model` has been changed outside of this cursor and the cursor recovers its position from associated markers. */ RecoverFromMarkers = 2, /** * There was an explicit user gesture. */ Explicit = 3, /** * There was a Paste. */ Paste = 4, /** * There was an Undo. */ Undo = 5, /** * There was a Redo. */ Redo = 6, } /** * An event describing that the cursor position has changed. */ export interface ICursorPositionChangedEvent { /** * Primary cursor's position. */ readonly position: Position; /** * Secondary cursors' position. */ readonly secondaryPositions: Position[]; /** * Reason. */ readonly reason: CursorChangeReason; /** * Source of the call that caused the event. */ readonly source: string; } /** * An event describing that the cursor selection has changed. */ export interface ICursorSelectionChangedEvent { /** * The primary selection. */ readonly selection: Selection; /** * The secondary selections. */ readonly secondarySelections: Selection[]; /** * The model version id. */ readonly modelVersionId: number; /** * The old selections. */ readonly oldSelections: Selection[] | null; /** * The model version id the that `oldSelections` refer to. */ readonly oldModelVersionId: number; /** * Source of the call that caused the event. */ readonly source: string; /** * Reason. */ readonly reason: CursorChangeReason; }
src/vs/editor/common/controller/cursorEvents.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017802110232878476, 0.00017473040497861803, 0.00017054250929504633, 0.0001746145135257393, 0.0000019768076526816003 ]
{ "id": 4, "code_window": [ "export class KeytarCredentialsService implements ICredentialsService {\n", "\n", "\tdeclare readonly _serviceBrand: undefined;\n", "\n", "\tprivate readonly _keytar = new IdleValue<Promise<KeytarModule>>(() => import('keytar'));\n", "\n", "\tasync getPassword(service: string, account: string): Promise<string | null> {\n", "\t\tconst keytar = await this._keytar.value;\n", "\t\treturn keytar.getPassword(service, account);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly _keytar = new IdleValue<Promise<typeof keytar>>(() => import('keytar'));\n" ], "file_path": "src/vs/platform/credentials/node/credentialsService.ts", "type": "replace", "edit_start_line_idx": 13 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Uri } from 'vscode'; export interface GitUriParams { path: string; ref: string; submoduleOf?: string; } export function isGitUri(uri: Uri): boolean { return /^git$/.test(uri.scheme); } export function fromGitUri(uri: Uri): GitUriParams { return JSON.parse(uri.query); } export interface GitUriOptions { replaceFileExtension?: boolean; submoduleOf?: string; } // As a mitigation for extensions like ESLint showing warnings and errors // for git URIs, let's change the file extension of these uris to .git, // when `replaceFileExtension` is true. export function toGitUri(uri: Uri, ref: string, options: GitUriOptions = {}): Uri { const params: GitUriParams = { path: uri.fsPath, ref }; if (options.submoduleOf) { params.submoduleOf = options.submoduleOf; } let path = uri.path; if (options.replaceFileExtension) { path = `${path}.git`; } else if (options.submoduleOf) { path = `${path}.diff`; } return uri.with({ scheme: 'git', path, query: JSON.stringify(params) }); }
extensions/git/src/uri.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017682537145446986, 0.00017435890913475305, 0.00017199281137436628, 0.00017362108337692916, 0.0000017953632323042257 ]
{ "id": 4, "code_window": [ "export class KeytarCredentialsService implements ICredentialsService {\n", "\n", "\tdeclare readonly _serviceBrand: undefined;\n", "\n", "\tprivate readonly _keytar = new IdleValue<Promise<KeytarModule>>(() => import('keytar'));\n", "\n", "\tasync getPassword(service: string, account: string): Promise<string | null> {\n", "\t\tconst keytar = await this._keytar.value;\n", "\t\treturn keytar.getPassword(service, account);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly _keytar = new IdleValue<Promise<typeof keytar>>(() => import('keytar'));\n" ], "file_path": "src/vs/platform/credentials/node/credentialsService.ts", "type": "replace", "edit_start_line_idx": 13 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { spawn } from 'child_process'; import { generateUuid } from 'vs/base/common/uuid'; import { isWindows } from 'vs/base/common/platform'; import { ILogService } from 'vs/platform/log/common/log'; import { INativeEnvironmentService } from 'vs/platform/environment/node/environmentService'; function getUnixShellEnvironment(logService: ILogService): Promise<typeof process.env> { const promise = new Promise<typeof process.env>((resolve, reject) => { const runAsNode = process.env['ELECTRON_RUN_AS_NODE']; logService.trace('getUnixShellEnvironment#runAsNode', runAsNode); const noAttach = process.env['ELECTRON_NO_ATTACH_CONSOLE']; logService.trace('getUnixShellEnvironment#noAttach', noAttach); const mark = generateUuid().replace(/-/g, '').substr(0, 12); const regex = new RegExp(mark + '(.*)' + mark); const env = { ...process.env, ELECTRON_RUN_AS_NODE: '1', ELECTRON_NO_ATTACH_CONSOLE: '1' }; const command = `'${process.execPath}' -p '"${mark}" + JSON.stringify(process.env) + "${mark}"'`; logService.trace('getUnixShellEnvironment#env', env); logService.trace('getUnixShellEnvironment#spawn', command); const child = spawn(process.env.SHELL!, ['-ilc', command], { detached: true, stdio: ['ignore', 'pipe', process.stderr], env }); const buffers: Buffer[] = []; child.on('error', () => resolve({})); child.stdout.on('data', b => buffers.push(b)); child.on('close', code => { if (code !== 0) { return reject(new Error('Failed to get environment')); } const raw = Buffer.concat(buffers).toString('utf8'); logService.trace('getUnixShellEnvironment#raw', raw); const match = regex.exec(raw); const rawStripped = match ? match[1] : '{}'; try { const env = JSON.parse(rawStripped); if (runAsNode) { env['ELECTRON_RUN_AS_NODE'] = runAsNode; } else { delete env['ELECTRON_RUN_AS_NODE']; } if (noAttach) { env['ELECTRON_NO_ATTACH_CONSOLE'] = noAttach; } else { delete env['ELECTRON_NO_ATTACH_CONSOLE']; } // https://github.com/Microsoft/vscode/issues/22593#issuecomment-336050758 delete env['XDG_RUNTIME_DIR']; logService.trace('getUnixShellEnvironment#result', env); resolve(env); } catch (err) { logService.error('getUnixShellEnvironment#error', err); reject(err); } }); }); // swallow errors return promise.catch(() => ({})); } let shellEnvPromise: Promise<typeof process.env> | undefined = undefined; /** * We need to get the environment from a user's shell. * This should only be done when Code itself is not launched * from within a shell. */ export function getShellEnvironment(logService: ILogService, environmentService: INativeEnvironmentService): Promise<typeof process.env> { if (!shellEnvPromise) { if (environmentService.args['disable-user-env-probe']) { logService.trace('getShellEnvironment: disable-user-env-probe set, skipping'); shellEnvPromise = Promise.resolve({}); } else if (isWindows) { logService.trace('getShellEnvironment: running on Windows, skipping'); shellEnvPromise = Promise.resolve({}); } else if (process.env['VSCODE_CLI'] === '1' && process.env['VSCODE_FORCE_USER_ENV'] !== '1') { logService.trace('getShellEnvironment: running on CLI, skipping'); shellEnvPromise = Promise.resolve({}); } else { logService.trace('getShellEnvironment: running on Unix'); shellEnvPromise = getUnixShellEnvironment(logService); } } return shellEnvPromise; }
src/vs/code/node/shellEnv.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.0001823130587581545, 0.00017138950352091342, 0.00016585887351538986, 0.00017080501129385084, 0.00000464454069515341 ]
{ "id": 5, "code_window": [ "\t\t@IUpdateService updateService: IUpdateService,\n", "\t\t@IStorageService storageService: IStorageService,\n", "\t\t@INotificationService notificationService: INotificationService,\n", "\t\t@IPreferencesService preferencesService: IPreferencesService,\n", "\t\t@IWorkbenchEnvironmentService protected readonly environmentService: INativeWorkbenchEnvironmentService,\n", "\t\t@IAccessibilityService accessibilityService: IAccessibilityService,\n", "\t\t@IMenubarService private readonly menubarService: IMenubarService,\n", "\t\t@IHostService hostService: IHostService,\n", "\t\t@IElectronService private readonly electronService: IElectronService\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t@IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService,\n" ], "file_path": "src/vs/workbench/electron-browser/window.ts", "type": "replace", "edit_start_line_idx": 612 }
/*--------------------------------------------------------------------------------------------- * 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 { URI } from 'vs/base/common/uri'; import * as errors from 'vs/base/common/errors'; import { equals } from 'vs/base/common/objects'; import * as DOM from 'vs/base/browser/dom'; import { IAction, Separator } from 'vs/base/common/actions'; import { IFileService } from 'vs/platform/files/common/files'; import { toResource, IUntitledTextResourceEditorInput, SideBySideEditor, pathsToEditors } from 'vs/workbench/common/editor'; import { IEditorService, IResourceEditorInputType } from 'vs/workbench/services/editor/common/editorService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IOpenFileRequest, IWindowsConfiguration, getTitleBarStyle, IAddFoldersRequest, IDesktopRunActionInWindowRequest, IDesktopRunKeybindingInWindowRequest, IDesktopOpenFileRequest } from 'vs/platform/windows/common/windows'; import { ITitleService } from 'vs/workbench/services/title/common/titleService'; import { IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { applyZoom } from 'vs/platform/windows/electron-sandbox/window'; import { setFullscreen, getZoomLevel } from 'vs/base/browser/browser'; import { ICommandService, CommandsRegistry } from 'vs/platform/commands/common/commands'; import { IResourceEditorInput } from 'vs/platform/editor/common/editor'; import { KeyboardMapperFactory } from 'vs/workbench/services/keybinding/electron-browser/nativeKeymapService'; import { ipcRenderer } from 'vs/base/parts/sandbox/electron-sandbox/globals'; import { IWorkspaceEditingService } from 'vs/workbench/services/workspaces/common/workspaceEditing'; import { IMenuService, MenuId, IMenu, MenuItemAction, ICommandAction, SubmenuItemAction, MenuRegistry } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { RunOnceScheduler } from 'vs/base/common/async'; import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { LifecyclePhase, ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IWorkspaceFolderCreationData, IWorkspacesService } from 'vs/platform/workspaces/common/workspaces'; import { IIntegrityService } from 'vs/workbench/services/integrity/common/integrity'; import { isWindows, isMacintosh } from 'vs/base/common/platform'; import { IProductService } from 'vs/platform/product/common/productService'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { WorkbenchState, IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { coalesce } from 'vs/base/common/arrays'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { MenubarControl } from '../browser/parts/titlebar/menubarControl'; import { ILabelService } from 'vs/platform/label/common/label'; import { IUpdateService } from 'vs/platform/update/common/update'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IPreferencesService } from '../services/preferences/common/preferences'; import { IMenubarData, IMenubarMenu, IMenubarKeybinding, IMenubarMenuItemSubmenu, IMenubarMenuItemAction, MenubarMenuItem } from 'vs/platform/menubar/common/menubar'; import { IMenubarService } from 'vs/platform/menubar/electron-sandbox/menubar'; import { withNullAsUndefined, assertIsDefined } from 'vs/base/common/types'; import { IOpenerService, OpenOptions } from 'vs/platform/opener/common/opener'; import { Schemas } from 'vs/base/common/network'; import { IElectronService } from 'vs/platform/electron/electron-sandbox/electron'; import { posix, dirname } from 'vs/base/common/path'; import { getBaseLabel } from 'vs/base/common/labels'; import { ITunnelService, extractLocalHostUriMetaDataForPortMapping } from 'vs/platform/remote/common/tunnel'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { IWorkingCopyService, WorkingCopyCapabilities } from 'vs/workbench/services/workingCopy/common/workingCopyService'; import { AutoSaveMode, IFilesConfigurationService } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService'; import { Event } from 'vs/base/common/event'; import { INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-browser/environmentService'; import { clearAllFontInfos } from 'vs/editor/browser/config/configuration'; import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver'; import { IAddressProvider, IAddress } from 'vs/platform/remote/common/remoteAgentConnection'; export class NativeWindow extends Disposable { private touchBarMenu: IMenu | undefined; private readonly touchBarDisposables = this._register(new DisposableStore()); private lastInstalledTouchedBar: ICommandAction[][] | undefined; private readonly customTitleContextMenuDisposable = this._register(new DisposableStore()); private previousConfiguredZoomLevel: number | undefined; private readonly addFoldersScheduler = this._register(new RunOnceScheduler(() => this.doAddFolders(), 100)); private pendingFoldersToAdd: URI[] = []; private readonly closeEmptyWindowScheduler = this._register(new RunOnceScheduler(() => this.onAllEditorsClosed(), 50)); private isDocumentedEdited = false; constructor( @IEditorService private readonly editorService: IEditorService, @IConfigurationService private readonly configurationService: IConfigurationService, @ITitleService private readonly titleService: ITitleService, @IWorkbenchThemeService protected themeService: IWorkbenchThemeService, @INotificationService private readonly notificationService: INotificationService, @ICommandService private readonly commandService: ICommandService, @IKeybindingService private readonly keybindingService: IKeybindingService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IWorkspaceEditingService private readonly workspaceEditingService: IWorkspaceEditingService, @IFileService private readonly fileService: IFileService, @IMenuService private readonly menuService: IMenuService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IIntegrityService private readonly integrityService: IIntegrityService, @IWorkbenchEnvironmentService private readonly environmentService: INativeWorkbenchEnvironmentService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IOpenerService private readonly openerService: IOpenerService, @IElectronService private readonly electronService: IElectronService, @ITunnelService private readonly tunnelService: ITunnelService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @IWorkingCopyService private readonly workingCopyService: IWorkingCopyService, @IFilesConfigurationService private readonly filesConfigurationService: IFilesConfigurationService, @IProductService private readonly productService: IProductService, @IRemoteAuthorityResolverService private readonly remoteAuthorityResolverService: IRemoteAuthorityResolverService ) { super(); this.registerListeners(); this.create(); } private registerListeners(): void { // React to editor input changes this._register(this.editorService.onDidActiveEditorChange(() => this.updateTouchbarMenu())); // prevent opening a real URL inside the shell [DOM.EventType.DRAG_OVER, DOM.EventType.DROP].forEach(event => { window.document.body.addEventListener(event, (e: DragEvent) => { DOM.EventHelper.stop(e); }); }); // Support runAction event ipcRenderer.on('vscode:runAction', async (event: unknown, request: IDesktopRunActionInWindowRequest) => { const args: unknown[] = request.args || []; // If we run an action from the touchbar, we fill in the currently active resource // as payload because the touch bar items are context aware depending on the editor if (request.from === 'touchbar') { const activeEditor = this.editorService.activeEditor; if (activeEditor) { const resource = toResource(activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY }); if (resource) { args.push(resource); } } } else { args.push({ from: request.from }); } try { await this.commandService.executeCommand(request.id, ...args); type CommandExecutedClassifcation = { id: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; from: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; }; this.telemetryService.publicLog2<{ id: String, from: String }, CommandExecutedClassifcation>('commandExecuted', { id: request.id, from: request.from }); } catch (error) { this.notificationService.error(error); } }); // Support runKeybinding event ipcRenderer.on('vscode:runKeybinding', (event: unknown, request: IDesktopRunKeybindingInWindowRequest) => { if (document.activeElement) { this.keybindingService.dispatchByUserSettingsLabel(request.userSettingsLabel, document.activeElement); } }); // Error reporting from main ipcRenderer.on('vscode:reportError', (event: unknown, error: string) => { if (error) { errors.onUnexpectedError(JSON.parse(error)); } }); // Support openFiles event for existing and new files ipcRenderer.on('vscode:openFiles', (event: unknown, request: IOpenFileRequest) => this.onOpenFiles(request)); // Support addFolders event if we have a workspace opened ipcRenderer.on('vscode:addFolders', (event: unknown, request: IAddFoldersRequest) => this.onAddFoldersRequest(request)); // Message support ipcRenderer.on('vscode:showInfoMessage', (event: unknown, message: string) => { this.notificationService.info(message); }); // Display change events ipcRenderer.on('vscode:displayChanged', () => { clearAllFontInfos(); }); // Fullscreen Events ipcRenderer.on('vscode:enterFullScreen', async () => { await this.lifecycleService.when(LifecyclePhase.Ready); setFullscreen(true); }); ipcRenderer.on('vscode:leaveFullScreen', async () => { await this.lifecycleService.when(LifecyclePhase.Ready); setFullscreen(false); }); // High Contrast Events ipcRenderer.on('vscode:enterHighContrast', async () => { await this.lifecycleService.when(LifecyclePhase.Ready); this.themeService.setOSHighContrast(true); }); ipcRenderer.on('vscode:leaveHighContrast', async () => { await this.lifecycleService.when(LifecyclePhase.Ready); this.themeService.setOSHighContrast(false); }); // keyboard layout changed event ipcRenderer.on('vscode:keyboardLayoutChanged', () => { KeyboardMapperFactory.INSTANCE._onKeyboardLayoutChanged(); }); // accessibility support changed event ipcRenderer.on('vscode:accessibilitySupportChanged', (event: unknown, accessibilitySupportEnabled: boolean) => { this.accessibilityService.setAccessibilitySupport(accessibilitySupportEnabled ? AccessibilitySupport.Enabled : AccessibilitySupport.Disabled); }); // Zoom level changes this.updateWindowZoomLevel(); this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('window.zoomLevel')) { this.updateWindowZoomLevel(); } else if (e.affectsConfiguration('keyboard.touchbar.enabled') || e.affectsConfiguration('keyboard.touchbar.ignored')) { this.updateTouchbarMenu(); } })); // Listen to visible editor changes this._register(this.editorService.onDidVisibleEditorsChange(() => this.onDidVisibleEditorsChange())); // Listen to editor closing (if we run with --wait) const filesToWait = this.environmentService.configuration.filesToWait; if (filesToWait) { this.trackClosedWaitFiles(filesToWait.waitMarkerFileUri, coalesce(filesToWait.paths.map(path => path.fileUri))); } // macOS OS integration if (isMacintosh) { this._register(this.editorService.onDidActiveEditorChange(() => { const file = toResource(this.editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY, filterByScheme: Schemas.file }); // Represented Filename this.updateRepresentedFilename(file?.fsPath); // Custom title menu this.provideCustomTitleContextMenu(file?.fsPath); })); } // Maximize/Restore on doubleclick (for macOS custom title) if (isMacintosh && getTitleBarStyle(this.configurationService, this.environmentService) === 'custom') { const titlePart = assertIsDefined(this.layoutService.getContainer(Parts.TITLEBAR_PART)); this._register(DOM.addDisposableListener(titlePart, DOM.EventType.DBLCLICK, e => { DOM.EventHelper.stop(e); this.electronService.handleTitleDoubleClick(); })); } // Document edited: indicate for dirty working copies this._register(this.workingCopyService.onDidChangeDirty(workingCopy => { const gotDirty = workingCopy.isDirty(); if (gotDirty && !(workingCopy.capabilities & WorkingCopyCapabilities.Untitled) && this.filesConfigurationService.getAutoSaveMode() === AutoSaveMode.AFTER_SHORT_DELAY) { return; // do not indicate dirty of working copies that are auto saved after short delay } this.updateDocumentEdited(gotDirty); })); this.updateDocumentEdited(); // Detect minimize / maximize this._register(Event.any( Event.map(Event.filter(this.electronService.onWindowMaximize, id => id === this.electronService.windowId), () => true), Event.map(Event.filter(this.electronService.onWindowUnmaximize, id => id === this.electronService.windowId), () => false) )(e => this.onDidChangeMaximized(e))); this.onDidChangeMaximized(this.environmentService.configuration.maximized ?? false); } private updateDocumentEdited(isDirty = this.workingCopyService.hasDirty): void { if ((!this.isDocumentedEdited && isDirty) || (this.isDocumentedEdited && !isDirty)) { this.isDocumentedEdited = isDirty; this.electronService.setDocumentEdited(isDirty); } } private onDidChangeMaximized(maximized: boolean): void { this.layoutService.updateWindowMaximizedState(maximized); } private onDidVisibleEditorsChange(): void { // Close when empty: check if we should close the window based on the setting // Overruled by: window has a workspace opened or this window is for extension development // or setting is disabled. Also enabled when running with --wait from the command line. const visibleEditorPanes = this.editorService.visibleEditorPanes; if (visibleEditorPanes.length === 0 && this.contextService.getWorkbenchState() === WorkbenchState.EMPTY && !this.environmentService.isExtensionDevelopment) { const closeWhenEmpty = this.configurationService.getValue<boolean>('window.closeWhenEmpty'); if (closeWhenEmpty || this.environmentService.args.wait) { this.closeEmptyWindowScheduler.schedule(); } } } private onAllEditorsClosed(): void { const visibleEditorPanes = this.editorService.visibleEditorPanes.length; if (visibleEditorPanes === 0) { this.electronService.closeWindow(); } } private updateWindowZoomLevel(): void { const windowConfig = this.configurationService.getValue<IWindowsConfiguration>(); let configuredZoomLevel = 0; if (windowConfig.window && typeof windowConfig.window.zoomLevel === 'number') { configuredZoomLevel = windowConfig.window.zoomLevel; // Leave early if the configured zoom level did not change (https://github.com/Microsoft/vscode/issues/1536) if (this.previousConfiguredZoomLevel === configuredZoomLevel) { return; } this.previousConfiguredZoomLevel = configuredZoomLevel; } if (getZoomLevel() !== configuredZoomLevel) { applyZoom(configuredZoomLevel); } } private updateRepresentedFilename(filePath: string | undefined): void { this.electronService.setRepresentedFilename(filePath ? filePath : ''); } private provideCustomTitleContextMenu(filePath: string | undefined): void { // Clear old menu this.customTitleContextMenuDisposable.clear(); // Provide new menu if a file is opened and we are on a custom title if (!filePath || getTitleBarStyle(this.configurationService, this.environmentService) !== 'custom') { return; } // Split up filepath into segments const segments = filePath.split(posix.sep); for (let i = segments.length; i > 0; i--) { const isFile = (i === segments.length); let pathOffset = i; if (!isFile) { pathOffset++; // for segments which are not the file name we want to open the folder } const path = segments.slice(0, pathOffset).join(posix.sep); let label: string; if (!isFile) { label = getBaseLabel(dirname(path)); } else { label = getBaseLabel(path); } const commandId = `workbench.action.revealPathInFinder${i}`; this.customTitleContextMenuDisposable.add(CommandsRegistry.registerCommand(commandId, () => this.electronService.showItemInFolder(path))); this.customTitleContextMenuDisposable.add(MenuRegistry.appendMenuItem(MenuId.TitleBarContext, { command: { id: commandId, title: label || posix.sep }, order: -i })); } } private create(): void { // Native menu controller if (isMacintosh || getTitleBarStyle(this.configurationService, this.environmentService) === 'native') { this._register(this.instantiationService.createInstance(NativeMenubarControl)); } // Handle open calls this.setupOpenHandlers(); // Notify main side when window ready this.lifecycleService.when(LifecyclePhase.Ready).then(() => this.electronService.notifyReady()); // Integrity warning this.integrityService.isPure().then(res => this.titleService.updateProperties({ isPure: res.isPure })); // Root warning this.lifecycleService.when(LifecyclePhase.Restored).then(async () => { const isAdmin = await this.electronService.isAdmin(); // Update title this.titleService.updateProperties({ isAdmin }); // Show warning message (unix only) if (isAdmin && !isWindows) { this.notificationService.warn(nls.localize('runningAsRoot', "It is not recommended to run {0} as root user.", this.productService.nameShort)); } }); // Touchbar menu (if enabled) this.updateTouchbarMenu(); } private setupOpenHandlers(): void { // Block window.open() calls window.open = function (): Window | null { throw new Error('Prevented call to window.open(). Use IOpenerService instead!'); }; // Handle external open() calls this.openerService.setExternalOpener({ openExternal: async (href: string) => { const success = await this.electronService.openExternal(href); if (!success) { const fileCandidate = URI.parse(href); if (fileCandidate.scheme === Schemas.file) { // if opening failed, and this is a file, we can still try to reveal it await this.electronService.showItemInFolder(fileCandidate.fsPath); } } return true; } }); // Register external URI resolver this.openerService.registerExternalUriResolver({ resolveExternalUri: async (uri: URI, options?: OpenOptions) => { if (options?.allowTunneling) { const portMappingRequest = extractLocalHostUriMetaDataForPortMapping(uri); if (portMappingRequest) { const remoteAuthority = this.environmentService.configuration.remoteAuthority; const addressProvider: IAddressProvider | undefined = remoteAuthority ? { getAddress: async (): Promise<IAddress> => { return (await this.remoteAuthorityResolverService.resolveAuthority(remoteAuthority)).authority; } } : undefined; const tunnel = await this.tunnelService.openTunnel(addressProvider, portMappingRequest.address, portMappingRequest.port); if (tunnel) { return { resolved: uri.with({ authority: tunnel.localAddress }), dispose: () => tunnel.dispose(), }; } } } return undefined; } }); } private updateTouchbarMenu(): void { if (!isMacintosh) { return; // macOS only } // Dispose old this.touchBarDisposables.clear(); this.touchBarMenu = undefined; // Create new (delayed) const scheduler: RunOnceScheduler = this.touchBarDisposables.add(new RunOnceScheduler(() => this.doUpdateTouchbarMenu(scheduler), 300)); scheduler.schedule(); } private doUpdateTouchbarMenu(scheduler: RunOnceScheduler): void { if (!this.touchBarMenu) { this.touchBarMenu = this.editorService.invokeWithinEditorContext(accessor => this.menuService.createMenu(MenuId.TouchBarContext, accessor.get(IContextKeyService))); this.touchBarDisposables.add(this.touchBarMenu); this.touchBarDisposables.add(this.touchBarMenu.onDidChange(() => scheduler.schedule())); } const actions: Array<MenuItemAction | Separator> = []; const disabled = this.configurationService.getValue<boolean>('keyboard.touchbar.enabled') === false; const ignoredItems = this.configurationService.getValue<string[]>('keyboard.touchbar.ignored') || []; // Fill actions into groups respecting order this.touchBarDisposables.add(createAndFillInActionBarActions(this.touchBarMenu, undefined, actions)); // Convert into command action multi array const items: ICommandAction[][] = []; let group: ICommandAction[] = []; if (!disabled) { for (const action of actions) { // Command if (action instanceof MenuItemAction) { if (ignoredItems.indexOf(action.item.id) >= 0) { continue; // ignored } group.push(action.item); } // Separator else if (action instanceof Separator) { if (group.length) { items.push(group); } group = []; } } if (group.length) { items.push(group); } } // Only update if the actions have changed if (!equals(this.lastInstalledTouchedBar, items)) { this.lastInstalledTouchedBar = items; this.electronService.updateTouchBar(items); } } private onAddFoldersRequest(request: IAddFoldersRequest): void { // Buffer all pending requests this.pendingFoldersToAdd.push(...request.foldersToAdd.map(folder => URI.revive(folder))); // Delay the adding of folders a bit to buffer in case more requests are coming if (!this.addFoldersScheduler.isScheduled()) { this.addFoldersScheduler.schedule(); } } private doAddFolders(): void { const foldersToAdd: IWorkspaceFolderCreationData[] = []; this.pendingFoldersToAdd.forEach(folder => { foldersToAdd.push(({ uri: folder })); }); this.pendingFoldersToAdd = []; this.workspaceEditingService.addFolders(foldersToAdd); } private async onOpenFiles(request: IDesktopOpenFileRequest): Promise<void> { const inputs: IResourceEditorInputType[] = []; const diffMode = !!(request.filesToDiff && (request.filesToDiff.length === 2)); if (!diffMode && request.filesToOpenOrCreate) { inputs.push(...(await pathsToEditors(request.filesToOpenOrCreate, this.fileService))); } if (diffMode && request.filesToDiff) { inputs.push(...(await pathsToEditors(request.filesToDiff, this.fileService))); } if (inputs.length) { this.openResources(inputs, diffMode); } if (request.filesToWait && inputs.length) { // In wait mode, listen to changes to the editors and wait until the files // are closed that the user wants to wait for. When this happens we delete // the wait marker file to signal to the outside that editing is done. this.trackClosedWaitFiles(URI.revive(request.filesToWait.waitMarkerFileUri), coalesce(request.filesToWait.paths.map(p => URI.revive(p.fileUri)))); } } private async trackClosedWaitFiles(waitMarkerFile: URI, resourcesToWaitFor: URI[]): Promise<void> { // Wait for the resources to be closed in the editor... await this.editorService.whenClosed(resourcesToWaitFor.map(resource => ({ resource })), { waitForSaved: true }); // ...before deleting the wait marker file await this.fileService.del(waitMarkerFile); } private async openResources(resources: Array<IResourceEditorInput | IUntitledTextResourceEditorInput>, diffMode: boolean): Promise<unknown> { await this.lifecycleService.when(LifecyclePhase.Ready); // In diffMode we open 2 resources as diff if (diffMode && resources.length === 2 && resources[0].resource && resources[1].resource) { return this.editorService.openEditor({ leftResource: resources[0].resource, rightResource: resources[1].resource, options: { pinned: true } }); } // For one file, just put it into the current active editor if (resources.length === 1) { return this.editorService.openEditor(resources[0]); } // Otherwise open all return this.editorService.openEditors(resources); } } class NativeMenubarControl extends MenubarControl { constructor( @IMenuService menuService: IMenuService, @IWorkspacesService workspacesService: IWorkspacesService, @IContextKeyService contextKeyService: IContextKeyService, @IKeybindingService keybindingService: IKeybindingService, @IConfigurationService configurationService: IConfigurationService, @ILabelService labelService: ILabelService, @IUpdateService updateService: IUpdateService, @IStorageService storageService: IStorageService, @INotificationService notificationService: INotificationService, @IPreferencesService preferencesService: IPreferencesService, @IWorkbenchEnvironmentService protected readonly environmentService: INativeWorkbenchEnvironmentService, @IAccessibilityService accessibilityService: IAccessibilityService, @IMenubarService private readonly menubarService: IMenubarService, @IHostService hostService: IHostService, @IElectronService private readonly electronService: IElectronService ) { super( menuService, workspacesService, contextKeyService, keybindingService, configurationService, labelService, updateService, storageService, notificationService, preferencesService, environmentService, accessibilityService, hostService ); if (isMacintosh) { this.menus['Preferences'] = this._register(this.menuService.createMenu(MenuId.MenubarPreferencesMenu, this.contextKeyService)); this.topLevelTitles['Preferences'] = nls.localize('mPreferences', "Preferences"); } for (const topLevelMenuName of Object.keys(this.topLevelTitles)) { const menu = this.menus[topLevelMenuName]; if (menu) { this._register(menu.onDidChange(() => this.updateMenubar())); } } (async () => { this.recentlyOpened = await this.workspacesService.getRecentlyOpened(); this.doUpdateMenubar(true); })(); this.registerListeners(); } protected doUpdateMenubar(firstTime: boolean): void { // Since the native menubar is shared between windows (main process) // only allow the focused window to update the menubar if (!this.hostService.hasFocus) { return; } // Send menus to main process to be rendered by Electron const menubarData = { menus: {}, keybindings: {} }; if (this.getMenubarMenus(menubarData)) { this.menubarService.updateMenubar(this.electronService.windowId, menubarData); } } private getMenubarMenus(menubarData: IMenubarData): boolean { if (!menubarData) { return false; } menubarData.keybindings = this.getAdditionalKeybindings(); for (const topLevelMenuName of Object.keys(this.topLevelTitles)) { const menu = this.menus[topLevelMenuName]; if (menu) { const menubarMenu: IMenubarMenu = { items: [] }; this.populateMenuItems(menu, menubarMenu, menubarData.keybindings); if (menubarMenu.items.length === 0) { return false; // Menus are incomplete } menubarData.menus[topLevelMenuName] = menubarMenu; } } return true; } private populateMenuItems(menu: IMenu, menuToPopulate: IMenubarMenu, keybindings: { [id: string]: IMenubarKeybinding | undefined }) { let groups = menu.getActions(); for (let group of groups) { const [, actions] = group; actions.forEach(menuItem => { if (menuItem instanceof SubmenuItemAction) { const submenu = { items: [] }; if (!this.menus[menuItem.item.submenu.id]) { const menu = this.menus[menuItem.item.submenu.id] = this.menuService.createMenu(menuItem.item.submenu, this.contextKeyService); this._register(menu.onDidChange(() => this.updateMenubar())); } const menuToDispose = this.menuService.createMenu(menuItem.item.submenu, this.contextKeyService); this.populateMenuItems(menuToDispose, submenu, keybindings); let menubarSubmenuItem: IMenubarMenuItemSubmenu = { id: menuItem.id, label: menuItem.label, submenu: submenu }; menuToPopulate.items.push(menubarSubmenuItem); menuToDispose.dispose(); } else { if (menuItem.id === 'workbench.action.openRecent') { const actions = this.getOpenRecentActions().map(this.transformOpenRecentAction); menuToPopulate.items.push(...actions); } let menubarMenuItem: IMenubarMenuItemAction = { id: menuItem.id, label: menuItem.label }; if (menuItem.checked) { menubarMenuItem.checked = true; } if (!menuItem.enabled) { menubarMenuItem.enabled = false; } menubarMenuItem.label = this.calculateActionLabel(menubarMenuItem); keybindings[menuItem.id] = this.getMenubarKeybinding(menuItem.id); menuToPopulate.items.push(menubarMenuItem); } }); menuToPopulate.items.push({ id: 'vscode.menubar.separator' }); } if (menuToPopulate.items.length > 0) { menuToPopulate.items.pop(); } } private transformOpenRecentAction(action: Separator | (IAction & { uri: URI })): MenubarMenuItem { if (action instanceof Separator) { return { id: 'vscode.menubar.separator' }; } return { id: action.id, uri: action.uri, enabled: action.enabled, label: action.label }; } private getAdditionalKeybindings(): { [id: string]: IMenubarKeybinding } { const keybindings: { [id: string]: IMenubarKeybinding } = {}; if (isMacintosh) { const keybinding = this.getMenubarKeybinding('workbench.action.quit'); if (keybinding) { keybindings['workbench.action.quit'] = keybinding; } } return keybindings; } private getMenubarKeybinding(id: string): IMenubarKeybinding | undefined { const binding = this.keybindingService.lookupKeybinding(id); if (!binding) { return undefined; } // first try to resolve a native accelerator const electronAccelerator = binding.getElectronAccelerator(); if (electronAccelerator) { return { label: electronAccelerator, userSettingsLabel: withNullAsUndefined(binding.getUserSettingsLabel()) }; } // we need this fallback to support keybindings that cannot show in electron menus (e.g. chords) const acceleratorLabel = binding.getLabel(); if (acceleratorLabel) { return { label: acceleratorLabel, isNative: false, userSettingsLabel: withNullAsUndefined(binding.getUserSettingsLabel()) }; } return undefined; } }
src/vs/workbench/electron-browser/window.ts
1
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.009197420440614223, 0.00040623772656545043, 0.00016301004507113248, 0.00017405953258275986, 0.0011901429388672113 ]
{ "id": 5, "code_window": [ "\t\t@IUpdateService updateService: IUpdateService,\n", "\t\t@IStorageService storageService: IStorageService,\n", "\t\t@INotificationService notificationService: INotificationService,\n", "\t\t@IPreferencesService preferencesService: IPreferencesService,\n", "\t\t@IWorkbenchEnvironmentService protected readonly environmentService: INativeWorkbenchEnvironmentService,\n", "\t\t@IAccessibilityService accessibilityService: IAccessibilityService,\n", "\t\t@IMenubarService private readonly menubarService: IMenubarService,\n", "\t\t@IHostService hostService: IHostService,\n", "\t\t@IElectronService private readonly electronService: IElectronService\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t@IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService,\n" ], "file_path": "src/vs/workbench/electron-browser/window.ts", "type": "replace", "edit_start_line_idx": 612 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event } from 'vs/base/common/event'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { $, EventHelper, EventLike } from 'vs/base/browser/dom'; import { domEvent } from 'vs/base/browser/event'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { KeyCode } from 'vs/base/common/keyCodes'; import { Disposable } from 'vs/base/common/lifecycle'; import { Color } from 'vs/base/common/color'; export interface ILinkDescriptor { readonly label: string; readonly href: string; readonly title?: string; } export interface ILinkStyles { readonly textLinkForeground?: Color; } export class Link extends Disposable { readonly el: HTMLAnchorElement; private styles: ILinkStyles = { textLinkForeground: Color.fromHex('#006AB1') }; constructor( link: ILinkDescriptor, @IOpenerService openerService: IOpenerService ) { super(); this.el = $<HTMLAnchorElement>('a', { tabIndex: 0, href: link.href, title: link.title }, link.label); const onClick = domEvent(this.el, 'click'); const onEnterPress = Event.chain(domEvent(this.el, 'keypress')) .map(e => new StandardKeyboardEvent(e)) .filter(e => e.keyCode === KeyCode.Enter) .event; const onOpen = Event.any<EventLike>(onClick, onEnterPress); this._register(onOpen(e => { EventHelper.stop(e, true); openerService.open(link.href); })); this.applyStyles(); } style(styles: ILinkStyles): void { this.styles = styles; this.applyStyles(); } private applyStyles(): void { this.el.style.color = this.styles.textLinkForeground?.toString() || ''; } }
src/vs/platform/opener/browser/link.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017417773779015988, 0.00017218671564478427, 0.0001678379630902782, 0.00017372227739542723, 0.0000022066017208999256 ]
{ "id": 5, "code_window": [ "\t\t@IUpdateService updateService: IUpdateService,\n", "\t\t@IStorageService storageService: IStorageService,\n", "\t\t@INotificationService notificationService: INotificationService,\n", "\t\t@IPreferencesService preferencesService: IPreferencesService,\n", "\t\t@IWorkbenchEnvironmentService protected readonly environmentService: INativeWorkbenchEnvironmentService,\n", "\t\t@IAccessibilityService accessibilityService: IAccessibilityService,\n", "\t\t@IMenubarService private readonly menubarService: IMenubarService,\n", "\t\t@IHostService hostService: IHostService,\n", "\t\t@IElectronService private readonly electronService: IElectronService\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t@IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService,\n" ], "file_path": "src/vs/workbench/electron-browser/window.ts", "type": "replace", "edit_start_line_idx": 612 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/
extensions/vscode-notebook-tests/test/second.vsctestnb
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017692048277240247, 0.00017692048277240247, 0.00017692048277240247, 0.00017692048277240247, 0 ]
{ "id": 5, "code_window": [ "\t\t@IUpdateService updateService: IUpdateService,\n", "\t\t@IStorageService storageService: IStorageService,\n", "\t\t@INotificationService notificationService: INotificationService,\n", "\t\t@IPreferencesService preferencesService: IPreferencesService,\n", "\t\t@IWorkbenchEnvironmentService protected readonly environmentService: INativeWorkbenchEnvironmentService,\n", "\t\t@IAccessibilityService accessibilityService: IAccessibilityService,\n", "\t\t@IMenubarService private readonly menubarService: IMenubarService,\n", "\t\t@IHostService hostService: IHostService,\n", "\t\t@IElectronService private readonly electronService: IElectronService\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t@IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService,\n" ], "file_path": "src/vs/workbench/electron-browser/window.ts", "type": "replace", "edit_start_line_idx": 612 }
{ "extends": "../shared.tsconfig.json", "compilerOptions": { "outDir": "./out" }, "exclude": [ "node_modules", ".vscode-test" ], "include": [ "src/**/*" ] }
extensions/emmet/tsconfig.json
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.0001765140623319894, 0.00017611784278415143, 0.00017572160868439823, 0.00017611784278415143, 3.962268237955868e-7 ]
{ "id": 6, "code_window": [ "\t\tthis.setAccessibilitySupport(environmentService.configuration.accessibilitySupport ? AccessibilitySupport.Enabled : AccessibilitySupport.Disabled);\n", "\t}\n", "\n", "\talwaysUnderlineAccessKeys(): Promise<boolean> {\n", "\t\tif (!isWindows) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\tasync alwaysUnderlineAccessKeys(): Promise<boolean> {\n" ], "file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts", "type": "replace", "edit_start_line_idx": 43 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ICredentialsService } from 'vs/platform/credentials/common/credentials'; import { IdleValue } from 'vs/base/common/async'; type KeytarModule = typeof import('keytar'); export class KeytarCredentialsService implements ICredentialsService { declare readonly _serviceBrand: undefined; private readonly _keytar = new IdleValue<Promise<KeytarModule>>(() => import('keytar')); async getPassword(service: string, account: string): Promise<string | null> { const keytar = await this._keytar.value; return keytar.getPassword(service, account); } async setPassword(service: string, account: string, password: string): Promise<void> { const keytar = await this._keytar.value; return keytar.setPassword(service, account, password); } async deletePassword(service: string, account: string): Promise<boolean> { const keytar = await this._keytar.value; return keytar.deletePassword(service, account); } async findPassword(service: string): Promise<string | null> { const keytar = await this._keytar.value; return keytar.findPassword(service); } async findCredentials(service: string): Promise<Array<{ account: string, password: string }>> { const keytar = await this._keytar.value; return keytar.findCredentials(service); } }
src/vs/platform/credentials/node/credentialsService.ts
1
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017921924882102758, 0.00017240112356375903, 0.00016882491763681173, 0.00017144480079878122, 0.0000036862145407212665 ]
{ "id": 6, "code_window": [ "\t\tthis.setAccessibilitySupport(environmentService.configuration.accessibilitySupport ? AccessibilitySupport.Enabled : AccessibilitySupport.Disabled);\n", "\t}\n", "\n", "\talwaysUnderlineAccessKeys(): Promise<boolean> {\n", "\t\tif (!isWindows) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\tasync alwaysUnderlineAccessKeys(): Promise<boolean> {\n" ], "file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts", "type": "replace", "edit_start_line_idx": 43 }
/*--------------------------------------------------------------------------------------------- * 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 * as path from 'vs/base/common/path'; import * as cp from 'child_process'; import * as pfs from 'vs/base/node/pfs'; import * as extpath from 'vs/base/node/extpath'; import * as platform from 'vs/base/common/platform'; import { promisify } from 'util'; import { Action } from 'vs/base/common/actions'; import { IWorkbenchActionRegistry, Extensions as ActionExtensions } from 'vs/workbench/common/actions'; import { Registry } from 'vs/platform/registry/common/platform'; import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import product from 'vs/platform/product/common/product'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import Severity from 'vs/base/common/severity'; import { ILogService } from 'vs/platform/log/common/log'; import { getPathFromAmdModule } from 'vs/base/common/amd'; function ignore<T>(code: string, value: T): (err: any) => Promise<T> { return err => err.code === code ? Promise.resolve<T>(value) : Promise.reject<T>(err); } let _source: string | null = null; function getSource(): string { if (!_source) { const root = getPathFromAmdModule(require, ''); _source = path.resolve(root, '..', 'bin', 'code'); } return _source; } function isAvailable(): Promise<boolean> { return Promise.resolve(pfs.exists(getSource())); } class InstallAction extends Action { static readonly ID = 'workbench.action.installCommandLine'; static readonly LABEL = nls.localize('install', "Install '{0}' command in PATH", product.applicationName); constructor( id: string, label: string, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @ILogService private readonly logService: ILogService ) { super(id, label); } private get target(): string { return `/usr/local/bin/${product.applicationName}`; } run(): Promise<void> { return isAvailable().then(isAvailable => { if (!isAvailable) { const message = nls.localize('not available', "This command is not available"); this.notificationService.info(message); return undefined; } return this.isInstalled() .then(isInstalled => { if (!isAvailable || isInstalled) { return Promise.resolve(null); } else { return pfs.unlink(this.target) .then(undefined, ignore('ENOENT', null)) .then(() => pfs.symlink(getSource(), this.target)) .then(undefined, err => { if (err.code === 'EACCES' || err.code === 'ENOENT') { return this.createBinFolderAndSymlinkAsAdmin(); } return Promise.reject(err); }); } }) .then(() => { this.logService.trace('cli#install', this.target); this.notificationService.info(nls.localize('successIn', "Shell command '{0}' successfully installed in PATH.", product.applicationName)); }); }); } private isInstalled(): Promise<boolean> { return pfs.lstat(this.target) .then(stat => stat.isSymbolicLink()) .then(() => extpath.realpath(this.target)) .then(link => link === getSource()) .then(undefined, ignore('ENOENT', false)); } private createBinFolderAndSymlinkAsAdmin(): Promise<void> { return new Promise<void>((resolve, reject) => { const buttons = [nls.localize('ok', "OK"), nls.localize('cancel2', "Cancel")]; this.dialogService.show(Severity.Info, nls.localize('warnEscalation', "Code will now prompt with 'osascript' for Administrator privileges to install the shell command."), buttons, { cancelId: 1 }).then(result => { switch (result.choice) { case 0 /* OK */: const command = 'osascript -e "do shell script \\"mkdir -p /usr/local/bin && ln -sf \'' + getSource() + '\' \'' + this.target + '\'\\" with administrator privileges"'; promisify(cp.exec)(command, {}) .then(undefined, _ => Promise.reject(new Error(nls.localize('cantCreateBinFolder', "Unable to create '/usr/local/bin'.")))) .then(() => resolve(), reject); break; case 1 /* Cancel */: reject(new Error(nls.localize('aborted', "Aborted"))); break; } }); }); } } class UninstallAction extends Action { static readonly ID = 'workbench.action.uninstallCommandLine'; static readonly LABEL = nls.localize('uninstall', "Uninstall '{0}' command from PATH", product.applicationName); constructor( id: string, label: string, @INotificationService private readonly notificationService: INotificationService, @ILogService private readonly logService: ILogService, @IDialogService private readonly dialogService: IDialogService ) { super(id, label); } private get target(): string { return `/usr/local/bin/${product.applicationName}`; } run(): Promise<void> { return isAvailable().then(isAvailable => { if (!isAvailable) { const message = nls.localize('not available', "This command is not available"); this.notificationService.info(message); return undefined; } const uninstall = () => { return pfs.unlink(this.target) .then(undefined, ignore('ENOENT', null)); }; return uninstall().then(undefined, err => { if (err.code === 'EACCES') { return this.deleteSymlinkAsAdmin(); } return Promise.reject(err); }).then(() => { this.logService.trace('cli#uninstall', this.target); this.notificationService.info(nls.localize('successFrom', "Shell command '{0}' successfully uninstalled from PATH.", product.applicationName)); }); }); } private deleteSymlinkAsAdmin(): Promise<void> { return new Promise<void>(async (resolve, reject) => { const buttons = [nls.localize('ok', "OK"), nls.localize('cancel2', "Cancel")]; const { choice } = await this.dialogService.show(Severity.Info, nls.localize('warnEscalationUninstall', "Code will now prompt with 'osascript' for Administrator privileges to uninstall the shell command."), buttons, { cancelId: 1 }); switch (choice) { case 0 /* OK */: const command = 'osascript -e "do shell script \\"rm \'' + this.target + '\'\\" with administrator privileges"'; promisify(cp.exec)(command, {}) .then(undefined, _ => Promise.reject(new Error(nls.localize('cantUninstall', "Unable to uninstall the shell command '{0}'.", this.target)))) .then(() => resolve(), reject); break; case 1 /* Cancel */: reject(new Error(nls.localize('aborted', "Aborted"))); break; } }); } } if (platform.isMacintosh) { const category = nls.localize('shellCommand', "Shell Command"); const workbenchActionsRegistry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); workbenchActionsRegistry.registerWorkbenchAction(SyncActionDescriptor.from(InstallAction), `Shell Command: Install \'${product.applicationName}\' command in PATH`, category); workbenchActionsRegistry.registerWorkbenchAction(SyncActionDescriptor.from(UninstallAction), `Shell Command: Uninstall \'${product.applicationName}\' command from PATH`, category); }
src/vs/workbench/contrib/cli/node/cli.contribution.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00018596883455757052, 0.00017158107948489487, 0.00016691358177922666, 0.00017091570771299303, 0.000004086326043761801 ]
{ "id": 6, "code_window": [ "\t\tthis.setAccessibilitySupport(environmentService.configuration.accessibilitySupport ? AccessibilitySupport.Enabled : AccessibilitySupport.Disabled);\n", "\t}\n", "\n", "\talwaysUnderlineAccessKeys(): Promise<boolean> {\n", "\t\tif (!isWindows) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\tasync alwaysUnderlineAccessKeys(): Promise<boolean> {\n" ], "file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts", "type": "replace", "edit_start_line_idx": 43 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IComposite } from 'vs/workbench/common/composite'; import { RawContextKey } from 'vs/platform/contextkey/common/contextkey'; export const ActivePanelContext = new RawContextKey<string>('activePanel', ''); export const PanelFocusContext = new RawContextKey<boolean>('panelFocus', false); export const PanelPositionContext = new RawContextKey<string>('panelPosition', 'bottom'); export interface IPanel extends IComposite { }
src/vs/workbench/common/panel.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017432162712793797, 0.00017279302119277418, 0.00017126441525761038, 0.00017279302119277418, 0.000001528605935163796 ]
{ "id": 6, "code_window": [ "\t\tthis.setAccessibilitySupport(environmentService.configuration.accessibilitySupport ? AccessibilitySupport.Enabled : AccessibilitySupport.Disabled);\n", "\t}\n", "\n", "\talwaysUnderlineAccessKeys(): Promise<boolean> {\n", "\t\tif (!isWindows) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\tasync alwaysUnderlineAccessKeys(): Promise<boolean> {\n" ], "file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts", "type": "replace", "edit_start_line_idx": 43 }
out node_modules
extensions/vscode-test-resolver/.gitignore
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00017710530664771795, 0.00017710530664771795, 0.00017710530664771795, 0.00017710530664771795, 0 ]
{ "id": 7, "code_window": [ "\t\tif (!isWindows) {\n", "\t\t\treturn Promise.resolve(false);\n", "\t\t}\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\treturn false;\n" ], "file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts", "type": "replace", "edit_start_line_idx": 45 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Database, Statement } from 'vscode-sqlite3'; import { Event } from 'vs/base/common/event'; import { timeout } from 'vs/base/common/async'; import { mapToString, setToString } from 'vs/base/common/map'; import { basename } from 'vs/base/common/path'; import { copy, renameIgnoreError, unlink } from 'vs/base/node/pfs'; import { IStorageDatabase, IStorageItemsChangeEvent, IUpdateRequest } from 'vs/base/parts/storage/common/storage'; interface IDatabaseConnection { readonly db: Database; readonly isInMemory: boolean; isErroneous?: boolean; lastError?: string; } export interface ISQLiteStorageDatabaseOptions { readonly logging?: ISQLiteStorageDatabaseLoggingOptions; } export interface ISQLiteStorageDatabaseLoggingOptions { logError?: (error: string | Error) => void; logTrace?: (msg: string) => void; } export class SQLiteStorageDatabase implements IStorageDatabase { static readonly IN_MEMORY_PATH = ':memory:'; get onDidChangeItemsExternal(): Event<IStorageItemsChangeEvent> { return Event.None; } // since we are the only client, there can be no external changes private static readonly BUSY_OPEN_TIMEOUT = 2000; // timeout in ms to retry when opening DB fails with SQLITE_BUSY private static readonly MAX_HOST_PARAMETERS = 256; // maximum number of parameters within a statement private readonly name = basename(this.path); private readonly logger = new SQLiteStorageDatabaseLogger(this.options.logging); private readonly whenConnected = this.connect(this.path); constructor(private readonly path: string, private readonly options: ISQLiteStorageDatabaseOptions = Object.create(null)) { } async getItems(): Promise<Map<string, string>> { const connection = await this.whenConnected; const items = new Map<string, string>(); const rows = await this.all(connection, 'SELECT * FROM ItemTable'); rows.forEach(row => items.set(row.key, row.value)); if (this.logger.isTracing) { this.logger.trace(`[storage ${this.name}] getItems(): ${items.size} rows`); } return items; } async updateItems(request: IUpdateRequest): Promise<void> { const connection = await this.whenConnected; return this.doUpdateItems(connection, request); } private doUpdateItems(connection: IDatabaseConnection, request: IUpdateRequest): Promise<void> { if (this.logger.isTracing) { this.logger.trace(`[storage ${this.name}] updateItems(): insert(${request.insert ? mapToString(request.insert) : '0'}), delete(${request.delete ? setToString(request.delete) : '0'})`); } return this.transaction(connection, () => { const toInsert = request.insert; const toDelete = request.delete; // INSERT if (toInsert && toInsert.size > 0) { const keysValuesChunks: (string[])[] = []; keysValuesChunks.push([]); // seed with initial empty chunk // Split key/values into chunks of SQLiteStorageDatabase.MAX_HOST_PARAMETERS // so that we can efficiently run the INSERT with as many HOST parameters as possible let currentChunkIndex = 0; toInsert.forEach((value, key) => { let keyValueChunk = keysValuesChunks[currentChunkIndex]; if (keyValueChunk.length > SQLiteStorageDatabase.MAX_HOST_PARAMETERS) { currentChunkIndex++; keyValueChunk = []; keysValuesChunks.push(keyValueChunk); } keyValueChunk.push(key, value); }); keysValuesChunks.forEach(keysValuesChunk => { this.prepare(connection, `INSERT INTO ItemTable VALUES ${new Array(keysValuesChunk.length / 2).fill('(?,?)').join(',')}`, stmt => stmt.run(keysValuesChunk), () => { const keys: string[] = []; let length = 0; toInsert.forEach((value, key) => { keys.push(key); length += value.length; }); return `Keys: ${keys.join(', ')} Length: ${length}`; }); }); } // DELETE if (toDelete && toDelete.size) { const keysChunks: (string[])[] = []; keysChunks.push([]); // seed with initial empty chunk // Split keys into chunks of SQLiteStorageDatabase.MAX_HOST_PARAMETERS // so that we can efficiently run the DELETE with as many HOST parameters // as possible let currentChunkIndex = 0; toDelete.forEach(key => { let keyChunk = keysChunks[currentChunkIndex]; if (keyChunk.length > SQLiteStorageDatabase.MAX_HOST_PARAMETERS) { currentChunkIndex++; keyChunk = []; keysChunks.push(keyChunk); } keyChunk.push(key); }); keysChunks.forEach(keysChunk => { this.prepare(connection, `DELETE FROM ItemTable WHERE key IN (${new Array(keysChunk.length).fill('?').join(',')})`, stmt => stmt.run(keysChunk), () => { const keys: string[] = []; toDelete.forEach(key => { keys.push(key); }); return `Keys: ${keys.join(', ')}`; }); }); } }); } async close(recovery?: () => Map<string, string>): Promise<void> { this.logger.trace(`[storage ${this.name}] close()`); const connection = await this.whenConnected; return this.doClose(connection, recovery); } private doClose(connection: IDatabaseConnection, recovery?: () => Map<string, string>): Promise<void> { return new Promise((resolve, reject) => { connection.db.close(closeError => { if (closeError) { this.handleSQLiteError(connection, `[storage ${this.name}] close(): ${closeError}`); } // Return early if this storage was created only in-memory // e.g. when running tests we do not need to backup. if (this.path === SQLiteStorageDatabase.IN_MEMORY_PATH) { return resolve(); } // If the DB closed successfully and we are not running in-memory // and the DB did not get errors during runtime, make a backup // of the DB so that we can use it as fallback in case the actual // DB becomes corrupt in the future. if (!connection.isErroneous && !connection.isInMemory) { return this.backup().then(resolve, error => { this.logger.error(`[storage ${this.name}] backup(): ${error}`); return resolve(); // ignore failing backup }); } // Recovery: if we detected errors while using the DB or we are using // an inmemory DB (as a fallback to not being able to open the DB initially) // and we have a recovery function provided, we recreate the DB with this // data to recover all known data without loss if possible. if (typeof recovery === 'function') { // Delete the existing DB. If the path does not exist or fails to // be deleted, we do not try to recover anymore because we assume // that the path is no longer writeable for us. return unlink(this.path).then(() => { // Re-open the DB fresh return this.doConnect(this.path).then(recoveryConnection => { const closeRecoveryConnection = () => { return this.doClose(recoveryConnection, undefined /* do not attempt to recover again */); }; // Store items return this.doUpdateItems(recoveryConnection, { insert: recovery() }).then(() => closeRecoveryConnection(), error => { // In case of an error updating items, still ensure to close the connection // to prevent SQLITE_BUSY errors when the connection is reestablished closeRecoveryConnection(); return Promise.reject(error); }); }); }).then(resolve, reject); } // Finally without recovery we just reject return reject(closeError || new Error('Database has errors or is in-memory without recovery option')); }); }); } private backup(): Promise<void> { const backupPath = this.toBackupPath(this.path); return copy(this.path, backupPath); } private toBackupPath(path: string): string { return `${path}.backup`; } async checkIntegrity(full: boolean): Promise<string> { this.logger.trace(`[storage ${this.name}] checkIntegrity(full: ${full})`); const connection = await this.whenConnected; const row = await this.get(connection, full ? 'PRAGMA integrity_check' : 'PRAGMA quick_check'); const integrity = full ? (row as any)['integrity_check'] : (row as any)['quick_check']; if (connection.isErroneous) { return `${integrity} (last error: ${connection.lastError})`; } if (connection.isInMemory) { return `${integrity} (in-memory!)`; } return integrity; } private async connect(path: string, retryOnBusy: boolean = true): Promise<IDatabaseConnection> { this.logger.trace(`[storage ${this.name}] open(${path}, retryOnBusy: ${retryOnBusy})`); try { return await this.doConnect(path); } catch (error) { this.logger.error(`[storage ${this.name}] open(): Unable to open DB due to ${error}`); // SQLITE_BUSY should only arise if another process is locking the same DB we want // to open at that time. This typically never happens because a DB connection is // limited per window. However, in the event of a window reload, it may be possible // that the previous connection was not properly closed while the new connection is // already established. // // In this case we simply wait for some time and retry once to establish the connection. // if (error.code === 'SQLITE_BUSY' && retryOnBusy) { await timeout(SQLiteStorageDatabase.BUSY_OPEN_TIMEOUT); return this.connect(path, false /* not another retry */); } // Otherwise, best we can do is to recover from a backup if that exists, as such we // move the DB to a different filename and try to load from backup. If that fails, // a new empty DB is being created automatically. // // The final fallback is to use an in-memory DB which should only happen if the target // folder is really not writeable for us. // try { await unlink(path); await renameIgnoreError(this.toBackupPath(path), path); return await this.doConnect(path); } catch (error) { this.logger.error(`[storage ${this.name}] open(): Unable to use backup due to ${error}`); // In case of any error to open the DB, use an in-memory // DB so that we always have a valid DB to talk to. return this.doConnect(SQLiteStorageDatabase.IN_MEMORY_PATH); } } } private handleSQLiteError(connection: IDatabaseConnection, msg: string): void { connection.isErroneous = true; connection.lastError = msg; this.logger.error(msg); } private doConnect(path: string): Promise<IDatabaseConnection> { return new Promise((resolve, reject) => { import('vscode-sqlite3').then(sqlite3 => { const connection: IDatabaseConnection = { db: new (this.logger.isTracing ? sqlite3.verbose().Database : sqlite3.Database)(path, error => { if (error) { return connection.db ? connection.db.close(() => reject(error)) : reject(error); } // The following exec() statement serves two purposes: // - create the DB if it does not exist yet // - validate that the DB is not corrupt (the open() call does not throw otherwise) return this.exec(connection, [ 'PRAGMA user_version = 1;', 'CREATE TABLE IF NOT EXISTS ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)' ].join('')).then(() => { return resolve(connection); }, error => { return connection.db.close(() => reject(error)); }); }), isInMemory: path === SQLiteStorageDatabase.IN_MEMORY_PATH }; // Errors connection.db.on('error', error => this.handleSQLiteError(connection, `[storage ${this.name}] Error (event): ${error}`)); // Tracing if (this.logger.isTracing) { connection.db.on('trace', sql => this.logger.trace(`[storage ${this.name}] Trace (event): ${sql}`)); } }, reject); }); } private exec(connection: IDatabaseConnection, sql: string): Promise<void> { return new Promise((resolve, reject) => { connection.db.exec(sql, error => { if (error) { this.handleSQLiteError(connection, `[storage ${this.name}] exec(): ${error}`); return reject(error); } return resolve(); }); }); } private get(connection: IDatabaseConnection, sql: string): Promise<object> { return new Promise((resolve, reject) => { connection.db.get(sql, (error, row) => { if (error) { this.handleSQLiteError(connection, `[storage ${this.name}] get(): ${error}`); return reject(error); } return resolve(row); }); }); } private all(connection: IDatabaseConnection, sql: string): Promise<{ key: string, value: string }[]> { return new Promise((resolve, reject) => { connection.db.all(sql, (error, rows) => { if (error) { this.handleSQLiteError(connection, `[storage ${this.name}] all(): ${error}`); return reject(error); } return resolve(rows); }); }); } private transaction(connection: IDatabaseConnection, transactions: () => void): Promise<void> { return new Promise((resolve, reject) => { connection.db.serialize(() => { connection.db.run('BEGIN TRANSACTION'); transactions(); connection.db.run('END TRANSACTION', error => { if (error) { this.handleSQLiteError(connection, `[storage ${this.name}] transaction(): ${error}`); return reject(error); } return resolve(); }); }); }); } private prepare(connection: IDatabaseConnection, sql: string, runCallback: (stmt: Statement) => void, errorDetails: () => string): void { const stmt = connection.db.prepare(sql); const statementErrorListener = (error: Error) => { this.handleSQLiteError(connection, `[storage ${this.name}] prepare(): ${error} (${sql}). Details: ${errorDetails()}`); }; stmt.on('error', statementErrorListener); runCallback(stmt); stmt.finalize(error => { if (error) { statementErrorListener(error); } stmt.removeListener('error', statementErrorListener); }); } } class SQLiteStorageDatabaseLogger { private readonly logTrace: ((msg: string) => void) | undefined; private readonly logError: ((error: string | Error) => void) | undefined; constructor(options?: ISQLiteStorageDatabaseLoggingOptions) { if (options && typeof options.logTrace === 'function') { this.logTrace = options.logTrace; } if (options && typeof options.logError === 'function') { this.logError = options.logError; } } get isTracing(): boolean { return !!this.logTrace; } trace(msg: string): void { if (this.logTrace) { this.logTrace(msg); } } error(error: string | Error): void { if (this.logError) { this.logError(error); } } }
src/vs/base/parts/storage/node/storage.ts
1
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.002376754069700837, 0.0002830607700161636, 0.00016525521641597152, 0.0001804500789148733, 0.0003348169266246259 ]
{ "id": 7, "code_window": [ "\t\tif (!isWindows) {\n", "\t\t\treturn Promise.resolve(false);\n", "\t\t}\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\treturn false;\n" ], "file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts", "type": "replace", "edit_start_line_idx": 45 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as vscode from 'vscode'; import { createRandomFile, deleteFile, closeAllEditors, pathEquals, rndName, disposeAll, testFs, delay, withLogDisabled, revertAllDirty } from '../utils'; import { join, posix, basename } from 'path'; import * as fs from 'fs'; import { TestFS } from '../memfs'; suite('vscode API - workspace', () => { teardown(closeAllEditors); test('MarkdownString', function () { let md = new vscode.MarkdownString(); assert.equal(md.value, ''); assert.equal(md.isTrusted, undefined); md = new vscode.MarkdownString('**bold**'); assert.equal(md.value, '**bold**'); md.appendText('**bold?**'); assert.equal(md.value, '**bold**\\*\\*bold?\\*\\*'); md.appendMarkdown('**bold**'); assert.equal(md.value, '**bold**\\*\\*bold?\\*\\***bold**'); }); test('textDocuments', () => { assert.ok(Array.isArray(vscode.workspace.textDocuments)); assert.throws(() => (<any>vscode.workspace).textDocuments = null); }); test('rootPath', () => { assert.ok(pathEquals(vscode.workspace.rootPath!, join(__dirname, '../../testWorkspace'))); assert.throws(() => (vscode.workspace as any).rootPath = 'farboo'); }); test('workspaceFile', () => { assert.ok(!vscode.workspace.workspaceFile); }); test('workspaceFolders', () => { if (vscode.workspace.workspaceFolders) { assert.equal(vscode.workspace.workspaceFolders.length, 1); assert.ok(pathEquals(vscode.workspace.workspaceFolders[0].uri.fsPath, join(__dirname, '../../testWorkspace'))); } }); test('getWorkspaceFolder', () => { const folder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(join(__dirname, '../../testWorkspace/far.js'))); assert.ok(!!folder); if (folder) { assert.ok(pathEquals(folder.uri.fsPath, join(__dirname, '../../testWorkspace'))); } }); test('openTextDocument', async () => { const uri = await createRandomFile(); // not yet there const existing1 = vscode.workspace.textDocuments.find(doc => doc.uri.toString() === uri.toString()); assert.equal(existing1, undefined); // open and assert its there const doc = await vscode.workspace.openTextDocument(uri); assert.ok(doc); assert.equal(doc.uri.toString(), uri.toString()); const existing2 = vscode.workspace.textDocuments.find(doc => doc.uri.toString() === uri.toString()); assert.equal(existing2 === doc, true); }); test('openTextDocument, illegal path', () => { return vscode.workspace.openTextDocument('funkydonky.txt').then(_doc => { throw new Error('missing error'); }, _err => { // good! }); }); test('openTextDocument, untitled is dirty', async function () { return vscode.workspace.openTextDocument(vscode.workspace.workspaceFolders![0].uri.with({ scheme: 'untitled', path: posix.join(vscode.workspace.workspaceFolders![0].uri.path, 'newfile.txt') })).then(doc => { assert.equal(doc.uri.scheme, 'untitled'); assert.ok(doc.isDirty); }); }); test('openTextDocument, untitled with host', function () { const uri = vscode.Uri.parse('untitled://localhost/c%24/Users/jrieken/code/samples/foobar.txt'); return vscode.workspace.openTextDocument(uri).then(doc => { assert.equal(doc.uri.scheme, 'untitled'); }); }); test('openTextDocument, untitled without path', function () { return vscode.workspace.openTextDocument().then(doc => { assert.equal(doc.uri.scheme, 'untitled'); assert.ok(doc.isDirty); }); }); test('openTextDocument, untitled without path but language ID', function () { return vscode.workspace.openTextDocument({ language: 'xml' }).then(doc => { assert.equal(doc.uri.scheme, 'untitled'); assert.equal(doc.languageId, 'xml'); assert.ok(doc.isDirty); }); }); test('openTextDocument, untitled without path but language ID and content', function () { return vscode.workspace.openTextDocument({ language: 'html', content: '<h1>Hello world!</h1>' }).then(doc => { assert.equal(doc.uri.scheme, 'untitled'); assert.equal(doc.languageId, 'html'); assert.ok(doc.isDirty); assert.equal(doc.getText(), '<h1>Hello world!</h1>'); }); }); test('openTextDocument, untitled closes on save', function () { const path = join(vscode.workspace.rootPath || '', './newfile.txt'); return vscode.workspace.openTextDocument(vscode.Uri.parse('untitled:' + path)).then(doc => { assert.equal(doc.uri.scheme, 'untitled'); assert.ok(doc.isDirty); let closed: vscode.TextDocument; let d0 = vscode.workspace.onDidCloseTextDocument(e => closed = e); return vscode.window.showTextDocument(doc).then(() => { return doc.save().then(() => { assert.ok(closed === doc); assert.ok(!doc.isDirty); assert.ok(fs.existsSync(path)); d0.dispose(); fs.unlinkSync(join(vscode.workspace.rootPath || '', './newfile.txt')); }); }); }); }); test('openTextDocument, uri scheme/auth/path', function () { let registration = vscode.workspace.registerTextDocumentContentProvider('sc', { provideTextDocumentContent() { return 'SC'; } }); return Promise.all([ vscode.workspace.openTextDocument(vscode.Uri.parse('sc://auth')).then(doc => { assert.equal(doc.uri.authority, 'auth'); assert.equal(doc.uri.path, ''); }), vscode.workspace.openTextDocument(vscode.Uri.parse('sc:///path')).then(doc => { assert.equal(doc.uri.authority, ''); assert.equal(doc.uri.path, '/path'); }), vscode.workspace.openTextDocument(vscode.Uri.parse('sc://auth/path')).then(doc => { assert.equal(doc.uri.authority, 'auth'); assert.equal(doc.uri.path, '/path'); }) ]).then(() => { registration.dispose(); }); }); test('openTextDocument, actual casing first', async function () { const fs = new TestFS('this-fs', false); const reg = vscode.workspace.registerFileSystemProvider(fs.scheme, fs, { isCaseSensitive: fs.isCaseSensitive }); let uriOne = vscode.Uri.parse('this-fs:/one'); let uriTwo = vscode.Uri.parse('this-fs:/two'); let uriONE = vscode.Uri.parse('this-fs:/ONE'); // same resource, different uri let uriTWO = vscode.Uri.parse('this-fs:/TWO'); fs.writeFile(uriOne, Buffer.from('one'), { create: true, overwrite: true }); fs.writeFile(uriTwo, Buffer.from('two'), { create: true, overwrite: true }); // lower case (actual case) comes first let docOne = await vscode.workspace.openTextDocument(uriOne); assert.equal(docOne.uri.toString(), uriOne.toString()); let docONE = await vscode.workspace.openTextDocument(uriONE); assert.equal(docONE === docOne, true); assert.equal(docONE.uri.toString(), uriOne.toString()); assert.equal(docONE.uri.toString() !== uriONE.toString(), true); // yep // upper case (NOT the actual case) comes first let docTWO = await vscode.workspace.openTextDocument(uriTWO); assert.equal(docTWO.uri.toString(), uriTWO.toString()); let docTwo = await vscode.workspace.openTextDocument(uriTwo); assert.equal(docTWO === docTwo, true); assert.equal(docTwo.uri.toString(), uriTWO.toString()); assert.equal(docTwo.uri.toString() !== uriTwo.toString(), true); // yep reg.dispose(); }); test('eol, read', () => { const a = createRandomFile('foo\nbar\nbar').then(file => { return vscode.workspace.openTextDocument(file).then(doc => { assert.equal(doc.eol, vscode.EndOfLine.LF); }); }); const b = createRandomFile('foo\nbar\nbar\r\nbaz').then(file => { return vscode.workspace.openTextDocument(file).then(doc => { assert.equal(doc.eol, vscode.EndOfLine.LF); }); }); const c = createRandomFile('foo\r\nbar\r\nbar').then(file => { return vscode.workspace.openTextDocument(file).then(doc => { assert.equal(doc.eol, vscode.EndOfLine.CRLF); }); }); return Promise.all([a, b, c]); }); test('eol, change via editor', () => { return createRandomFile('foo\nbar\nbar').then(file => { return vscode.workspace.openTextDocument(file).then(doc => { assert.equal(doc.eol, vscode.EndOfLine.LF); return vscode.window.showTextDocument(doc).then(editor => { return editor.edit(builder => builder.setEndOfLine(vscode.EndOfLine.CRLF)); }).then(value => { assert.ok(value); assert.ok(doc.isDirty); assert.equal(doc.eol, vscode.EndOfLine.CRLF); }); }); }); }); test('eol, change via applyEdit', () => { return createRandomFile('foo\nbar\nbar').then(file => { return vscode.workspace.openTextDocument(file).then(doc => { assert.equal(doc.eol, vscode.EndOfLine.LF); const edit = new vscode.WorkspaceEdit(); edit.set(file, [vscode.TextEdit.setEndOfLine(vscode.EndOfLine.CRLF)]); return vscode.workspace.applyEdit(edit).then(value => { assert.ok(value); assert.ok(doc.isDirty); assert.equal(doc.eol, vscode.EndOfLine.CRLF); }); }); }); }); test('eol, change via onWillSave', async function () { let called = false; let sub = vscode.workspace.onWillSaveTextDocument(e => { called = true; e.waitUntil(Promise.resolve([vscode.TextEdit.setEndOfLine(vscode.EndOfLine.LF)])); }); const file = await createRandomFile('foo\r\nbar\r\nbar'); const doc = await vscode.workspace.openTextDocument(file); assert.equal(doc.eol, vscode.EndOfLine.CRLF); const edit = new vscode.WorkspaceEdit(); edit.set(file, [vscode.TextEdit.insert(new vscode.Position(0, 0), '-changes-')]); const successEdit = await vscode.workspace.applyEdit(edit); assert.ok(successEdit); const successSave = await doc.save(); assert.ok(successSave); assert.ok(called); assert.ok(!doc.isDirty); assert.equal(doc.eol, vscode.EndOfLine.LF); sub.dispose(); }); function assertEqualPath(a: string, b: string): void { assert.ok(pathEquals(a, b), `${a} <-> ${b}`); } test('events: onDidOpenTextDocument, onDidChangeTextDocument, onDidSaveTextDocument', async () => { const file = await createRandomFile(); let disposables: vscode.Disposable[] = []; await revertAllDirty(); // needed for a clean state for `onDidSaveTextDocument` (#102365) let pendingAsserts: Function[] = []; let onDidOpenTextDocument = false; disposables.push(vscode.workspace.onDidOpenTextDocument(e => { pendingAsserts.push(() => assertEqualPath(e.uri.fsPath, file.fsPath)); onDidOpenTextDocument = true; })); let onDidChangeTextDocument = false; disposables.push(vscode.workspace.onDidChangeTextDocument(e => { pendingAsserts.push(() => assertEqualPath(e.document.uri.fsPath, file.fsPath)); onDidChangeTextDocument = true; })); let onDidSaveTextDocument = false; disposables.push(vscode.workspace.onDidSaveTextDocument(e => { pendingAsserts.push(() => assertEqualPath(e.uri.fsPath, file.fsPath)); onDidSaveTextDocument = true; })); const doc = await vscode.workspace.openTextDocument(file); const editor = await vscode.window.showTextDocument(doc); await editor.edit((builder) => { builder.insert(new vscode.Position(0, 0), 'Hello World'); }); await doc.save(); assert.ok(onDidOpenTextDocument); assert.ok(onDidChangeTextDocument); assert.ok(onDidSaveTextDocument); pendingAsserts.forEach(assert => assert()); disposeAll(disposables); return deleteFile(file); }); test('events: onDidSaveTextDocument fires even for non dirty file when saved', async () => { const file = await createRandomFile(); let disposables: vscode.Disposable[] = []; let pendingAsserts: Function[] = []; await revertAllDirty(); // needed for a clean state for `onDidSaveTextDocument` (#102365) let onDidSaveTextDocument = false; disposables.push(vscode.workspace.onDidSaveTextDocument(e => { pendingAsserts.push(() => assertEqualPath(e.uri.fsPath, file.fsPath)); onDidSaveTextDocument = true; })); const doc = await vscode.workspace.openTextDocument(file); await vscode.window.showTextDocument(doc); await vscode.commands.executeCommand('workbench.action.files.save'); assert.ok(onDidSaveTextDocument); pendingAsserts.forEach(fn => fn()); disposeAll(disposables); return deleteFile(file); }); test('openTextDocument, with selection', function () { return createRandomFile('foo\nbar\nbar').then(file => { return vscode.workspace.openTextDocument(file).then(doc => { return vscode.window.showTextDocument(doc, { selection: new vscode.Range(new vscode.Position(1, 1), new vscode.Position(1, 2)) }).then(editor => { assert.equal(editor.selection.start.line, 1); assert.equal(editor.selection.start.character, 1); assert.equal(editor.selection.end.line, 1); assert.equal(editor.selection.end.character, 2); }); }); }); }); test('registerTextDocumentContentProvider, simple', function () { let registration = vscode.workspace.registerTextDocumentContentProvider('foo', { provideTextDocumentContent(uri) { return uri.toString(); } }); const uri = vscode.Uri.parse('foo://testing/virtual.js'); return vscode.workspace.openTextDocument(uri).then(doc => { assert.equal(doc.getText(), uri.toString()); assert.equal(doc.isDirty, false); assert.equal(doc.uri.toString(), uri.toString()); registration.dispose(); }); }); test('registerTextDocumentContentProvider, constrains', function () { // built-in assert.throws(function () { vscode.workspace.registerTextDocumentContentProvider('untitled', { provideTextDocumentContent() { return null; } }); }); // built-in assert.throws(function () { vscode.workspace.registerTextDocumentContentProvider('file', { provideTextDocumentContent() { return null; } }); }); // missing scheme return vscode.workspace.openTextDocument(vscode.Uri.parse('notThere://foo/far/boo/bar')).then(() => { assert.ok(false, 'expected failure'); }, _err => { // expected }); }); test('registerTextDocumentContentProvider, multiple', function () { // duplicate registration let registration1 = vscode.workspace.registerTextDocumentContentProvider('foo', { provideTextDocumentContent(uri) { if (uri.authority === 'foo') { return '1'; } return undefined; } }); let registration2 = vscode.workspace.registerTextDocumentContentProvider('foo', { provideTextDocumentContent(uri) { if (uri.authority === 'bar') { return '2'; } return undefined; } }); return Promise.all([ vscode.workspace.openTextDocument(vscode.Uri.parse('foo://foo/bla')).then(doc => { assert.equal(doc.getText(), '1'); }), vscode.workspace.openTextDocument(vscode.Uri.parse('foo://bar/bla')).then(doc => { assert.equal(doc.getText(), '2'); }) ]).then(() => { registration1.dispose(); registration2.dispose(); }); }); test('registerTextDocumentContentProvider, evil provider', function () { // duplicate registration let registration1 = vscode.workspace.registerTextDocumentContentProvider('foo', { provideTextDocumentContent(_uri) { return '1'; } }); let registration2 = vscode.workspace.registerTextDocumentContentProvider('foo', { provideTextDocumentContent(_uri): string { throw new Error('fail'); } }); return vscode.workspace.openTextDocument(vscode.Uri.parse('foo://foo/bla')).then(doc => { assert.equal(doc.getText(), '1'); registration1.dispose(); registration2.dispose(); }); }); test('registerTextDocumentContentProvider, invalid text', function () { let registration = vscode.workspace.registerTextDocumentContentProvider('foo', { provideTextDocumentContent(_uri) { return <any>123; } }); return vscode.workspace.openTextDocument(vscode.Uri.parse('foo://auth/path')).then(() => { assert.ok(false, 'expected failure'); }, _err => { // expected registration.dispose(); }); }); test('registerTextDocumentContentProvider, show virtual document', function () { let registration = vscode.workspace.registerTextDocumentContentProvider('foo', { provideTextDocumentContent(_uri) { return 'I am virtual'; } }); return vscode.workspace.openTextDocument(vscode.Uri.parse('foo://something/path')).then(doc => { return vscode.window.showTextDocument(doc).then(editor => { assert.ok(editor.document === doc); assert.equal(editor.document.getText(), 'I am virtual'); registration.dispose(); }); }); }); test('registerTextDocumentContentProvider, open/open document', function () { let callCount = 0; let registration = vscode.workspace.registerTextDocumentContentProvider('foo', { provideTextDocumentContent(_uri) { callCount += 1; return 'I am virtual'; } }); const uri = vscode.Uri.parse('foo://testing/path'); return Promise.all([vscode.workspace.openTextDocument(uri), vscode.workspace.openTextDocument(uri)]).then(docs => { let [first, second] = docs; assert.ok(first === second); assert.ok(vscode.workspace.textDocuments.some(doc => doc.uri.toString() === uri.toString())); assert.equal(callCount, 1); registration.dispose(); }); }); test('registerTextDocumentContentProvider, empty doc', function () { let registration = vscode.workspace.registerTextDocumentContentProvider('foo', { provideTextDocumentContent(_uri) { return ''; } }); const uri = vscode.Uri.parse('foo:doc/empty'); return vscode.workspace.openTextDocument(uri).then(doc => { assert.equal(doc.getText(), ''); assert.equal(doc.uri.toString(), uri.toString()); registration.dispose(); }); }); test('registerTextDocumentContentProvider, change event', async function () { let callCount = 0; let emitter = new vscode.EventEmitter<vscode.Uri>(); let registration = vscode.workspace.registerTextDocumentContentProvider('foo', { onDidChange: emitter.event, provideTextDocumentContent(_uri) { return 'call' + (callCount++); } }); const uri = vscode.Uri.parse('foo://testing/path3'); const doc = await vscode.workspace.openTextDocument(uri); assert.equal(callCount, 1); assert.equal(doc.getText(), 'call0'); return new Promise(resolve => { let subscription = vscode.workspace.onDidChangeTextDocument(event => { assert.ok(event.document === doc); assert.equal(event.document.getText(), 'call1'); subscription.dispose(); registration.dispose(); resolve(); }); emitter.fire(doc.uri); }); }); test('findFiles', () => { return vscode.workspace.findFiles('**/image.png').then((res) => { assert.equal(res.length, 2); assert.equal(basename(vscode.workspace.asRelativePath(res[0])), 'image.png'); }); }); test('findFiles - null exclude', async () => { await vscode.workspace.findFiles('**/file.txt').then((res) => { // search.exclude folder is still searched, files.exclude folder is not assert.equal(res.length, 1); assert.equal(basename(vscode.workspace.asRelativePath(res[0])), 'file.txt'); }); await vscode.workspace.findFiles('**/file.txt', null).then((res) => { // search.exclude and files.exclude folders are both searched assert.equal(res.length, 2); assert.equal(basename(vscode.workspace.asRelativePath(res[0])), 'file.txt'); }); }); test('findFiles - exclude', () => { return vscode.workspace.findFiles('**/image.png').then((res) => { assert.equal(res.length, 2); assert.equal(basename(vscode.workspace.asRelativePath(res[0])), 'image.png'); }); }); test('findFiles, exclude', () => { return vscode.workspace.findFiles('**/image.png', '**/sub/**').then((res) => { assert.equal(res.length, 1); assert.equal(basename(vscode.workspace.asRelativePath(res[0])), 'image.png'); }); }); test('findFiles, cancellation', () => { const source = new vscode.CancellationTokenSource(); const token = source.token; // just to get an instance first source.cancel(); return vscode.workspace.findFiles('*.js', null, 100, token).then((res) => { assert.deepEqual(res, []); }); }); test('findTextInFiles', async () => { const options: vscode.FindTextInFilesOptions = { include: '*.ts', previewOptions: { matchLines: 1, charsPerLine: 100 } }; const results: vscode.TextSearchResult[] = []; await vscode.workspace.findTextInFiles({ pattern: 'foo' }, options, result => { results.push(result); }); assert.equal(results.length, 1); const match = <vscode.TextSearchMatch>results[0]; assert(match.preview.text.indexOf('foo') >= 0); assert.equal(vscode.workspace.asRelativePath(match.uri), '10linefile.ts'); }); test('findTextInFiles, cancellation', async () => { const results: vscode.TextSearchResult[] = []; const cancellation = new vscode.CancellationTokenSource(); cancellation.cancel(); await vscode.workspace.findTextInFiles({ pattern: 'foo' }, result => { results.push(result); }, cancellation.token); }); test('applyEdit', async () => { const doc = await vscode.workspace.openTextDocument(vscode.Uri.parse('untitled:' + join(vscode.workspace.rootPath || '', './new2.txt'))); let edit = new vscode.WorkspaceEdit(); edit.insert(doc.uri, new vscode.Position(0, 0), new Array(1000).join('Hello World')); let success = await vscode.workspace.applyEdit(edit); assert.equal(success, true); assert.equal(doc.isDirty, true); }); test('applyEdit should fail when editing deleted resource', withLogDisabled(async () => { const resource = await createRandomFile(); const edit = new vscode.WorkspaceEdit(); edit.deleteFile(resource); edit.insert(resource, new vscode.Position(0, 0), ''); let success = await vscode.workspace.applyEdit(edit); assert.equal(success, false); })); test('applyEdit should fail when renaming deleted resource', withLogDisabled(async () => { const resource = await createRandomFile(); const edit = new vscode.WorkspaceEdit(); edit.deleteFile(resource); edit.renameFile(resource, resource); let success = await vscode.workspace.applyEdit(edit); assert.equal(success, false); })); test('applyEdit should fail when editing renamed from resource', withLogDisabled(async () => { const resource = await createRandomFile(); const newResource = vscode.Uri.file(resource.fsPath + '.1'); const edit = new vscode.WorkspaceEdit(); edit.renameFile(resource, newResource); edit.insert(resource, new vscode.Position(0, 0), ''); let success = await vscode.workspace.applyEdit(edit); assert.equal(success, false); })); test('applyEdit "edit A -> rename A to B -> edit B"', async () => { await testEditRenameEdit(oldUri => oldUri.with({ path: oldUri.path + 'NEW' })); }); test('applyEdit "edit A -> rename A to B (different case)" -> edit B', async () => { await testEditRenameEdit(oldUri => oldUri.with({ path: oldUri.path.toUpperCase() })); }); test('applyEdit "edit A -> rename A to B (same case)" -> edit B', async () => { await testEditRenameEdit(oldUri => oldUri); }); async function testEditRenameEdit(newUriCreator: (oldUri: vscode.Uri) => vscode.Uri): Promise<void> { const oldUri = await createRandomFile(); const newUri = newUriCreator(oldUri); const edit = new vscode.WorkspaceEdit(); edit.insert(oldUri, new vscode.Position(0, 0), 'BEFORE'); edit.renameFile(oldUri, newUri); edit.insert(newUri, new vscode.Position(0, 0), 'AFTER'); assert.ok(await vscode.workspace.applyEdit(edit)); let doc = await vscode.workspace.openTextDocument(newUri); assert.equal(doc.getText(), 'AFTERBEFORE'); assert.equal(doc.isDirty, true); } function nameWithUnderscore(uri: vscode.Uri) { return uri.with({ path: posix.join(posix.dirname(uri.path), `_${posix.basename(uri.path)}`) }); } test('WorkspaceEdit: applying edits before and after rename duplicates resource #42633', withLogDisabled(async function () { let docUri = await createRandomFile(); let newUri = nameWithUnderscore(docUri); let we = new vscode.WorkspaceEdit(); we.insert(docUri, new vscode.Position(0, 0), 'Hello'); we.insert(docUri, new vscode.Position(0, 0), 'Foo'); we.renameFile(docUri, newUri); we.insert(newUri, new vscode.Position(0, 0), 'Bar'); assert.ok(await vscode.workspace.applyEdit(we)); let doc = await vscode.workspace.openTextDocument(newUri); assert.equal(doc.getText(), 'BarHelloFoo'); })); test('WorkspaceEdit: Problem recreating a renamed resource #42634', withLogDisabled(async function () { let docUri = await createRandomFile(); let newUri = nameWithUnderscore(docUri); let we = new vscode.WorkspaceEdit(); we.insert(docUri, new vscode.Position(0, 0), 'Hello'); we.insert(docUri, new vscode.Position(0, 0), 'Foo'); we.renameFile(docUri, newUri); we.createFile(docUri); we.insert(docUri, new vscode.Position(0, 0), 'Bar'); assert.ok(await vscode.workspace.applyEdit(we)); let newDoc = await vscode.workspace.openTextDocument(newUri); assert.equal(newDoc.getText(), 'HelloFoo'); let doc = await vscode.workspace.openTextDocument(docUri); assert.equal(doc.getText(), 'Bar'); })); test('WorkspaceEdit api - after saving a deleted file, it still shows up as deleted. #42667', withLogDisabled(async function () { let docUri = await createRandomFile(); let we = new vscode.WorkspaceEdit(); we.deleteFile(docUri); we.insert(docUri, new vscode.Position(0, 0), 'InsertText'); assert.ok(!(await vscode.workspace.applyEdit(we))); try { await vscode.workspace.openTextDocument(docUri); assert.ok(false); } catch (e) { assert.ok(true); } })); test('WorkspaceEdit: edit and rename parent folder duplicates resource #42641', async function () { let dir = vscode.Uri.parse(`${testFs.scheme}:/before-${rndName()}`); await testFs.createDirectory(dir); let docUri = await createRandomFile('', dir); let docParent = docUri.with({ path: posix.dirname(docUri.path) }); let newParent = nameWithUnderscore(docParent); let we = new vscode.WorkspaceEdit(); we.insert(docUri, new vscode.Position(0, 0), 'Hello'); we.renameFile(docParent, newParent); assert.ok(await vscode.workspace.applyEdit(we)); try { await vscode.workspace.openTextDocument(docUri); assert.ok(false); } catch (e) { assert.ok(true); } let newUri = newParent.with({ path: posix.join(newParent.path, posix.basename(docUri.path)) }); let doc = await vscode.workspace.openTextDocument(newUri); assert.ok(doc); assert.equal(doc.getText(), 'Hello'); }); test('WorkspaceEdit: rename resource followed by edit does not work #42638', withLogDisabled(async function () { let docUri = await createRandomFile(); let newUri = nameWithUnderscore(docUri); let we = new vscode.WorkspaceEdit(); we.renameFile(docUri, newUri); we.insert(newUri, new vscode.Position(0, 0), 'Hello'); assert.ok(await vscode.workspace.applyEdit(we)); let doc = await vscode.workspace.openTextDocument(newUri); assert.equal(doc.getText(), 'Hello'); })); test('WorkspaceEdit: create & override', withLogDisabled(async function () { let docUri = await createRandomFile('before'); let we = new vscode.WorkspaceEdit(); we.createFile(docUri); assert.ok(!await vscode.workspace.applyEdit(we)); assert.equal((await vscode.workspace.openTextDocument(docUri)).getText(), 'before'); we = new vscode.WorkspaceEdit(); we.createFile(docUri, { overwrite: true }); assert.ok(await vscode.workspace.applyEdit(we)); assert.equal((await vscode.workspace.openTextDocument(docUri)).getText(), ''); })); test('WorkspaceEdit: create & ignoreIfExists', withLogDisabled(async function () { let docUri = await createRandomFile('before'); let we = new vscode.WorkspaceEdit(); we.createFile(docUri, { ignoreIfExists: true }); assert.ok(await vscode.workspace.applyEdit(we)); assert.equal((await vscode.workspace.openTextDocument(docUri)).getText(), 'before'); we = new vscode.WorkspaceEdit(); we.createFile(docUri, { overwrite: true, ignoreIfExists: true }); assert.ok(await vscode.workspace.applyEdit(we)); assert.equal((await vscode.workspace.openTextDocument(docUri)).getText(), ''); })); test('WorkspaceEdit: rename & ignoreIfExists', withLogDisabled(async function () { let aUri = await createRandomFile('aaa'); let bUri = await createRandomFile('bbb'); let we = new vscode.WorkspaceEdit(); we.renameFile(aUri, bUri); assert.ok(!await vscode.workspace.applyEdit(we)); we = new vscode.WorkspaceEdit(); we.renameFile(aUri, bUri, { ignoreIfExists: true }); assert.ok(await vscode.workspace.applyEdit(we)); we = new vscode.WorkspaceEdit(); we.renameFile(aUri, bUri, { overwrite: false, ignoreIfExists: true }); assert.ok(!await vscode.workspace.applyEdit(we)); we = new vscode.WorkspaceEdit(); we.renameFile(aUri, bUri, { overwrite: true, ignoreIfExists: true }); assert.ok(await vscode.workspace.applyEdit(we)); })); test('WorkspaceEdit: delete & ignoreIfNotExists', withLogDisabled(async function () { let docUri = await createRandomFile(); let we = new vscode.WorkspaceEdit(); we.deleteFile(docUri, { ignoreIfNotExists: false }); assert.ok(await vscode.workspace.applyEdit(we)); we = new vscode.WorkspaceEdit(); we.deleteFile(docUri, { ignoreIfNotExists: false }); assert.ok(!await vscode.workspace.applyEdit(we)); we = new vscode.WorkspaceEdit(); we.deleteFile(docUri, { ignoreIfNotExists: true }); assert.ok(await vscode.workspace.applyEdit(we)); })); test('WorkspaceEdit: insert & rename multiple', async function () { let [f1, f2, f3] = await Promise.all([createRandomFile(), createRandomFile(), createRandomFile()]); let we = new vscode.WorkspaceEdit(); we.insert(f1, new vscode.Position(0, 0), 'f1'); we.insert(f2, new vscode.Position(0, 0), 'f2'); we.insert(f3, new vscode.Position(0, 0), 'f3'); let f1_ = nameWithUnderscore(f1); we.renameFile(f1, f1_); assert.ok(await vscode.workspace.applyEdit(we)); assert.equal((await vscode.workspace.openTextDocument(f3)).getText(), 'f3'); assert.equal((await vscode.workspace.openTextDocument(f2)).getText(), 'f2'); assert.equal((await vscode.workspace.openTextDocument(f1_)).getText(), 'f1'); try { await vscode.workspace.fs.stat(f1); assert.ok(false); } catch { assert.ok(true); } }); test('workspace.applyEdit drops the TextEdit if there is a RenameFile later #77735 (with opened editor)', async function () { await test77735(true); }); test('workspace.applyEdit drops the TextEdit if there is a RenameFile later #77735 (without opened editor)', async function () { await test77735(false); }); async function test77735(withOpenedEditor: boolean): Promise<void> { const docUriOriginal = await createRandomFile(); const docUriMoved = docUriOriginal.with({ path: `${docUriOriginal.path}.moved` }); if (withOpenedEditor) { const document = await vscode.workspace.openTextDocument(docUriOriginal); await vscode.window.showTextDocument(document); } else { await vscode.commands.executeCommand('workbench.action.closeAllEditors'); } for (let i = 0; i < 4; i++) { let we = new vscode.WorkspaceEdit(); let oldUri: vscode.Uri; let newUri: vscode.Uri; let expected: string; if (i % 2 === 0) { oldUri = docUriOriginal; newUri = docUriMoved; we.insert(oldUri, new vscode.Position(0, 0), 'Hello'); expected = 'Hello'; } else { oldUri = docUriMoved; newUri = docUriOriginal; we.delete(oldUri, new vscode.Range(new vscode.Position(0, 0), new vscode.Position(0, 5))); expected = ''; } we.renameFile(oldUri, newUri); assert.ok(await vscode.workspace.applyEdit(we)); const document = await vscode.workspace.openTextDocument(newUri); assert.equal(document.isDirty, true); await document.save(); assert.equal(document.isDirty, false); assert.equal(document.getText(), expected); await delay(10); } } test('The api workspace.applyEdit failed for some case of mixing resourceChange and textEdit #80688', async function () { const file1 = await createRandomFile(); const file2 = await createRandomFile(); let we = new vscode.WorkspaceEdit(); we.insert(file1, new vscode.Position(0, 0), 'import1;'); const file2Name = basename(file2.fsPath); const file2NewUri = vscode.Uri.parse(file2.toString().replace(file2Name, `new/${file2Name}`)); we.renameFile(file2, file2NewUri); we.insert(file1, new vscode.Position(0, 0), 'import2;'); await vscode.workspace.applyEdit(we); const document = await vscode.workspace.openTextDocument(file1); // const expected = 'import1;import2;'; const expected2 = 'import2;import1;'; assert.equal(document.getText(), expected2); }); test('The api workspace.applyEdit failed for some case of mixing resourceChange and textEdit #80688', async function () { const file1 = await createRandomFile(); const file2 = await createRandomFile(); let we = new vscode.WorkspaceEdit(); we.insert(file1, new vscode.Position(0, 0), 'import1;'); we.insert(file1, new vscode.Position(0, 0), 'import2;'); const file2Name = basename(file2.fsPath); const file2NewUri = vscode.Uri.parse(file2.toString().replace(file2Name, `new/${file2Name}`)); we.renameFile(file2, file2NewUri); await vscode.workspace.applyEdit(we); const document = await vscode.workspace.openTextDocument(file1); const expected = 'import1;import2;'; // const expected2 = 'import2;import1;'; assert.equal(document.getText(), expected); }); });
extensions/vscode-api-tests/src/singlefolder-tests/workspace.test.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00019071222050115466, 0.00016884627984836698, 0.00016251728811766952, 0.00016848498489707708, 0.000003304660367575707 ]
{ "id": 7, "code_window": [ "\t\tif (!isWindows) {\n", "\t\t\treturn Promise.resolve(false);\n", "\t\t}\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\treturn false;\n" ], "file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts", "type": "replace", "edit_start_line_idx": 45 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@types/node@^12.11.7": version "12.11.7" resolved "https://registry.yarnpkg.com/@types/node/-/node-12.11.7.tgz#57682a9771a3f7b09c2497f28129a0462966524a" integrity sha512-JNbGaHFCLwgHn/iCckiGSOZ1XYHsKFwREtzPwSGCVld1SGhOlmZw2D4ZI94HQCrBHbADzW9m4LER/8olJTRGHA== [email protected]: version "3.2.3" resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-3.2.3.tgz#57d35b8686e851e2cc04c403f1c00203976a1813" integrity sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw== ansi-regex@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.0.tgz#ed0317c322064f79466c02966bddb605ab37d998" integrity sha1-7QMXwyIGT3lGbAKWa922Bas32Zg= ansi-regex@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-4.1.0.tgz#8b9f8f08cf1acb843756a839ca8c7e3168c51997" integrity sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg== ansi-styles@^3.2.0, ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== dependencies: color-convert "^1.9.0" anymatch@~3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.1.tgz#c55ecf02185e2469259399310c173ce31233b142" integrity sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg== dependencies: normalize-path "^3.0.0" picomatch "^2.0.4" argparse@^1.0.7: version "1.0.10" resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== dependencies: sprintf-js "~1.0.2" balanced-match@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c= binary-extensions@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.0.0.tgz#23c0df14f6a88077f5f986c0d167ec03c3d5537c" integrity sha512-Phlt0plgpIIBOGTT/ehfFnbNlfsDEiqmzE2KRXoX1bLIlir4X/MR+zSyBEkL05ffWgnRSf/DXv+WrUAVr93/ow== brace-expansion@^1.1.7: version "1.1.11" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== dependencies: balanced-match "^1.0.0" concat-map "0.0.1" braces@~3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== dependencies: fill-range "^7.0.1" [email protected]: version "1.3.1" resolved "https://registry.yarnpkg.com/browser-stdout/-/browser-stdout-1.3.1.tgz#baa559ee14ced73452229bad7326467c61fabd60" integrity sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw== camelcase@^5.0.0: version "5.3.1" resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320" integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg== chalk@^2.0.1: version "2.4.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== dependencies: ansi-styles "^3.2.1" escape-string-regexp "^1.0.5" supports-color "^5.3.0" [email protected]: version "3.3.0" resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.3.0.tgz#12c0714668c55800f659e262d4962a97faf554a6" integrity sha512-dGmKLDdT3Gdl7fBUe8XK+gAtGmzy5Fn0XkkWQuYxGIgWVPPse2CxFA5mtrlD0TOHaHjEUqkWNyP1XdHoJES/4A== dependencies: anymatch "~3.1.1" braces "~3.0.2" glob-parent "~5.1.0" is-binary-path "~2.1.0" is-glob "~4.0.1" normalize-path "~3.0.0" readdirp "~3.2.0" optionalDependencies: fsevents "~2.1.1" cliui@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/cliui/-/cliui-5.0.0.tgz#deefcfdb2e800784aa34f46fa08e06851c7bbbc5" integrity sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA== dependencies: string-width "^3.1.0" strip-ansi "^5.2.0" wrap-ansi "^5.1.0" color-convert@^1.9.0: version "1.9.3" resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== dependencies: color-name "1.1.3" [email protected]: version "1.1.3" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= [email protected]: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= [email protected]: version "3.2.6" resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.6.tgz#e83d17de16d8a7efb7717edbe5fb10135eee629b" integrity sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ== dependencies: ms "^2.1.1" decamelize@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" integrity sha1-9lNNFRSCabIDUue+4m9QH5oZEpA= define-properties@^1.1.2, define-properties@^1.1.3: version "1.1.3" resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1" integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ== dependencies: object-keys "^1.0.12" [email protected]: version "3.5.0" resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12" integrity sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA== emoji-regex@^7.0.1: version "7.0.3" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-7.0.3.tgz#933a04052860c85e83c122479c4748a8e4c72156" integrity sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA== es-abstract@^1.5.1: version "1.14.2" resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.14.2.tgz#7ce108fad83068c8783c3cdf62e504e084d8c497" integrity sha512-DgoQmbpFNOofkjJtKwr87Ma5EW4Dc8fWhD0R+ndq7Oc456ivUfGOOP6oAZTTKl5/CcNMP+EN+e3/iUzgE0veZg== dependencies: es-to-primitive "^1.2.0" function-bind "^1.1.1" has "^1.0.3" has-symbols "^1.0.0" is-callable "^1.1.4" is-regex "^1.0.4" object-inspect "^1.6.0" object-keys "^1.1.1" string.prototype.trimleft "^2.0.0" string.prototype.trimright "^2.0.0" es-to-primitive@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.0.tgz#edf72478033456e8dda8ef09e00ad9650707f377" integrity sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg== dependencies: is-callable "^1.1.4" is-date-object "^1.0.1" is-symbol "^1.0.2" [email protected], escape-string-regexp@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= esprima@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== fill-range@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ== dependencies: to-regex-range "^5.0.1" [email protected], find-up@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73" integrity sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg== dependencies: locate-path "^3.0.0" flat@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/flat/-/flat-4.1.0.tgz#090bec8b05e39cba309747f1d588f04dbaf98db2" integrity sha512-Px/TiLIznH7gEDlPXcUD4KnBusa6kR6ayRUVcnEAbreRIuhkqow/mun59BuRXwoYk7ZQOLW1ZM05ilIvK38hFw== dependencies: is-buffer "~2.0.3" fs.realpath@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= fsevents@~2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.1.2.tgz#4c0a1fb34bc68e543b4b82a9ec392bfbda840805" integrity sha512-R4wDiBwZ0KzpgOWetKDug1FZcYhqYnUYKtfZYt4mD5SBz76q0KR4Q9o7GIPamsVPGmW3EYPPJ0dOOjvx32ldZA== function-bind@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== get-caller-file@^2.0.1: version "2.0.5" resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== glob-parent@~5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.0.tgz#5f4c1d1e748d30cd73ad2944b3577a81b081e8c2" integrity sha512-qjtRgnIVmOfnKUE3NJAQEdk+lKrxfw8t5ke7SXtfMTHcjsBfOfWXCQfdb30zfDoZQ2IRSIiidmjtbHZPZ++Ihw== dependencies: is-glob "^4.0.1" [email protected]: version "7.1.3" resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.3.tgz#3960832d3f1574108342dafd3a67b332c0969df1" integrity sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" inherits "2" minimatch "^3.0.4" once "^1.3.0" path-is-absolute "^1.0.0" [email protected]: version "1.10.5" resolved "https://registry.yarnpkg.com/growl/-/growl-1.10.5.tgz#f2735dc2283674fa67478b10181059355c369e5e" integrity sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA== has-flag@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= has-symbols@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.0.tgz#ba1a8f1af2a0fc39650f5c850367704122063b44" integrity sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q= has@^1.0.1, has@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796" integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw== dependencies: function-bind "^1.1.1" [email protected]: version "1.2.0" resolved "https://registry.yarnpkg.com/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f" integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw== inflight@^1.0.4: version "1.0.6" resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= dependencies: once "^1.3.0" wrappy "1" inherits@2: version "2.0.3" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" integrity sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4= is-binary-path@~2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-2.1.0.tgz#ea1f7f3b80f064236e83470f86c09c254fb45b09" integrity sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw== dependencies: binary-extensions "^2.0.0" is-buffer@~2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-2.0.3.tgz#4ecf3fcf749cbd1e472689e109ac66261a25e725" integrity sha512-U15Q7MXTuZlrbymiz95PJpZxu8IlipAp4dtS3wOdgPXx3mqBnslrWU14kxfHB+Py/+2PVKSr37dMAgM2A4uArw== is-callable@^1.1.4: version "1.1.4" resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.1.4.tgz#1e1adf219e1eeb684d691f9d6a05ff0d30a24d75" integrity sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA== is-date-object@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.1.tgz#9aa20eb6aeebbff77fbd33e74ca01b33581d3a16" integrity sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY= is-extglob@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= is-fullwidth-code-point@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8= is-glob@^4.0.1, is-glob@~4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc" integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg== dependencies: is-extglob "^2.1.1" is-number@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== is-regex@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.0.4.tgz#5517489b547091b0930e095654ced25ee97e9491" integrity sha1-VRdIm1RwkbCTDglWVM7SXul+lJE= dependencies: has "^1.0.1" is-symbol@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.0.2.tgz#a055f6ae57192caee329e7a860118b497a950f38" integrity sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw== dependencies: has-symbols "^1.0.0" isexe@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= [email protected]: version "3.13.1" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.13.1.tgz#aff151b30bfdfa8e49e05da22e7415e9dfa37847" integrity sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw== dependencies: argparse "^1.0.7" esprima "^4.0.0" locate-path@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-3.0.0.tgz#dbec3b3ab759758071b58fe59fc41871af21400e" integrity sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A== dependencies: p-locate "^3.0.0" path-exists "^3.0.0" lodash@^4.17.15: version "4.17.15" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.15.tgz#b447f6670a0455bbfeedd11392eff330ea097548" integrity sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A== [email protected]: version "2.2.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-2.2.0.tgz#5740e1c5d6f0dfda4ad9323b5332107ef6b4c40a" integrity sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg== dependencies: chalk "^2.0.1" [email protected], minimatch@^3.0.4: version "3.0.4" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA== dependencies: brace-expansion "^1.1.7" [email protected]: version "0.0.8" resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" integrity sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0= [email protected]: version "0.5.1" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" integrity sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM= dependencies: minimist "0.0.8" mocha@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/mocha/-/mocha-7.0.1.tgz#276186d35a4852f6249808c6dd4a1376cbf6c6ce" integrity sha512-9eWmWTdHLXh72rGrdZjNbG3aa1/3NRPpul1z0D979QpEnFdCG0Q5tv834N+94QEN2cysfV72YocQ3fn87s70fg== dependencies: ansi-colors "3.2.3" browser-stdout "1.3.1" chokidar "3.3.0" debug "3.2.6" diff "3.5.0" escape-string-regexp "1.0.5" find-up "3.0.0" glob "7.1.3" growl "1.10.5" he "1.2.0" js-yaml "3.13.1" log-symbols "2.2.0" minimatch "3.0.4" mkdirp "0.5.1" ms "2.1.1" node-environment-flags "1.0.6" object.assign "4.1.0" strip-json-comments "2.0.1" supports-color "6.0.0" which "1.3.1" wide-align "1.1.3" yargs "13.3.0" yargs-parser "13.1.1" yargs-unparser "1.6.0" [email protected]: version "2.1.1" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.1.tgz#30a5864eb3ebb0a66f2ebe6d727af06a09d86e0a" integrity sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg== ms@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== [email protected]: version "1.0.6" resolved "https://registry.yarnpkg.com/node-environment-flags/-/node-environment-flags-1.0.6.tgz#a30ac13621f6f7d674260a54dede048c3982c088" integrity sha512-5Evy2epuL+6TM0lCQGpFIj6KwiEsGh1SrHUhTbNX+sLbBtjidPZFAnVK9y5yU1+h//RitLbRHTIMyxQPtxMdHw== dependencies: object.getownpropertydescriptors "^2.0.3" semver "^5.7.0" normalize-path@^3.0.0, normalize-path@~3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== object-inspect@^1.6.0: version "1.6.0" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.6.0.tgz#c70b6cbf72f274aab4c34c0c82f5167bf82cf15b" integrity sha512-GJzfBZ6DgDAmnuaM3104jR4s1Myxr3Y3zfIyN4z3UdqN69oSRacNK8UhnobDdC+7J2AHCjGwxQubNJfE70SXXQ== object-keys@^1.0.11, object-keys@^1.0.12, object-keys@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e" integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== [email protected]: version "4.1.0" resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.0.tgz#968bf1100d7956bb3ca086f006f846b3bc4008da" integrity sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w== dependencies: define-properties "^1.1.2" function-bind "^1.1.1" has-symbols "^1.0.0" object-keys "^1.0.11" object.getownpropertydescriptors@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.0.3.tgz#8758c846f5b407adab0f236e0986f14b051caa16" integrity sha1-h1jIRvW0B62rDyNuCYbxSwUcqhY= dependencies: define-properties "^1.1.2" es-abstract "^1.5.1" once@^1.3.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= dependencies: wrappy "1" p-limit@^2.0.0: version "2.2.1" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.2.1.tgz#aa07a788cc3151c939b5131f63570f0dd2009537" integrity sha512-85Tk+90UCVWvbDavCLKPOLC9vvY8OwEX/RtKF+/1OADJMVlFfEHOiMTPVyxg7mk/dKa+ipdHm0OUkTvCpMTuwg== dependencies: p-try "^2.0.0" p-locate@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-3.0.0.tgz#322d69a05c0264b25997d9f40cd8a891ab0064a4" integrity sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ== dependencies: p-limit "^2.0.0" p-try@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== path-exists@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515" integrity sha1-zg6+ql94yxiSXqfYENe1mwEP1RU= path-is-absolute@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= picomatch@^2.0.4: version "2.2.1" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.1.tgz#21bac888b6ed8601f831ce7816e335bc779f0a4a" integrity sha512-ISBaA8xQNmwELC7eOjqFKMESB2VIqt4PPDD0nsS95b/9dZXvVKOlz9keMSnoGGKcOHXfTvDD6WMaRoSc9UuhRA== readdirp@~3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.2.0.tgz#c30c33352b12c96dfb4b895421a49fd5a9593839" integrity sha512-crk4Qu3pmXwgxdSgGhgA/eXiJAPQiX4GMOZZMXnqKxHX7TaoL+3gQVo/WeuAiogr07DpnfjIMpXXa+PAIvwPGQ== dependencies: picomatch "^2.0.4" require-directory@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= require-main-filename@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-2.0.0.tgz#d0b329ecc7cc0f61649f62215be69af54aa8989b" integrity sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg== semver@^5.7.0: version "5.7.1" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== semver@^6.3.0: version "6.3.0" resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d" integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw== set-blocking@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc= sprintf-js@~1.0.2: version "1.0.3" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= "string-width@^1.0.2 || 2": version "2.1.1" resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e" integrity sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw== dependencies: is-fullwidth-code-point "^2.0.0" strip-ansi "^4.0.0" string-width@^3.0.0, string-width@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-3.1.0.tgz#22767be21b62af1081574306f69ac51b62203961" integrity sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w== dependencies: emoji-regex "^7.0.1" is-fullwidth-code-point "^2.0.0" strip-ansi "^5.1.0" string.prototype.trimleft@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/string.prototype.trimleft/-/string.prototype.trimleft-2.1.0.tgz#6cc47f0d7eb8d62b0f3701611715a3954591d634" integrity sha512-FJ6b7EgdKxxbDxc79cOlok6Afd++TTs5szo+zJTUyow3ycrRfJVE2pq3vcN53XexvKZu/DJMDfeI/qMiZTrjTw== dependencies: define-properties "^1.1.3" function-bind "^1.1.1" string.prototype.trimright@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/string.prototype.trimright/-/string.prototype.trimright-2.1.0.tgz#669d164be9df9b6f7559fa8e89945b168a5a6c58" integrity sha512-fXZTSV55dNBwv16uw+hh5jkghxSnc5oHq+5K/gXgizHwAvMetdAJlHqqoFC1FSDVPYWLkAKl2cxpUT41sV7nSg== dependencies: define-properties "^1.1.3" function-bind "^1.1.1" strip-ansi@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f" integrity sha1-qEeQIusaw2iocTibY1JixQXuNo8= dependencies: ansi-regex "^3.0.0" strip-ansi@^5.0.0, strip-ansi@^5.1.0, strip-ansi@^5.2.0: version "5.2.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-5.2.0.tgz#8c9a536feb6afc962bdfa5b104a5091c1ad9c0ae" integrity sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA== dependencies: ansi-regex "^4.1.0" [email protected]: version "2.0.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" integrity sha1-PFMZQukIwml8DsNEhYwobHygpgo= [email protected]: version "6.0.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-6.0.0.tgz#76cfe742cf1f41bb9b1c29ad03068c05b4c0e40a" integrity sha512-on9Kwidc1IUQo+bQdhi8+Tijpo0e1SS6RoGo2guUwn5vdaxw8RXOF9Vb2ws+ihWOmh4JnCJOvaziZWP1VABaLg== dependencies: has-flag "^3.0.0" supports-color@^5.3.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== dependencies: has-flag "^3.0.0" to-regex-range@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== dependencies: is-number "^7.0.0" [email protected]: version "6.0.0-next.2" resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-6.0.0-next.2.tgz#3d73f86d812304cb91b9fb1efee40ec60b09ed7f" integrity sha512-dKQXRYNUY6BHALQJBJlyZyv9oWlYpbJ2vVoQNNVNPLAYQ3hzNp4zy+iSo7zGx1BPXByArJQDWTKLQh8dz3dnNw== [email protected]: version "7.0.0-next.5.1" resolved "https://registry.yarnpkg.com/vscode-languageclient/-/vscode-languageclient-7.0.0-next.5.1.tgz#ed93f14e4c2cdccedf15002c7bf8ef9cb638f36c" integrity sha512-OONvbk3IFpubwF8/Y5uPQaq5J5CEskpeET3SfK4iGlv5OUK+44JawH/SEW5wXuEPpfdMLEMZLuGLU5v5d7N7PQ== dependencies: semver "^6.3.0" vscode-languageserver-protocol "3.16.0-next.4" [email protected]: version "3.16.0-next.4" resolved "https://registry.yarnpkg.com/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.16.0-next.4.tgz#8f8b1b831d4dfd9b26aa1ba3d2a32c427a91c99f" integrity sha512-6GmPUp2MhJy2H1CTWp2B40Pa9BeC9glrXWmQWVG6A/0V9UbcAjVC9m56znm2GL32iyLDIprTBe8gBvvvcjbpaQ== dependencies: vscode-jsonrpc "6.0.0-next.2" vscode-languageserver-types "3.16.0-next.2" [email protected]: version "3.16.0-next.2" resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.16.0-next.2.tgz#940bd15c992295a65eae8ab6b8568a1e8daa3083" integrity sha512-QjXB7CKIfFzKbiCJC4OWC8xUncLsxo19FzGVp/ADFvvi87PlmBSCAtZI5xwGjF5qE0xkLf0jjKUn3DzmpDP52Q== vscode-nls@^4.1.2: version "4.1.2" resolved "https://registry.yarnpkg.com/vscode-nls/-/vscode-nls-4.1.2.tgz#ca8bf8bb82a0987b32801f9fddfdd2fb9fd3c167" integrity sha512-7bOHxPsfyuCqmP+hZXscLhiHwe7CSuFE4hyhbs22xPIhQ4jv99FcR4eBzfYYVLP356HNFpdvz63FFb/xw6T4Iw== which-module@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/which-module/-/which-module-2.0.0.tgz#d9ef07dce77b9902b8a3a8fa4b31c3e3f7e6e87a" integrity sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho= [email protected]: version "1.3.1" resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== dependencies: isexe "^2.0.0" [email protected]: version "1.1.3" resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.3.tgz#ae074e6bdc0c14a431e804e624549c633b000457" integrity sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA== dependencies: string-width "^1.0.2 || 2" wrap-ansi@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-5.1.0.tgz#1fd1f67235d5b6d0fee781056001bfb694c03b09" integrity sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q== dependencies: ansi-styles "^3.2.0" string-width "^3.0.0" strip-ansi "^5.0.0" wrappy@1: version "1.0.2" resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= y18n@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.0.tgz#95ef94f85ecc81d007c264e190a120f0a3c8566b" integrity sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w== [email protected], yargs-parser@^13.1.1: version "13.1.1" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-13.1.1.tgz#d26058532aa06d365fe091f6a1fc06b2f7e5eca0" integrity sha512-oVAVsHz6uFrg3XQheFII8ESO2ssAf9luWuAd6Wexsu4F3OtIW0o8IribPXYrD4WC24LWtPrJlGy87y5udK+dxQ== dependencies: camelcase "^5.0.0" decamelize "^1.2.0" [email protected]: version "1.6.0" resolved "https://registry.yarnpkg.com/yargs-unparser/-/yargs-unparser-1.6.0.tgz#ef25c2c769ff6bd09e4b0f9d7c605fb27846ea9f" integrity sha512-W9tKgmSn0DpSatfri0nx52Joq5hVXgeLiqR/5G0sZNDoLZFOr/xjBUDcShCOGNsBnEMNo1KAMBkTej1Hm62HTw== dependencies: flat "^4.1.0" lodash "^4.17.15" yargs "^13.3.0" [email protected], yargs@^13.3.0: version "13.3.0" resolved "https://registry.yarnpkg.com/yargs/-/yargs-13.3.0.tgz#4c657a55e07e5f2cf947f8a366567c04a0dedc83" integrity sha512-2eehun/8ALW8TLoIl7MVaRUrg+yCnenu8B4kBlRxj3GJGDKU1Og7sMXPNm1BYyM1DOJmTZ4YeN/Nwxv+8XJsUA== dependencies: cliui "^5.0.0" find-up "^3.0.0" get-caller-file "^2.0.1" require-directory "^2.1.1" require-main-filename "^2.0.0" set-blocking "^2.0.0" string-width "^3.0.0" which-module "^2.0.0" y18n "^4.0.0" yargs-parser "^13.1.1"
extensions/css-language-features/yarn.lock
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.00018896297842729837, 0.0001672240614425391, 0.000163345190230757, 0.00016588036669418216, 0.000004192545929981861 ]
{ "id": 7, "code_window": [ "\t\tif (!isWindows) {\n", "\t\t\treturn Promise.resolve(false);\n", "\t\t}\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\treturn false;\n" ], "file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts", "type": "replace", "edit_start_line_idx": 45 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IJSONSchema } from 'vs/base/common/jsonSchema'; import * as platform from 'vs/platform/registry/common/platform'; import { Event, Emitter } from 'vs/base/common/event'; export const Extensions = { JSONContribution: 'base.contributions.json' }; export interface ISchemaContributions { schemas: { [id: string]: IJSONSchema }; } export interface IJSONContributionRegistry { readonly onDidChangeSchema: Event<string>; /** * Register a schema to the registry. */ registerSchema(uri: string, unresolvedSchemaContent: IJSONSchema): void; /** * Notifies all listeners that the content of the given schema has changed. * @param uri The id of the schema */ notifySchemaChanged(uri: string): void; /** * Get all schemas */ getSchemaContributions(): ISchemaContributions; } function normalizeId(id: string) { if (id.length > 0 && id.charAt(id.length - 1) === '#') { return id.substring(0, id.length - 1); } return id; } class JSONContributionRegistry implements IJSONContributionRegistry { private schemasById: { [id: string]: IJSONSchema }; private readonly _onDidChangeSchema = new Emitter<string>(); readonly onDidChangeSchema: Event<string> = this._onDidChangeSchema.event; constructor() { this.schemasById = {}; } public registerSchema(uri: string, unresolvedSchemaContent: IJSONSchema): void { this.schemasById[normalizeId(uri)] = unresolvedSchemaContent; this._onDidChangeSchema.fire(uri); } public notifySchemaChanged(uri: string): void { this._onDidChangeSchema.fire(uri); } public getSchemaContributions(): ISchemaContributions { return { schemas: this.schemasById, }; } } const jsonContributionRegistry = new JSONContributionRegistry(); platform.Registry.add(Extensions.JSONContribution, jsonContributionRegistry);
src/vs/platform/jsonschemas/common/jsonContributionRegistry.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.0009568065870553255, 0.0002940897538792342, 0.0001663279690546915, 0.0001744847686495632, 0.00024805968860164285 ]
{ "id": 8, "code_window": [ "\t\t}\n", "\n", "\t\treturn new Promise<boolean>(async (resolve) => {\n", "\t\t\tconst Registry = await import('vscode-windows-registry');\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst Registry = await import('vscode-windows-registry');\n" ], "file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts", "type": "replace", "edit_start_line_idx": 48 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { isWindows, isLinux } from 'vs/base/common/platform'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { Registry } from 'vs/platform/registry/common/platform'; import { AccessibilityService } from 'vs/platform/accessibility/common/accessibilityService'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IJSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditing'; import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-browser/environmentService'; interface AccessibilityMetrics { enabled: boolean; } type AccessibilityMetricsClassification = { enabled: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; }; export class NativeAccessibilityService extends AccessibilityService implements IAccessibilityService { declare readonly _serviceBrand: undefined; private didSendTelemetry = false; constructor( @IWorkbenchEnvironmentService environmentService: INativeWorkbenchEnvironmentService, @IContextKeyService contextKeyService: IContextKeyService, @IConfigurationService configurationService: IConfigurationService, @ITelemetryService private readonly _telemetryService: ITelemetryService ) { super(contextKeyService, configurationService); this.setAccessibilitySupport(environmentService.configuration.accessibilitySupport ? AccessibilitySupport.Enabled : AccessibilitySupport.Disabled); } alwaysUnderlineAccessKeys(): Promise<boolean> { if (!isWindows) { return Promise.resolve(false); } return new Promise<boolean>(async (resolve) => { const Registry = await import('vscode-windows-registry'); let value; try { value = Registry.GetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\Accessibility\\Keyboard Preference', 'On'); } catch { resolve(false); } resolve(value === '1'); }); } setAccessibilitySupport(accessibilitySupport: AccessibilitySupport): void { super.setAccessibilitySupport(accessibilitySupport); if (!this.didSendTelemetry && accessibilitySupport === AccessibilitySupport.Enabled) { this._telemetryService.publicLog2<AccessibilityMetrics, AccessibilityMetricsClassification>('accessibility', { enabled: true }); this.didSendTelemetry = true; } } } registerSingleton(IAccessibilityService, NativeAccessibilityService, true); // On linux we do not automatically detect that a screen reader is detected, thus we have to implicitly notify the renderer to enable accessibility when user configures it in settings class LinuxAccessibilityContribution implements IWorkbenchContribution { constructor( @IJSONEditingService jsonEditingService: IJSONEditingService, @IAccessibilityService accessibilityService: AccessibilityService, @IEnvironmentService environmentService: IEnvironmentService ) { const forceRendererAccessibility = () => { if (accessibilityService.isScreenReaderOptimized()) { jsonEditingService.write(environmentService.argvResource, [{ path: ['force-renderer-accessibility'], value: true }], true); } }; forceRendererAccessibility(); accessibilityService.onDidChangeScreenReaderOptimized(forceRendererAccessibility); } } if (isLinux) { Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(LinuxAccessibilityContribution, LifecyclePhase.Ready); }
src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts
1
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.998180627822876, 0.1998060792684555, 0.00016686409071553499, 0.0002109369816025719, 0.39890265464782715 ]
{ "id": 8, "code_window": [ "\t\t}\n", "\n", "\t\treturn new Promise<boolean>(async (resolve) => {\n", "\t\t\tconst Registry = await import('vscode-windows-registry');\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "\t\tconst Registry = await import('vscode-windows-registry');\n" ], "file_path": "src/vs/workbench/services/accessibility/electron-browser/accessibilityService.ts", "type": "replace", "edit_start_line_idx": 48 }
/*--------------------------------------------------------------------------------------------- * 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 type * as vscode from 'vscode'; import * as env from 'vs/base/common/platform'; import { DebugAdapterExecutable } from 'vs/workbench/api/common/extHostTypes'; import { ExecutableDebugAdapter, SocketDebugAdapter, NamedPipeDebugAdapter } from 'vs/workbench/contrib/debug/node/debugAdapter'; import { AbstractDebugAdapter } from 'vs/workbench/contrib/debug/common/abstractDebugAdapter'; import { IExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace'; import { IExtHostExtensionService } from 'vs/workbench/api/common/extHostExtensionService'; import { IExtHostDocumentsAndEditors, ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors'; import { IAdapterDescriptor } from 'vs/workbench/contrib/debug/common/debug'; import { IExtHostConfiguration, ExtHostConfigProvider } from '../common/extHostConfiguration'; import { IExtHostCommands } from 'vs/workbench/api/common/extHostCommands'; import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/common/extensionDescriptionRegistry'; import { IExtHostTerminalService } from 'vs/workbench/api/common/extHostTerminalService'; import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService'; import { ExtHostDebugServiceBase, ExtHostDebugSession, ExtHostVariableResolverService } from 'vs/workbench/api/common/extHostDebugService'; import { ISignService } from 'vs/platform/sign/common/sign'; import { SignService } from 'vs/platform/sign/node/signService'; import { hasChildProcesses, prepareCommand, runInExternalTerminal } from 'vs/workbench/contrib/debug/node/terminals'; import { IDisposable } from 'vs/base/common/lifecycle'; import { AbstractVariableResolverService } from 'vs/workbench/services/configurationResolver/common/variableResolver'; export class ExtHostDebugService extends ExtHostDebugServiceBase { readonly _serviceBrand: undefined; private _integratedTerminalInstance?: vscode.Terminal; private _terminalDisposedListener: IDisposable | undefined; constructor( @IExtHostRpcService extHostRpcService: IExtHostRpcService, @IExtHostWorkspace workspaceService: IExtHostWorkspace, @IExtHostExtensionService extensionService: IExtHostExtensionService, @IExtHostDocumentsAndEditors editorsService: IExtHostDocumentsAndEditors, @IExtHostConfiguration configurationService: IExtHostConfiguration, @IExtHostTerminalService private _terminalService: IExtHostTerminalService, @IExtHostCommands commandService: IExtHostCommands ) { super(extHostRpcService, workspaceService, extensionService, editorsService, configurationService, commandService); } protected createDebugAdapter(adapter: IAdapterDescriptor, session: ExtHostDebugSession): AbstractDebugAdapter | undefined { switch (adapter.type) { case 'server': return new SocketDebugAdapter(adapter); case 'pipeServer': return new NamedPipeDebugAdapter(adapter); case 'executable': return new ExecutableDebugAdapter(adapter, session.type); } return super.createDebugAdapter(adapter, session); } protected daExecutableFromPackage(session: ExtHostDebugSession, extensionRegistry: ExtensionDescriptionRegistry): DebugAdapterExecutable | undefined { const dae = ExecutableDebugAdapter.platformAdapterExecutable(extensionRegistry.getAllExtensionDescriptions(), session.type); if (dae) { return new DebugAdapterExecutable(dae.command, dae.args, dae.options); } return undefined; } protected createSignService(): ISignService | undefined { return new SignService(); } public async $runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments): Promise<number | undefined> { if (args.kind === 'integrated') { if (!this._terminalDisposedListener) { // React on terminal disposed and check if that is the debug terminal #12956 this._terminalDisposedListener = this._terminalService.onDidCloseTerminal(terminal => { if (this._integratedTerminalInstance && this._integratedTerminalInstance === terminal) { this._integratedTerminalInstance = undefined; } }); } let needNewTerminal = true; // be pessimistic if (this._integratedTerminalInstance) { const pid = await this._integratedTerminalInstance.processId; needNewTerminal = await hasChildProcesses(pid); // if no processes running in terminal reuse terminal } const configProvider = await this._configurationService.getConfigProvider(); const shell = this._terminalService.getDefaultShell(true, configProvider); let cwdForPrepareCommand: string | undefined; if (needNewTerminal || !this._integratedTerminalInstance) { const options: vscode.TerminalOptions = { shellPath: shell, // shellArgs: this._terminalService._getDefaultShellArgs(configProvider), cwd: args.cwd, name: args.title || nls.localize('debug.terminal.title', "debuggee"), }; this._integratedTerminalInstance = this._terminalService.createTerminalFromOptions(options); } else { cwdForPrepareCommand = args.cwd; } const terminal = this._integratedTerminalInstance; terminal.show(); const shellProcessId = await this._integratedTerminalInstance.processId; const command = prepareCommand(shell, args.args, cwdForPrepareCommand, args.env); terminal.sendText(command, true); return shellProcessId; } else if (args.kind === 'external') { return runInExternalTerminal(args, await this._configurationService.getConfigProvider()); } return super.$runInTerminal(args); } protected createVariableResolver(folders: vscode.WorkspaceFolder[], editorService: ExtHostDocumentsAndEditors, configurationService: ExtHostConfigProvider): AbstractVariableResolverService { return new ExtHostVariableResolverService(folders, editorService, configurationService, process.env as env.IProcessEnvironment); } }
src/vs/workbench/api/node/extHostDebugService.ts
0
https://github.com/microsoft/vscode/commit/c393e6a3a9e855d9cd0fb34199578923e6e936cb
[ 0.0002954665687866509, 0.0001886843383545056, 0.00016558422066736966, 0.00017073466733563691, 0.00003913841283065267 ]