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": 5,
"code_window": [
" * @default []\n",
" * @description List of files/patterns to load in the browser.\n",
" */\n",
" files?: (FilePattern|string)[];\n",
" /**\n",
" * @default []\n",
" * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']...\n",
" * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM).\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" files?: (FilePattern | string)[];\n"
],
"file_path": "karma/karma.d.ts",
"type": "replace",
"edit_start_line_idx": 193
} | /// <reference path="../node/node.d.ts" />
/// <reference path="sql.js.d.ts" />
import fs = require("fs");
import SQL = require("sql.js");
var DB_PATH = "data.db";
function createFile(path: string): void {
var fd = fs.openSync(path, "a");
fs.closeSync(fd);
}
// Open the database file. If it does not exist, create a blank database in memory.
var databaseData: Buffer;
databaseData = fs.existsSync(DB_PATH) ? fs.readFileSync(DB_PATH) : null;
var db = new SQL.Database(databaseData);
// Create a new table 'test_table' in the database in memory.
var createTableStatement =
"DROP TABLE IF EXISTS test_table;" +
"CREATE TABLE test_table (id INTEGER PRIMARY KEY, content TEXT);";
db.run(createTableStatement);
// Insert 2 records for testing.
var insertRecordStatement =
"INSERT INTO test_table (id, content) VALUES (@id, @content);";
db.run(insertRecordStatement, {
"@id": 1,
"@content": "Content 1"
});
db.run(insertRecordStatement, {
"@id": 2,
"@content": "Content 2"
});
try {
// This query will throw exception: primary key constraint failed.
db.run(insertRecordStatement, {
"@id": 1,
"@content": "Content 3"
});
} catch (ex) {
console.warn(ex);
}
// A simple SELECT query.
var selectRecordStatement =
"SELECT * FROM test_table WHERE id = @id;"
var selectStatementObject = db.prepare(selectRecordStatement);
var results = selectStatementObject.get({
"@id": 1
});
console.log(results);
selectStatementObject.free();
// Access the results one by one, asynchronously.
var selectRecordsStatement =
"SELECT * FROM test_table;";
db.each(
selectRecordsStatement,
(obj: { [columnName: string]: number | string | Uint8Array }): void => {
console.log(obj);
},
(): void => {
console.info("Iteration done.");
dbAccessDone();
});
function dbAccessDone(): void {
// Save the database into SQLite version 3 format.
if (!fs.existsSync(DB_PATH)) {
createFile(DB_PATH);
}
var exportedData = db.export();
fs.writeFileSync(DB_PATH, exportedData);
// Finally, close the database connection and release the resources in memory.
db.close();
}
| sql.js/sql.js-tests.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b | [
0.00017401803052052855,
0.00016952719306573272,
0.00016469786351080984,
0.00017030152957886457,
0.0000028308527362241875
] |
{
"id": 5,
"code_window": [
" * @default []\n",
" * @description List of files/patterns to load in the browser.\n",
" */\n",
" files?: (FilePattern|string)[];\n",
" /**\n",
" * @default []\n",
" * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']...\n",
" * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM).\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" files?: (FilePattern | string)[];\n"
],
"file_path": "karma/karma.d.ts",
"type": "replace",
"edit_start_line_idx": 193
} | /// <reference path="moment.d.ts" />
moment().add('hours', 1).fromNow();
var day = new Date(2011, 9, 16);
var dayWrapper = moment(day);
var otherDay = moment(new Date(2020, 3, 7));
var day1 = moment(1318781876406);
var day2 = moment.unix(1318781876);
var day3 = moment("Dec 25, 1995");
var day4 = moment("12-25-1995", "MM-DD-YYYY");
var day5 = moment("12-25-1995", ["MM-DD-YYYY", "YYYY-MM-DD"]);
var day6 = moment("05-06-1995", ["MM-DD-YYYY", "DD-MM-YYYY"]);
var now = moment();
var day7 = moment([2010, 1, 14, 15, 25, 50, 125]);
var day8 = moment([2010]);
var day9 = moment([2010, 6]);
var day10 = moment([2010, 6, 10]);
var array = [2010, 1, 14, 15, 25, 50, 125];
var day11 = moment(Date.UTC.apply({}, array));
var day12 = moment.unix(1318781876);
moment({ years: 2010, months: 3, days: 5, hours: 15, minutes: 10, seconds: 3, milliseconds: 123 });
moment("20140101", "YYYYMMDD", true);
moment("20140101", "YYYYMMDD", "en");
moment("20140101", "YYYYMMDD", "en", true);
moment("20140101", ["YYYYMMDD"], true);
moment("20140101", ["YYYYMMDD"], "en");
moment("20140101", ["YYYYMMDD"], "en", true);
moment(day.toISOString(), moment.ISO_8601);
moment(day.toISOString(), moment.ISO_8601, true);
moment(day.toISOString(), moment.ISO_8601, "en", true);
moment(day.toISOString(), [moment.ISO_8601]);
moment(day.toISOString(), [moment.ISO_8601], true);
moment(day.toISOString(), [moment.ISO_8601], "en", true);
var a = moment([2012]);
var b = moment(a);
a.year(2000);
b.year(); // 2012
moment.utc();
moment.utc(12345);
moment.utc([12, 34, 56]);
moment.utc({ years: 2010, months: 3, days: 5, hours: 15, minutes: 10, seconds: 3, milliseconds: 123 });
moment.utc("1-2-3");
moment.utc("1-2-3", "3-2-1");
moment.utc("1-2-3", "3-2-1", true);
moment.utc("1-2-3", "3-2-1", "en");
moment.utc("1-2-3", "3-2-1", "en", true);
moment.utc("01-01-2014", ["DD-MM-YYYY", "MM-DD-YYYY"]);
moment.utc("01-01-2014", ["DD-MM-YYYY", "MM-DD-YYYY"], true);
moment.utc("01-01-2014", ["DD-MM-YYYY", "MM-DD-YYYY"], "en");
moment.utc("01-01-2014", ["DD-MM-YYYY", "MM-DD-YYYY"], "en", true);
var a2 = moment.utc([2011, 0, 1, 8]);
a.hours();
a.local();
a.hours();
moment("2011-10-10", "YYYY-MM-DD").isValid();
moment("2011-10-50", "YYYY-MM-DD").isValid();
moment("2011-10-10T10:20:90").isValid();
moment([2011, 0, 1]).isValid();
moment([2011, 0, 50]).isValid();
moment("not a date").isValid();
moment().add('days', 7).subtract('months', 1).year(2009).hours(0).minutes(0).seconds(0);
moment().add('days', 7);
moment().add('days', 7).add('months', 1);
moment().add({days:7,months:1});
moment().add('milliseconds', 1000000);
moment().add('days', 360);
moment([2010, 0, 31]);
moment([2010, 0, 31]).add('months', 1);
var m = moment(new Date(2011, 2, 12, 5, 0, 0));
m.hours();
m.add('days', 1).hours();
var m2 = moment(new Date(2011, 2, 12, 5, 0, 0));
m2.hours();
m2.add('hours', 24).hours();
var duration = moment.duration({'days': 1});
moment([2012, 0, 31]).add(duration);
moment().add('seconds', 1);
moment().add('seconds', '1');
moment().add(1, 'seconds');
moment().add('1', 'seconds');
moment().add('seconds', '1');
moment().subtract('days', 7);
moment().seconds(30);
moment().minutes(30);
moment().hours(12);
moment().date(5);
moment().day(5);
moment().day("Sunday");
moment().month(5);
moment().month("January");
moment().year(1984);
moment().startOf('year');
moment().month(0).date(1).hours(0).minutes(0).seconds(0).milliseconds(0);
moment().startOf('hour');
moment().minutes(0).seconds(0).milliseconds(0);
moment().weekday();
moment().weekday(0);
moment().isoWeekday(1);
moment().isoWeekday();
moment().weekYear(2);
moment().weekYear();
moment().isoWeekYear(3);
moment().isoWeekYear();
moment().week();
moment().week(45);
moment().weeks();
moment().weeks(45);
moment().isoWeek();
moment().isoWeek(45);
moment().isoWeeks();
moment().isoWeeks(45);
moment().dayOfYear();
moment().dayOfYear(45);
moment().set('year', 2013);
moment().set('month', 3); // April
moment().set('date', 1);
moment().set('hour', 13);
moment().set('minute', 20);
moment().set('second', 30);
moment().set('millisecond', 123);
moment().set({'year': 2013, 'month': 3});
var getMilliseconds: number = moment().milliseconds();
var getSeconds: number = moment().seconds();
var getMinutes: number = moment().minutes();
var getHours: number = moment().hours();
var getDate: number = moment().date();
var getDay: number = moment().day();
var getMonth: number = moment().month();
var getQuater: number = moment().quarter();
var getYear: number = moment().year();
moment().hours(0).minutes(0).seconds(0).milliseconds(0);
var a3 = moment([2011, 0, 1, 8]);
a3.hours();
a3.utc();
a3.hours();
var a4 = moment([2010, 1, 14, 15, 25, 50, 125]);
a4.format("dddd, MMMM Do YYYY, h:mm:ss a");
a4.format("ddd, hA");
moment().format('\\L');
moment().format('[today] DDDD');
var a5 = moment([2007, 0, 29]);
var b5 = moment([2007, 0, 28]);
a5.from(b5);
var a6 = moment([2007, 0, 29]);
var b6 = moment([2007, 0, 28]);
a6.from(b6);
a6.from([2007, 0, 28]);
a6.from(new Date(2007, 0, 28));
a6.from("1-28-2007");
var a7 = moment();
var b7 = moment("10-10-1900", "MM-DD-YYYY");
a7.from(b7);
var start = moment([2007, 0, 5]);
var end = moment([2007, 0, 10]);
start.from(end);
start.from(end, true);
moment([2007, 0, 29]).fromNow();
moment([2007, 0, 29]).fromNow();
moment([2007, 0, 29]).fromNow(true);
var a8 = moment([2007, 0, 29]);
var b8 = moment([2007, 0, 28]);
a8.diff(b8) ;
a8.diff(b8, 'days');
a8.diff(b8, 'years')
a8.diff(b8, 'years', true);
moment([2007, 0, 29]).toDate();
moment([2007, 1, 23]).toISOString();
moment(1318874398806).valueOf();
moment(1318874398806).unix();
moment([2000]).isLeapYear();
moment().zone();
moment().utcOffset();
moment("2012-2", "YYYY-MM").daysInMonth();
moment([2011, 2, 12]).isDST();
moment.isMoment();
moment.isMoment(new Date());
moment.isMoment(moment());
moment.isDate(new Date());
moment.isDate(/regexp/);
moment.isDuration();
moment.isDuration(new Date());
moment.isDuration(moment.duration());
moment().isBetween(moment(), moment());
moment().isBetween(new Date(), new Date());
moment().isBetween([1,1,2000], [1,1,2001], "year");
moment.localeData('fr');
moment(1316116057189).fromNow();
moment.localeData('en');
var globalLang = moment();
var localLang = moment();
localLang.localeData('fr');
localLang.format('LLLL');
globalLang.format('LLLL');
moment.duration(100);
moment.duration(2, 'seconds');
moment.duration({
seconds: 2,
minutes: 2,
hours: 2,
days: 2,
weeks: 2,
months: 2,
years: 2
});
moment.duration(1, "minutes").humanize();
moment.duration(500).milliseconds();
moment.duration(500).asMilliseconds();
moment.duration(500).seconds();
moment.duration(500).asSeconds();
moment.duration().minutes();
moment.duration().asMinutes();
moment.duration().toISOString();
moment.duration().toJSON();
var adur = moment.duration(3, 'd');
var bdur = moment.duration(2, 'd');
adur.subtract(bdur).days();
adur.subtract(1).days();
adur.subtract(1, 'd').days();
// Selecting a language
moment.locale();
moment.locale('en');
moment.locale(['en', 'fr']);
// Defining a custom language:
moment.locale('en', {
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
weekdays: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
weekdaysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
weekdaysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
longDateFormat: {
LTS: "h:mm:ss A",
LT: "h:mm A",
L: "MM/DD/YYYY",
LL: "MMMM D YYYY",
LLL: "MMMM D YYYY LT",
LLLL: "dddd, MMMM D YYYY LT"
},
relativeTime: {
future: "in %s",
past: "%s ago",
s: "seconds",
m: "a minute",
mm: "%d minutes",
h: "an hour",
hh: "%d hours",
d: "a day",
dd: "%d days",
M: "a month",
MM: "%d months",
y: "a year",
yy: "%d years"
},
meridiem: function (hour, minute, isLower) {
if (hour < 9) {
return "??";
} else if (hour < 11 && minute < 30) {
return "??";
} else if (hour < 13 && minute < 30) {
return "??";
} else if (hour < 18) {
return "??";
} else {
return "??";
}
},
calendar: {
lastDay: '[Yesterday at] LT',
sameDay: '[Today at] LT',
nextDay: '[Tomorrow at] LT',
lastWeek: '[last] dddd [at] LT',
nextWeek: 'dddd [at] LT',
sameElse: 'L'
},
ordinal: function (number) {
var b = number % 10;
return (~~(number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
},
week: {
dow: 1,
doy: 4
}
});
moment.locale('en', {
months : [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
]
});
moment.locale('en', {
months : function (momentToFormat: moment.Moment, format: string) {
// momentToFormat is the moment currently being formatted
// format is the formatting string
if (/^MMMM/.test(format)) { // if the format starts with 'MMMM'
return this.nominative[momentToFormat.month()];
} else {
return this.subjective[momentToFormat.month()];
}
}
});
moment.locale('en', {
monthsShort : [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]
});
moment.locale('en', {
monthsShort : function (momentToFormat: moment.Moment, format: string) {
if (/^MMMM/.test(format)) {
return this.nominative[momentToFormat.month()];
} else {
return this.subjective[momentToFormat.month()];
}
}
});
moment.locale('en', {
weekdays : [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
]
});
moment.locale('en', {
weekdays : function (momentToFormat: moment.Moment) {
return this.weekdays[momentToFormat.day()];
}
});
moment.locale('en', {
weekdaysShort : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
});
moment.locale('en', {
weekdaysShort : function (momentToFormat: moment.Moment) {
return this.weekdaysShort[momentToFormat.day()];
}
});
moment.locale('en', {
weekdaysMin : ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
});
moment.locale('en', {
weekdaysMin : function (momentToFormat: moment.Moment) {
return this.weekdaysMin[momentToFormat.day()];
}
});
moment.locale('en', {
longDateFormat : {
LTS: "h:mm:ss A",
LT: "h:mm A",
L: "MM/DD/YYYY",
l: "M/D/YYYY",
LL: "MMMM Do YYYY",
ll: "MMM D YYYY",
LLL: "MMMM Do YYYY LT",
lll: "MMM D YYYY LT",
LLLL: "dddd, MMMM Do YYYY LT",
llll: "ddd, MMM D YYYY LT"
}
});
moment.locale('en', {
longDateFormat : {
LTS: "h:mm A",
LT: "h:mm A",
L: "MM/DD/YYYY",
LL: "MMMM Do YYYY",
LLL: "MMMM Do YYYY LT",
LLLL: "dddd, MMMM Do YYYY LT"
}
});
moment.locale('en', {
relativeTime : {
future: "in %s",
past: "%s ago",
s: "seconds",
m: "a minute",
mm: "%d minutes",
h: "an hour",
hh: "%d hours",
d: "a day",
dd: "%d days",
M: "a month",
MM: "%d months",
y: "a year",
yy: "%d years"
}
});
moment.locale('en', {
meridiem : function (hour, minute, isLowercase) {
if (hour < 9) {
return "早上";
} else if (hour < 11 && minute < 30) {
return "上午";
} else if (hour < 13 && minute < 30) {
return "中午";
} else if (hour < 18) {
return "下午";
} else {
return "晚上";
}
}
});
moment.locale('en', {
calendar : {
lastDay : '[Yesterday at] LT',
sameDay : '[Today at] LT',
nextDay : function () {
return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
},
lastWeek : '[last] dddd [at] LT',
nextWeek : 'dddd [at] LT',
sameElse : 'L'
}
});
moment.locale('en', {
ordinal : function (number) {
var b = number % 10;
var output = (~~ (number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
return number + output;
}
});
console.log(moment.version);
moment.defaultFormat = 'YYYY-MM-DD HH:mm';
| moment/moment-tests.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b | [
0.00017712506814859807,
0.00017339580517727882,
0.00017011341697070748,
0.00017333237337879837,
0.0000016508779481227975
] |
{
"id": 6,
"code_window": [
" * of that, you'll want to engineer this so that your automated builds use the coverage entry in the \"reporters\" list,\n",
" * but your interactive debugging does not.\n",
" *\n",
" */\n",
" preprocessors?: { [name: string]: string|string[] }\n",
" /**\n",
" * @default 'http:'\n",
" * Possible Values:\n",
" * <ul>\n",
" * <li>http:</li>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" preprocessors?: { [name: string]: string | string[] }\n"
],
"file_path": "karma/karma.d.ts",
"type": "replace",
"edit_start_line_idx": 259
} | // Type definitions for karma v0.13.9
// Project: https://github.com/karma-runner/karma
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../bluebird/bluebird.d.ts" />
/// <reference path="../node/node.d.ts" />
/// <reference path="../log4js/log4js.d.ts" />
declare module 'karma' {
// See Karma public API https://karma-runner.github.io/0.13/dev/public-api.html
import Promise = require('bluebird');
import https = require('https');
import log4js = require('log4js');
namespace karma {
interface Karma {
/**
* `start` method is deprecated since 0.13. It will be removed in 0.14.
* Please use
* <code>
* server = new Server(config, [done])
* server.start()
* </code>
* instead.
*/
server: DeprecatedServer;
Server: Server;
runner: Runner;
launcher: Launcher;
VERSION: string;
}
interface LauncherStatic {
generateId(): string;
//TODO: injector should be of type `di.Injector`
new(emitter: NodeJS.EventEmitter, injector: any): Launcher;
}
interface Launcher {
Launcher: LauncherStatic;
//TODO: Can this return value ever be typified?
launch(names: string[], protocol: string, hostname: string, port: number, urlRoot: string): any[];
kill(id: string, callback: Function): boolean;
restart(id: string): boolean;
killAll(callback: Function): void;
areAllCaptured(): boolean;
markCaptured(id: string): void;
}
interface DeprecatedServer {
start(options?: any, callback?: ServerCallback): void;
}
interface Runner {
run(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): void;
}
interface Server extends NodeJS.EventEmitter {
new(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): Server;
/**
* Start the server
*/
start(): void;
/**
* Get properties from the injector
* @param token
*/
get(token: string): any;
/**
* Force a refresh of the file list
*/
refreshFiles(): Promise<any>;
///**
// * Backward-compatibility with karma-intellij bundled with WebStorm.
// * Deprecated since version 0.13, to be removed in 0.14
// */
//static start(): void;
}
interface ServerCallback {
(exitCode: number): void;
}
interface Config {
set: (config: ConfigOptions) => void;
LOG_DISABLE: string;
LOG_ERROR: string;
LOG_WARN: string;
LOG_INFO: string;
LOG_DEBUG: string;
}
interface ConfigFile {
configFile: string;
}
interface ConfigOptions {
/**
* @description Enable or disable watching files and executing the tests whenever one of these files changes.
* @default true
*/
autoWatch?: boolean;
/**
* @description When Karma is watching the files for changes, it tries to batch multiple changes into a single run
* so that the test runner doesn't try to start and restart running tests more than it should.
* The configuration setting tells Karma how long to wait (in milliseconds) after any changes have occurred
* before starting the test process again.
* @default 250
*/
autoWatchBatchDelay?: number;
/**
* @default ''
* @description The root path location that will be used to resolve all relative paths defined in <code>files</code> and <code>exclude</code>.
* If the basePath configuration is a relative path then it will be resolved to
* the <code>__dirname</code> of the configuration file.
*/
basePath?: string;
/**
* @default 2000
* @description How long does Karma wait for a browser to reconnect (in ms).
* <p>
* With a flaky connection it is pretty common that the browser disconnects,
* but the actual test execution is still running without any problems. Karma does not treat a disconnection
* as immediate failure and will wait <code>browserDisconnectTimeout</code> (ms).
* If the browser reconnects during that time, everything is fine.
* </p>
*/
browserDisconnectTimeout?: number;
/**
* @default 0
* @description The number of disconnections tolerated.
* <p>
* The <code>disconnectTolerance</code> value represents the maximum number of tries a browser will attempt
* in the case of a disconnection. Usually any disconnection is considered a failure,
* but this option allows you to define a tolerance level when there is a flaky network link between
* the Karma server and the browsers.
* </p>
*/
browserDisconnectTolerance?: number;
/**
* @default 10000
* @description How long will Karma wait for a message from a browser before disconnecting from it (in ms).
* <p>
* If, during test execution, Karma does not receive any message from a browser within
* <code>browserNoActivityTimeout</code> (ms), it will disconnect from the browser
* </p>
*/
browserNoActivityTimeout?: number;
/**
* @default []
* Possible Values:
* <ul>
* <li>Chrome (launcher comes installed with Karma)</li>
* <li>ChromeCanary (launcher comes installed with Karma)</li>
* <li>PhantomJS (launcher comes installed with Karma)</li>
* <li>Firefox (launcher requires karma-firefox-launcher plugin)</li>
* <li>Opera (launcher requires karma-opera-launcher plugin)</li>
* <li>Internet Explorer (launcher requires karma-ie-launcher plugin)</li>
* <li>Safari (launcher requires karma-safari-launcher plugin)</li>
* </ul>
* @description A list of browsers to launch and capture. When Karma starts up, it will also start up each browser
* which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well.
* You can capture any browser manually by opening the browser and visiting the URL where
* the Karma web server is listening (by default it is <code>http://localhost:9876/</code>).
*/
browsers?: string[];
/**
* @default 60000
* @description Timeout for capturing a browser (in ms).
* <p>
* The <code>captureTimeout</code> value represents the maximum boot-up time allowed for a
* browser to start and connect to Karma. If any browser does not get captured within the timeout, Karma
* will kill it and try to launch it again and, after three attempts to capture it, Karma will give up.
* </p>
*/
captureTimeout?: number;
client?: ClientOptions;
/**
* @default true
* @description Enable or disable colors in the output (reporters and logs).
*/
colors?: boolean;
/**
* @default []
* @description List of files/patterns to exclude from loaded files.
*/
exclude?: string[];
/**
* @default []
* @description List of files/patterns to load in the browser.
*/
files?: (FilePattern|string)[];
/**
* @default []
* @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']...
* Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM).
*/
frameworks?: string[];
/**
* @default 'localhost'
* @description Hostname to be used when capturing browsers.
*/
hostname?: string;
/**
* @default {}
* @description Options object to be used by Node's https class.
* Object description can be found in the
* [NodeJS.org API docs](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener)
*/
httpsServerOptions?: https.ServerOptions;
/**
* @default config.LOG_INFO
* Possible values:
* <ul>
* <li>config.LOG_DISABLE</li>
* <li>config.LOG_ERROR</li>
* <li>config.LOG_WARN</li>
* <li>config.LOG_INFO</li>
* <li>config.LOG_DEBUG</li>
* </ul>
* @description Level of logging.
*/
logLevel?: string;
/**
* @default [{type: 'console'}]
* @description A list of log appenders to be used. See the documentation for [log4js] for more information.
*/
loggers?: log4js.AppenderConfigBase[];
/**
* @default ['karma-*']
* @description List of plugins to load. A plugin can be a string (in which case it will be required
* by Karma) or an inlined plugin - Object.
* By default, Karma loads all sibling NPM modules which have a name starting with karma-*.
* Note: Just about all plugins in Karma require an additional library to be installed (via NPM).
*/
plugins?: any[];
/**
* @default 9876
* @description The port where the web server will be listening.
*/
port?: number;
/**
* @default {'**\/*.coffee': 'coffee'}
* @description A map of preprocessors to use.
*
* Preprocessors can be loaded through [plugins].
*
* Note: Just about all preprocessors in Karma (other than CoffeeScript and some other defaults)
* require an additional library to be installed (via NPM).
*
* Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance,
* if you are using the "coverage" preprocessor on your source files, if you then attempt to interactively debug
* your tests, you'll discover that your expected source code is completely changed from what you expected. Because
* of that, you'll want to engineer this so that your automated builds use the coverage entry in the "reporters" list,
* but your interactive debugging does not.
*
*/
preprocessors?: { [name: string]: string|string[] }
/**
* @default 'http:'
* Possible Values:
* <ul>
* <li>http:</li>
* <li>https:</li>
* </ul>
* @description Protocol used for running the Karma webserver.
* Determines the use of the Node http or https class.
* Note: Using <code>'https:'</code> requires you to specify <code>httpsServerOptions</code>.
*/
protocol?: string;
/**
* @default {}
* @description A map of path-proxy pairs.
*/
proxies?: { [path: string]: string }
/**
* @default true
* @description Whether or not Karma or any browsers should raise an error when an inavlid SSL certificate is found.
*/
proxyValidateSSL?: boolean;
/**
* @default 0
* @description Karma will report all the tests that are slower than given time limit (in ms).
* This is disabled by default (since the default value is 0).
*/
reportSlowerThan?: number;
/**
* @default ['progress']
* Possible Values:
* <ul>
* <li>dots</li>
* <li>progress</li>
* </ul>
* @description A list of reporters to use.
* Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins.
* Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via NPM).
*/
reporters?: string[];
/**
* @default false
* @description Continuous Integration mode.
* If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending
* on whether all tests passed or any tests failed.
*/
singleRun?: boolean;
/**
* @default ['polling', 'websocket']
* @description An array of allowed transport methods between the browser and testing server. This configuration setting
* is handed off to [socket.io](http://socket.io/) (which manages the communication
* between browsers and the testing server).
*/
transports?: string[];
/**
* @default '/'
* @description The base url, where Karma runs.
* All of Karma's urls get prefixed with the urlRoot. This is helpful when using proxies, as
* sometimes you might want to proxy a url that is already taken by Karma.
*/
urlRoot?: string;
}
interface ClientOptions {
/**
* @default undefined
* @description When karma run is passed additional arguments on the command-line, they
* are passed through to the test adapter as karma.config.args (an array of strings).
* The client.args option allows you to set this value for actions other than run.
* How this value is used is up to your test adapter - you should check your adapter's
* documentation to see how (and if) it uses this value.
*/
args?: string[];
/**
* @default true
* @description Run the tests inside an iFrame or a new window
* If true, Karma runs the tests inside an iFrame. If false, Karma runs the tests in a new window. Some tests may not run in an
* iFrame and may need a new window to run.
*/
useIframe?: boolean;
/**
* @default true
* @description Capture all console output and pipe it to the terminal.
*/
captureConsole?: boolean;
}
interface FilePattern {
/**
* The pattern to use for matching. This property is mandatory.
*/
pattern: string;
/**
* @default true
* @description If <code>autoWatch</code> is true all files that have set watched to true will be watched
* for changes.
*/
watched?: boolean;
/**
* @default true
* @description Should the files be included in the browser using <script> tag? Use false if you want to
* load them manually, eg. using Require.js.
*/
included?: boolean;
/**
* @default true
* @description Should the files be served by Karma's webserver?
*/
served?: boolean;
/**
* @default false
* @description Should the files be served from disk on each request by Karma's webserver?
*/
nocache?: boolean;
}
}
var karma: karma.Karma;
export = karma;
}
| karma/karma.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b | [
0.23264339566230774,
0.006266389973461628,
0.0001646275195525959,
0.00018883867596741766,
0.03672465682029724
] |
{
"id": 6,
"code_window": [
" * of that, you'll want to engineer this so that your automated builds use the coverage entry in the \"reporters\" list,\n",
" * but your interactive debugging does not.\n",
" *\n",
" */\n",
" preprocessors?: { [name: string]: string|string[] }\n",
" /**\n",
" * @default 'http:'\n",
" * Possible Values:\n",
" * <ul>\n",
" * <li>http:</li>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" preprocessors?: { [name: string]: string | string[] }\n"
],
"file_path": "karma/karma.d.ts",
"type": "replace",
"edit_start_line_idx": 259
} | # Dojo Definitions Usage Notes
## Overview
Anyone that has used Dojo for any length of time has probably discovered three things:
* Dojo is very powerful
* Dojo can be challenging to learn
* Dojo doesn't always play well with other
Having said that, there are ways that Dojo can be coerced out of its shell to work with other JavaScript technologies. This README is intended to describe some techniques for getting the full power of Dojo to work in an environment where almost everything can take advantage of TypeScript.
*Disclaimer*: Dojo is VERY big framework and, as such the type definitions are generated by a [tool](https://github.com/vansimke/DojoTypeDescriptionGenerator) from dojo's [API](dojotoolkit.org/api) docs. The generated files were then hand-polished to eliminate any import errors and clean up some obvious errors. This is all to say that the generated type definitions are not flawless and are not guaranteed to reflect the actual implementations.
## Basic Usage
A normal dojo module might look something like this:
```js
define(['dojo/request', 'dojo/request/xhr'],
function (request, xhr) {
...
}
);
```
When using the TypeScript, you can write the following:
```ts
import request = require("dojo/request");
import xhr = require("dojo/request/xhr");
...
```
Inside of the define variable, both `request` and `xhr` will work as the functions that come from Dojo, only they are strongly typed.
## Advanced Usage
Dojo and TypeScript both use different and conflicting class semantics. In order to satisfy both systems, some unconventional work is needed.
For the example, let's take this example custom Dojo widget:
```js
define(["dojo/_base/declare", "dijit/_WidgetBase", "dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin",
"dojo/text!./templates/Foo.html", "dojo/i18n!app/common/nls/resources",
"dijit/form/TextBox"],
function(declare, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin,
template, res) {
templateString: template,
res: res,
myArray: null,
constructor: function() {
this.myArray = [];
},
sayHello: function() {
alert(res.message.helloTypeScript);
}
});
```
the equivalent TypeScript version is next, explanation of each section below:
```ts
/// <amd-dependency path="dojo/text!./_templates/Foo.html" />
/// <amd-dependency path="dojo/i18n!app/common/nls/resources" />
/// <amd-dependency path="dijit/form/TextBox" />
/// <reference path="../typings/dojo.d.ts" />
/// <reference path="../typings/dijit.d.ts" />
declare var require: (moduleId: string) => any;
import dojoDeclare = require("dojo/_base/declare");
import _WidgetBase = require("dijit/_WidgetBase");
import _TemplatedMixin = require("dijit/_TemplatedMixin");
import _WidgetsInTemplateMixin = require("dijit/_WidgetsInTemplateMixin");
// make sure to set the 'dynamic' fields of the dojo/text and dojo/i18n modules to 'false' in
// order to ensure that Dojo loads the tempalte and resources from its cache instead of trying to
// pull from the server
var template:string = require("dojo/text!./templates/Foo.html");
var res = require("dojo/i18n!app/common/nls/resources");
class Foo extends dijit._WidgetBase {
constructor(args?: Object, elem?: HTMLElement) {
return new Foo_(args, elem);
super();
}
res: any;
myArray: string[];
sayHello(): void {
alert(res.message.helloTypeScript);
}
}
var Foo_ = dojoDeclare("", [_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], (function (Source: any) {
var result: any = {};
result.templateString = template;
result.res = res;
result.constructor = function () {
this.myArray = [];
}
for (var i in Source.prototype) {
if (i !== "constructor" && Source.prototype.hasOwnProperty(i)) {
result[i] = Source.prototype[i];
}
}
return result;
} (Foo)));
export =Foo;
```
Well, no one ever said that it would be easy... but it isn't too bad. Let's go through this one step at a time.
The first two lines are required due to TypeScript's inability to work with plugin-type modules. Since we need to use plugins, we use this technique. Basically, the 'amd-dependency' comments are directives to the TypeScript compiler that asks it to add the value in the "path" attribute as a dependency in the module's "define" statement. This directive, however, does not allow a variable to be assigned into the module. To obtain that, we need to add these two lines:
```ts
var template:string = require("dojo/text!./templates/Foo.html");
var res = require("dojo/i18n!app/common/nls/resources");
```
These statements will trigger context-sensitive require calls to be made to pull the requested values from the Dojo loader's cache. Unfortunately, this usage of "require" is not recognized. In order to make this work a new function prototype must be declared, thus this line:
```ts
declare var require: (moduleId: string) => any;
```
There is one more thing that we have to do in order to get the plugins to work properly. The AMD spec (that Dojo's loader adheres to) states that plugins should be loaded dynamically from the server (i.e. the loader shouldn't cache the response). This, I presume, is to allow content to be dynamically generated by the server. This, however, means that the context-sensitive require fails (since it isn't allowed to use the cache). In order correct this, the dojo/text and dojo/i18n modules must be loaded in advance and their 'dynamic' fields set to false. If your app has a single entry point, then you can create something like this (JavaScript shown):
```js
define(["require", "dojo/dom", "dojo/text", "dojo/i18n"],
function (require, dom, text, i18n) {
//set dojo/text and dojo/i18n to static resources to allow to be loaded via
//require() call inside of module and load cached version
text.dynamic = false;
i18n.dynamic = false;
require(["./views/ShellView"], function (ShellView) {
var shell = new ShellView(null, dom.byId("root"));
});
});
```
The main module above loads the basic modules, including dojo/text and dojo/i18n. Their dynamic fields are set to false, and then call is made to require to load pull in the application loader. By doing this in a two-step process, we can be sure that the dojo/text and dojo/i18n modules are properly configured before the application tries to make use of it.
The rest isn't so complicated, I promise...
The third line:
```ts
/// <amd-dependency path="dijit/form/TextBox" />
```
is another amd-dependency call that will load a dijit/form/CheckBox. Presumeably, this control is used in the templated widget and, therefore, needs to be preloaded. Since we don't need access to it in the module, we load it this way. If we tried to use an "import" statement, the TypeScript compiler would recognize that we don't use the dependency in the module and would optimize it away.
The next four lines:
```ts
import dojoDeclare = require("dojo/_base/declare");
import _WidgetBase = require("dijit/_WidgetBase");
import _TemplatedMixin = require("dijit/_TemplatedMixin");
import _WidgetsInTemplateMixin = require("dijit/_WidgetsInTemplateMixin");
```
are simple requests for the AMD loader to pull in the Dojo modules that we need for the widget. All of Dojo's conventions (including relative module paths) can be used here. Notice that the dojo/_base/declare module is called "dojoDeclare"; this was done to prevent a conflict with TypeScript's "declare" keyword.
The following is the class definition:
```ts
class Foo extends dijit._WidgetBase {
constructor(args?: Object, elem?: HTMLElement) {
return new Foo_(args, elem);
super();
}
res: any;
myArray: string[];
sayHello(): void {
alert(res.message.helloTypeScript);
}
}
```
There are only three odd things going on here.
The first is the constructor function which has a "return" statement. This means that the returned value will be used instead of a new "Foo" object. This allows us to defer to the Dojo class declaration and return that object. Also notice that we pass the arguments through to the Dojo class so that it has all of the information that it needs to properly construct the widget.
The second odd thing is the call to super() after the return statement in the constuctor. This is just there to make the TypeScript compiler happy since it requires this whenever a class inherits from a base class (dijit._WidgetBase in this case). Since it occurs after the return statement, it is never called, but I won't tell if you don't :).
The third odd thing is more subtle: the myArray field is declared, but never initialized. Normally, the constructor should initialize this. However, we are defering to the Dojo classes constructor. It will take the responsibility of inititializing the array.
The final part of the module is this:
```ts
var Foo_ = dojoDeclare("", [_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], (function (Source: any) {
var result: any = {};
result.templateString = template;
result.res = res;
result.constructor = function () {
this.myArray = [];
}
for (var i in Source.prototype) {
if (i !== "constructor" && Source.prototype.hasOwnProperty(i)) {
result[i] = Source.prototype[i];
}
}
return result;
} (Foo)));
```
You'll notice that the third argument to dojoDeclare is not an object literal, like you might expect. Rather, a self-executing function is used to dynamically generate the object literal. The templateString and res fields are manually set to equal the resources that were required above. Additionally, a constructor function is added to initialize the myArray array. Finally, the Foo class's prototype is inspected and all of its "ownProperties" are added. This allows the Foo class to evolved and its methods will automatically be mapped to the Dojo class.
Mind blown? Let's try to look at it this way:
Dojo expects things to work in a certain way and that way, in general, is fine. What we want TypeScript for is the strong typing. In order to get both, we are using a Dojo class, but implementing it in the context of a TypeScript one.
The fact that the TypeScript class defers to the Dojo one means that we get a Dojo class instead of a TypeScript one. This means that everything that we do in the TypeScript class itself is really meaningless since it will be the Dojo class that we are working with. Here is the trick: we define the methods in the TypeScript class which provides the strong typing that we are looking for. We then point the Dojo class's methods to those implementations. In short, we are still using Dojo classes all the way down, but we implement the methods in a TypeScript class so that we get compiler and IDE support.
Please submit any improvements to this technique. It isn't the prettiest thing ever, but it does accomplish the goal of integrating TypeScript and Dojo together. | dojo/README.md | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b | [
0.00017498410306870937,
0.00016706838505342603,
0.00016084936214610934,
0.00016718149709049612,
0.0000037127201721887104
] |
{
"id": 6,
"code_window": [
" * of that, you'll want to engineer this so that your automated builds use the coverage entry in the \"reporters\" list,\n",
" * but your interactive debugging does not.\n",
" *\n",
" */\n",
" preprocessors?: { [name: string]: string|string[] }\n",
" /**\n",
" * @default 'http:'\n",
" * Possible Values:\n",
" * <ul>\n",
" * <li>http:</li>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" preprocessors?: { [name: string]: string | string[] }\n"
],
"file_path": "karma/karma.d.ts",
"type": "replace",
"edit_start_line_idx": 259
} | parallel/parallel-tests.ts.tscparams | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b | [
0.00017070179455913603,
0.00017070179455913603,
0.00017070179455913603,
0.00017070179455913603,
0
] |
|
{
"id": 6,
"code_window": [
" * of that, you'll want to engineer this so that your automated builds use the coverage entry in the \"reporters\" list,\n",
" * but your interactive debugging does not.\n",
" *\n",
" */\n",
" preprocessors?: { [name: string]: string|string[] }\n",
" /**\n",
" * @default 'http:'\n",
" * Possible Values:\n",
" * <ul>\n",
" * <li>http:</li>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" preprocessors?: { [name: string]: string | string[] }\n"
],
"file_path": "karma/karma.d.ts",
"type": "replace",
"edit_start_line_idx": 259
} | // Type definitions for jquery.color.js v2.1.2
// Project: https://github.com/jquery/jquery-color
// Definitions by: Derek Cicerone <https://github.com/derekcicerone/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface JQueryColor {
/**
* Returns the red component of the color (integer from 0 - 255).
*/
red(): number;
/**
* Returns a copy of the color object with the red set to val.
*/
red(val: number): JQueryColor;
/**
* Returns a copy of the color object with the red set to val.
*/
red(val: string): JQueryColor;
/**
* Returns the green component of the color (integer from 0 - 255).
*/
green(): number;
/**
* Returns a copy of the color object with the green set to val.
*/
green(val: number): JQueryColor;
/**
* Returns a copy of the color object with the green set to val.
*/
green(val: string): JQueryColor;
/**
* Returns the blue component of the color (integer from 0 - 255).
*/
blue(): number;
/**
* Returns a copy of the color object with the blue set to val.
*/
blue(val: number): JQueryColor;
/**
* Returns a copy of the color object with the blue set to val.
*/
blue(val: string): JQueryColor;
/**
* Returns the alpha value of this color (float from 0.0 - 1.0).
*/
alpha(): number;
/**
* Returns a copy of the color object with the alpha set to val.
*/
alpha(val: number): JQueryColor;
/**
* Returns a copy of the color object with the alpha set to val.
*/
alpha(val: string): JQueryColor;
/**
* Returns the hue component of the color (integer from 0 - 359).
*/
hue(): number;
/**
* Returns a copy of the color object with the hue set to val.
*/
hue(val: number): JQueryColor;
/**
* Returns a copy of the color object with the hue set to val.
*/
hue(val: string): JQueryColor;
/**
* Returns the saturation component of the color (float from 0.0 - 1.0).
*/
saturation(): number;
/**
* Returns a copy of the color object with the saturation set to val.
*/
saturation(val: number): JQueryColor;
/**
* Returns a copy of the color object with the saturation set to val.
*/
saturation(val: string): JQueryColor;
/**
* Returns the lightness component of the color (float from 0.0 - 1.0).
*/
lightness(): number;
/**
* Returns a copy of the color object with the lightness set to val.
*/
lightness(val: number): JQueryColor;
/**
* Returns a copy of the color object with the lightness set to val.
*/
lightness(val: string): JQueryColor;
/**
* Returns a rgba "tuple" [ red, green, blue, alpha ].
*/
rgba(): number[];
/**
* Returns a copy of the color with any defined values set to the new value.
*/
rgba(red: number, green: number, blue: number, alpha?: number): JQueryColor;
/**
* Returns a copy of the color with any defined values set to the new value.
*/
rgba(val: RgbaColor): JQueryColor;
/**
* Returns a copy of the color with any defined values set to the new value.
*/
rgba(vals: number[]): JQueryColor;
/**
* Returns a HSL tuple [ hue, saturation, lightness, alpha ].
*/
hsla(): number[];
/**
* Returns a copy of the color with any defined values set to the new value.
*/
hsla(hue: number, saturation: number, lightness: number, alpha?: number): JQueryColor;
/**
* Returns a copy of the color with any defined values set to the new value.
*/
hsla(val: HslaColor): JQueryColor;
/**
* Returns a copy of the color with any defined values set to the new value.
*/
hsla(vals: number[]): JQueryColor;
/**
* Returns a CSS string "rgba(255, 255, 255, 0.4)".
*/
toRgbaString(): string;
/**
* Returns a css string "hsla(330, 75%, 25%, 0.4)".
*/
toHslaString(): string;
/**
* Returns a css string "#abcdef", with "includeAlpha" uses "#rrggbbaa" (alpha *= 255).
*/
toHexString(includeAlpha?: boolean): string;
/**
* The color distance (0.0 - 1.0) of the way between this color and othercolor.
*/
transition(othercolor: JQueryColor, distance: number): JQueryColor;
/**
* Will apply this color on top of the other color using alpha blending.
*/
blend(othercolor: JQueryColor): void;
/**
* Checks if two colors are equal.
*/
is(otherColor: JQueryColor): boolean;
}
interface HslaColor {
hue?: number;
saturation?: number;
lightness?: number;
alpha?: number;
}
interface RgbaColor {
red?: number;
green?: number;
blue?: number;
alpha?: number;
}
interface JQueryStatic {
Color(color: HslaColor): JQueryColor;
Color(color: RgbaColor): JQueryColor;
Color(color: string): JQueryColor;
}
| jquery.color/jquery.color.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b | [
0.00017299596220254898,
0.00016925085219554603,
0.000164457451319322,
0.00016950882854871452,
0.0000022046579033485614
] |
{
"id": 0,
"code_window": [
"async function createAdmin({ email, password, firstname, lastname }) {\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n",
" const app = await strapi({ appDir, distDir }).load();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/admin-create.js",
"type": "replace",
"edit_start_line_idx": 98
} | 'use strict';
const ts = require('typescript');
const reportDiagnostics = require('../utils/report-diagnostics');
const resolveConfigOptions = require('../utils/resolve-config-options');
module.exports = {
/**
* Default TS -> JS Compilation for Strapi
* @param {string} tsConfigPath
*/
run(tsConfigPath) {
// Parse the tsconfig.json file & resolve the configuration options
const { fileNames, options, projectReferences } = resolveConfigOptions(tsConfigPath);
const program = ts.createProgram({
rootNames: fileNames,
projectReferences,
options,
});
const emitResults = program.emit();
const diagnostics = ts.sortAndDeduplicateDiagnostics(
ts.getPreEmitDiagnostics(program).concat(emitResults.diagnostics)
);
if (diagnostics.length > 0) {
reportDiagnostics(diagnostics);
}
// If the compilation failed, exit early
if (emitResults.emitSkipped) {
process.exit(1);
}
},
};
| packages/utils/typescript/lib/compilers/basic.js | 1 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017563134315423667,
0.0001710286596789956,
0.00016831973334774375,
0.00017008181021083146,
0.000002753085709628067
] |
{
"id": 0,
"code_window": [
"async function createAdmin({ email, password, firstname, lastname }) {\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n",
" const app = await strapi({ appDir, distDir }).load();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/admin-create.js",
"type": "replace",
"edit_start_line_idx": 98
} | {
"components.Row.open": "Apri",
"components.Row.regenerate": "Rigenera",
"containers.HomePage.Block.title": "Versioni",
"containers.HomePage.Button.update": "Aggiorna",
"containers.HomePage.PluginHeader.title": "Documentazione - Impostazioni",
"containers.HomePage.PopUpWarning.confirm": "Ho capito",
"containers.HomePage.PopUpWarning.message": "Sei sicuro di voler eliminare questa versione?",
"containers.HomePage.copied": "Token copiato negli appunti",
"containers.HomePage.form.jwtToken": "Recupera il tuo token jwt",
"containers.HomePage.form.jwtToken.description": "Copia questo token e usalo in swagger per fare richieste",
"containers.HomePage.form.password": "Password",
"containers.HomePage.form.password.inputDescription": "Imposta una password per accedere alla documentazione",
"containers.HomePage.form.restrictedAccess": "Accesso limitato",
"containers.HomePage.form.restrictedAccess.inputDescription": "Rendi l'endpoint della documentazione privato. Di default l'accesso è pubblico",
"containers.HomePage.form.showGeneratedFiles": "Mostra file generati",
"containers.HomePage.form.showGeneratedFiles.inputDescription": "Utile quando vuoi sovrascrivere la documentazione generata. \nIl plugin genera file suddivisi per modello e per plugin. \nAbilitando questa opzione sarà più semplice personalizzare la tua documentazione.",
"error.deleteDoc.versionMissing": "La versione che stai tentando di cancellare non esiste.",
"error.noVersion": "Una versione è richiesta",
"error.regenerateDoc": "Si è verificato un errore durante la rigenerazione della documentazione",
"error.regenerateDoc.versionMissing": "La versione che stai tentando di generare non esiste",
"notification.delete.success": "Doc eliminata",
"notification.generate.success": "Doc generata",
"notification.update.success": "Impostazioni aggiornate con successo",
"plugin.name": "Documentazione"
}
| packages/plugins/documentation/admin/src/translations/it.json | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017551898781675845,
0.0001739595172693953,
0.00017187610501423478,
0.00017448342987336218,
0.0000015326490938605275
] |
{
"id": 0,
"code_window": [
"async function createAdmin({ email, password, firstname, lastname }) {\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n",
" const app = await strapi({ appDir, distDir }).load();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/admin-create.js",
"type": "replace",
"edit_start_line_idx": 98
} | import pluginPkg from '../../package.json';
const pluginId = pluginPkg.name.replace(/^@strapi\/plugin-/i, '');
export default pluginId;
| packages/core/email/admin/src/pluginId.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017673199181444943,
0.00017673199181444943,
0.00017673199181444943,
0.00017673199181444943,
0
] |
{
"id": 0,
"code_window": [
"async function createAdmin({ email, password, firstname, lastname }) {\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n",
" const app = await strapi({ appDir, distDir }).load();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/admin-create.js",
"type": "replace",
"edit_start_line_idx": 98
} | import produce from 'immer';
import { set } from 'lodash';
const initialState = {
menu: [],
isLoading: true,
};
const reducer = (state, action) =>
// eslint-disable-next-line consistent-return
produce(state, draftState => {
switch (action.type) {
case 'CHECK_PERMISSIONS_SUCCEEDED': {
action.data.forEach(checkedPermissions => {
if (checkedPermissions.hasPermission) {
set(
draftState,
['menu', ...checkedPermissions.path.split('.'), 'isDisplayed'],
checkedPermissions.hasPermission
);
}
});
// Remove the not needed links in each section
draftState.menu.forEach((section, sectionIndex) => {
draftState.menu[sectionIndex].links = section.links.filter(
link => link.isDisplayed === true
);
});
draftState.isLoading = false;
break;
}
default:
return draftState;
}
});
export default reducer;
export { initialState };
| packages/core/admin/admin/src/hooks/useSettingsMenu/reducer.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017603336891625077,
0.00017426445265300572,
0.0001694495149422437,
0.00017557253886479884,
0.0000024496716832800303
] |
{
"id": 1,
"code_window": [
"async function changePassword({ email, password }) {\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/admin-reset.js",
"type": "replace",
"edit_start_line_idx": 50
} | 'use strict';
const compilers = require('./compilers');
const getConfigPath = require('./utils/get-config-path');
module.exports = async (srcDir, { watch = false } = {}) => {
// TODO: Use the Strapi debug logger instead or don't log at all
console.log(`Starting the compilation for TypeScript files in ${srcDir}`);
const compiler = watch ? compilers.watch : compilers.basic;
const configPath = getConfigPath(srcDir);
compiler.run(configPath);
};
| packages/utils/typescript/lib/compile.js | 1 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00046771930647082627,
0.0003184774541296065,
0.00016923558723647147,
0.0003184774541296065,
0.000149241866893135
] |
{
"id": 1,
"code_window": [
"async function changePassword({ email, password }) {\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/admin-reset.js",
"type": "replace",
"edit_start_line_idx": 50
} | 'use strict';
const { inputObjectType } = require('nexus');
/**
* Build a map of filters type for every GraphQL scalars
* @return {Object<string, NexusInputTypeDef>}
*/
const buildScalarFilters = ({ strapi }) => {
const { naming, mappers } = strapi.plugin('graphql').service('utils');
const { helpers } = strapi.plugin('graphql').service('internals');
return helpers.getEnabledScalars().reduce((acc, type) => {
const operators = mappers.graphqlScalarToOperators(type);
const typeName = naming.getScalarFilterInputTypeName(type);
if (!operators || operators.length === 0) {
return acc;
}
return {
...acc,
[typeName]: inputObjectType({
name: typeName,
definition(t) {
for (const operator of operators) {
operator.add(t, type);
}
},
}),
};
}, {});
};
module.exports = context => ({
scalars: buildScalarFilters(context),
});
| packages/plugins/graphql/server/services/internals/types/filters.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017874498735181987,
0.00017486297292634845,
0.0001675161038292572,
0.00017659540753811598,
0.000004357918896857882
] |
{
"id": 1,
"code_window": [
"async function changePassword({ email, password }) {\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/admin-reset.js",
"type": "replace",
"edit_start_line_idx": 50
} | <!--- GenericInput.stories.mdx --->
import { useState } from 'react';
import { Meta, Story, Canvas } from '@storybook/addon-docs/blocks';
import { Grid, GridItem } from '@strapi/design-system/Grid';
import { HeaderLayout, ContentLayout } from '@strapi/design-system/Layout';
import { Main } from '@strapi/design-system/Main';
import { Stack } from '@strapi/design-system/Stack';
import { Box } from '@strapi/design-system/Box';
import set from 'lodash/set';
import GenericInput from './index';
import layout from './storyUtils/layout';
<Meta title="components/GenericInput" component={GenericInput} />
# GenericInput
This is the doc of the `GenericInput` component
## GenericInput
Description...
<Canvas>
<Story name="base">
{() => {
const [state, setState] = useState({
firstname: 'ee',
email: '',
private: null,
isNullable: null,
isActiveByDefault: true,
isInactiveByDefault: false
});
return (
<ContentLayout>
<Stack spacing={4}>
{layout.map((row, rowIndex) => {
return (
<Box key={rowIndex}>
<Grid gap={4}>
{row.map(input => {
return (
<GridItem key={input.name} {...input.size}>
<GenericInput
{...input}
value={state[input.name]}
onChange={({ target: { name, value } }) => {
setState(prev => {
return { ...prev, [name]: value };
});
}}
/>
</GridItem>
);
})}
</Grid>
</Box>
);
})}
</Stack>
</ContentLayout>
);
}}
</Story>
</Canvas>
| packages/core/helper-plugin/lib/src/components/GenericInput/GenericInput.stories.mdx | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017990547348745167,
0.00017402997764293104,
0.0001642045535845682,
0.0001743633474688977,
0.000004523216830421006
] |
{
"id": 1,
"code_window": [
"async function changePassword({ email, password }) {\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/admin-reset.js",
"type": "replace",
"edit_start_line_idx": 50
} | import checkPermissions from '../checkPermissions';
jest.mock('@strapi/helper-plugin', () => ({
hasPermissions: () => Promise.resolve(true),
}));
describe('checkPermissions', () => {
it('creates an array of boolean corresponding to the permission state', async () => {
const userPermissions = {};
const permissions = [{ permissions: {} }, { permissions: {} }];
const expected = [true, true];
const actual = await Promise.all(checkPermissions(userPermissions, permissions));
expect(actual).toEqual(expected);
});
});
| packages/core/admin/admin/src/hooks/useMenu/utils/tests/checkPermissions.test.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.0001771264214767143,
0.00017655153351370245,
0.0001759766455506906,
0.00017655153351370245,
5.748879630118608e-7
] |
{
"id": 2,
"code_window": [
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/configurationDump.js",
"type": "replace",
"edit_start_line_idx": 20
} | 'use strict';
const path = require('path');
const _ = require('lodash');
const inquirer = require('inquirer');
const tsUtils = require('@strapi/typescript-utils');
const strapi = require('../index');
const promptQuestions = [
{ type: 'input', name: 'email', message: 'User email?' },
{ type: 'password', name: 'password', message: 'New password?' },
{
type: 'confirm',
name: 'confirm',
message: "Do you really want to reset this user's password?",
},
];
/**
* Reset user's password
* @param {Object} cmdOptions - command options
* @param {string} cmdOptions.email - user's email
* @param {string} cmdOptions.password - user's new password
*/
module.exports = async function(cmdOptions = {}) {
const { email, password } = cmdOptions;
if (_.isEmpty(email) && _.isEmpty(password) && process.stdin.isTTY) {
const inquiry = await inquirer.prompt(promptQuestions);
if (!inquiry.confirm) {
process.exit(0);
}
return changePassword(inquiry);
}
if (_.isEmpty(email) || _.isEmpty(password)) {
console.error('Missing required options `email` or `password`');
process.exit(1);
}
return changePassword({ email, password });
};
async function changePassword({ email, password }) {
const appDir = process.cwd();
const isTSProject = await tsUtils.isUsingTypeScript(appDir);
if (isTSProject) await tsUtils.compile(appDir, { watch: false });
const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;
const app = await strapi({ appDir, distDir }).load();
await app.admin.services.user.resetPasswordByEmail(email, password);
console.log(`Successfully reset user's password`);
process.exit(0);
}
| packages/core/strapi/lib/commands/admin-reset.js | 1 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.9980915188789368,
0.2854451537132263,
0.00016525819955859333,
0.00018005444144364446,
0.45046091079711914
] |
{
"id": 2,
"code_window": [
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/configurationDump.js",
"type": "replace",
"edit_start_line_idx": 20
} | 'use strict';
const { createStrapiInstance } = require('../../../../../../test/helpers/strapi');
const { createAuthRequest, createRequest } = require('../../../../../../test/helpers/request');
const { createUtils } = require('../../../../../../test/helpers/utils');
const edition = process.env.STRAPI_DISABLE_EE === 'true' ? 'CE' : 'EE';
if (edition === 'CE') {
test('Provider Login (skipped)', () => {
expect(true).toBeTruthy();
});
return;
}
let strapi;
let utils;
const requests = {
public: undefined,
admin: undefined,
noPermissions: undefined,
};
const localData = {
restrictedUser: null,
restrictedRole: null,
};
const restrictedUser = {
email: '[email protected]',
password: 'Restricted123',
};
const restrictedRole = {
name: 'restricted-role',
description: '',
};
const createFixtures = async () => {
const role = await utils.createRole(restrictedRole);
const user = await utils.createUserIfNotExists({
...restrictedUser,
roles: [role.id],
});
localData.restrictedUser = user;
localData.restrictedRole = role;
return { role, user };
};
const deleteFixtures = async () => {
await utils.deleteUserById(localData.restrictedUser.id);
await utils.deleteRolesById([localData.restrictedRole.id]);
};
describe('Provider Login', () => {
let hasSSO;
beforeAll(async () => {
strapi = await createStrapiInstance();
utils = createUtils(strapi);
// eslint-disable-next-line node/no-extraneous-require
hasSSO = require('@strapi/strapi/lib/utils/ee').features.isEnabled('sso');
await createFixtures();
requests.public = createRequest({ strapi });
requests.admin = await createAuthRequest({ strapi });
requests.noPermissions = await createAuthRequest({ strapi, userInfo: restrictedUser });
});
afterAll(async () => {
await deleteFixtures();
await strapi.destroy();
});
describe('Get the provider list', () => {
test.each(Object.keys(requests))('It should be available for everyone (%s)', async type => {
const rq = requests[type];
const res = await rq.get('/admin/providers');
if (hasSSO) {
expect(res.status).toBe(200);
expect(Array.isArray(res.body)).toBeTruthy();
expect(res.body).toHaveLength(0);
} else {
expect(res.status).toBe(404);
expect(Array.isArray(res.body)).toBeFalsy();
}
});
});
describe('Read the provider login options', () => {
test('It should fail with a public request', async () => {
const res = await requests.public.get('/admin/providers/options');
expect(res.status).toBe(hasSSO ? 401 : 404);
});
test('It should fail with an authenticated request (restricted user)', async () => {
const res = await requests.noPermissions.get('/admin/providers/options');
expect(res.status).toBe(hasSSO ? 403 : 404);
});
test('It should succeed with an authenticated request (admin)', async () => {
const res = await requests.admin.get('/admin/providers/options');
if (hasSSO) {
expect(res.status).toBe(200);
expect(res.body.data).toBeDefined();
expect(typeof res.body.data.autoRegister).toBe('boolean');
expect(res.body.data.defaultRole).toBeDefined();
} else {
expect(res.status).toBe(404);
}
});
});
describe('Update the provider login options', () => {
let newOptions;
beforeAll(async () => {
const superAdminRole = await utils.getSuperAdminRole();
newOptions = {
defaultRole: superAdminRole.id,
autoRegister: false,
};
});
test('It should fail with a public request', async () => {
const res = await requests.public.put('/admin/providers/options', { body: newOptions });
expect(res.status).toBe(hasSSO ? 401 : 405);
});
test('It should fail with an authenticated request (restricted user)', async () => {
const res = await requests.noPermissions.put('/admin/providers/options', {
body: newOptions,
});
expect(res.status).toBe(hasSSO ? 403 : 405);
});
test('It should succeed with an authenticated request (admin)', async () => {
const res = await requests.admin.put('/admin/providers/options', { body: newOptions });
if (hasSSO) {
expect(res.status).toBe(200);
expect(res.body.data).toBeDefined();
expect(res.body.data).toMatchObject(newOptions);
} else {
expect(res.status).toBe(405);
}
});
test('It should fail with an invalid payload', async () => {
const res = await requests.admin.put('/admin/providers/options', {
body: { ...newOptions, autoRegister: 'foobar' },
});
expect(res.status).toBe(hasSSO ? 400 : 405);
});
});
});
| packages/core/admin/ee/server/tests/provider-login.test.e2e.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.0001932194281835109,
0.00017703016055747867,
0.00017089216271415353,
0.00017644422769080848,
0.000004685712610807968
] |
{
"id": 2,
"code_window": [
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/configurationDump.js",
"type": "replace",
"edit_start_line_idx": 20
} | 'use strict';
const email = require('./email');
module.exports = {
email,
};
| packages/core/email/server/services/index.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017765347729437053,
0.00017765347729437053,
0.00017765347729437053,
0.00017765347729437053,
0
] |
{
"id": 2,
"code_window": [
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/configurationDump.js",
"type": "replace",
"edit_start_line_idx": 20
} | /**
*
* InputJSON
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import cm from 'codemirror';
import trimStart from 'lodash/trimStart';
import { Stack } from '@strapi/design-system/Stack';
import { FieldHint, FieldError } from '@strapi/design-system/Field';
import jsonlint from './jsonlint';
import { EditorWrapper, StyledBox } from './components';
import Label from './Label';
import FieldWrapper from './FieldWrapper';
const WAIT = 600;
const DEFAULT_THEME = 'blackboard';
const loadCss = async () => {
await import(
/* webpackChunkName: "codemirror-javacript" */ 'codemirror/mode/javascript/javascript'
);
await import(/* webpackChunkName: "codemirror-addon-lint" */ 'codemirror/addon/lint/lint');
await import(
/* webpackChunkName: "codemirror-addon-lint-js" */ 'codemirror/addon/lint/javascript-lint'
);
await import(
/* webpackChunkName: "codemirror-addon-closebrackets" */ 'codemirror/addon/edit/closebrackets'
);
await import(
/* webpackChunkName: "codemirror-addon-mark-selection" */ 'codemirror/addon/selection/mark-selection'
);
await import(/* webpackChunkName: "codemirror-css" */ 'codemirror/lib/codemirror.css');
await import(/* webpackChunkName: "codemirror-theme" */ 'codemirror/theme/blackboard.css');
};
loadCss();
class InputJSON extends React.Component {
timer = null;
constructor(props) {
super(props);
this.editor = React.createRef();
this.state = { error: false, markedText: null };
}
componentDidMount() {
// Init codemirror component
this.codeMirror = cm.fromTextArea(this.editor.current, {
autoCloseBrackets: true,
lineNumbers: true,
matchBrackets: true,
mode: 'application/json',
readOnly: this.props.disabled,
smartIndent: true,
styleSelectedText: true,
tabSize: 2,
theme: DEFAULT_THEME,
fontSize: '13px',
});
this.codeMirror.on('change', this.handleChange);
this.setSize();
this.setInitValue();
}
componentDidUpdate(prevProps) {
if (prevProps.value !== this.props.value && !this.codeMirror.state.focused) {
this.setInitValue();
}
}
setInitValue = () => {
const { value } = this.props;
try {
if (value === null) return this.codeMirror.setValue('');
return this.codeMirror.setValue(value);
} catch (err) {
return this.setState({ error: true });
}
};
setSize = () => this.codeMirror.setSize('100%', 'auto');
getContentAtLine = line => this.codeMirror.getLine(line);
getEditorOption = opt => this.codeMirror.getOption(opt);
getValue = () => this.codeMirror.getValue();
markSelection = ({ message }) => {
let line = parseInt(message.split(':')[0].split('line ')[1], 10) - 1;
let content = this.getContentAtLine(line);
if (content === '{') {
line += 1;
content = this.getContentAtLine(line);
}
const chEnd = content.length;
const chStart = chEnd - trimStart(content, ' ').length;
const markedText = this.codeMirror.markText(
{ line, ch: chStart },
{ line, ch: chEnd },
{ className: 'colored' }
);
this.setState({ markedText });
};
handleChange = (doc, change) => {
if (change.origin === 'setValue') {
return;
}
const { name, onChange } = this.props;
let value = doc.getValue();
if (value === '') {
value = null;
}
// Update the parent
onChange({
target: {
name,
value,
type: 'json',
},
});
// Remove higlight error
if (this.state.markedText) {
this.state.markedText.clear();
this.setState({ markedText: null, error: null });
}
clearTimeout(this.timer);
this.timer = setTimeout(() => this.testJSON(doc.getValue()), WAIT);
};
testJSON = value => {
try {
jsonlint.parse(value);
} catch (err) {
this.markSelection(err);
}
};
render() {
if (this.state.error) {
return <div>error json</div>;
}
return (
<FieldWrapper name={this.props.name} hint={this.props.description} error={this.props.error}>
<Stack spacing={1}>
<Label
intlLabel={this.props.intlLabel}
labelAction={this.props.labelAction}
name={this.props.name}
required={this.props.required}
/>
<StyledBox error={this.props.error}>
<EditorWrapper disabled={this.props.disabled}>
<textarea
ref={this.editor}
autoComplete="off"
id={this.props.id || this.props.name}
defaultValue=""
/>
</EditorWrapper>
</StyledBox>
<FieldHint />
<FieldError />
</Stack>
</FieldWrapper>
);
}
}
InputJSON.defaultProps = {
description: null,
disabled: false,
id: undefined,
error: undefined,
intlLabel: undefined,
labelAction: undefined,
onChange: () => {},
value: null,
required: false,
};
InputJSON.propTypes = {
description: PropTypes.shape({
id: PropTypes.string.isRequired,
defaultMessage: PropTypes.string.isRequired,
values: PropTypes.object,
}),
disabled: PropTypes.bool,
error: PropTypes.string,
id: PropTypes.string,
intlLabel: PropTypes.shape({
id: PropTypes.string.isRequired,
defaultMessage: PropTypes.string.isRequired,
values: PropTypes.object,
}),
labelAction: PropTypes.element,
name: PropTypes.string.isRequired,
onChange: PropTypes.func,
value: PropTypes.any,
required: PropTypes.bool,
};
export default InputJSON;
| packages/core/admin/admin/src/content-manager/components/InputJSON/index.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.0001797574950614944,
0.0001761781022651121,
0.00016981587396003306,
0.00017654127441346645,
0.00000212264808396867
] |
{
"id": 3,
"code_window": [
"\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/configurationRestore.js",
"type": "replace",
"edit_start_line_idx": 21
} | 'use strict';
const path = require('path');
const { yup } = require('@strapi/utils');
const _ = require('lodash');
const inquirer = require('inquirer');
const tsUtils = require('@strapi/typescript-utils');
const strapi = require('../index');
const emailValidator = yup
.string()
.email('Invalid email address')
.lowercase();
const passwordValidator = yup
.string()
.min(8, 'Password must be at least 8 characters long')
.matches(/[a-z]/, 'Password must contain at least one lowercase character')
.matches(/[A-Z]/, 'Password must contain at least one uppercase character')
.matches(/\d/, 'Password must contain at least one number');
const adminCreateSchema = yup.object().shape({
email: emailValidator,
password: passwordValidator,
firstname: yup.string().required('First name is required'),
lastname: yup.string(),
});
const promptQuestions = [
{
type: 'input',
name: 'email',
message: 'Admin email?',
async validate(value) {
const validEmail = await emailValidator.validate(value);
return validEmail === value || validEmail;
},
},
{
type: 'password',
name: 'password',
message: 'Admin password?',
async validate(value) {
const validPassword = await passwordValidator.validate(value);
return validPassword === value || validPassword;
},
},
{ type: 'input', name: 'firstname', message: 'First name?' },
{ type: 'input', name: 'lastname', message: 'Last name?' },
{
type: 'confirm',
name: 'confirm',
message: 'Do you really want to create a new admin?',
},
];
/**
* Create new admin user
* @param {Object} cmdOptions - command options
* @param {string} cmdOptions.email - new admin's email
* @param {string} [cmdOptions.password] - new admin's password
* @param {string} cmdOptions.firstname - new admin's first name
* @param {string} [cmdOptions.lastname] - new admin's last name
*/
module.exports = async function(cmdOptions = {}) {
let { email, password, firstname, lastname } = cmdOptions;
if (
_.isEmpty(email) &&
_.isEmpty(password) &&
_.isEmpty(firstname) &&
_.isEmpty(lastname) &&
process.stdin.isTTY
) {
const inquiry = await inquirer.prompt(promptQuestions);
if (!inquiry.confirm) {
process.exit(0);
}
({ email, password, firstname, lastname } = inquiry);
}
try {
await adminCreateSchema.validate({ email, password, firstname, lastname });
} catch (err) {
console.error(err.errors[0]);
process.exit(1);
}
return createAdmin({ email, password, firstname, lastname });
};
async function createAdmin({ email, password, firstname, lastname }) {
const appDir = process.cwd();
const isTSProject = await tsUtils.isUsingTypeScript(appDir);
if (isTSProject) await tsUtils.compile(appDir, { watch: false });
const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;
const app = await strapi({ appDir, distDir }).load();
const user = await app.admin.services.user.exists({ email });
if (user) {
console.error(`User with email "${email}" already exists`);
process.exit(1);
}
const superAdminRole = await app.admin.services.role.getSuperAdmin();
await app.admin.services.user.create({
email,
firstname,
lastname,
isActive: true,
roles: [superAdminRole.id],
...(password && { password, registrationToken: null }),
});
console.log(`Successfully created new admin`);
process.exit(0);
}
| packages/core/strapi/lib/commands/admin-create.js | 1 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.998397171497345,
0.15392199158668518,
0.0001661393471295014,
0.00017401704099029303,
0.3600376546382904
] |
{
"id": 3,
"code_window": [
"\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/configurationRestore.js",
"type": "replace",
"edit_start_line_idx": 21
} | {
"ComponentIconPicker.search.placeholder": "Suche nach einem Icon",
"attribute.boolean": "Boolean",
"attribute.boolean.description": "Ja oder nein, 1 oder 0, wahr oder falsch",
"attribute.component": "Komponente",
"attribute.component.description": "Gruppierung an Feldern, die wiederholt und wiederbenutzt werden kann",
"attribute.date": "Datum",
"attribute.date.description": "Eine Datums-Auswahl mit Stunden, Minuten und Sekunden",
"attribute.datetime": "Datum mit Uhrzeit",
"attribute.dynamiczone": "Dynamische Zone",
"attribute.dynamiczone.description": "Beliebige Komponenten beim Bearbeiten des Inhalts wählen",
"attribute.email": "E-Mail",
"attribute.email.description": "E-Mail-Feld mit Validierung",
"attribute.enumeration": "Enumeration",
"attribute.enumeration.description": "Aufzählung an Auswahlmöglichkeiten, von denen eine gewählt werden muss",
"attribute.json": "JSON",
"attribute.json.description": "Daten im JSON-Format",
"attribute.media": "Medien",
"attribute.media.description": "Dateien wie Bilder, Videos, etc",
"attribute.null": " ",
"attribute.number": "Zahl",
"attribute.number.description": "Zahlen (ganzzahlig, Gleitkommazahl, dezimal)",
"attribute.password": "Passwort",
"attribute.password.description": "Passwort-Feld mit Verschlüsselung",
"attribute.relation": "Beziehung",
"attribute.relation.description": "Beziehung mit einem anderen Eintrag",
"attribute.richtext": "Formatierter Text",
"attribute.richtext.description": "Ein Text-Editor mit Formatierungsoptionen",
"attribute.text": "Text",
"attribute.text.description": "Ein- oder mehrzeiliger Text wie Titel oder Beschreibungen",
"attribute.time": "Uhrzeit",
"attribute.timestamp": "Zeitstempel",
"attribute.uid": "UID",
"attribute.uid.description": "Einzigartiger Identifier",
"button.attributes.add.another": "Weiteres Feld hinzufügen",
"button.component.add": "Komponente hinzufügen",
"button.component.create": "Neue Komponente erstellen",
"button.model.create": "Neue Sammlung erstellen",
"button.single-types.create": "Neuen Einzel-Eintrag erstellen",
"component.repeatable": "(wiederholbar)",
"components.SelectComponents.displayed-value": "{number, plural, =0 {# Komponenten} one {# Komponente} other {# Komponenten}} ausgewählt",
"components.componentSelect.no-component-available": "Du hast bereits alle Komponenten hinzugefügt",
"components.componentSelect.no-component-available.with-search": "Es gibt keine Komponenten, die diesem Begriff entsprechen",
"components.componentSelect.value-component": "{number} Komponente ausgewählt (Tippen um nach Komponente zu suchen)",
"components.componentSelect.value-components": "{number} Komponenten ausgewählt",
"configurations": "Konfigurationen",
"contentType.apiId-plural.description": "API-ID im Plural",
"contentType.apiId-plural.label": "Plural API ID",
"contentType.apiId-singular.description": "Die UID wird verwendet, um API-Routen und Datenbank-Tabellen/-Sammlungen zu erstellen",
"contentType.apiId-singular.label": "Singular API ID",
"contentType.collectionName.description": "Nützlich wenn sich der Name der Sammlung und der Tabellenname unterscheiden",
"contentType.collectionName.label": "Name der Sammlung",
"contentType.displayName.label": "Anzeigename",
"contentType.draftAndPublish.description": "Lege einen Entwurf des Eintrags an bevor er veröffentlicht wird",
"contentType.draftAndPublish.label": "Entwurf/Veröffentlichen-System",
"contentType.kind.change.warning": "Du hast die Art eines Inhaltstyps geändert: API wird resettet (Routen, Controller und Services werden überschrieben).",
"error.attributeName.reserved-name": "Dieser Name kann nicht für Attribute genutzt werden, da er andere Funktionalitäten beeinträchtigen würde",
"error.contentType.pluralName-used": "Dieser Wert kann nicht gleich sein wie der Singular-Wert",
"error.contentType.singularName-used": "Dieser Wert kann nicht gleich sein wie der Plural-Wert",
"error.contentTypeName.reserved-name": "Dieser Name kann nicht genutzt werden, da er andere Funktionalitäten beeinträchtigen würde",
"error.validation.enum-duplicate": "Doppelte Werte sind nicht erlaubt",
"error.validation.enum-empty-string": "Leere Werte sind nicht erlaubt",
"error.validation.enum-number": "Werte können nicht mit einer Zahl beginnen",
"error.validation.minSupMax": "Wert kann nicht höher sein",
"error.validation.positive": "Muss eine positive Zahl sein",
"error.validation.regex": "Regex-Pattern ist ungültig",
"error.validation.relation.targetAttribute-taken": "Dieser Name existiert bereits im Ziel-Typ",
"form.attribute.component.option.add": "Komponente hinzufügen",
"form.attribute.component.option.create": "Neue Komponente erstellen",
"form.attribute.component.option.create.description": "Eine Komponente ist überall verfügbar und wird unter Inhaltstypen und anderen Komponenten geteilt.",
"form.attribute.component.option.repeatable": "Wiederholbare Komponenten",
"form.attribute.component.option.repeatable.description": "Nützlich für mehrere Instanzen (Array) an Zutaten, Meta-Tags, etc...",
"form.attribute.component.option.reuse-existing": "Bereits existierende Komponente nutzen",
"form.attribute.component.option.reuse-existing.description": "Eine bereits erstellte Komponente benutzen, um Daten über Inhaltstypen hinweg konsistent zu halten.",
"form.attribute.component.option.single": "Einzelne Komponente",
"form.attribute.component.option.single.description": "Nützlich um Felder wie volle Addresse, Hauptinformationen, etc. zu grupppieren",
"form.attribute.item.customColumnName": "Eigener Spaltenname",
"form.attribute.item.customColumnName.description": "Dies ist nützlich, um Spalten in der Datenbank für Antworten der API umzubenennen",
"form.attribute.item.date.type.date": "Datum (Bsp: 01.01.{currentYear})",
"form.attribute.item.date.type.datetime": "Datum & Uhrzeit (Bsp: 01.01.{currentYear} 00:00)",
"form.attribute.item.date.type.time": "Uhrzeit (Bsp: 00:00)",
"form.attribute.item.defineRelation.fieldName": "Feldname",
"form.attribute.item.enumeration.graphql": "Namensüberschreibung für GraphQL",
"form.attribute.item.enumeration.graphql.description": "Ermöglicht, den standardmäßig generierten Namen für GraphQL zu überschreiben",
"form.attribute.item.enumeration.placeholder": "Bsp:\nMorgen\nMittag\nAbend",
"form.attribute.item.enumeration.rules": "Werte (einer pro Zeile)",
"form.attribute.item.maximum": "Maximalwert",
"form.attribute.item.maximumLength": "Maximallänge",
"form.attribute.item.minimum": "Mindestwert",
"form.attribute.item.minimumLength": "Mindestlänge",
"form.attribute.item.number.type": "Zahlenformat",
"form.attribute.item.number.type.biginteger": "große Ganzzahl (ex: 123456789)",
"form.attribute.item.number.type.decimal": "dezimal (z.B.: 2.22)",
"form.attribute.item.number.type.float": "Gleitkommazahl (z.B.: 3.33333333)",
"form.attribute.item.number.type.integer": "ganzzahlig (z.B.: 10)",
"form.attribute.item.privateField": "Privates Feld",
"form.attribute.item.privateField.description": "Dieses Feld wird nicht in API-Abfragen angezeigt",
"form.attribute.item.requiredField": "Benötigtes Feld",
"form.attribute.item.requiredField.description": "Du wirst keinen Eintrag anlegen können, wenn dieses Feld leer ist",
"form.attribute.item.text.regex": "RegExp-Pattern",
"form.attribute.item.text.regex.description": "Der Text der Regular Expression",
"form.attribute.item.uniqueField": "Einzigartiges Feld",
"form.attribute.item.uniqueField.description": "Du wirst keinen Eintrag anlegen können, wenn es bereits einen Eintrag mit identischem Inhalt gibt",
"form.attribute.media.allowed-types": "Wähle erlaubte Arten von Medien",
"form.attribute.media.allowed-types.option-files": "Dateien",
"form.attribute.media.allowed-types.option-images": "Bilder",
"form.attribute.media.allowed-types.option-videos": "Videos",
"form.attribute.media.option.multiple": "Mehrere Medien",
"form.attribute.media.option.multiple.description": "Nützlich für Slider, Galerien oder Downloads von mehreren Dateien",
"form.attribute.media.option.single": "Einzelne Medien-Datei",
"form.attribute.media.option.single.description": "Nützlich für Profilbilder oder Cover-Bilder",
"form.attribute.settings.default": "Standardwert",
"form.attribute.text.option.long-text": "Mehrzeiliger Text",
"form.attribute.text.option.long-text.description": "Nützlich für Beschreibungen, Biographien. Exakte Suche ist deaktiviert",
"form.attribute.text.option.short-text": "Einzeiliger Text",
"form.attribute.text.option.short-text.description": "Nützlich für Titel, Namen, Links (URL). Ermöglicht exakte Suche.",
"form.button.add-components-to-dynamiczone": "Komponenten zur Zone hinzufügen",
"form.button.add-field": "Weiteres Feld hinzufügen",
"form.button.add-first-field-to-created-component": "Erstes Feld zur Komponente hinzufügen",
"form.button.add.field.to.collectionType": "Weiteres Feld zur Sammlung hinzufügen",
"form.button.add.field.to.component": "Weiteres Feld zur Komponente hinzufügen",
"form.button.add.field.to.contentType": "Weiteres Feld zum Inhaltstyp hinzufügen",
"form.button.add.field.to.singleType": "Weiteres Feld zum Einzel-Eintrag hinzufügen",
"form.button.cancel": "Abbrechen",
"form.button.collection-type.description": "Nützlich für mehrere Instanzen wie Artikel, Produkte, Kommentare, etc.",
"form.button.collection-type.name": "Inhalts-Typ",
"form.button.configure-component": "Komponente konfigurieren",
"form.button.configure-view": "Ansicht konfigurieren",
"form.button.select-component": "Komponente auswählen",
"form.button.single-type.description": "Nützlich für einzelne Instanz wie Über uns, Startseite, etc.",
"form.button.single-type.name": "Einzel-Eintrag",
"form.contentType.divider.draft-publish": "Entwurf/Veröffentlichen",
"from": "von",
"listView.headerLayout.description": "Baue die Daten-Architektur deines Inhalts",
"menu.section.components.name": "Komponenten",
"menu.section.models.name": "Sammlungen",
"menu.section.single-types.name": "Einzel-Einträge",
"modalForm.attribute.form.base.name.description": "Leerzeichen sind im Name eines Attributs nicht erlaubt",
"modalForm.attribute.form.base.name.placeholder": "z.B. Slug, SEO URL, Canonical URL",
"modalForm.attribute.target-field": "Verknüpftes Feld",
"modalForm.attributes.select-component": "Wähle eine Komponente",
"modalForm.attributes.select-components": "Wähle die Komponenten",
"modalForm.collectionType.header-create": "Erstelle einen Inhalts-Typ",
"modalForm.component.header-create": "Erstelle eine Komponente",
"modalForm.components.create-component.category.label": "Wähle Kategorie oder gebe neuen Namen ein, um eine zu erstellen",
"modalForm.components.icon.label": "Icon",
"modalForm.editCategory.base.name.description": "Leerzeichen sind im Name einer Kategorie nicht erlaubt",
"modalForm.header-edit": "Bearbeite {name}",
"modalForm.header.categories": "Kategorien",
"modalForm.singleType.header-create": "Erstelle einen Einzel-Eintrag",
"modalForm.sub-header.addComponentToDynamicZone": "Komponente zur dynamischen Zone hinzufügen",
"modalForm.sub-header.attribute.create": "Erstelle neues {type}-Feld",
"modalForm.sub-header.attribute.create.step": "Neue Komponente ({step}/2)",
"modalForm.sub-header.attribute.edit": "Bearbeite {name}",
"modalForm.sub-header.chooseAttribute.collectionType": "Wähle ein Feld für die Sammlung",
"modalForm.sub-header.chooseAttribute.component": "Wähle ein Feld für die Komponente",
"modalForm.sub-header.chooseAttribute.singleType": "Wähle ein Feld für den Einzel-Eintrag",
"modelPage.attribute.relation-polymorphic": "Beziehung (polymorph)",
"modelPage.attribute.relationWith": "Beziehung mit",
"notification.error.dynamiczone-min.validation": "Eine dynamische Zone braucht mindestens eine Komponente, bevor sie gespeichert werden kann",
"notification.info.autoreaload-disable": "Das autoReload-Feature wird für dieses Plugin benötigt. Starte deinen Server mit `strapi develop`",
"notification.info.creating.notSaved": "Bitte speichere deine Arbeit bevor du einen neuen Inhaltstyp oder eine neue Komponente erstellst",
"plugin.description.long": "Modelliere die Datenstruktur deiner API. Lege neue Felder und Beziehungen innerhalb von einer Minute an. Erforderliche Dateien werden automatisch in deinem Projekt angelegt und aktualisiert.",
"plugin.description.short": "Modelliere die Datenstruktur deiner API.",
"plugin.name": "Content-Type Builder",
"popUpForm.navContainer.advanced": "Fortgeschrittene Einstellungen",
"popUpForm.navContainer.base": "Grundeinstellungen",
"popUpWarning.bodyMessage.cancel-modifications": "Bist du dir sicher, dass du alle deine Änderungen abbrechen willst?",
"popUpWarning.bodyMessage.cancel-modifications.with-components": "Bist du dir sicher, dass du alle deine Änderungen abbrechen willst? Es wurden Komponenten erstellt oder bearbeitet...",
"popUpWarning.bodyMessage.category.delete": "Bist du dir sicher, dass du diese Kategorie löschen willst? Alle dazugehörigen Komponenten werden ebenfalls gelöscht.",
"popUpWarning.bodyMessage.component.delete": "Bist du dir sicher, dass du diese Komponente löschen willst?",
"popUpWarning.bodyMessage.contentType.delete": "Bist du sicher, dass du diesen Inhaltstyp löschen willst?",
"popUpWarning.draft-publish.button.confirm": "Ja, deaktivieren",
"popUpWarning.draft-publish.message": "Wenn du das Entwurf/Veröffentlichen-System deaktivierst werden alle Entwürfe gelöscht.",
"popUpWarning.draft-publish.second-message": "Bist du dir sicher, dass du es deaktivieren willst?",
"prompt.unsaved": "Bist du dir sicher, dass du diese Seite verlassen willst? Deine Änderungen werden verworfen.",
"relation.attributeName.placeholder": "z.B.: Autor, Kategorie",
"relation.manyToMany": "hat und gehört zu vielen",
"relation.manyToOne": "hat viele",
"relation.manyWay": "hat viele",
"relation.oneToMany": "gehört zu vielen",
"relation.oneToOne": "hat und gehört zu ein(-er/-em)",
"relation.oneWay": "hat ein(-e/-en)",
"table.button.no-fields": "Neues Feld hinzufügen",
"table.content.create-first-content-type": "Erstelle deinen ersten Inhalts-Typ",
"table.content.no-fields.collection-type": "Füge diesem Inhalts-Typ das erstes Feld hinzu",
"table.content.no-fields.component": "Füge dieser Komponente das erstes Feld hinzu"
}
| packages/core/content-type-builder/admin/src/translations/de.json | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017825752729550004,
0.00017390454013366252,
0.00016628277080599219,
0.0001739287981763482,
0.000002376940301473951
] |
{
"id": 3,
"code_window": [
"\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/configurationRestore.js",
"type": "replace",
"edit_start_line_idx": 21
} | {
"BoundRoute.title": "Rota definida para",
"EditForm.inputSelect.description.role": "Ele anexará o novo usuário autenticado ao nível selecionado.",
"EditForm.inputSelect.label.role": "Nível padrão para usuários autenticados",
"EditForm.inputToggle.description.email": "Não permitir que o usuário crie várias contas usando o mesmo endereço de e-mail com diferentes provedores de autenticação.",
"EditForm.inputToggle.description.sign-up": "Quando desativado (OFF), o processo de registro é proibido. Nenhum novo usuário poderá se registrar, não importa o provedor usado.",
"EditForm.inputToggle.label.email": "Limitar 1 conta por endereço de email",
"EditForm.inputToggle.label.sign-up": "Ativar registro de usuários",
"HeaderNav.link.advancedSettings": "Configurações avançadas",
"HeaderNav.link.emailTemplates": "Modelos de email",
"HeaderNav.link.providers": "Provedores",
"Plugin.permissions.plugins.description": "Defina todas as ações permitidas para o plugin {name}.",
"Plugins.header.description": "Somente ações vinculadas por uma rota estão listadas abaixo.",
"Plugins.header.title": "Permissões",
"Policies.header.hint": "Selecione as ações do aplicativo ou as ações do plugin e clique no ícone do cog para exibir a rota",
"Policies.header.title": "Configurações avançadas",
"PopUpForm.Email.email_templates.inputDescription": "Se não tiver certeza de como usar variáveis, {link}",
"PopUpForm.Email.options.from.email.label": "Email do remetente",
"PopUpForm.Email.options.from.email.placeholder": "[email protected]",
"PopUpForm.Email.options.from.name.label": "Nome do remetente",
"PopUpForm.Email.options.from.name.placeholder": "Kai Doe",
"PopUpForm.Email.options.message.label": "Mensagem",
"PopUpForm.Email.options.object.label": "Assunto",
"PopUpForm.Email.options.response_email.label": "Email de resposta",
"PopUpForm.Email.options.response_email.placeholder": "[email protected]",
"PopUpForm.Providers.enabled.description": "Se desativado, os usuários não poderão usar este provedor",
"PopUpForm.Providers.enabled.label": "Ativar",
"PopUpForm.Providers.key.label": "ID do cliente",
"PopUpForm.Providers.key.placeholder": "TEXT",
"PopUpForm.Providers.redirectURL.front-end.label": "O URL de redirecionamento para seu aplicativo front-end",
"PopUpForm.Providers.secret.label": "Segredo do Cliente",
"PopUpForm.Providers.secret.placeholder": "TEXT",
"PopUpForm.Providers.subdomain.label": "Host URI (Subdomain)",
"PopUpForm.Providers.subdomain.placeholder": "my.subdomain.com",
"PopUpForm.header.edit.email-templates": "Editar modelos de email",
"notification.success.submit": "As configurações foram atualizadas",
"plugin.description.long": "Proteja sua API com um processo de autenticação completo baseado no JWT. Esse plugin também vem com uma estratégia de ACL que permite gerenciar as permissões entre os grupos de usuários.",
"plugin.description.short": "Proteja sua API com um processo de autenticação completo baseado no JWT",
"plugin.name": "Papéis e permissões"
}
| packages/plugins/users-permissions/admin/src/translations/pt-BR.json | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.0001797307631932199,
0.0001748140639392659,
0.00017080697580240667,
0.00017461908282712102,
0.0000030996272926131496
] |
{
"id": 3,
"code_window": [
"\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/configurationRestore.js",
"type": "replace",
"edit_start_line_idx": 21
} | export const SET_LAYOUT = 'ContentManager/EditViewLayoutManager/SET_LAYOUT';
export const RESET_PROPS = 'ContentManager/EditViewLayoutManager/RESET_PROPS';
| packages/core/admin/admin/src/content-manager/pages/EditViewLayoutManager/constants.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.0001743315951898694,
0.0001743315951898694,
0.0001743315951898694,
0.0001743315951898694,
0
] |
{
"id": 4,
"code_window": [
" // Now load up the Strapi framework for real.\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/console.js",
"type": "replace",
"edit_start_line_idx": 17
} | 'use strict';
const ts = require('typescript');
const reportDiagnostics = require('../utils/report-diagnostics');
const resolveConfigOptions = require('../utils/resolve-config-options');
module.exports = {
/**
* Default TS -> JS Compilation for Strapi
* @param {string} tsConfigPath
*/
run(tsConfigPath) {
// Parse the tsconfig.json file & resolve the configuration options
const { fileNames, options, projectReferences } = resolveConfigOptions(tsConfigPath);
const program = ts.createProgram({
rootNames: fileNames,
projectReferences,
options,
});
const emitResults = program.emit();
const diagnostics = ts.sortAndDeduplicateDiagnostics(
ts.getPreEmitDiagnostics(program).concat(emitResults.diagnostics)
);
if (diagnostics.length > 0) {
reportDiagnostics(diagnostics);
}
// If the compilation failed, exit early
if (emitResults.emitSkipped) {
process.exit(1);
}
},
};
| packages/utils/typescript/lib/compilers/basic.js | 1 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017495172505732626,
0.00017046391440089792,
0.00016713512013666332,
0.00016988441348075867,
0.00000318867228088493
] |
{
"id": 4,
"code_window": [
" // Now load up the Strapi framework for real.\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/console.js",
"type": "replace",
"edit_start_line_idx": 17
} | import getLocaleFromQuery from './getLocaleFromQuery';
const getInitialLocale = (query, locales = []) => {
const localeFromQuery = getLocaleFromQuery(query);
if (localeFromQuery) {
return locales.find(locale => locale.code === localeFromQuery);
}
// Returns the default locale when nothing is in the query
return locales.find(locale => locale.isDefault);
};
export default getInitialLocale;
| packages/plugins/i18n/admin/src/utils/getInitialLocale.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017780174675863236,
0.00017739375471137464,
0.00017698577721603215,
0.00017739375471137464,
4.0798477130010724e-7
] |
{
"id": 4,
"code_window": [
" // Now load up the Strapi framework for real.\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/console.js",
"type": "replace",
"edit_start_line_idx": 17
} | const getRequestUrl = path => `/admin/${path}`;
export default getRequestUrl;
| packages/core/admin/admin/src/utils/getRequestUrl.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00028740320703946054,
0.00028740320703946054,
0.00028740320703946054,
0.00028740320703946054,
0
] |
{
"id": 4,
"code_window": [
" // Now load up the Strapi framework for real.\n",
" const appDir = process.cwd();\n",
"\n",
" const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n",
"\n",
" if (isTSProject) await tsUtils.compile(appDir, { watch: false });\n",
"\n",
" const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isTSProject)\n",
" await tsUtils.compile(appDir, {\n",
" watch: false,\n",
" configOptions: { options: { incremental: true } },\n",
" });\n"
],
"file_path": "packages/core/strapi/lib/commands/console.js",
"type": "replace",
"edit_start_line_idx": 17
} | import { getTrad } from '../../../utils';
export function handleAPIError(error) {
const errorPayload = error.response.data.error.details.errors;
const validationErrors = errorPayload.reduce((acc, err) => {
acc[err.path.join('.')] = {
id: getTrad(`apiError.${err.message}`),
defaultMessage: err.message,
};
return acc;
}, {});
return validationErrors;
}
| packages/core/admin/admin/src/content-manager/components/EditViewDataManagerProvider/utils/handleAPIError.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00020792313443962485,
0.00019361436716280878,
0.00017930558533407748,
0.00019361436716280878,
0.000014308774552773684
] |
{
"id": 5,
"code_window": [
"\n",
"const compilers = require('./compilers');\n",
"const getConfigPath = require('./utils/get-config-path');\n",
"\n",
"module.exports = async (srcDir, { watch = false } = {}) => {\n",
" // TODO: Use the Strapi debug logger instead or don't log at all\n",
" console.log(`Starting the compilation for TypeScript files in ${srcDir}`);\n",
"\n",
" const compiler = watch ? compilers.watch : compilers.basic;\n",
" const configPath = getConfigPath(srcDir);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"module.exports = async (\n",
" srcDir,\n",
" { watch = false, configOptions = { options: {}, fileNames: [] } }\n",
") => {\n"
],
"file_path": "packages/utils/typescript/lib/compile.js",
"type": "replace",
"edit_start_line_idx": 5
} | 'use strict';
const ts = require('typescript');
const reportDiagnostics = require('../utils/report-diagnostics');
const resolveConfigOptions = require('../utils/resolve-config-options');
module.exports = {
/**
* Default TS -> JS Compilation for Strapi
* @param {string} tsConfigPath
*/
run(tsConfigPath) {
// Parse the tsconfig.json file & resolve the configuration options
const { fileNames, options, projectReferences } = resolveConfigOptions(tsConfigPath);
const program = ts.createProgram({
rootNames: fileNames,
projectReferences,
options,
});
const emitResults = program.emit();
const diagnostics = ts.sortAndDeduplicateDiagnostics(
ts.getPreEmitDiagnostics(program).concat(emitResults.diagnostics)
);
if (diagnostics.length > 0) {
reportDiagnostics(diagnostics);
}
// If the compilation failed, exit early
if (emitResults.emitSkipped) {
process.exit(1);
}
},
};
| packages/utils/typescript/lib/compilers/basic.js | 1 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.0007336298003792763,
0.000313793309032917,
0.00016627134755253792,
0.0001776360149960965,
0.00024244558881036937
] |
{
"id": 5,
"code_window": [
"\n",
"const compilers = require('./compilers');\n",
"const getConfigPath = require('./utils/get-config-path');\n",
"\n",
"module.exports = async (srcDir, { watch = false } = {}) => {\n",
" // TODO: Use the Strapi debug logger instead or don't log at all\n",
" console.log(`Starting the compilation for TypeScript files in ${srcDir}`);\n",
"\n",
" const compiler = watch ? compilers.watch : compilers.basic;\n",
" const configPath = getConfigPath(srcDir);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"module.exports = async (\n",
" srcDir,\n",
" { watch = false, configOptions = { options: {}, fileNames: [] } }\n",
") => {\n"
],
"file_path": "packages/utils/typescript/lib/compile.js",
"type": "replace",
"edit_start_line_idx": 5
} | import React, { useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { useIntl } from 'react-intl';
import { Box } from '@strapi/design-system/Box';
import { Button } from '@strapi/design-system/Button';
import Filter from '@strapi/icons/Filter';
import { FilterListURLQuery, FilterPopoverURLQuery, useTracking } from '@strapi/helper-plugin';
const Filters = ({ displayedFilters }) => {
const [isVisible, setIsVisible] = useState(false);
const { formatMessage } = useIntl();
const buttonRef = useRef();
const { trackUsage } = useTracking();
const handleToggle = () => {
if (!isVisible) {
trackUsage('willFilterEntries');
}
setIsVisible(prev => !prev);
};
return (
<>
<Box paddingTop={1} paddingBottom={1}>
<Button
variant="tertiary"
ref={buttonRef}
startIcon={<Filter />}
onClick={handleToggle}
size="S"
>
{formatMessage({ id: 'app.utils.filters', defaultMessage: 'Filters' })}
</Button>
{isVisible && (
<FilterPopoverURLQuery
displayedFilters={displayedFilters}
isVisible={isVisible}
onToggle={handleToggle}
source={buttonRef}
/>
)}
</Box>
<FilterListURLQuery filtersSchema={displayedFilters} />
</>
);
};
Filters.propTypes = {
displayedFilters: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string.isRequired,
metadatas: PropTypes.shape({ label: PropTypes.string }),
fieldSchema: PropTypes.shape({ type: PropTypes.string }),
})
).isRequired,
};
export default Filters;
| packages/core/admin/admin/src/content-manager/components/AttributeFilter/Filters.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.0001766708301147446,
0.00017485085118096322,
0.0001731413503875956,
0.00017474083870183676,
0.0000014244577641875367
] |
{
"id": 5,
"code_window": [
"\n",
"const compilers = require('./compilers');\n",
"const getConfigPath = require('./utils/get-config-path');\n",
"\n",
"module.exports = async (srcDir, { watch = false } = {}) => {\n",
" // TODO: Use the Strapi debug logger instead or don't log at all\n",
" console.log(`Starting the compilation for TypeScript files in ${srcDir}`);\n",
"\n",
" const compiler = watch ? compilers.watch : compilers.basic;\n",
" const configPath = getConfigPath(srcDir);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"module.exports = async (\n",
" srcDir,\n",
" { watch = false, configOptions = { options: {}, fileNames: [] } }\n",
") => {\n"
],
"file_path": "packages/utils/typescript/lib/compile.js",
"type": "replace",
"edit_start_line_idx": 5
} | import { set } from 'lodash';
const mergeMetasWithSchema = (data, schemas, mainSchemaKey) => {
const findSchema = refUid => schemas.find(obj => obj.uid === refUid);
const merged = Object.assign({}, data);
const mainUID = data[mainSchemaKey].uid;
const mainSchema = findSchema(mainUID);
set(merged, [mainSchemaKey], { ...data[mainSchemaKey], ...mainSchema });
Object.keys(data.components).forEach(compoUID => {
const compoSchema = findSchema(compoUID);
set(merged, ['components', compoUID], { ...data.components[compoUID], ...compoSchema });
});
return merged;
};
export default mergeMetasWithSchema;
| packages/core/admin/admin/src/content-manager/utils/mergeMetasWithSchema.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017384524107910693,
0.00017316763114649802,
0.00017227086937054992,
0.00017338682664558291,
6.611564913328039e-7
] |
{
"id": 5,
"code_window": [
"\n",
"const compilers = require('./compilers');\n",
"const getConfigPath = require('./utils/get-config-path');\n",
"\n",
"module.exports = async (srcDir, { watch = false } = {}) => {\n",
" // TODO: Use the Strapi debug logger instead or don't log at all\n",
" console.log(`Starting the compilation for TypeScript files in ${srcDir}`);\n",
"\n",
" const compiler = watch ? compilers.watch : compilers.basic;\n",
" const configPath = getConfigPath(srcDir);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"module.exports = async (\n",
" srcDir,\n",
" { watch = false, configOptions = { options: {}, fileNames: [] } }\n",
") => {\n"
],
"file_path": "packages/utils/typescript/lib/compile.js",
"type": "replace",
"edit_start_line_idx": 5
} | 'use strict';
const baseConfig = require('../../../jest.base-config');
const pkg = require('./package');
module.exports = {
...baseConfig,
displayName: (pkg.strapi && pkg.strapi.name) || pkg.name,
roots: [__dirname],
};
| packages/plugins/graphql/jest.config.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.0003865700273308903,
0.00028020772151649,
0.00017384540115017444,
0.00028020772151649,
0.00010636231309035793
] |
{
"id": 6,
"code_window": [
" const compiler = watch ? compilers.watch : compilers.basic;\n",
" const configPath = getConfigPath(srcDir);\n",
"\n",
" compiler.run(configPath);\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" compiler.run(configPath, configOptions);\n"
],
"file_path": "packages/utils/typescript/lib/compile.js",
"type": "replace",
"edit_start_line_idx": 12
} | 'use strict';
const REPL = require('repl');
const path = require('path');
const tsUtils = require('@strapi/typescript-utils');
const strapi = require('../index');
/**
* `$ strapi console`
*/
module.exports = async () => {
// Now load up the Strapi framework for real.
const appDir = process.cwd();
const isTSProject = await tsUtils.isUsingTypeScript(appDir);
if (isTSProject) await tsUtils.compile(appDir, { watch: false });
const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;
const app = await strapi({ appDir, distDir }).load();
app.start().then(() => {
const repl = REPL.start(app.config.info.name + ' > ' || 'strapi > '); // eslint-disable-line prefer-template
repl.on('exit', function(err) {
if (err) {
app.log.error(err);
process.exit(1);
}
app.server.destroy();
process.exit(0);
});
});
};
| packages/core/strapi/lib/commands/console.js | 1 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.0005633358960039914,
0.0002715196751523763,
0.0001723185123410076,
0.00017521216068416834,
0.00016848462109919637
] |
{
"id": 6,
"code_window": [
" const compiler = watch ? compilers.watch : compilers.basic;\n",
" const configPath = getConfigPath(srcDir);\n",
"\n",
" compiler.run(configPath);\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" compiler.run(configPath, configOptions);\n"
],
"file_path": "packages/utils/typescript/lib/compile.js",
"type": "replace",
"edit_start_line_idx": 12
} | 'use strict';
const _ = require('lodash');
const { ApplicationError, ValidationError } = require('@strapi/utils').errors;
const { getService } = require('../utils');
const { validateDeleteRoleBody } = require('./validation/user');
module.exports = {
/**
* Default action.
*
* @return {Object}
*/
async createRole(ctx) {
if (_.isEmpty(ctx.request.body)) {
throw new ValidationError('Request body cannot be empty');
}
await getService('role').createRole(ctx.request.body);
ctx.send({ ok: true });
},
async getRole(ctx) {
const { id } = ctx.params;
const role = await getService('role').getRole(id);
if (!role) {
return ctx.notFound();
}
ctx.send({ role });
},
async getRoles(ctx) {
const roles = await getService('role').getRoles();
ctx.send({ roles });
},
async updateRole(ctx) {
const roleID = ctx.params.role;
if (_.isEmpty(ctx.request.body)) {
throw new ValidationError('Request body cannot be empty');
}
await getService('role').updateRole(roleID, ctx.request.body);
ctx.send({ ok: true });
},
async deleteRole(ctx) {
const roleID = ctx.params.role;
if (!roleID) {
await validateDeleteRoleBody(ctx.params);
}
// Fetch public role.
const publicRole = await strapi
.query('plugin::users-permissions.role')
.findOne({ where: { type: 'public' } });
const publicRoleID = publicRole.id;
// Prevent from removing the public role.
if (roleID.toString() === publicRoleID.toString()) {
throw new ApplicationError('Cannot delete public role');
}
await getService('role').deleteRole(roleID, publicRoleID);
ctx.send({ ok: true });
},
};
| packages/plugins/users-permissions/server/controllers/role.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017762502830009907,
0.00017442266107536852,
0.00017176108667626977,
0.00017399100761394948,
0.000001687303779362992
] |
{
"id": 6,
"code_window": [
" const compiler = watch ? compilers.watch : compilers.basic;\n",
" const configPath = getConfigPath(srcDir);\n",
"\n",
" compiler.run(configPath);\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" compiler.run(configPath, configOptions);\n"
],
"file_path": "packages/utils/typescript/lib/compile.js",
"type": "replace",
"edit_start_line_idx": 12
} | {
"plugin.name": "Mi plugin"
}
| examples/getstarted/src/plugins/myplugin/admin/src/translations/es.json | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00018027621263172477,
0.00018027621263172477,
0.00018027621263172477,
0.00018027621263172477,
0
] |
{
"id": 6,
"code_window": [
" const compiler = watch ? compilers.watch : compilers.basic;\n",
" const configPath = getConfigPath(srcDir);\n",
"\n",
" compiler.run(configPath);\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" compiler.run(configPath, configOptions);\n"
],
"file_path": "packages/utils/typescript/lib/compile.js",
"type": "replace",
"edit_start_line_idx": 12
} | 'use strict';
const createContext = require('../../../../../../test/helpers/create-context');
const singleTypes = require('../single-types');
describe('Single Types', () => {
test('Successfull find', async () => {
const state = {
userAbility: {
can: jest.fn(),
cannot: jest.fn(() => false),
},
};
const notFound = jest.fn();
const createPermissionsManager = jest.fn(() => ({
ability: state.userAbility,
}));
const permissionChecker = {
cannot: {
read: jest.fn(() => false),
create: jest.fn(() => false),
},
buildReadQuery: jest.fn(query => query),
};
global.strapi = {
admin: {
services: {
permission: {
createPermissionsManager,
},
},
},
plugins: {
'content-manager': {
services: {
'entity-manager': {
find() {
return Promise.resolve();
},
assocCreatorRoles(enitty) {
return enitty;
},
},
'permission-checker': {
create() {
return permissionChecker;
},
},
},
},
},
entityService: {
find: jest.fn(),
},
};
const modelUid = 'test-model';
const ctx = createContext(
{
params: {
model: modelUid,
},
},
{ state, notFound }
);
await singleTypes.find(ctx);
expect(permissionChecker.cannot.read).toHaveBeenCalled();
expect(permissionChecker.cannot.create).toHaveBeenCalled();
expect(notFound).toHaveBeenCalled();
});
test('Successfull create', async () => {
const modelUid = 'test-uid';
const state = {
userAbility: {
can: jest.fn(),
cannot: jest.fn(() => false),
},
user: {
id: 1,
},
};
const createPermissionsManager = jest.fn(() => ({
ability: state.userAbility,
}));
const permissionChecker = {
cannot: {
update: jest.fn(() => false),
create: jest.fn(() => false),
},
sanitizeCreateInput: obj => obj,
sanitizeOutput: obj => obj,
buildReadQuery: jest.fn(query => query),
};
const createFn = jest.fn(() => ({}));
const sendTelemetry = jest.fn(() => ({}));
global.strapi = {
admin: {
services: {
permission: {
createPermissionsManager,
},
},
},
getModel() {
return {
options: {
draftAndPublish: true,
},
attributes: {
title: {
type: 'string',
},
},
};
},
plugins: {
'content-manager': {
services: {
'entity-manager': {
find() {
return Promise.resolve();
},
assocCreatorRoles(enitty) {
return enitty;
},
create: createFn,
},
'permission-checker': {
create() {
return permissionChecker;
},
},
},
},
},
entityService: {
find: jest.fn(),
},
telemetry: {
send: sendTelemetry,
},
};
const ctx = createContext(
{
params: {
model: modelUid,
},
body: {
title: 'test',
},
},
{ state }
);
await singleTypes.createOrUpdate(ctx);
expect(permissionChecker.cannot.create).toHaveBeenCalled();
expect(createFn).toHaveBeenCalledWith(
expect.objectContaining({
title: 'test',
createdBy: 1,
updatedBy: 1,
}),
modelUid,
{ params: {} }
);
expect(sendTelemetry).toHaveBeenCalledWith('didCreateFirstContentTypeEntry', {
model: modelUid,
});
});
test('Successfull delete', async () => {
const modelUid = 'test-uid';
const entity = {
id: 1,
title: 'entityTitle',
};
const state = {
userAbility: {
can: jest.fn(),
cannot: jest.fn(() => false),
},
user: {
id: 1,
},
};
const createPermissionsManager = jest.fn(() => ({
ability: state.userAbility,
}));
const permissionChecker = {
cannot: {
delete: jest.fn(() => false),
},
sanitizeOutput: jest.fn(obj => obj),
buildReadQuery: jest.fn(query => query),
};
const deleteFn = jest.fn(() => ({}));
global.strapi = {
admin: {
services: {
permission: {
createPermissionsManager,
},
},
},
getModel() {
return {
options: {
draftAndPublish: true,
},
attributes: {
title: {
type: 'string',
},
},
};
},
plugins: {
'content-manager': {
services: {
'entity-manager': {
find() {
return Promise.resolve(entity);
},
assocCreatorRoles(enitty) {
return enitty;
},
delete: deleteFn,
},
'permission-checker': {
create() {
return permissionChecker;
},
},
},
},
},
entityService: {
find: jest.fn(),
},
};
const ctx = createContext(
{
params: {
id: entity.id,
model: modelUid,
},
},
{ state }
);
await singleTypes.delete(ctx);
expect(deleteFn).toHaveBeenCalledWith(entity, modelUid);
expect(permissionChecker.cannot.delete).toHaveBeenCalledWith(entity);
expect(permissionChecker.sanitizeOutput).toHaveBeenCalled();
});
test('Successfull publish', async () => {
const modelUid = 'test-uid';
const entity = {
id: 1,
title: 'entityTitle',
};
const state = {
userAbility: {
can: jest.fn(),
cannot: jest.fn(() => false),
},
user: {
id: 1,
},
};
const createPermissionsManager = jest.fn(() => ({
ability: state.userAbility,
}));
const permissionChecker = {
cannot: {
publish: jest.fn(() => false),
},
sanitizeOutput: jest.fn(obj => obj),
buildReadQuery: jest.fn(query => query),
};
const publishFn = jest.fn(() => ({}));
global.strapi = {
admin: {
services: {
permission: {
createPermissionsManager,
},
},
},
getModel() {
return {
options: {
draftAndPublish: true,
},
attributes: {
title: {
type: 'string',
},
},
};
},
plugins: {
'content-manager': {
services: {
'entity-manager': {
find() {
return Promise.resolve(entity);
},
assocCreatorRoles(enitty) {
return enitty;
},
publish: publishFn,
},
'permission-checker': {
create() {
return permissionChecker;
},
},
},
},
},
entityService: {
find: jest.fn(),
},
};
const ctx = createContext(
{
params: {
id: entity.id,
model: modelUid,
},
},
{ state }
);
await singleTypes.publish(ctx);
expect(publishFn).toHaveBeenCalledWith(entity, { updatedBy: state.user.id }, modelUid);
expect(permissionChecker.cannot.publish).toHaveBeenCalledWith(entity);
expect(permissionChecker.sanitizeOutput).toHaveBeenCalled();
});
test('Successfull unpublish', async () => {
const modelUid = 'test-uid';
const entity = {
id: 1,
title: 'entityTitle',
};
const state = {
userAbility: {
can: jest.fn(),
cannot: jest.fn(() => false),
},
user: {
id: 1,
},
};
const createPermissionsManager = jest.fn(() => ({
ability: state.userAbility,
}));
const permissionChecker = {
cannot: {
unpublish: jest.fn(() => false),
},
sanitizeOutput: jest.fn(obj => obj),
buildReadQuery: jest.fn(query => query),
};
const unpublishFn = jest.fn(() => ({}));
global.strapi = {
admin: {
services: {
permission: {
createPermissionsManager,
},
},
},
getModel() {
return {
options: {
draftAndPublish: true,
},
attributes: {
title: {
type: 'string',
},
},
};
},
plugins: {
'content-manager': {
services: {
'entity-manager': {
find() {
return Promise.resolve(entity);
},
assocCreatorRoles(enitty) {
return enitty;
},
unpublish: unpublishFn,
},
'permission-checker': {
create() {
return permissionChecker;
},
},
},
},
},
entityService: {
find: jest.fn(),
},
};
const ctx = createContext(
{
params: {
id: entity.id,
model: modelUid,
},
},
{ state }
);
await singleTypes.unpublish(ctx);
expect(unpublishFn).toHaveBeenCalledWith(entity, { updatedBy: state.user.id }, modelUid);
expect(permissionChecker.cannot.unpublish).toHaveBeenCalledWith(entity);
expect(permissionChecker.sanitizeOutput).toHaveBeenCalled();
});
});
| packages/core/content-manager/server/controllers/__tests__/single-types.test.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017905748973134905,
0.00017422249948140234,
0.00017071806360036135,
0.00017390689754392952,
0.000002144968675565906
] |
{
"id": 7,
"code_window": [
"'use strict';\n",
"\n",
"const ts = require('typescript');\n",
"\n",
"const reportDiagnostics = require('../utils/report-diagnostics');\n",
"const resolveConfigOptions = require('../utils/resolve-config-options');\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { merge } = require('lodash');\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "add",
"edit_start_line_idx": 3
} | 'use strict';
const path = require('path');
const _ = require('lodash');
const inquirer = require('inquirer');
const tsUtils = require('@strapi/typescript-utils');
const strapi = require('../index');
const promptQuestions = [
{ type: 'input', name: 'email', message: 'User email?' },
{ type: 'password', name: 'password', message: 'New password?' },
{
type: 'confirm',
name: 'confirm',
message: "Do you really want to reset this user's password?",
},
];
/**
* Reset user's password
* @param {Object} cmdOptions - command options
* @param {string} cmdOptions.email - user's email
* @param {string} cmdOptions.password - user's new password
*/
module.exports = async function(cmdOptions = {}) {
const { email, password } = cmdOptions;
if (_.isEmpty(email) && _.isEmpty(password) && process.stdin.isTTY) {
const inquiry = await inquirer.prompt(promptQuestions);
if (!inquiry.confirm) {
process.exit(0);
}
return changePassword(inquiry);
}
if (_.isEmpty(email) || _.isEmpty(password)) {
console.error('Missing required options `email` or `password`');
process.exit(1);
}
return changePassword({ email, password });
};
async function changePassword({ email, password }) {
const appDir = process.cwd();
const isTSProject = await tsUtils.isUsingTypeScript(appDir);
if (isTSProject) await tsUtils.compile(appDir, { watch: false });
const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;
const app = await strapi({ appDir, distDir }).load();
await app.admin.services.user.resetPasswordByEmail(email, password);
console.log(`Successfully reset user's password`);
process.exit(0);
}
| packages/core/strapi/lib/commands/admin-reset.js | 1 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.004959959536790848,
0.0008730000699870288,
0.00016935259918682277,
0.00018019336857832968,
0.0016688101459294558
] |
{
"id": 7,
"code_window": [
"'use strict';\n",
"\n",
"const ts = require('typescript');\n",
"\n",
"const reportDiagnostics = require('../utils/report-diagnostics');\n",
"const resolveConfigOptions = require('../utils/resolve-config-options');\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { merge } = require('lodash');\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "add",
"edit_start_line_idx": 3
} | 'use strict';
const { yup, validateYupSchema } = require('@strapi/utils');
const providerOptionsUpdateSchema = yup.object().shape({
autoRegister: yup.boolean().required(),
defaultRole: yup
.strapiID()
.required()
.test('is-valid-role', 'You must submit a valid default role', roleId => {
return strapi.admin.services.role.exists({ id: roleId });
}),
});
module.exports = {
validateProviderOptionsUpdate: validateYupSchema(providerOptionsUpdateSchema),
};
| packages/core/admin/ee/server/validation/authentication.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00019901931227650493,
0.00018458892009221017,
0.0001701585279079154,
0.00018458892009221017,
0.00001443039218429476
] |
{
"id": 7,
"code_window": [
"'use strict';\n",
"\n",
"const ts = require('typescript');\n",
"\n",
"const reportDiagnostics = require('../utils/report-diagnostics');\n",
"const resolveConfigOptions = require('../utils/resolve-config-options');\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { merge } = require('lodash');\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "add",
"edit_start_line_idx": 3
} | import { has, get, omit } from 'lodash';
import LOCALIZED_FIELDS from './localizedFields';
const localizedPath = ['pluginOptions', 'i18n', 'localized'];
const addLocalisationToFields = attributes =>
Object.keys(attributes).reduce((acc, current) => {
const currentAttribute = attributes[current];
if (LOCALIZED_FIELDS.includes(currentAttribute.type)) {
const i18n = { localized: true };
const pluginOptions = currentAttribute.pluginOptions
? { ...currentAttribute.pluginOptions, i18n }
: { i18n };
acc[current] = { ...currentAttribute, pluginOptions };
return acc;
}
acc[current] = currentAttribute;
return acc;
}, {});
const disableAttributesLocalisation = attributes =>
Object.keys(attributes).reduce((acc, current) => {
acc[current] = omit(attributes[current], 'pluginOptions.i18n');
return acc;
}, {});
const mutateCTBContentTypeSchema = (nextSchema, prevSchema) => {
// Don't perform mutations components
if (!has(nextSchema, localizedPath)) {
return nextSchema;
}
const isNextSchemaLocalized = get(nextSchema, localizedPath, false);
const isPrevSchemaLocalized = get(prevSchema, ['schema', ...localizedPath], false);
// No need to perform modification on the schema, if the i18n feature was not changed
// at the ct level
if (isNextSchemaLocalized && isPrevSchemaLocalized) {
return nextSchema;
}
if (isNextSchemaLocalized) {
const attributes = addLocalisationToFields(nextSchema.attributes);
return { ...nextSchema, attributes };
}
// Remove the i18n object from the pluginOptions
if (!isNextSchemaLocalized) {
const pluginOptions = omit(nextSchema.pluginOptions, 'i18n');
const attributes = disableAttributesLocalisation(nextSchema.attributes);
return { ...nextSchema, pluginOptions, attributes };
}
return nextSchema;
};
export default mutateCTBContentTypeSchema;
export { addLocalisationToFields, disableAttributesLocalisation };
| packages/plugins/i18n/admin/src/utils/mutateCTBContentTypeSchema.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.0002445081772748381,
0.00018028113117907196,
0.000167808510013856,
0.00016967230476439,
0.0000262644280155655
] |
{
"id": 7,
"code_window": [
"'use strict';\n",
"\n",
"const ts = require('typescript');\n",
"\n",
"const reportDiagnostics = require('../utils/report-diagnostics');\n",
"const resolveConfigOptions = require('../utils/resolve-config-options');\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { merge } = require('lodash');\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "add",
"edit_start_line_idx": 3
} | {
"name": "{{ pluginName }}",
"version": "0.0.0",
"description": "This is the description of the plugin.",
"strapi": {
"name": "{{ pluginName }}",
"description": "Description of {{ pluginName }} plugin",
"kind": "plugin"
},
"dependencies": {},
"devDependencies": {
"typescript": "4.6.3",
"@strapi/strapi": "4.1.8"
},
"author": {
"name": "A Strapi developer"
},
"maintainers": [
{
"name": "A Strapi developer"
}
],
"engines": {
"node": ">=12.x.x <=16.x.x",
"npm": ">=6.0.0"
},
"scripts": {
"develop": "tsc -w",
"build": "tsc"
},
"license": "MIT"
}
| packages/generators/generators/lib/templates/ts/plugin-package.json.hbs | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017822541121859103,
0.0001728380157146603,
0.000170146522577852,
0.00017149007180705667,
0.0000032903358260227833
] |
{
"id": 8,
"code_window": [
"module.exports = {\n",
" /**\n",
" * Default TS -> JS Compilation for Strapi\n",
" * @param {string} tsConfigPath\n",
" */\n",
" run(tsConfigPath) {\n",
" // Parse the tsconfig.json file & resolve the configuration options\n",
" const { fileNames, options, projectReferences } = resolveConfigOptions(tsConfigPath);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" run(tsConfigPath, configOptions) {\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "replace",
"edit_start_line_idx": 12
} | 'use strict';
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const tsUtils = require('@strapi/typescript-utils');
const strapi = require('../index');
/**
* Will restore configurations. It reads from a file or stdin
* @param {string} file filepath to use as input
* @param {string} strategy import strategy. one of (replace, merge, keep, default: replace)
*/
module.exports = async function({ file: filePath, strategy = 'replace' }) {
const input = filePath ? fs.readFileSync(filePath) : await readStdin(process.stdin);
const appDir = process.cwd();
const isTSProject = await tsUtils.isUsingTypeScript(appDir);
if (isTSProject) await tsUtils.compile(appDir, { watch: false });
const distDir = isTSProject ? path.join(appDir, 'dist') : appDir;
const app = await strapi({ appDir, distDir }).load();
let dataToImport;
try {
dataToImport = JSON.parse(input);
} catch (error) {
throw new Error(`Invalid input data: ${error.message}. Expected a valid JSON array.`);
}
if (!Array.isArray(dataToImport)) {
throw new Error(`Invalid input data. Expected a valid JSON array.`);
}
const importer = createImporter(app.db, strategy);
for (const config of dataToImport) {
await importer.import(config);
}
console.log(
`Successfully imported configuration with ${strategy} strategy. Statistics: ${importer.printStatistics()}.`
);
process.exit(0);
};
const readStdin = () => {
const { stdin } = process;
let result = '';
if (stdin.isTTY) return Promise.resolve(result);
return new Promise((resolve, reject) => {
stdin.setEncoding('utf8');
stdin.on('readable', () => {
let chunk;
while ((chunk = stdin.read())) {
result += chunk;
}
});
stdin.on('end', () => {
resolve(result);
});
stdin.on('error', reject);
});
};
const createImporter = (db, strategy) => {
switch (strategy) {
case 'replace':
return createReplaceImporter(db);
case 'merge':
return createMergeImporter(db);
case 'keep':
return createKeepImporter(db);
default:
throw new Error(`No importer available for strategy "${strategy}"`);
}
};
/**
* Replace importer. Will replace the keys that already exist and create the new ones
* @param {Object} db - DatabaseManager instance
*/
const createReplaceImporter = db => {
const stats = {
created: 0,
replaced: 0,
};
return {
printStatistics() {
return `${stats.created} created, ${stats.replaced} replaced`;
},
async import(conf) {
const matching = await db.query('strapi::core-store').count({ where: { key: conf.key } });
if (matching > 0) {
stats.replaced += 1;
await db.query('strapi::core-store').update({
where: { key: conf.key },
data: conf,
});
} else {
stats.created += 1;
await db.query('strapi::core-store').create({ data: conf });
}
},
};
};
/**
* Merge importer. Will merge the keys that already exist with their new value and create the new ones
* @param {Object} db - DatabaseManager instance
*/
const createMergeImporter = db => {
const stats = {
created: 0,
merged: 0,
};
return {
printStatistics() {
return `${stats.created} created, ${stats.merged} merged`;
},
async import(conf) {
const existingConf = await db
.query('strapi::core-store')
.findOne({ where: { key: conf.key } });
if (existingConf) {
stats.merged += 1;
await db.query('strapi::core-store').update({
where: { key: conf.key },
data: _.merge(existingConf, conf),
});
} else {
stats.created += 1;
await db.query('strapi::core-store').create({ data: conf });
}
},
};
};
/**
* Merge importer. Will keep the keys that already exist without changing them and create the new ones
* @param {Object} db - DatabaseManager instance
*/
const createKeepImporter = db => {
const stats = {
created: 0,
untouched: 0,
};
return {
printStatistics() {
return `${stats.created} created, ${stats.untouched} untouched`;
},
async import(conf) {
const matching = await db.query('strapi::core-store').count({ where: { key: conf.key } });
if (matching > 0) {
stats.untouched += 1;
// if configuration already exists do not overwrite it
return;
}
stats.created += 1;
await db.query('strapi::core-store').create({ data: conf });
},
};
};
| packages/core/strapi/lib/commands/configurationRestore.js | 1 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.0027189466636627913,
0.0003150750999338925,
0.00016706532915122807,
0.0001735275873215869,
0.0005676870350725949
] |
{
"id": 8,
"code_window": [
"module.exports = {\n",
" /**\n",
" * Default TS -> JS Compilation for Strapi\n",
" * @param {string} tsConfigPath\n",
" */\n",
" run(tsConfigPath) {\n",
" // Parse the tsconfig.json file & resolve the configuration options\n",
" const { fileNames, options, projectReferences } = resolveConfigOptions(tsConfigPath);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" run(tsConfigPath, configOptions) {\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "replace",
"edit_start_line_idx": 12
} | import styled from 'styled-components';
const Container = styled.div`
padding: 18px 30px 66px 30px;
`;
export default Container;
| packages/core/admin/admin/src/content-manager/components/Container/index.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017508641758468002,
0.00017508641758468002,
0.00017508641758468002,
0.00017508641758468002,
0
] |
{
"id": 8,
"code_window": [
"module.exports = {\n",
" /**\n",
" * Default TS -> JS Compilation for Strapi\n",
" * @param {string} tsConfigPath\n",
" */\n",
" run(tsConfigPath) {\n",
" // Parse the tsconfig.json file & resolve the configuration options\n",
" const { fileNames, options, projectReferences } = resolveConfigOptions(tsConfigPath);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" run(tsConfigPath, configOptions) {\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "replace",
"edit_start_line_idx": 12
} | import { useEffect } from 'react';
import { useQuery } from 'react-query';
import { useNotifyAT } from '@strapi/design-system/LiveRegions';
import { useNotification, useQueryParams } from '@strapi/helper-plugin';
import { useIntl } from 'react-intl';
import { axiosInstance, getRequestUrl } from '../utils';
export const useAssets = ({ skipWhen }) => {
const { formatMessage } = useIntl();
const toggleNotification = useNotification();
const { notifyStatus } = useNotifyAT();
const [{ rawQuery }] = useQueryParams();
const dataRequestURL = getRequestUrl('files');
const getAssets = async () => {
const { data } = await axiosInstance.get(`${dataRequestURL}${rawQuery}`);
return data;
};
const { data, error, isLoading } = useQuery([`assets`, rawQuery], getAssets, {
enabled: !skipWhen,
staleTime: 0,
cacheTime: 0,
});
useEffect(() => {
if (data) {
notifyStatus(
formatMessage({
id: 'list.asset.at.finished',
defaultMessage: 'The assets have finished loading.',
})
);
}
}, [data, notifyStatus, formatMessage]);
useEffect(() => {
if (error) {
toggleNotification({
type: 'warning',
message: { id: 'notification.error' },
});
}
}, [error, toggleNotification]);
return { data, error, isLoading };
};
| packages/core/upload/admin/src/hooks/useAssets.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017516539082862437,
0.000172610001754947,
0.00016832372057251632,
0.00017258324078284204,
0.0000023803370368113974
] |
{
"id": 8,
"code_window": [
"module.exports = {\n",
" /**\n",
" * Default TS -> JS Compilation for Strapi\n",
" * @param {string} tsConfigPath\n",
" */\n",
" run(tsConfigPath) {\n",
" // Parse the tsconfig.json file & resolve the configuration options\n",
" const { fileNames, options, projectReferences } = resolveConfigOptions(tsConfigPath);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" run(tsConfigPath, configOptions) {\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "replace",
"edit_start_line_idx": 12
} | module.exports = ({ env }) => ({
host: env('HOST', '0.0.0.0'),
port: env.int('PORT', 1337),
app: {
keys: env.array('APP_KEYS', ['toBeModified1', 'toBeModified2']),
},
});
| examples/kitchensink/config/server.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.0001733060198603198,
0.0001733060198603198,
0.0001733060198603198,
0.0001733060198603198,
0
] |
{
"id": 9,
"code_window": [
" // Parse the tsconfig.json file & resolve the configuration options\n",
" const { fileNames, options, projectReferences } = resolveConfigOptions(tsConfigPath);\n",
"\n",
" const program = ts.createProgram({\n",
" rootNames: fileNames,\n",
" projectReferences,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" rootNames: configOptions.fileNames ? configOptions.fileNames : fileNames,\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "replace",
"edit_start_line_idx": 17
} | 'use strict';
const ts = require('typescript');
const reportDiagnostics = require('../utils/report-diagnostics');
const resolveConfigOptions = require('../utils/resolve-config-options');
module.exports = {
/**
* Default TS -> JS Compilation for Strapi
* @param {string} tsConfigPath
*/
run(tsConfigPath) {
// Parse the tsconfig.json file & resolve the configuration options
const { fileNames, options, projectReferences } = resolveConfigOptions(tsConfigPath);
const program = ts.createProgram({
rootNames: fileNames,
projectReferences,
options,
});
const emitResults = program.emit();
const diagnostics = ts.sortAndDeduplicateDiagnostics(
ts.getPreEmitDiagnostics(program).concat(emitResults.diagnostics)
);
if (diagnostics.length > 0) {
reportDiagnostics(diagnostics);
}
// If the compilation failed, exit early
if (emitResults.emitSkipped) {
process.exit(1);
}
},
};
| packages/utils/typescript/lib/compilers/basic.js | 1 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.9978634715080261,
0.49917495250701904,
0.00017631539958529174,
0.4993300139904022,
0.4982718527317047
] |
{
"id": 9,
"code_window": [
" // Parse the tsconfig.json file & resolve the configuration options\n",
" const { fileNames, options, projectReferences } = resolveConfigOptions(tsConfigPath);\n",
"\n",
" const program = ts.createProgram({\n",
" rootNames: fileNames,\n",
" projectReferences,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" rootNames: configOptions.fileNames ? configOptions.fileNames : fileNames,\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "replace",
"edit_start_line_idx": 17
} | import React, { useState } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { Stack } from '@strapi/design-system/Stack';
import { DatePicker } from '@strapi/design-system/DatePicker';
import { TimePicker } from '@strapi/design-system/TimePicker';
import { Field, FieldHint, FieldLabel, FieldError } from '@strapi/design-system/Field';
import { Flex } from '@strapi/design-system/Flex';
import { Box } from '@strapi/design-system/Box';
import { parseDate } from './parseDate';
const CustomField = styled(Field)`
> div {
> div {
p[data-strapi-field-error='true'] {
display: none;
}
}
}
`;
const LabelAction = styled(Box)`
svg path {
fill: ${({ theme }) => theme.colors.neutral500};
}
`;
const DateTimePicker = ({
ariaLabel,
clearLabel,
disabled,
error,
hint,
label,
labelAction,
onChange,
onClear,
name,
required,
size,
step,
value,
...props
}) => {
const initialDate = parseDate(value);
const [dateValue, setDateValue] = useState(initialDate);
const [timeValue, setTimeValue] = useState(
initialDate
? `${initialDate.getHours()}:${initialDate.getMinutes()}:${initialDate.getSeconds()}`
: null
);
const handleDateChange = e => {
setDateValue(e);
if (timeValue) {
const dateToSet = new Date(e);
dateToSet.setHours(timeValue.split(':')[0]);
dateToSet.setMinutes(timeValue.split(':')[1]);
if (onChange) {
onChange(dateToSet);
}
} else {
const dateToSet = new Date(e);
setTimeValue(`${dateToSet.getHours()}:${dateToSet.getMinutes()}:${dateToSet.getSeconds()}`);
if (onChange) {
onChange(dateToSet);
}
}
};
const handleTimeChange = e => {
setTimeValue(e);
const dateToSet = new Date(dateValue);
dateToSet.setHours(e.split(':')[0]);
dateToSet.setMinutes(e.split(':')[1]);
if (!dateValue) {
setDateValue(new Date());
}
if (onChange) {
onChange(dateToSet);
}
};
const handleDateClear = () => {
setDateValue(undefined);
setTimeValue(undefined);
onClear();
};
const handleTimeClear = () => {
setTimeValue(undefined);
let dateToSet;
if (dateValue) {
dateToSet = new Date(dateValue);
dateToSet.setHours('00');
dateToSet.setMinutes('00');
}
if (onChange) {
onChange(dateToSet);
}
};
return (
<CustomField
name={name}
role="group"
aria-labelledby="datetime-label"
hint={hint}
error={error}
>
<Stack spacing={1}>
{label && (
<Flex>
<FieldLabel required={required} id="datetime-label">
{label}
</FieldLabel>
{labelAction && <LabelAction paddingLeft={1}>{labelAction}</LabelAction>}
</Flex>
)}
<Stack horizontal spacing={2}>
<DatePicker
data-testid="datetimepicker-date"
name={name}
ariaLabel={label || ariaLabel}
error={error}
selectedDate={dateValue}
selectedDateLabel={formattedDate => `Date picker, current is ${formattedDate}`}
onChange={handleDateChange}
size={size}
onClear={onClear && handleDateClear}
clearLabel={clearLabel}
disabled={disabled}
{...props}
/>
<TimePicker
data-testid="datetimepicker-time"
size={size}
aria-label={label || ariaLabel}
error={error}
value={timeValue}
onChange={handleTimeChange}
onClear={onClear && handleTimeClear}
clearLabel={clearLabel}
disabled={disabled}
step={step}
/>
</Stack>
<FieldHint />
<FieldError id="datetimepicker" />
</Stack>
</CustomField>
);
};
DateTimePicker.displayName = 'DateTimePicker';
DateTimePicker.defaultProps = {
ariaLabel: undefined,
clearLabel: 'clear',
disabled: false,
error: undefined,
hint: undefined,
label: undefined,
labelAction: undefined,
onClear: undefined,
required: false,
size: 'M',
step: 1,
value: undefined,
};
DateTimePicker.propTypes = {
ariaLabel: PropTypes.string,
clearLabel: PropTypes.string,
disabled: PropTypes.bool,
error: PropTypes.string,
hint: PropTypes.string,
label: PropTypes.string,
labelAction: PropTypes.element,
name: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
onClear: PropTypes.func,
required: PropTypes.bool,
size: PropTypes.oneOf(['S', 'M']),
step: PropTypes.number,
value: PropTypes.instanceOf(Date),
};
export default DateTimePicker;
| packages/core/helper-plugin/lib/src/components/DateTimePicker/index.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017974412185139954,
0.00017651804955676198,
0.00017180040595121682,
0.0001767693756846711,
0.000002042851292571868
] |
{
"id": 9,
"code_window": [
" // Parse the tsconfig.json file & resolve the configuration options\n",
" const { fileNames, options, projectReferences } = resolveConfigOptions(tsConfigPath);\n",
"\n",
" const program = ts.createProgram({\n",
" rootNames: fileNames,\n",
" projectReferences,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" rootNames: configOptions.fileNames ? configOptions.fileNames : fileNames,\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "replace",
"edit_start_line_idx": 17
} | 'use strict';
const path = require('path');
const execa = require('execa');
const yargs = require('yargs');
process.env.NODE_ENV = 'test';
const appName = 'testApp';
process.env.ENV_PATH = path.resolve(__dirname, '..', appName, '.env');
const { cleanTestApp, generateTestApp } = require('./helpers/test-app-generator');
const databases = {
postgres: {
client: 'postgres',
connection: {
host: '127.0.0.1',
port: 5432,
database: 'strapi_test',
username: 'strapi',
password: 'strapi',
},
},
mysql: {
client: 'mysql',
connection: {
host: '127.0.0.1',
port: 3306,
database: 'strapi_test',
username: 'strapi',
password: 'strapi',
},
},
sqlite: {
client: 'sqlite',
connection: {
filename: './tmp/data.db',
},
useNullAsDefault: true,
},
};
const runAllTests = async args => {
return execa('yarn', ['test:e2e', ...args], {
stdio: 'inherit',
cwd: path.resolve(__dirname, '..'),
env: {
FORCE_COLOR: 1,
ENV_PATH: process.env.ENV_PATH,
JWT_SECRET: 'aSecret',
},
});
};
const main = async (database, args) => {
try {
await cleanTestApp(appName);
await generateTestApp({ appName, database });
await runAllTests(args).catch(() => {
process.stdout.write('Tests failed\n', () => {
process.exit(1);
});
});
process.exit(0);
} catch (error) {
console.error(error);
process.stdout.write('Tests failed\n', () => {
process.exit(1);
});
}
};
yargs
.command(
'$0',
'run end to end tests',
yargs => {
yargs.option('database', {
alias: 'db',
describe: 'choose a database',
choices: Object.keys(databases),
default: 'sqlite',
});
},
argv => {
const { database, _: args } = argv;
main(databases[database], args);
}
)
.help().argv;
| test/e2e.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017858450883068144,
0.00017419953655917197,
0.0001676893443800509,
0.00017453123291488737,
0.00000276705350188422
] |
{
"id": 9,
"code_window": [
" // Parse the tsconfig.json file & resolve the configuration options\n",
" const { fileNames, options, projectReferences } = resolveConfigOptions(tsConfigPath);\n",
"\n",
" const program = ts.createProgram({\n",
" rootNames: fileNames,\n",
" projectReferences,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" rootNames: configOptions.fileNames ? configOptions.fileNames : fileNames,\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "replace",
"edit_start_line_idx": 17
} | 'use strict';
const { createTestBuilder } = require('../../../../../../test/helpers/builder');
const { createStrapiInstance } = require('../../../../../../test/helpers/strapi');
const { createAuthRequest } = require('../../../../../../test/helpers/request');
let strapi;
let rq;
const component = {
displayName: 'somecomponent',
attributes: {
name: {
type: 'string',
},
},
};
const ct = {
displayName: 'withcomponent',
singularName: 'withcomponent',
pluralName: 'withcomponents',
attributes: {
field: {
type: 'component',
component: 'default.somecomponent',
repeatable: true,
required: false,
min: 2,
max: 5,
},
},
};
describe('Non repeatable and Not required component', () => {
const builder = createTestBuilder();
beforeAll(async () => {
await builder
.addComponent(component)
.addContentType(ct)
.build();
strapi = await createStrapiInstance();
rq = await createAuthRequest({ strapi });
rq.setURLPrefix('/content-manager/collection-types/api::withcomponent.withcomponent');
});
afterAll(async () => {
await strapi.destroy();
await builder.cleanup();
});
describe('POST new entry', () => {
test('Creating entry with JSON works', async () => {
const res = await rq.post('/', {
body: {
field: [
{
name: 'someString',
},
{
name: 'someString',
},
],
},
qs: {
populate: ['field'],
},
});
expect(res.statusCode).toBe(200);
expect(Array.isArray(res.body.field)).toBe(true);
expect(res.body.field).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.anything(),
name: 'someString',
}),
])
);
});
test.each(['someString', 128219, false, {}, null])(
'Throws if the field is not an array %p',
async value => {
const res = await rq.post('/', {
body: {
field: value,
},
});
expect(res.statusCode).toBe(400);
}
);
test('Throws when sending a non empty array with less then the min', async () => {
const res = await rq.post('/', {
body: {
field: [
{
name: 'test',
},
],
},
});
expect(res.statusCode).toBe(400);
});
test('Success when sending an empty array', async () => {
const res = await rq.post('/', {
body: {
field: [],
},
});
expect(res.statusCode).toBe(200);
});
test('Throws when sending too many items', async () => {
const res = await rq.post('/', {
body: {
field: [
{
name: 'one',
},
{
name: 'one',
},
{
name: 'one',
},
{
name: 'one',
},
{
name: 'one',
},
{
name: 'one',
},
],
},
});
expect(res.statusCode).toBe(400);
});
test('Can send input without the component field', async () => {
const res = await rq.post('/', {
body: {},
qs: {
populate: ['field'],
},
});
expect(res.statusCode).toBe(200);
expect(res.body.field).toEqual([]);
});
});
describe('GET entries', () => {
test('Data is ordered in the order sent', async () => {
const res = await rq.post('/', {
body: {
field: [
{
name: 'firstString',
},
{
name: 'someString',
},
],
},
qs: {
populate: ['field'],
},
});
const getRes = await rq.get(`/${res.body.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(Array.isArray(getRes.body.field)).toBe(true);
expect(getRes.body.field[0]).toMatchObject({
name: 'firstString',
});
expect(getRes.body.field[1]).toMatchObject({
name: 'someString',
});
});
test('Should return entries with their nested components', async () => {
const res = await rq.get('/', {
qs: {
populate: ['field'],
},
});
expect(res.statusCode).toBe(200);
expect(res.body.pagination).toBeDefined();
expect(Array.isArray(res.body.results)).toBe(true);
res.body.results.forEach(entry => {
expect(Array.isArray(entry.field)).toBe(true);
if (entry.field.length === 0) return;
expect(entry.field).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: expect.any(String),
}),
])
);
});
});
});
describe('PUT entry', () => {
test.each(['someString', 128219, false, {}, null])(
'Throws when sending invalid updated field %p',
async value => {
const res = await rq.post('/', {
body: {
field: [
{
name: 'someString',
},
{
name: 'someString',
},
],
},
qs: {
populate: ['field'],
},
});
const updateRes = await rq.put(`/${res.body.id}`, {
body: {
field: value,
},
qs: {
populate: ['field'],
},
});
expect(updateRes.statusCode).toBe(400);
// shouldn't have been updated
const getRes = await rq.get(`/${res.body.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(getRes.body).toMatchObject({
id: res.body.id,
field: res.body.field,
});
}
);
test('Updates order at each request', async () => {
const res = await rq.post('/', {
body: {
field: [
{
name: 'someString',
},
{
name: 'otherString',
},
],
},
qs: {
populate: ['field'],
},
});
expect(res.body.field[0]).toMatchObject({
name: 'someString',
});
expect(res.body.field[1]).toMatchObject({
name: 'otherString',
});
const updateRes = await rq.put(`/${res.body.id}`, {
body: {
field: [
{
name: 'otherString',
},
{
name: 'someString',
},
],
},
qs: {
populate: ['field'],
},
});
expect(updateRes.statusCode).toBe(200);
expect(Array.isArray(updateRes.body.field)).toBe(true);
expect(updateRes.body.field[0]).toMatchObject({
name: 'otherString',
});
expect(updateRes.body.field[1]).toMatchObject({
name: 'someString',
});
const getRes = await rq.get(`/${res.body.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(Array.isArray(getRes.body.field)).toBe(true);
expect(getRes.body.field[0]).toMatchObject({
name: 'otherString',
});
expect(getRes.body.field[1]).toMatchObject({
name: 'someString',
});
});
test('Keeps the previous value if component not sent', async () => {
const res = await rq.post('/', {
body: {
field: [
{
name: 'someString',
},
{
name: 'otherString',
},
],
},
qs: {
populate: ['field'],
},
});
const updateRes = await rq.put(`/${res.body.id}`, {
body: {},
qs: {
populate: ['field'],
},
});
expect(updateRes.statusCode).toBe(200);
expect(updateRes.body).toMatchObject({
id: res.body.id,
field: res.body.field,
});
const getRes = await rq.get(`/${res.body.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(getRes.body).toMatchObject({
id: res.body.id,
field: res.body.field,
});
});
test('Throws when not enough items', async () => {
const res = await rq.post('/', {
body: {
field: [
{
name: 'someString',
},
{
name: 'new String',
},
],
},
qs: {
populate: ['field'],
},
});
const updateRes = await rq.put(`/${res.body.id}`, {
body: {
field: [
{
name: 'lala',
},
],
},
qs: {
populate: ['field'],
},
});
expect(updateRes.statusCode).toBe(400);
const getRes = await rq.get(`/${res.body.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(getRes.body).toMatchObject(res.body);
});
test('Throws when too many items', async () => {
const res = await rq.post('/', {
body: {
field: [
{
name: 'someString',
},
{
name: 'test',
},
],
},
qs: {
populate: ['field'],
},
});
const updateRes = await rq.put(`/${res.body.id}`, {
body: {
field: [
{
name: 'someString',
},
{
name: 'someString',
},
{
name: 'someString',
},
{
name: 'someString',
},
{
name: 'someString',
},
{
name: 'someString',
},
],
},
qs: {
populate: ['field'],
},
});
expect(updateRes.statusCode).toBe(400);
const getRes = await rq.get(`/${res.body.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(getRes.body).toMatchObject(res.body);
});
test('Replaces the previous components if sent without id', async () => {
const res = await rq.post('/', {
body: {
field: [
{
name: 'someString',
},
{ name: 'test' },
],
},
qs: {
populate: ['field'],
},
});
const updateRes = await rq.put(`/${res.body.id}`, {
body: {
field: [
{
name: 'new String',
},
{
name: 'test',
},
],
},
qs: {
populate: ['field'],
},
});
expect(updateRes.statusCode).toBe(200);
const oldIds = res.body.field.map(val => val.id);
updateRes.body.field.forEach(val => {
expect(oldIds.includes(val.id)).toBe(false);
});
expect(updateRes.body).toMatchObject({
id: res.body.id,
field: [
{
name: 'new String',
},
{
name: 'test',
},
],
});
const getRes = await rq.get(`/${res.body.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(getRes.body).toMatchObject({
id: res.body.id,
field: [
{
name: 'new String',
},
{
name: 'test',
},
],
});
});
test('Throws on invalid id in component', async () => {
const res = await rq.post('/', {
body: {
field: [
{
name: 'someString',
},
{
name: 'test',
},
],
},
qs: {
populate: ['field'],
},
});
const updateRes = await rq.put(`/${res.body.id}`, {
body: {
field: [
{
id: 'invalid_id',
name: 'new String',
},
],
},
qs: {
populate: ['field'],
},
});
expect(updateRes.statusCode).toBe(400);
});
test('Updates component with ids, create new ones and removes old ones', async () => {
const res = await rq.post('/', {
body: {
field: [
{
name: 'one',
},
{
name: 'two',
},
{
name: 'three',
},
],
},
qs: {
populate: ['field'],
},
});
const updateRes = await rq.put(`/${res.body.id}`, {
body: {
field: [
{
id: res.body.field[0].id, // send old id to update the previous component
name: 'newOne',
},
{
name: 'newTwo',
},
{
id: res.body.field[2].id,
name: 'three',
},
{
name: 'four',
},
],
},
qs: {
populate: ['field'],
},
});
const expectedResult = {
id: res.body.id,
field: [
{
id: res.body.field[0].id,
name: 'newOne',
},
{
name: 'newTwo',
},
{
id: res.body.field[2].id,
name: 'three',
},
{
name: 'four',
},
],
};
expect(updateRes.statusCode).toBe(200);
expect(updateRes.body).toMatchObject(expectedResult);
const getRes = await rq.get(`/${res.body.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(getRes.body).toMatchObject(expectedResult);
});
});
describe('DELETE entry', () => {
test('Returns entry with components', async () => {
const res = await rq.post('/', {
body: {
field: [
{
name: 'someString',
},
{
name: 'someOtherString',
},
{
name: 'otherSomeString',
},
],
},
qs: {
populate: ['field'],
},
});
const deleteRes = await rq.delete(`/${res.body.id}`, {
qs: {
populate: ['field'],
},
});
expect(deleteRes.statusCode).toBe(200);
expect(deleteRes.body).toMatchObject(res.body);
const getRes = await rq.get(`/${res.body.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(404);
});
});
});
| packages/core/content-manager/server/tests/components/repeatable-not-required-min-max.test.e2e.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00018016142712440342,
0.00017493826453574002,
0.00017057699733413756,
0.000174519547726959,
0.000002059181497315876
] |
{
"id": 10,
"code_window": [
" projectReferences,\n",
" options,\n",
" });\n",
"\n",
" const emitResults = program.emit();\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" options: merge(options, configOptions.options),\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "replace",
"edit_start_line_idx": 19
} | 'use strict';
const compilers = require('./compilers');
const getConfigPath = require('./utils/get-config-path');
module.exports = async (srcDir, { watch = false } = {}) => {
// TODO: Use the Strapi debug logger instead or don't log at all
console.log(`Starting the compilation for TypeScript files in ${srcDir}`);
const compiler = watch ? compilers.watch : compilers.basic;
const configPath = getConfigPath(srcDir);
compiler.run(configPath);
};
| packages/utils/typescript/lib/compile.js | 1 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017481032409705222,
0.0001725046313367784,
0.00017019892402458936,
0.0001725046313367784,
0.0000023057000362314284
] |
{
"id": 10,
"code_window": [
" projectReferences,\n",
" options,\n",
" });\n",
"\n",
" const emitResults = program.emit();\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" options: merge(options, configOptions.options),\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "replace",
"edit_start_line_idx": 19
} | 'use strict';
module.exports = ({ key, attribute }, { remove }) => {
if (attribute.type === 'password') {
remove(key);
}
};
| packages/core/utils/lib/sanitize/visitors/remove-password.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017331363051198423,
0.00017331363051198423,
0.00017331363051198423,
0.00017331363051198423,
0
] |
{
"id": 10,
"code_window": [
" projectReferences,\n",
" options,\n",
" });\n",
"\n",
" const emitResults = program.emit();\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" options: merge(options, configOptions.options),\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "replace",
"edit_start_line_idx": 19
} | import * as yup from 'yup';
import { translatedErrors } from '@strapi/helper-plugin';
const schema = yup.object().shape({
name: yup.string(translatedErrors.string).required(translatedErrors.required),
type: yup
.string(translatedErrors.string)
.oneOf(['read-only', 'full-access'])
.required(translatedErrors.required),
description: yup.string().nullable(),
});
export default schema;
| packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/EditView/utils/schema.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.00017863117682281882,
0.00017726776422932744,
0.00017590435163583606,
0.00017726776422932744,
0.0000013634125934913754
] |
{
"id": 10,
"code_window": [
" projectReferences,\n",
" options,\n",
" });\n",
"\n",
" const emitResults = program.emit();\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" options: merge(options, configOptions.options),\n"
],
"file_path": "packages/utils/typescript/lib/compilers/basic.js",
"type": "replace",
"edit_start_line_idx": 19
} | import React, { memo } from 'react';
import PropTypes from 'prop-types';
import get from 'lodash/get';
import { useIntl } from 'react-intl';
import { IconButton } from '@strapi/design-system/IconButton';
import { Flex } from '@strapi/design-system/Flex';
import { Stack } from '@strapi/design-system/Stack';
import { Typography } from '@strapi/design-system/Typography';
import { Box } from '@strapi/design-system/Box';
import Lock from '@strapi/icons/Lock';
import Pencil from '@strapi/icons/Pencil';
import Trash from '@strapi/icons/Trash';
import { stopPropagation, onRowClick, pxToRem } from '@strapi/helper-plugin';
import useDataManager from '../../hooks/useDataManager';
import getTrad from '../../utils/getTrad';
import Curve from '../../icons/Curve';
import UpperFist from '../UpperFirst';
import BoxWrapper from './BoxWrapper';
import AttributeIcon from '../AttributeIcon';
function ListRow({
configurable,
editTarget,
firstLoopComponentUid,
isFromDynamicZone,
name,
onClick,
relation,
repeatable,
secondLoopComponentUid,
target,
targetUid,
type,
}) {
const { contentTypes, isInDevelopmentMode, removeAttribute } = useDataManager();
const { formatMessage } = useIntl();
const isMorph = type === 'relation' && relation.includes('morph');
const ico = ['integer', 'biginteger', 'float', 'decimal'].includes(type) ? 'number' : type;
let readableType = type;
if (['integer', 'biginteger', 'float', 'decimal'].includes(type)) {
readableType = 'number';
} else if (['string'].includes(type)) {
readableType = 'text';
}
const contentType = get(contentTypes, [target], {});
const contentTypeFriendlyName = get(contentType, ['schema', 'displayName'], '');
const isPluginContentType = get(contentType, 'plugin');
const src = target ? 'relation' : ico;
const handleClick = () => {
if (isMorph) {
return;
}
if (configurable !== false) {
const attrType = type;
onClick(
// Tells where the attribute is located in the main modifiedData object : contentType, component or components
editTarget,
// main data type uid
secondLoopComponentUid || firstLoopComponentUid || targetUid,
// Name of the attribute
name,
// Type of the attribute
attrType
);
}
};
let loopNumber;
if (secondLoopComponentUid && firstLoopComponentUid) {
loopNumber = 2;
} else if (firstLoopComponentUid) {
loopNumber = 1;
} else {
loopNumber = 0;
}
return (
<BoxWrapper
as="tr"
{...onRowClick({
fn: handleClick,
condition: isInDevelopmentMode && configurable && !isMorph,
})}
>
<td style={{ position: 'relative' }}>
{loopNumber !== 0 && <Curve color={isFromDynamicZone ? 'primary200' : 'neutral150'} />}
<Stack paddingLeft={2} spacing={4} horizontal>
<AttributeIcon key={src} type={src} />
<Typography fontWeight="bold">{name}</Typography>
</Stack>
</td>
<td>
{target ? (
<Typography>
{formatMessage({
id: getTrad(
`modelPage.attribute.${isMorph ? 'relation-polymorphic' : 'relationWith'}`
),
defaultMessage: 'Relation with',
})}
<span style={{ fontStyle: 'italic' }}>
<UpperFist content={contentTypeFriendlyName} />
{isPluginContentType &&
`(${formatMessage({
id: getTrad(`from`),
defaultMessage: 'from',
})}: ${isPluginContentType})`}
</span>
</Typography>
) : (
<Typography>
{formatMessage({
id: getTrad(`attribute.${readableType}`),
defaultMessage: type,
})}
{repeatable &&
formatMessage({
id: getTrad('component.repeatable'),
defaultMessage: '(repeatable)',
})}
</Typography>
)}
</td>
<td>
{isInDevelopmentMode ? (
<Flex justifyContent="flex-end" {...stopPropagation}>
{configurable ? (
<Stack horizontal spacing={1}>
{!isMorph && (
<IconButton
onClick={handleClick}
label={`${formatMessage({
id: 'app.utils.edit',
defaultMessage: 'Edit',
})} ${name}`}
noBorder
icon={<Pencil />}
/>
)}
<IconButton
onClick={e => {
e.stopPropagation();
removeAttribute(
editTarget,
name,
secondLoopComponentUid || firstLoopComponentUid || ''
);
}}
label={`${formatMessage({
id: 'global.delete',
defaultMessage: 'Delete',
})} ${name}`}
noBorder
icon={<Trash />}
/>
</Stack>
) : (
<Lock />
)}
</Flex>
) : (
/*
In production mode the edit icons aren't visible, therefore
we need to reserve the same space, otherwise the height of the
row might collapse, leading to bad positioned curve icons
*/
<Box height={pxToRem(32)} />
)}
</td>
</BoxWrapper>
);
}
ListRow.defaultProps = {
configurable: true,
firstLoopComponentUid: null,
isFromDynamicZone: false,
onClick: () => {},
relation: '',
repeatable: false,
secondLoopComponentUid: null,
target: null,
targetUid: null,
type: null,
};
ListRow.propTypes = {
configurable: PropTypes.bool,
editTarget: PropTypes.string.isRequired,
firstLoopComponentUid: PropTypes.string,
isFromDynamicZone: PropTypes.bool,
name: PropTypes.string.isRequired,
onClick: PropTypes.func,
relation: PropTypes.string,
repeatable: PropTypes.bool,
secondLoopComponentUid: PropTypes.string,
target: PropTypes.string,
targetUid: PropTypes.string,
type: PropTypes.string,
};
export default memo(ListRow);
export { ListRow };
| packages/core/content-type-builder/admin/src/components/ListRow/index.js | 0 | https://github.com/strapi/strapi/commit/c444692191b2a3b8bfd8543378da288a8d42da1c | [
0.0001812056143535301,
0.00017219684377778322,
0.00016307175974361598,
0.00017236570420209318,
0.0000035317141282575903
] |
{
"id": 0,
"code_window": [
"/* not type checking this file because flow doesn't play well with Proxy */\n",
"\n",
"import { warn, makeMap } from '../util/index'\n",
"\n",
"let hasProxy, proxyHandlers, initProxy\n",
"\n",
"if (process.env.NODE_ENV !== 'production') {\n",
" const allowedGlobals = makeMap(\n",
" 'Infinity,undefined,NaN,isFinite,isNaN,' +\n",
" 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"let initProxy\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 4
} | /* not type checking this file because flow doesn't play well with Proxy */
import { warn, makeMap } from '../util/index'
let hasProxy, proxyHandlers, initProxy
if (process.env.NODE_ENV !== 'production') {
const allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
)
const warnNonPresent = (target, key) => {
warn(
`Property or method "${key}" is not defined on the instance but ` +
`referenced during render. Make sure to declare reactive data ` +
`properties in the data option.`,
target
)
}
hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/)
proxyHandlers = {
has (target, key) {
const has = key in target
const isAllowed = allowedGlobals(key) || key.charAt(0) === '_'
if (!has && !isAllowed) {
warnNonPresent(target, key)
}
return has || !isAllowed
},
get (target, key) {
if (typeof key === 'string' && !(key in target)) {
warnNonPresent(target, key)
}
return target[key]
}
}
initProxy = function initProxy (vm) {
if (hasProxy) {
vm._renderProxy = new Proxy(vm, proxyHandlers)
} else {
vm._renderProxy = vm
}
}
}
export { initProxy }
| src/core/instance/proxy.js | 1 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.999138593673706,
0.8179275989532471,
0.0012199374614283442,
0.9981372356414795,
0.36659005284309387
] |
{
"id": 0,
"code_window": [
"/* not type checking this file because flow doesn't play well with Proxy */\n",
"\n",
"import { warn, makeMap } from '../util/index'\n",
"\n",
"let hasProxy, proxyHandlers, initProxy\n",
"\n",
"if (process.env.NODE_ENV !== 'production') {\n",
" const allowedGlobals = makeMap(\n",
" 'Infinity,undefined,NaN,isFinite,isNaN,' +\n",
" 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"let initProxy\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 4
} | const fs = require('fs')
const path = require('path')
const zlib = require('zlib')
const rollup = require('rollup')
const uglify = require('uglify-js')
if (!fs.existsSync('dist')) {
fs.mkdirSync('dist')
}
// Update main file
const version = process.env.VERSION || require('../package.json').version
const main = fs
.readFileSync('src/core/index.js', 'utf-8')
.replace(/Vue\.version = '[^']+'/, "Vue.version = '" + version + "'")
fs.writeFileSync('src/core/index.js', main)
// update weex subversion
const weexVersion = process.env.WEEX_VERSION || require('../packages/weex-vue-framework/package.json').version
const weexMain = fs
.readFileSync('src/entries/weex-framework.js', 'utf-8')
.replace(/Vue\.version = '[^']+'/, "Vue.version = '" + weexVersion + "'")
fs.writeFileSync('src/entries/weex-framework.js', weexMain)
let builds = require('./config').getAllBuilds()
// filter builds via command line arg
if (process.argv[2]) {
const filters = process.argv[2].split(',')
builds = builds.filter(b => {
return filters.some(f => b.dest.indexOf(f) > -1)
})
} else {
// filter out weex builds by default
builds = builds.filter(b => {
return b.dest.indexOf('weex') === -1
})
}
build(builds)
function build (builds) {
let built = 0
const total = builds.length
const next = () => {
buildEntry(builds[built]).then(() => {
built++
if (built < total) {
next()
}
}).catch(logError)
}
next()
}
function buildEntry (config) {
const isProd = /min\.js$/.test(config.dest)
return rollup.rollup(config).then(bundle => {
const code = bundle.generate(config).code
if (isProd) {
var minified = (config.banner ? config.banner + '\n' : '') + uglify.minify(code, {
fromString: true,
output: {
screw_ie8: true,
ascii_only: true
},
compress: {
pure_funcs: ['makeMap']
}
}).code
return write(config.dest, minified, true)
} else {
return write(config.dest, code)
}
})
}
function write (dest, code, zip) {
return new Promise((resolve, reject) => {
function report (extra) {
console.log(blue(path.relative(process.cwd(), dest)) + ' ' + getSize(code) + (extra || ''))
resolve()
}
fs.writeFile(dest, code, err => {
if (err) return reject(err)
if (zip) {
zlib.gzip(code, (err, zipped) => {
if (err) return reject(err)
report(' (gzipped: ' + getSize(zipped) + ')')
})
} else {
report()
}
})
})
}
function getSize (code) {
return (code.length / 1024).toFixed(2) + 'kb'
}
function logError (e) {
console.log(e)
}
function blue (str) {
return '\x1b[1m\x1b[34m' + str + '\x1b[39m\x1b[22m'
}
| build/build.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.00019084810628555715,
0.00017068942543119192,
0.00016616626817267388,
0.00016879808390513062,
0.000006401465725502931
] |
{
"id": 0,
"code_window": [
"/* not type checking this file because flow doesn't play well with Proxy */\n",
"\n",
"import { warn, makeMap } from '../util/index'\n",
"\n",
"let hasProxy, proxyHandlers, initProxy\n",
"\n",
"if (process.env.NODE_ENV !== 'production') {\n",
" const allowedGlobals = makeMap(\n",
" 'Infinity,undefined,NaN,isFinite,isNaN,' +\n",
" 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"let initProxy\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 4
} | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Vue.js tree-view demo</title>
<style>
body {
font-family: Menlo, Consolas, monospace;
color: #444;
}
.item {
cursor: pointer;
}
.bold {
font-weight: bold;
}
ul {
padding-left: 1em;
line-height: 1.5em;
list-style-type: dot;
}
</style>
<!-- Delete ".min" for console warnings in development -->
<script src="../../dist/vue.min.js"></script>
</head>
<body>
<!-- item template -->
<script type="text/x-template" id="item-template">
<li>
<div
:class="{bold: isFolder}"
@click="toggle"
@dblclick="changeType">
{{model.name}}
<span v-if="isFolder">[{{open ? '-' : '+'}}]</span>
</div>
<ul v-show="open" v-if="isFolder">
<item
class="item"
v-for="model in model.children"
:model="model">
</item>
<li class="add" @click="addChild">+</li>
</ul>
</li>
</script>
<p>(You can double click on an item to turn it into a folder.)</p>
<!-- the demo root element -->
<ul id="demo">
<item
class="item"
:model="treeData">
</item>
</ul>
<!-- demo code -->
<script src="tree.js"></script>
</body>
</html>
| examples/tree/index.html | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.0001745771151036024,
0.0001718304120004177,
0.00016583007527515292,
0.0001732650416670367,
0.000002978878228532267
] |
{
"id": 0,
"code_window": [
"/* not type checking this file because flow doesn't play well with Proxy */\n",
"\n",
"import { warn, makeMap } from '../util/index'\n",
"\n",
"let hasProxy, proxyHandlers, initProxy\n",
"\n",
"if (process.env.NODE_ENV !== 'production') {\n",
" const allowedGlobals = makeMap(\n",
" 'Infinity,undefined,NaN,isFinite,isNaN,' +\n",
" 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"let initProxy\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 4
} | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Vue.js custom directive integration example (select2)</title>
<!-- Delete ".min" for console warnings in development -->
<script src="../../dist/vue.min.js"></script>
<script src="https://unpkg.com/jquery"></script>
<script src="https://unpkg.com/[email protected]"></script>
<link href="https://unpkg.com/[email protected]/dist/css/select2.min.css" rel="stylesheet">
<style>
html, body {
font: 13px/18px sans-serif;
}
select {
min-width: 300px;
}
</style>
</head>
<body>
<div id="el">
</div>
<!-- using string template here to work around HTML <option> placement restriction -->
<script type="text/x-template" id="demo-template">
<div>
<p>Selected: {{ selected }}</p>
<select2 :options="options" v-model="selected">
<option disabled value="0">Select one</option>
</select2>
</div>
</script>
<script type="text/x-template" id="select2-template">
<select>
<slot></slot>
</select>
</script>
<script>
Vue.component('select2', {
props: ['options', 'value'],
template: '#select2-template',
mounted: function () {
var vm = this
$(this.$el)
.val(this.value)
// init select2
.select2({ data: this.options })
// emit event on change.
.on('change', function () {
vm.$emit('input', this.value)
})
},
watch: {
value: function (value) {
// update value
$(this.$el).val(value).trigger('change')
},
options: function (options) {
// update options
$(this.$el).select2({ data: options })
}
},
destroyed: function () {
$(this.$el).off().select2('destroy')
}
})
var vm = new Vue({
el: '#el',
template: '#demo-template',
data: {
selected: 0,
options: [
{ id: 1, text: 'Hello' },
{ id: 2, text: 'World' }
]
}
})
</script>
</body>
</html>
| examples/select2/index.html | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.00017446062702219933,
0.00017177432891912758,
0.00016787218919489533,
0.000171999228768982,
0.000002277024123031879
] |
{
"id": 1,
"code_window": [
" `properties in the data option.`,\n",
" target\n",
" )\n",
" }\n",
"\n",
" hasProxy =\n",
" typeof Proxy !== 'undefined' &&\n",
" Proxy.toString().match(/native code/)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const hasProxy =\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 23
} | /* not type checking this file because flow doesn't play well with Proxy */
import { warn, makeMap } from '../util/index'
let hasProxy, proxyHandlers, initProxy
if (process.env.NODE_ENV !== 'production') {
const allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
)
const warnNonPresent = (target, key) => {
warn(
`Property or method "${key}" is not defined on the instance but ` +
`referenced during render. Make sure to declare reactive data ` +
`properties in the data option.`,
target
)
}
hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/)
proxyHandlers = {
has (target, key) {
const has = key in target
const isAllowed = allowedGlobals(key) || key.charAt(0) === '_'
if (!has && !isAllowed) {
warnNonPresent(target, key)
}
return has || !isAllowed
},
get (target, key) {
if (typeof key === 'string' && !(key in target)) {
warnNonPresent(target, key)
}
return target[key]
}
}
initProxy = function initProxy (vm) {
if (hasProxy) {
vm._renderProxy = new Proxy(vm, proxyHandlers)
} else {
vm._renderProxy = vm
}
}
}
export { initProxy }
| src/core/instance/proxy.js | 1 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.9987776875495911,
0.3345385789871216,
0.00028098735492676497,
0.0045982850715518,
0.4693889021873474
] |
{
"id": 1,
"code_window": [
" `properties in the data option.`,\n",
" target\n",
" )\n",
" }\n",
"\n",
" hasProxy =\n",
" typeof Proxy !== 'undefined' &&\n",
" Proxy.toString().match(/native code/)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const hasProxy =\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 23
} | import Vue from 'vue'
describe('Directive v-on', () => {
let vm, spy, spy2, el
beforeEach(() => {
spy = jasmine.createSpy()
spy2 = jasmine.createSpy()
el = document.createElement('div')
document.body.appendChild(el)
})
afterEach(() => {
document.body.removeChild(vm.$el)
})
it('should bind event to a method', () => {
vm = new Vue({
el,
template: '<div v-on:click="foo"></div>',
methods: { foo: spy }
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
const args = spy.calls.allArgs()
const event = args[0] && args[0][0] || {}
expect(event.type).toBe('click')
})
it('should bind event to a inline statement', () => {
vm = new Vue({
el,
template: '<div v-on:click="foo(1,2,3,$event)"></div>',
methods: { foo: spy }
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
const args = spy.calls.allArgs()
const firstArgs = args[0]
expect(firstArgs.length).toBe(4)
expect(firstArgs[0]).toBe(1)
expect(firstArgs[1]).toBe(2)
expect(firstArgs[2]).toBe(3)
expect(firstArgs[3].type).toBe('click')
})
it('should support inline function expression', () => {
const spy = jasmine.createSpy()
vm = new Vue({
el,
template: `<div class="test" @click="function (e) { log(e.target.className) }"></div>`,
methods: {
log: spy
}
}).$mount()
triggerEvent(vm.$el, 'click')
expect(spy).toHaveBeenCalledWith('test')
})
it('should support shorthand', () => {
vm = new Vue({
el,
template: '<a href="#test" @click.prevent="foo"></a>',
methods: { foo: spy }
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
})
it('should support stop propagation', () => {
vm = new Vue({
el,
template: `
<div @click.stop="foo"></div>
`,
methods: { foo: spy }
})
const hash = window.location.hash
triggerEvent(vm.$el, 'click')
expect(window.location.hash).toBe(hash)
})
it('should support prevent default', () => {
vm = new Vue({
el,
template: `
<div @click="bar">
<div @click.stop="foo"></div>
</div>
`,
methods: { foo: spy, bar: spy2 }
})
triggerEvent(vm.$el.firstChild, 'click')
expect(spy).toHaveBeenCalled()
expect(spy2).not.toHaveBeenCalled()
})
it('should support capture', () => {
const callOrder = []
vm = new Vue({
el,
template: `
<div @click.capture="foo">
<div @click="bar"></div>
</div>
`,
methods: {
foo () { callOrder.push(1) },
bar () { callOrder.push(2) }
}
})
triggerEvent(vm.$el.firstChild, 'click')
expect(callOrder.toString()).toBe('1,2')
})
it('should support keyCode', () => {
vm = new Vue({
el,
template: `<input @keyup.enter="foo">`,
methods: { foo: spy }
})
triggerEvent(vm.$el, 'keyup', e => {
e.keyCode = 13
})
expect(spy).toHaveBeenCalled()
})
it('should support number keyCode', () => {
vm = new Vue({
el,
template: `<input @keyup.13="foo">`,
methods: { foo: spy }
})
triggerEvent(vm.$el, 'keyup', e => {
e.keyCode = 13
})
expect(spy).toHaveBeenCalled()
})
it('should support custom keyCode', () => {
Vue.config.keyCodes.test = 1
vm = new Vue({
el,
template: `<input @keyup.test="foo">`,
methods: { foo: spy }
})
triggerEvent(vm.$el, 'keyup', e => {
e.keyCode = 1
})
expect(spy).toHaveBeenCalled()
})
it('should bind to a child component', () => {
Vue.component('bar', {
template: '<span>Hello</span>'
})
vm = new Vue({
el,
template: '<bar @custom="foo"></bar>',
methods: { foo: spy }
})
vm.$children[0].$emit('custom', 'foo', 'bar')
expect(spy).toHaveBeenCalledWith('foo', 'bar')
})
it('should be able to bind native events for a child component', () => {
Vue.component('bar', {
template: '<span>Hello</span>'
})
vm = new Vue({
el,
template: '<bar @click.native="foo"></bar>',
methods: { foo: spy }
})
vm.$children[0].$emit('click')
expect(spy).not.toHaveBeenCalled()
triggerEvent(vm.$children[0].$el, 'click')
expect(spy).toHaveBeenCalled()
})
it('remove listener', done => {
const spy2 = jasmine.createSpy('remove listener')
vm = new Vue({
el,
methods: { foo: spy, bar: spy2 },
data: {
ok: true
},
render (h) {
return this.ok
? h('input', { on: { click: this.foo }})
: h('input', { on: { input: this.bar }})
}
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
expect(spy2.calls.count()).toBe(0)
vm.ok = false
waitForUpdate(() => {
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1) // should no longer trigger
triggerEvent(vm.$el, 'input')
expect(spy2.calls.count()).toBe(1)
}).then(done)
})
it('remove listener on child component', done => {
const spy2 = jasmine.createSpy('remove listener')
vm = new Vue({
el,
methods: { foo: spy, bar: spy2 },
data: {
ok: true
},
components: {
test: {
template: '<div></div>'
}
},
render (h) {
return this.ok
? h('test', { on: { foo: this.foo }})
: h('test', { on: { bar: this.bar }})
}
})
vm.$children[0].$emit('foo')
expect(spy.calls.count()).toBe(1)
expect(spy2.calls.count()).toBe(0)
vm.ok = false
waitForUpdate(() => {
vm.$children[0].$emit('foo')
expect(spy.calls.count()).toBe(1) // should no longer trigger
vm.$children[0].$emit('bar')
expect(spy2.calls.count()).toBe(1)
}).then(done)
})
it('warn missing handlers', () => {
vm = new Vue({
el,
data: { none: null },
template: `<div @click="none"></div>`
})
expect(`Invalid handler for event "click": got null`).toHaveBeenWarned()
expect(() => {
triggerEvent(vm.$el, 'click')
}).not.toThrow()
})
})
| test/unit/features/directives/on.spec.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.0001793544797692448,
0.0001730410585878417,
0.00016114581376314163,
0.00017360778292641044,
0.00000358128932020918
] |
{
"id": 1,
"code_window": [
" `properties in the data option.`,\n",
" target\n",
" )\n",
" }\n",
"\n",
" hasProxy =\n",
" typeof Proxy !== 'undefined' &&\n",
" Proxy.toString().match(/native code/)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const hasProxy =\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 23
} | var base = require('./karma.base.config.js')
module.exports = function (config) {
var options = Object.assign(base, {
browsers: ['PhantomJS'],
reporters: ['mocha', 'coverage'],
coverageReporter: {
reporters: [
{ type: 'lcov', dir: '../coverage', subdir: '.' },
{ type: 'text-summary', dir: '../coverage', subdir: '.' }
]
},
singleRun: true
})
// add babel-plugin-coverage for code intrumentation
options.webpack.babel = {
plugins: [['coverage', {
ignore: [
'test/',
'src/compiler/parser/html-parser.js',
'src/core/instance/proxy.js',
'src/sfc/deindent.js'
]
}]]
}
config.set(options)
}
| build/karma.cover.config.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.0001723180030239746,
0.00016886647790670395,
0.00016702679567970335,
0.00016725466412026435,
0.0000024423623017355567
] |
{
"id": 1,
"code_window": [
" `properties in the data option.`,\n",
" target\n",
" )\n",
" }\n",
"\n",
" hasProxy =\n",
" typeof Proxy !== 'undefined' &&\n",
" Proxy.toString().match(/native code/)\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const hasProxy =\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 23
} | var app = new Vue({
el: '#app',
data: {
databases: []
}
})
function loadSamples() {
app.databases = Object.freeze(ENV.generateData().toArray());
Monitoring.renderRate.ping();
setTimeout(loadSamples, ENV.timeout);
}
loadSamples()
| benchmarks/dbmon/app.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.0001747426576912403,
0.00017380647477693856,
0.00017287030641455203,
0.00017380647477693856,
9.361756383441389e-7
] |
{
"id": 2,
"code_window": [
" typeof Proxy !== 'undefined' &&\n",
" Proxy.toString().match(/native code/)\n",
"\n",
" proxyHandlers = {\n",
" has (target, key) {\n",
" const has = key in target\n",
" const isAllowed = allowedGlobals(key) || key.charAt(0) === '_'\n",
" if (!has && !isAllowed) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const hasHandler = {\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 27
} | /* not type checking this file because flow doesn't play well with Proxy */
import { warn, makeMap } from '../util/index'
let hasProxy, proxyHandlers, initProxy
if (process.env.NODE_ENV !== 'production') {
const allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
)
const warnNonPresent = (target, key) => {
warn(
`Property or method "${key}" is not defined on the instance but ` +
`referenced during render. Make sure to declare reactive data ` +
`properties in the data option.`,
target
)
}
hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/)
proxyHandlers = {
has (target, key) {
const has = key in target
const isAllowed = allowedGlobals(key) || key.charAt(0) === '_'
if (!has && !isAllowed) {
warnNonPresent(target, key)
}
return has || !isAllowed
},
get (target, key) {
if (typeof key === 'string' && !(key in target)) {
warnNonPresent(target, key)
}
return target[key]
}
}
initProxy = function initProxy (vm) {
if (hasProxy) {
vm._renderProxy = new Proxy(vm, proxyHandlers)
} else {
vm._renderProxy = vm
}
}
}
export { initProxy }
| src/core/instance/proxy.js | 1 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.9990807771682739,
0.49975720047950745,
0.0001746338966768235,
0.49990612268447876,
0.4988192617893219
] |
{
"id": 2,
"code_window": [
" typeof Proxy !== 'undefined' &&\n",
" Proxy.toString().match(/native code/)\n",
"\n",
" proxyHandlers = {\n",
" has (target, key) {\n",
" const has = key in target\n",
" const isAllowed = allowedGlobals(key) || key.charAt(0) === '_'\n",
" if (!has && !isAllowed) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const hasHandler = {\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 27
} | flow
dist
packages
| .eslintignore | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.00017586945614311844,
0.00017586945614311844,
0.00017586945614311844,
0.00017586945614311844,
0
] |
{
"id": 2,
"code_window": [
" typeof Proxy !== 'undefined' &&\n",
" Proxy.toString().match(/native code/)\n",
"\n",
" proxyHandlers = {\n",
" has (target, key) {\n",
" const has = key in target\n",
" const isAllowed = allowedGlobals(key) || key.charAt(0) === '_'\n",
" if (!has && !isAllowed) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const hasHandler = {\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 27
} | import { patch } from 'web/runtime/patch'
import { createPatchFunction } from 'core/vdom/patch'
import baseModules from 'core/vdom/modules/index'
import * as nodeOps from 'web/runtime/node-ops'
import platformModules from 'web/runtime/modules/index'
import VNode from 'core/vdom/vnode'
const modules = baseModules.concat(platformModules)
describe('vdom patch: hooks', () => {
let vnode0
beforeEach(() => {
vnode0 = new VNode('p', { attrs: { id: '1' }}, [createTextVNode('hello world')])
patch(null, vnode0)
})
it('should call `insert` listener after both parents, siblings and children have been inserted', () => {
const result = []
function insert (vnode) {
expect(vnode.elm.children.length).toBe(2)
expect(vnode.elm.parentNode.children.length).toBe(3)
result.push(vnode)
}
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first sibling'),
new VNode('div', { hook: { insert }}, [
new VNode('span', {}, undefined, 'child 1'),
new VNode('span', {}, undefined, 'child 2')
]),
new VNode('span', {}, undefined, 'can touch me')
])
patch(vnode0, vnode1)
expect(result.length).toBe(1)
})
it('should call `prepatch` listener', () => {
const result = []
function prepatch (oldVnode, newVnode) {
expect(oldVnode).toEqual(vnode1.children[1])
expect(newVnode).toEqual(vnode2.children[1])
result.push(newVnode)
}
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first sibling'),
new VNode('div', { hook: { prepatch }}, [
new VNode('span', {}, undefined, 'child 1'),
new VNode('span', {}, undefined, 'child 2')
])
])
const vnode2 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first sibling'),
new VNode('div', { hook: { prepatch }}, [
new VNode('span', {}, undefined, 'child 1'),
new VNode('span', {}, undefined, 'child 2')
])
])
patch(vnode0, vnode1)
patch(vnode1, vnode2)
expect(result.length).toBe(1)
})
it('should call `postpatch` after `prepatch` listener', () => {
const pre = []
const post = []
function prepatch (oldVnode, newVnode) {
pre.push(pre)
}
function postpatch (oldVnode, newVnode) {
expect(pre.length).toBe(post.length + 1)
post.push(post)
}
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first sibling'),
new VNode('div', { hook: { prepatch, postpatch }}, [
new VNode('span', {}, undefined, 'child 1'),
new VNode('span', {}, undefined, 'child 2')
])
])
const vnode2 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first sibling'),
new VNode('div', { hook: { prepatch, postpatch }}, [
new VNode('span', {}, undefined, 'child 1'),
new VNode('span', {}, undefined, 'child 2')
])
])
patch(vnode0, vnode1)
patch(vnode1, vnode2)
expect(pre.length).toBe(1)
expect(post.length).toBe(1)
})
it('should call `update` listener', () => {
const result1 = []
const result2 = []
function cb (result, oldVnode, newVnode) {
if (result.length > 1) {
expect(result[result.length - 1]).toEqual(oldVnode)
}
result.push(newVnode)
}
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first sibling'),
new VNode('div', { hook: { update: cb.bind(null, result1) }}, [
new VNode('span', {}, undefined, 'child 1'),
new VNode('span', { hook: { update: cb.bind(null, result2) }}, undefined, 'child 2')
])
])
const vnode2 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first sibling'),
new VNode('div', { hook: { update: cb.bind(null, result1) }}, [
new VNode('span', {}, undefined, 'child 1'),
new VNode('span', { hook: { update: cb.bind(null, result2) }}, undefined, 'child 2')
])
])
patch(vnode0, vnode1)
patch(vnode1, vnode2)
expect(result1.length).toBe(1)
expect(result2.length).toBe(1)
})
it('should call `remove` listener', () => {
const result = []
function remove (vnode, rm) {
const parent = vnode.elm.parentNode
expect(vnode.elm.children.length).toBe(2)
expect(vnode.elm.children.length).toBe(2)
result.push(vnode)
rm()
expect(parent.children.length).toBe(1)
}
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first sibling'),
new VNode('div', { hook: { remove }}, [
new VNode('span', {}, undefined, 'child 1'),
new VNode('span', {}, undefined, 'child 2')
])
])
const vnode2 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first sibling')
])
patch(vnode0, vnode1)
patch(vnode1, vnode2)
expect(result.length).toBe(1)
})
it('should call `init` and `prepatch` listeners on root', () => {
let count = 0
function init (vnode) { count++ }
function prepatch (oldVnode, newVnode) { count++ }
const vnode1 = new VNode('div', { hook: { init, prepatch }})
patch(vnode0, vnode1)
expect(count).toBe(1)
const vnode2 = new VNode('span', { hook: { init, prepatch }})
patch(vnode1, vnode2)
expect(count).toBe(2)
})
it('should remove element when all remove listeners are done', () => {
let rm1, rm2, rm3
const patch1 = createPatchFunction({
nodeOps,
modules: modules.concat([
{ remove (_, rm) { rm1 = rm } },
{ remove (_, rm) { rm2 = rm } }
])
})
const vnode1 = new VNode('div', {}, [
new VNode('a', { hook: { remove (_, rm) { rm3 = rm } }})
])
const vnode2 = new VNode('div', {}, [])
let elm = patch1(vnode0, vnode1)
expect(elm.children.length).toBe(1)
elm = patch1(vnode1, vnode2)
expect(elm.children.length).toBe(1)
rm1()
expect(elm.children.length).toBe(1)
rm3()
expect(elm.children.length).toBe(1)
rm2()
expect(elm.children.length).toBe(0)
})
it('should invoke the remove hook on replaced root', () => {
const result = []
const parent = nodeOps.createElement('div')
vnode0 = nodeOps.createElement('div')
parent.appendChild(vnode0)
function remove (vnode, rm) {
result.push(vnode)
rm()
}
const vnode1 = new VNode('div', { hook: { remove }}, [
new VNode('b', {}, undefined, 'child 1'),
new VNode('i', {}, undefined, 'child 2')
])
const vnode2 = new VNode('span', {}, [
new VNode('b', {}, undefined, 'child 1'),
new VNode('i', {}, undefined, 'child 2')
])
patch(vnode0, vnode1)
patch(vnode1, vnode2)
expect(result.length).toBe(1)
})
it('should invoke global `destroy` hook for all removed children', () => {
const result = []
function destroy (vnode) { result.push(vnode) }
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first sibling'),
new VNode('div', {}, [
new VNode('span', { hook: { destroy }}, undefined, 'child 1'),
new VNode('span', {}, undefined, 'child 2')
])
])
const vnode2 = new VNode('div')
patch(vnode0, vnode1)
patch(vnode1, vnode2)
expect(result.length).toBe(1)
})
it('should handle text vnodes with `undefined` `data` property', () => {
const vnode1 = new VNode('div', {}, [createTextVNode(' ')])
const vnode2 = new VNode('div', {}, [])
patch(vnode0, vnode1)
patch(vnode1, vnode2)
})
it('should invoke `destroy` module hook for all removed children', () => {
let created = 0
let destroyed = 0
const patch1 = createPatchFunction({
nodeOps,
modules: modules.concat([
{ create () { created++ } },
{ destroy () { destroyed++ } }
])
})
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first sibling'),
new VNode('div', {}, [
new VNode('span', {}, undefined, 'child 1'),
new VNode('span', {}, undefined, 'child 2')
])
])
const vnode2 = new VNode('div', {})
patch1(vnode0, vnode1)
expect(destroyed).toBe(1) // should invoke for replaced root nodes too
patch1(vnode1, vnode2)
expect(created).toBe(5)
expect(destroyed).toBe(5)
})
it('should not invoke `create` and `remove` module hook for text nodes', () => {
let created = 0
let removed = 0
const patch1 = createPatchFunction({
nodeOps,
modules: modules.concat([
{ create () { created++ } },
{ remove () { removed++ } }
])
})
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first child'),
createTextVNode(''),
new VNode('span', {}, undefined, 'third child')
])
const vnode2 = new VNode('div', {})
patch1(vnode0, vnode1)
patch1(vnode1, vnode2)
expect(created).toBe(3)
expect(removed).toBe(2)
})
it('should not invoke `destroy` module hook for text nodes', () => {
let created = 0
let destroyed = 0
const patch1 = createPatchFunction({
nodeOps,
modules: modules.concat([
{ create () { created++ } },
{ destroy () { destroyed++ } }
])
})
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first sibling'),
new VNode('div', {}, [
new VNode('span', {}, undefined, 'child 1'),
new VNode('span', {}, [
createTextVNode('text1'),
createTextVNode('text2')
])
])
])
const vnode2 = new VNode('div', {})
patch1(vnode0, vnode1)
expect(destroyed).toBe(1) // should invoke for replaced root nodes too
patch1(vnode1, vnode2)
expect(created).toBe(5)
expect(destroyed).toBe(5)
})
it('should call `create` listener before inserted into parent but after children', () => {
const result = []
function create (empty, vnode) {
expect(vnode.elm.children.length).toBe(2)
expect(vnode.elm.parentNode).toBe(null)
result.push(vnode)
}
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'first sibling'),
new VNode('div', { hook: { create }}, [
new VNode('span', {}, undefined, 'child 1'),
new VNode('span', {}, undefined, 'child 2')
]),
new VNode('span', {}, undefined, 'can\'t touch me')
])
patch(vnode0, vnode1)
expect(result.length).toBe(1)
})
})
| test/unit/modules/vdom/patch/hooks.spec.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.00018111319513991475,
0.00017691623361315578,
0.00017226478666998446,
0.0001770690141711384,
0.00000198914494831115
] |
{
"id": 2,
"code_window": [
" typeof Proxy !== 'undefined' &&\n",
" Proxy.toString().match(/native code/)\n",
"\n",
" proxyHandlers = {\n",
" has (target, key) {\n",
" const has = key in target\n",
" const isAllowed = allowedGlobals(key) || key.charAt(0) === '_'\n",
" if (!has && !isAllowed) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const hasHandler = {\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 27
} | require('es6-promise/auto')
// import all helpers
const helpersContext = require.context('../helpers', true)
helpersContext.keys().forEach(helpersContext)
// require all test files
const testsContext = require.context('./', true, /\.spec$/)
testsContext.keys().forEach(testsContext)
| test/unit/index.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.00017779429617803544,
0.00017779429617803544,
0.00017779429617803544,
0.00017779429617803544,
0
] |
{
"id": 3,
"code_window": [
" if (!has && !isAllowed) {\n",
" warnNonPresent(target, key)\n",
" }\n",
" return has || !isAllowed\n",
" },\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" }\n",
" }\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 35
} | /* not type checking this file because flow doesn't play well with Proxy */
import { warn, makeMap } from '../util/index'
let hasProxy, proxyHandlers, initProxy
if (process.env.NODE_ENV !== 'production') {
const allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
)
const warnNonPresent = (target, key) => {
warn(
`Property or method "${key}" is not defined on the instance but ` +
`referenced during render. Make sure to declare reactive data ` +
`properties in the data option.`,
target
)
}
hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/)
proxyHandlers = {
has (target, key) {
const has = key in target
const isAllowed = allowedGlobals(key) || key.charAt(0) === '_'
if (!has && !isAllowed) {
warnNonPresent(target, key)
}
return has || !isAllowed
},
get (target, key) {
if (typeof key === 'string' && !(key in target)) {
warnNonPresent(target, key)
}
return target[key]
}
}
initProxy = function initProxy (vm) {
if (hasProxy) {
vm._renderProxy = new Proxy(vm, proxyHandlers)
} else {
vm._renderProxy = vm
}
}
}
export { initProxy }
| src/core/instance/proxy.js | 1 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.9957653284072876,
0.1671311855316162,
0.0001704989408608526,
0.001707323594018817,
0.3705776631832123
] |
{
"id": 3,
"code_window": [
" if (!has && !isAllowed) {\n",
" warnNonPresent(target, key)\n",
" }\n",
" return has || !isAllowed\n",
" },\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" }\n",
" }\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 35
} | /* @flow */
import { dirRE } from './parser/index'
// operators like typeof, instanceof and in are allowed
const prohibitedKeywordRE = new RegExp('\\b' + (
'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
'super,throw,while,yield,delete,export,import,return,switch,default,' +
'extends,finally,continue,debugger,function,arguments'
).split(',').join('\\b|\\b') + '\\b')
// check valid identifier for v-for
const identRE = /[A-Za-z_$][\w$]*/
// strip strings in expressions
const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g
// detect problematic expressions in a template
export function detectErrors (ast: ?ASTNode): Array<string> {
const errors: Array<string> = []
if (ast) {
checkNode(ast, errors)
}
return errors
}
function checkNode (node: ASTNode, errors: Array<string>) {
if (node.type === 1) {
for (const name in node.attrsMap) {
if (dirRE.test(name)) {
const value = node.attrsMap[name]
if (value) {
if (name === 'v-for') {
checkFor(node, `v-for="${value}"`, errors)
} else {
checkExpression(value, `${name}="${value}"`, errors)
}
}
}
}
if (node.children) {
for (let i = 0; i < node.children.length; i++) {
checkNode(node.children[i], errors)
}
}
} else if (node.type === 2) {
checkExpression(node.expression, node.text, errors)
}
}
function checkFor (node: ASTElement, text: string, errors: Array<string>) {
checkExpression(node.for || '', text, errors)
checkIdentifier(node.alias, 'v-for alias', text, errors)
checkIdentifier(node.iterator1, 'v-for iterator', text, errors)
checkIdentifier(node.iterator2, 'v-for iterator', text, errors)
}
function checkIdentifier (ident: ?string, type: string, text: string, errors: Array<string>) {
if (typeof ident === 'string' && !identRE.test(ident)) {
errors.push(`- invalid ${type} "${ident}" in expression: ${text}`)
}
}
function checkExpression (exp: string, text: string, errors: Array<string>) {
try {
new Function(`return ${exp}`)
} catch (e) {
const keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE)
if (keywordMatch) {
errors.push(
`- avoid using JavaScript keyword as property name: ` +
`"${keywordMatch[0]}" in expression ${text}`
)
} else {
errors.push(`- invalid expression: ${text}`)
}
}
}
| src/compiler/error-detector.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.00017367872351314873,
0.00016859767492860556,
0.00016429240349680185,
0.0001693453232292086,
0.000002935319344032905
] |
{
"id": 3,
"code_window": [
" if (!has && !isAllowed) {\n",
" warnNonPresent(target, key)\n",
" }\n",
" return has || !isAllowed\n",
" },\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" }\n",
" }\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 35
} | import Vue from 'vue'
describe('Instance properties', () => {
it('$data', () => {
const data = { a: 1 }
const vm = new Vue({
data
})
expect(vm.a).toBe(1)
expect(vm.$data).toBe(data)
// vm -> data
vm.a = 2
expect(data.a).toBe(2)
// data -> vm
data.a = 3
expect(vm.a).toBe(3)
})
it('$options', () => {
const A = Vue.extend({
methods: {
a () {}
}
})
const vm = new A({
methods: {
b () {}
}
})
expect(typeof vm.$options.methods.a).toBe('function')
expect(typeof vm.$options.methods.b).toBe('function')
})
it('$root/$children', done => {
const vm = new Vue({
template: '<div><test v-if="ok"></test></div>',
data: { ok: true },
components: {
test: {
template: '<div></div>'
}
}
}).$mount()
expect(vm.$root).toBe(vm)
expect(vm.$children.length).toBe(1)
expect(vm.$children[0].$root).toBe(vm)
vm.ok = false
waitForUpdate(() => {
expect(vm.$children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$children.length).toBe(1)
expect(vm.$children[0].$root).toBe(vm)
}).then(done)
})
it('$parent', () => {
const calls = []
const makeOption = name => ({
name,
template: `<div><slot></slot></div>`,
created () {
calls.push(`${name}:${this.$parent.$options.name}`)
}
})
new Vue({
template: `
<div>
<outer><middle><inner></inner></middle></outer>
<next></next>
</div>
`,
components: {
outer: makeOption('outer'),
middle: makeOption('middle'),
inner: makeOption('inner'),
next: makeOption('next')
}
}).$mount()
expect(calls).toEqual(['outer:undefined', 'middle:outer', 'inner:middle', 'next:undefined'])
})
})
| test/unit/features/instance/properties.spec.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.00017700620810501277,
0.00017450824088882655,
0.0001723456080071628,
0.00017416378250345588,
0.0000015391141232612426
] |
{
"id": 3,
"code_window": [
" if (!has && !isAllowed) {\n",
" warnNonPresent(target, key)\n",
" }\n",
" return has || !isAllowed\n",
" },\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" }\n",
" }\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 35
} | import { patch } from 'web/runtime/patch'
import VNode from 'core/vdom/vnode'
function prop (name) {
return obj => { return obj[name] }
}
function map (fn, list) {
const ret = []
for (let i = 0; i < list.length; i++) {
ret[i] = fn(list[i])
}
return ret
}
function spanNum (n) {
if (typeof n === 'string') {
return new VNode('span', {}, undefined, n)
} else {
return new VNode('span', { key: n }, undefined, n.toString())
}
}
function shuffle (array) {
let currentIndex = array.length
let temporaryValue
let randomIndex
// while there remain elements to shuffle...
while (currentIndex !== 0) {
// pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex)
currentIndex -= 1
// and swap it with the current element.
temporaryValue = array[currentIndex]
array[currentIndex] = array[randomIndex]
array[randomIndex] = temporaryValue
}
return array
}
const inner = prop('innerHTML')
const tag = prop('tagName')
describe('vdom patch: children', () => {
let vnode0
beforeEach(() => {
vnode0 = new VNode('p', { attrs: { id: '1' }}, [createTextVNode('hello world')])
patch(null, vnode0)
})
it('should appends elements', () => {
const vnode1 = new VNode('p', {}, [1].map(spanNum))
const vnode2 = new VNode('p', {}, [1, 2, 3].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(1)
elm = patch(vnode1, vnode2)
expect(elm.children.length).toBe(3)
expect(elm.children[1].innerHTML).toBe('2')
expect(elm.children[2].innerHTML).toBe('3')
})
it('should prepends elements', () => {
const vnode1 = new VNode('p', {}, [4, 5].map(spanNum))
const vnode2 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(2)
elm = patch(vnode1, vnode2)
expect(map(inner, elm.children)).toEqual(['1', '2', '3', '4', '5'])
})
it('should add elements in the middle', () => {
const vnode1 = new VNode('p', {}, [1, 2, 4, 5].map(spanNum))
const vnode2 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(4)
elm = patch(vnode1, vnode2)
expect(map(inner, elm.children)).toEqual(['1', '2', '3', '4', '5'])
})
it('should add elements at begin and end', () => {
const vnode1 = new VNode('p', {}, [2, 3, 4].map(spanNum))
const vnode2 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(3)
elm = patch(vnode1, vnode2)
expect(map(inner, elm.children)).toEqual(['1', '2', '3', '4', '5'])
})
it('should add children to parent with no children', () => {
const vnode1 = new VNode('p', { key: 'p' })
const vnode2 = new VNode('p', { key: 'p' }, [1, 2, 3].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(0)
elm = patch(vnode1, vnode2)
expect(map(inner, elm.children)).toEqual(['1', '2', '3'])
})
it('should remove all children from parent', () => {
const vnode1 = new VNode('p', { key: 'p' }, [1, 2, 3].map(spanNum))
const vnode2 = new VNode('p', { key: 'p' })
let elm = patch(vnode0, vnode1)
expect(map(inner, elm.children)).toEqual(['1', '2', '3'])
elm = patch(vnode1, vnode2)
expect(elm.children.length).toBe(0)
})
it('should remove elements from the beginning', () => {
const vnode1 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum))
const vnode2 = new VNode('p', {}, [3, 4, 5].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(5)
elm = patch(vnode1, vnode2)
expect(map(inner, elm.children)).toEqual(['3', '4', '5'])
})
it('should removes elements from end', () => {
const vnode1 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum))
const vnode2 = new VNode('p', {}, [1, 2, 3].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(5)
elm = patch(vnode1, vnode2)
expect(elm.children.length).toBe(3)
expect(map(inner, elm.children)).toEqual(['1', '2', '3'])
})
it('should remove elements from the middle', () => {
const vnode1 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum))
const vnode2 = new VNode('p', {}, [1, 2, 4, 5].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(5)
elm = patch(vnode1, vnode2)
expect(elm.children.length).toBe(4)
expect(map(inner, elm.children)).toEqual(['1', '2', '4', '5'])
})
it('should moves element forward', () => {
const vnode1 = new VNode('p', {}, [1, 2, 3, 4].map(spanNum))
const vnode2 = new VNode('p', {}, [2, 3, 1, 4].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(4)
elm = patch(vnode1, vnode2)
expect(elm.children.length).toBe(4)
expect(map(inner, elm.children)).toEqual(['2', '3', '1', '4'])
})
it('should move elements to end', () => {
const vnode1 = new VNode('p', {}, [1, 2, 3].map(spanNum))
const vnode2 = new VNode('p', {}, [2, 3, 1].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(3)
elm = patch(vnode1, vnode2)
expect(elm.children.length).toBe(3)
expect(map(inner, elm.children)).toEqual(['2', '3', '1'])
})
it('should move element backwards', () => {
const vnode1 = new VNode('p', {}, [1, 2, 3, 4].map(spanNum))
const vnode2 = new VNode('p', {}, [1, 4, 2, 3].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(4)
elm = patch(vnode1, vnode2)
expect(elm.children.length).toBe(4)
expect(map(inner, elm.children)).toEqual(['1', '4', '2', '3'])
})
it('should swap first and last', () => {
const vnode1 = new VNode('p', {}, [1, 2, 3, 4].map(spanNum))
const vnode2 = new VNode('p', {}, [4, 2, 3, 1].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(4)
elm = patch(vnode1, vnode2)
expect(elm.children.length).toBe(4)
expect(map(inner, elm.children)).toEqual(['4', '2', '3', '1'])
})
it('should move to left and replace', () => {
const vnode1 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum))
const vnode2 = new VNode('p', {}, [4, 1, 2, 3, 6].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(5)
elm = patch(vnode1, vnode2)
expect(elm.children.length).toBe(5)
expect(map(inner, elm.children)).toEqual(['4', '1', '2', '3', '6'])
})
it('should move to left and leaves hold', () => {
const vnode1 = new VNode('p', {}, [1, 4, 5].map(spanNum))
const vnode2 = new VNode('p', {}, [4, 6].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(3)
elm = patch(vnode1, vnode2)
expect(map(inner, elm.children)).toEqual(['4', '6'])
})
it('should handle moved and set to undefined element ending at the end', () => {
const vnode1 = new VNode('p', {}, [2, 4, 5].map(spanNum))
const vnode2 = new VNode('p', {}, [4, 5, 3].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(3)
elm = patch(vnode1, vnode2)
expect(elm.children.length).toBe(3)
expect(map(inner, elm.children)).toEqual(['4', '5', '3'])
})
it('should move a key in non-keyed nodes with a size up', () => {
const vnode1 = new VNode('p', {}, [1, 'a', 'b', 'c'].map(spanNum))
const vnode2 = new VNode('p', {}, ['d', 'a', 'b', 'c', 1, 'e'].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(4)
expect(elm.textContent, '1abc')
elm = patch(vnode1, vnode2)
expect(elm.children.length).toBe(6)
expect(elm.textContent, 'dabc1e')
})
it('should reverse element', () => {
const vnode1 = new VNode('p', {}, [1, 2, 3, 4, 5, 6, 7, 8].map(spanNum))
const vnode2 = new VNode('p', {}, [8, 7, 6, 5, 4, 3, 2, 1].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(8)
elm = patch(vnode1, vnode2)
expect(map(inner, elm.children)).toEqual(['8', '7', '6', '5', '4', '3', '2', '1'])
})
it('something', () => {
const vnode1 = new VNode('p', {}, [0, 1, 2, 3, 4, 5].map(spanNum))
const vnode2 = new VNode('p', {}, [4, 3, 2, 1, 5, 0].map(spanNum))
let elm = patch(vnode0, vnode1)
expect(elm.children.length).toBe(6)
elm = patch(vnode1, vnode2)
expect(map(inner, elm.children)).toEqual(['4', '3', '2', '1', '5', '0'])
})
it('should handle random shuffle', () => {
let n
let i
const arr = []
const opacities = []
const elms = 14
const samples = 5
function spanNumWithOpacity (n, o) {
return new VNode('span', { key: n, style: { opacity: o }}, undefined, n.toString())
}
for (n = 0; n < elms; ++n) { arr[n] = n }
for (n = 0; n < samples; ++n) {
const vnode1 = new VNode('span', {}, arr.map(n => {
return spanNumWithOpacity(n, '1')
}))
const shufArr = shuffle(arr.slice(0))
let elm = patch(vnode0, vnode1)
for (i = 0; i < elms; ++i) {
expect(elm.children[i].innerHTML).toBe(i.toString())
opacities[i] = Math.random().toFixed(5).toString()
}
const vnode2 = new VNode('span', {}, arr.map(n => {
return spanNumWithOpacity(shufArr[n], opacities[n])
}))
elm = patch(vnode1, vnode2)
for (i = 0; i < elms; ++i) {
expect(elm.children[i].innerHTML).toBe(shufArr[i].toString())
expect(opacities[i].indexOf(elm.children[i].style.opacity)).toBe(0)
}
}
})
it('should append elements with updating children without keys', () => {
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'hello')
])
const vnode2 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'hello'),
new VNode('span', {}, undefined, 'world')
])
let elm = patch(vnode0, vnode1)
expect(map(inner, elm.children)).toEqual(['hello'])
elm = patch(vnode1, vnode2)
expect(map(inner, elm.children)).toEqual(['hello', 'world'])
})
it('should handle unmoved text nodes with updating children without keys', () => {
const vnode1 = new VNode('div', {}, [
createTextVNode('text'),
new VNode('span', {}, undefined, 'hello')
])
const vnode2 = new VNode('div', {}, [
createTextVNode('text'),
new VNode('span', {}, undefined, 'hello')
])
let elm = patch(vnode0, vnode1)
expect(elm.childNodes[0].textContent).toBe('text')
elm = patch(vnode1, vnode2)
expect(elm.childNodes[0].textContent).toBe('text')
})
it('should handle changing text children with updating children without keys', () => {
const vnode1 = new VNode('div', {}, [
createTextVNode('text'),
new VNode('span', {}, undefined, 'hello')
])
const vnode2 = new VNode('div', {}, [
createTextVNode('text2'),
new VNode('span', {}, undefined, 'hello')
])
let elm = patch(vnode0, vnode1)
expect(elm.childNodes[0].textContent).toBe('text')
elm = patch(vnode1, vnode2)
expect(elm.childNodes[0].textContent).toBe('text2')
})
it('should prepend element with updating children without keys', () => {
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'world')
])
const vnode2 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'hello'),
new VNode('span', {}, undefined, 'world')
])
let elm = patch(vnode0, vnode1)
expect(map(inner, elm.children)).toEqual(['world'])
elm = patch(vnode1, vnode2)
expect(map(inner, elm.children)).toEqual(['hello', 'world'])
})
it('should prepend element of different tag type with updating children without keys', () => {
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'world')
])
const vnode2 = new VNode('div', {}, [
new VNode('div', {}, undefined, 'hello'),
new VNode('span', {}, undefined, 'world')
])
let elm = patch(vnode0, vnode1)
expect(map(inner, elm.children)).toEqual(['world'])
elm = patch(vnode1, vnode2)
expect(map(prop('tagName'), elm.children)).toEqual(['DIV', 'SPAN'])
expect(map(inner, elm.children)).toEqual(['hello', 'world'])
})
it('should remove elements with updating children without keys', () => {
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'one'),
new VNode('span', {}, undefined, 'two'),
new VNode('span', {}, undefined, 'three')
])
const vnode2 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'one'),
new VNode('span', {}, undefined, 'three')
])
let elm = patch(vnode0, vnode1)
expect(map(inner, elm.children)).toEqual(['one', 'two', 'three'])
elm = patch(vnode1, vnode2)
expect(map(inner, elm.children)).toEqual(['one', 'three'])
})
it('should remove a single text node with updating children without keys', () => {
const vnode1 = new VNode('div', {}, undefined, 'one')
const vnode2 = new VNode('div', {})
let elm = patch(vnode0, vnode1)
expect(elm.textContent).toBe('one')
elm = patch(vnode1, vnode2)
expect(elm.textContent).toBe('')
})
it('should remove a single text node when children are updated', () => {
const vnode1 = new VNode('div', {}, undefined, 'one')
const vnode2 = new VNode('div', {}, [
new VNode('div', {}, undefined, 'two'),
new VNode('span', {}, undefined, 'three')
])
let elm = patch(vnode0, vnode1)
expect(elm.textContent).toBe('one')
elm = patch(vnode1, vnode2)
expect(map(prop('textContent'), elm.childNodes)).toEqual(['two', 'three'])
})
it('should remove a text node among other elements', () => {
const vnode1 = new VNode('div', {}, [
createTextVNode('one'),
new VNode('span', {}, undefined, 'two')
])
const vnode2 = new VNode('div', {}, [
new VNode('div', {}, undefined, 'three')
])
let elm = patch(vnode0, vnode1)
expect(map(prop('textContent'), elm.childNodes)).toEqual(['one', 'two'])
elm = patch(vnode1, vnode2)
expect(elm.childNodes.length).toBe(1)
expect(elm.childNodes[0].tagName).toBe('DIV')
expect(elm.childNodes[0].textContent).toBe('three')
})
it('should reorder elements', () => {
const vnode1 = new VNode('div', {}, [
new VNode('span', {}, undefined, 'one'),
new VNode('div', {}, undefined, 'two'),
new VNode('b', {}, undefined, 'three')
])
const vnode2 = new VNode('div', {}, [
new VNode('b', {}, undefined, 'three'),
new VNode('span', {}, undefined, 'two'),
new VNode('div', {}, undefined, 'one')
])
let elm = patch(vnode0, vnode1)
expect(map(inner, elm.children)).toEqual(['one', 'two', 'three'])
elm = patch(vnode1, vnode2)
expect(map(inner, elm.children)).toEqual(['three', 'two', 'one'])
})
it('should handle children with the same key but with different tag', () => {
const vnode1 = new VNode('div', {}, [
new VNode('div', { key: 1 }, undefined, 'one'),
new VNode('div', { key: 2 }, undefined, 'two'),
new VNode('div', { key: 3 }, undefined, 'three'),
new VNode('div', { key: 4 }, undefined, 'four')
])
const vnode2 = new VNode('div', {}, [
new VNode('div', { key: 4 }, undefined, 'four'),
new VNode('span', { key: 3 }, undefined, 'three'),
new VNode('span', { key: 2 }, undefined, 'two'),
new VNode('div', { key: 1 }, undefined, 'one')
])
let elm = patch(vnode0, vnode1)
expect(map(tag, elm.children)).toEqual(['DIV', 'DIV', 'DIV', 'DIV'])
expect(map(inner, elm.children)).toEqual(['one', 'two', 'three', 'four'])
elm = patch(vnode1, vnode2)
expect(map(tag, elm.children)).toEqual(['DIV', 'SPAN', 'SPAN', 'DIV'])
expect(map(inner, elm.children)).toEqual(['four', 'three', 'two', 'one'])
})
it('should handle children with the same tag, same key, but one with data and one without data', () => {
const vnode1 = new VNode('div', {}, [
new VNode('div', { class: 'hi' }, undefined, 'one')
])
const vnode2 = new VNode('div', {}, [
new VNode('div', undefined, undefined, 'four')
])
let elm = patch(vnode0, vnode1)
const child1 = elm.children[0]
expect(child1.className).toBe('hi')
elm = patch(vnode1, vnode2)
const child2 = elm.children[0]
expect(child1).not.toBe(child2)
expect(child2.className).toBe('')
})
it('should handle static vnodes properly', function () {
function makeNode (text) {
return new VNode('div', undefined, [
new VNode(undefined, undefined, undefined, text)
])
}
const b = makeNode('B')
b.isStatic = true
b.key = `__static__1`
const vnode1 = new VNode('div', {}, [makeNode('A'), b, makeNode('C')])
const vnode2 = new VNode('div', {}, [b])
const vnode3 = new VNode('div', {}, [makeNode('A'), b, makeNode('C')])
let elm = patch(vnode0, vnode1)
expect(elm.textContent).toBe('ABC')
elm = patch(vnode1, vnode2)
expect(elm.textContent).toBe('B')
elm = patch(vnode2, vnode3)
expect(elm.textContent).toBe('ABC')
})
it('should handle static vnodes inside ', function () {
function makeNode (text) {
return new VNode('div', undefined, [
new VNode(undefined, undefined, undefined, text)
])
}
const b = makeNode('B')
b.isStatic = true
b.key = `__static__1`
const vnode1 = new VNode('div', {}, [makeNode('A'), b, makeNode('C')])
const vnode2 = new VNode('div', {}, [b])
const vnode3 = new VNode('div', {}, [makeNode('A'), b, makeNode('C')])
let elm = patch(vnode0, vnode1)
expect(elm.textContent).toBe('ABC')
elm = patch(vnode1, vnode2)
expect(elm.textContent).toBe('B')
elm = patch(vnode2, vnode3)
expect(elm.textContent).toBe('ABC')
})
})
| test/unit/modules/vdom/patch/children.spec.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.00020054492051713169,
0.0001732898090267554,
0.0001670916099101305,
0.00017270456010010093,
0.000004808915036846884
] |
{
"id": 4,
"code_window": [
"\n",
" get (target, key) {\n",
" if (typeof key === 'string' && !(key in target)) {\n",
" warnNonPresent(target, key)\n",
" }\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const getHandler = {\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "add",
"edit_start_line_idx": 37
} | /* not type checking this file because flow doesn't play well with Proxy */
import { warn, makeMap } from '../util/index'
let hasProxy, proxyHandlers, initProxy
if (process.env.NODE_ENV !== 'production') {
const allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
)
const warnNonPresent = (target, key) => {
warn(
`Property or method "${key}" is not defined on the instance but ` +
`referenced during render. Make sure to declare reactive data ` +
`properties in the data option.`,
target
)
}
hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/)
proxyHandlers = {
has (target, key) {
const has = key in target
const isAllowed = allowedGlobals(key) || key.charAt(0) === '_'
if (!has && !isAllowed) {
warnNonPresent(target, key)
}
return has || !isAllowed
},
get (target, key) {
if (typeof key === 'string' && !(key in target)) {
warnNonPresent(target, key)
}
return target[key]
}
}
initProxy = function initProxy (vm) {
if (hasProxy) {
vm._renderProxy = new Proxy(vm, proxyHandlers)
} else {
vm._renderProxy = vm
}
}
}
export { initProxy }
| src/core/instance/proxy.js | 1 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.9978770017623901,
0.35152745246887207,
0.00016643521666992456,
0.0567183792591095,
0.4585677981376648
] |
{
"id": 4,
"code_window": [
"\n",
" get (target, key) {\n",
" if (typeof key === 'string' && !(key in target)) {\n",
" warnNonPresent(target, key)\n",
" }\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const getHandler = {\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "add",
"edit_start_line_idx": 37
} | // Full spec-compliant TodoMVC with localStorage persistence
// and hash-based routing in ~150 lines.
// localStorage persistence
var STORAGE_KEY = 'todos-vuejs-2.0'
var todoStorage = {
fetch: function () {
var todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
todos.forEach(function (todo, index) {
todo.id = index
})
todoStorage.uid = todos.length
return todos
},
save: function (todos) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(todos))
}
}
// visibility filters
var filters = {
all: function (todos) {
return todos
},
active: function (todos) {
return todos.filter(function (todo) {
return !todo.completed
})
},
completed: function (todos) {
return todos.filter(function (todo) {
return todo.completed
})
}
}
// app Vue instance
var app = new Vue({
// app initial state
data: {
todos: todoStorage.fetch(),
newTodo: '',
editedTodo: null,
visibility: 'all'
},
// watch todos change for localStorage persistence
watch: {
todos: {
handler: function (todos) {
todoStorage.save(todos)
},
deep: true
}
},
// computed properties
// https://vuejs.org/guide/computed.html
computed: {
filteredTodos: function () {
return filters[this.visibility](this.todos)
},
remaining: function () {
return filters.active(this.todos).length
},
allDone: {
get: function () {
return this.remaining === 0
},
set: function (value) {
this.todos.forEach(function (todo) {
todo.completed = value
})
}
}
},
filters: {
pluralize: function (n) {
return n === 1 ? 'item' : 'items'
}
},
// methods that implement data logic.
// note there's no DOM manipulation here at all.
methods: {
addTodo: function () {
var value = this.newTodo && this.newTodo.trim()
if (!value) {
return
}
this.todos.push({
id: todoStorage.uid++,
title: value,
completed: false
})
this.newTodo = ''
},
removeTodo: function (todo) {
this.todos.splice(this.todos.indexOf(todo), 1)
},
editTodo: function (todo) {
this.beforeEditCache = todo.title
this.editedTodo = todo
},
doneEdit: function (todo) {
if (!this.editedTodo) {
return
}
this.editedTodo = null
todo.title = todo.title.trim()
if (!todo.title) {
this.removeTodo(todo)
}
},
cancelEdit: function (todo) {
this.editedTodo = null
todo.title = this.beforeEditCache
},
removeCompleted: function () {
this.todos = filters.active(this.todos)
}
},
// a custom directive to wait for the DOM to be updated
// before focusing on the input field.
// https://vuejs.org/guide/custom-directive.html
directives: {
'todo-focus': function (el, value) {
if (value) {
el.focus()
}
}
}
})
// handle routing
function onHashChange () {
var visibility = window.location.hash.replace(/#\/?/, '')
if (filters[visibility]) {
app.visibility = visibility
} else {
window.location.hash = ''
app.visibility = 'all'
}
}
window.addEventListener('hashchange', onHashChange)
onHashChange()
// mount
app.$mount('.todoapp')
| examples/todomvc/app.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.0001849703403422609,
0.00017313318676315248,
0.00016892973508220166,
0.0001729392824927345,
0.000003368148099980317
] |
{
"id": 4,
"code_window": [
"\n",
" get (target, key) {\n",
" if (typeof key === 'string' && !(key in target)) {\n",
" warnNonPresent(target, key)\n",
" }\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const getHandler = {\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "add",
"edit_start_line_idx": 37
} | /* @flow */
import RenderStream from './render-stream'
import { createWriteFunction } from './write'
import { createRenderFunction } from './render'
export function createRenderer ({
modules = [],
directives = {},
isUnaryTag = (() => false),
cache
}: {
modules: Array<Function>,
directives: Object,
isUnaryTag: Function,
cache: ?Object
} = {}): {
renderToString: Function,
renderToStream: Function
} {
const render = createRenderFunction(modules, directives, isUnaryTag, cache)
return {
renderToString (
component: Component,
done: (err: ?Error, res: ?string) => any
): void {
let result = ''
const write = createWriteFunction(text => {
result += text
}, done)
try {
render(component, write, () => {
done(null, result)
})
} catch (e) {
done(e)
}
},
renderToStream (component: Component): RenderStream {
return new RenderStream((write, done) => {
render(component, write, done)
})
}
}
}
| src/server/create-renderer.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.00017621053848415613,
0.0001739286963129416,
0.00017071919864974916,
0.00017472532636020333,
0.000002134078386006877
] |
{
"id": 4,
"code_window": [
"\n",
" get (target, key) {\n",
" if (typeof key === 'string' && !(key in target)) {\n",
" warnNonPresent(target, key)\n",
" }\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const getHandler = {\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "add",
"edit_start_line_idx": 37
} | machine:
node:
version: 6
test:
override:
- bash build/ci.sh
| circle.yml | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.0001689078490016982,
0.0001689078490016982,
0.0001689078490016982,
0.0001689078490016982,
0
] |
{
"id": 5,
"code_window": [
"\n",
" initProxy = function initProxy (vm) {\n",
" if (hasProxy) {\n",
" vm._renderProxy = new Proxy(vm, proxyHandlers)\n",
" } else {\n",
" vm._renderProxy = vm\n",
" }\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // determine which proxy handler to use\n",
" let handlers\n",
" const options = vm.$options\n",
" if (options.template || options.el) {\n",
" handlers = hasHandler\n",
" }\n",
" if (options.render) {\n",
" handlers = options.render._withStripped ? getHandler : hasHandler\n",
" }\n",
" vm._renderProxy = handlers ? new Proxy(vm, handlers) : vm\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 47
} | /* not type checking this file because flow doesn't play well with Proxy */
import { warn, makeMap } from '../util/index'
let hasProxy, proxyHandlers, initProxy
if (process.env.NODE_ENV !== 'production') {
const allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
)
const warnNonPresent = (target, key) => {
warn(
`Property or method "${key}" is not defined on the instance but ` +
`referenced during render. Make sure to declare reactive data ` +
`properties in the data option.`,
target
)
}
hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/)
proxyHandlers = {
has (target, key) {
const has = key in target
const isAllowed = allowedGlobals(key) || key.charAt(0) === '_'
if (!has && !isAllowed) {
warnNonPresent(target, key)
}
return has || !isAllowed
},
get (target, key) {
if (typeof key === 'string' && !(key in target)) {
warnNonPresent(target, key)
}
return target[key]
}
}
initProxy = function initProxy (vm) {
if (hasProxy) {
vm._renderProxy = new Proxy(vm, proxyHandlers)
} else {
vm._renderProxy = vm
}
}
}
export { initProxy }
| src/core/instance/proxy.js | 1 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.997989296913147,
0.32017257809638977,
0.00017243866750504822,
0.0024566722568124533,
0.45152750611305237
] |
{
"id": 5,
"code_window": [
"\n",
" initProxy = function initProxy (vm) {\n",
" if (hasProxy) {\n",
" vm._renderProxy = new Proxy(vm, proxyHandlers)\n",
" } else {\n",
" vm._renderProxy = vm\n",
" }\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // determine which proxy handler to use\n",
" let handlers\n",
" const options = vm.$options\n",
" if (options.template || options.el) {\n",
" handlers = hasHandler\n",
" }\n",
" if (options.render) {\n",
" handlers = options.render._withStripped ? getHandler : hasHandler\n",
" }\n",
" vm._renderProxy = handlers ? new Proxy(vm, handlers) : vm\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 47
} | try {
var vueVersion = require('vue').version
} catch (e) {}
var packageName = require('./package.json').name
var packageVersion = require('./package.json').version
if (vueVersion && vueVersion !== packageVersion) {
throw new Error(
'\n\nVue packages version mismatch:\n\n' +
'- vue@' + vueVersion + '\n' +
'- ' + packageName + '@' + packageVersion + '\n\n' +
'This may cause things to work incorrectly. Make sure to use the same version for both.\n' +
'If you are using vue-loader@>=10.0, simply update vue-template-compiler.\n' +
'If you are using vue-loader@<10.0 or vueify, re-installing vue-loader/vueify should bump ' + packageName + ' to the latest.\n'
)
}
module.exports = require('./build')
| packages/vue-template-compiler/index.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.0001762562314979732,
0.00017571197531651706,
0.0001751677191350609,
0.00017571197531651706,
5.442561814561486e-7
] |
{
"id": 5,
"code_window": [
"\n",
" initProxy = function initProxy (vm) {\n",
" if (hasProxy) {\n",
" vm._renderProxy = new Proxy(vm, proxyHandlers)\n",
" } else {\n",
" vm._renderProxy = vm\n",
" }\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // determine which proxy handler to use\n",
" let handlers\n",
" const options = vm.$options\n",
" if (options.template || options.el) {\n",
" handlers = hasHandler\n",
" }\n",
" if (options.render) {\n",
" handlers = options.render._withStripped ? getHandler : hasHandler\n",
" }\n",
" vm._renderProxy = handlers ? new Proxy(vm, handlers) : vm\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 47
} | const path = require('path')
module.exports = {
vue: path.resolve(__dirname, '../src/entries/web-runtime-with-compiler'),
compiler: path.resolve(__dirname, '../src/compiler'),
core: path.resolve(__dirname, '../src/core'),
shared: path.resolve(__dirname, '../src/shared'),
web: path.resolve(__dirname, '../src/platforms/web'),
weex: path.resolve(__dirname, '../src/platforms/weex'),
server: path.resolve(__dirname, '../src/server'),
entries: path.resolve(__dirname, '../src/entries'),
sfc: path.resolve(__dirname, '../src/sfc')
}
| build/alias.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.00017736775043886155,
0.00017590512288734317,
0.00017444250988774002,
0.00017590512288734317,
0.0000014626202755607665
] |
{
"id": 5,
"code_window": [
"\n",
" initProxy = function initProxy (vm) {\n",
" if (hasProxy) {\n",
" vm._renderProxy = new Proxy(vm, proxyHandlers)\n",
" } else {\n",
" vm._renderProxy = vm\n",
" }\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // determine which proxy handler to use\n",
" let handlers\n",
" const options = vm.$options\n",
" if (options.template || options.el) {\n",
" handlers = hasHandler\n",
" }\n",
" if (options.render) {\n",
" handlers = options.render._withStripped ? getHandler : hasHandler\n",
" }\n",
" vm._renderProxy = handlers ? new Proxy(vm, handlers) : vm\n"
],
"file_path": "src/core/instance/proxy.js",
"type": "replace",
"edit_start_line_idx": 47
} | try {
var vueVersion = require('weex-vue-framework').version
} catch (e) {}
var packageName = require('./package.json').name
var packageVersion = require('./package.json').version
if (vueVersion && vueVersion !== packageVersion) {
throw new Error(
'\n\nVue packages version mismatch:\n\n' +
'- vue@' + vueVersion + '\n' +
'- ' + packageName + '@' + packageVersion + '\n\n' +
'This may cause things to work incorrectly. Make sure to use the same version for both.\n' +
'If you are using weex-vue-loader, re-installing them should bump ' + packageName + ' to the latest.\n'
)
}
module.exports = require('./build')
| packages/weex-template-compiler/index.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.00017610772920306772,
0.00017565066809765995,
0.00017519360699225217,
0.00017565066809765995,
4.5706110540777445e-7
] |
{
"id": 6,
"code_window": [
" })\n",
"\n",
" it('should warn missing property in render fns without `with`', () => {\n",
" new Vue({\n",
" render (h) {\n",
" return h('div', [this.a])\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const render = function (h) {\n",
" return h('div', [this.a])\n",
" }\n",
" render._withStripped = true\n",
" new Vue({\n",
" render\n",
" }).$mount()\n",
" expect(`Property or method \"a\" is not defined`).toHaveBeenWarned()\n",
" })\n",
"\n",
" it('should not warn for hand-written render functions', () => {\n"
],
"file_path": "test/unit/features/instance/render-proxy.spec.js",
"type": "add",
"edit_start_line_idx": 12
} | /* not type checking this file because flow doesn't play well with Proxy */
import { warn, makeMap } from '../util/index'
let hasProxy, proxyHandlers, initProxy
if (process.env.NODE_ENV !== 'production') {
const allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
)
const warnNonPresent = (target, key) => {
warn(
`Property or method "${key}" is not defined on the instance but ` +
`referenced during render. Make sure to declare reactive data ` +
`properties in the data option.`,
target
)
}
hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/)
proxyHandlers = {
has (target, key) {
const has = key in target
const isAllowed = allowedGlobals(key) || key.charAt(0) === '_'
if (!has && !isAllowed) {
warnNonPresent(target, key)
}
return has || !isAllowed
},
get (target, key) {
if (typeof key === 'string' && !(key in target)) {
warnNonPresent(target, key)
}
return target[key]
}
}
initProxy = function initProxy (vm) {
if (hasProxy) {
vm._renderProxy = new Proxy(vm, proxyHandlers)
} else {
vm._renderProxy = vm
}
}
}
export { initProxy }
| src/core/instance/proxy.js | 1 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.001115663442760706,
0.0003922094765584916,
0.00016587736899964511,
0.00017214362742379308,
0.000353871175320819
] |
{
"id": 6,
"code_window": [
" })\n",
"\n",
" it('should warn missing property in render fns without `with`', () => {\n",
" new Vue({\n",
" render (h) {\n",
" return h('div', [this.a])\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const render = function (h) {\n",
" return h('div', [this.a])\n",
" }\n",
" render._withStripped = true\n",
" new Vue({\n",
" render\n",
" }).$mount()\n",
" expect(`Property or method \"a\" is not defined`).toHaveBeenWarned()\n",
" })\n",
"\n",
" it('should not warn for hand-written render functions', () => {\n"
],
"file_path": "test/unit/features/instance/render-proxy.spec.js",
"type": "add",
"edit_start_line_idx": 12
} | /**
* Not type checking this file because flow doesn't like attaching
* properties to Elements.
*/
import { looseEqual, looseIndexOf } from 'shared/util'
import { warn, isAndroid, isIE9, isIE, isEdge } from 'core/util/index'
const modelableTagRE = /^input|select|textarea|vue-component-[0-9]+(-[0-9a-zA-Z_-]*)?$/
/* istanbul ignore if */
if (isIE9) {
// http://www.matts411.com/post/internet-explorer-9-oninput/
document.addEventListener('selectionchange', () => {
const el = document.activeElement
if (el && el.vmodel) {
trigger(el, 'input')
}
})
}
export default {
inserted (el, binding, vnode) {
if (process.env.NODE_ENV !== 'production') {
if (!modelableTagRE.test(vnode.tag)) {
warn(
`v-model is not supported on element type: <${vnode.tag}>. ` +
'If you are working with contenteditable, it\'s recommended to ' +
'wrap a library dedicated for that purpose inside a custom component.',
vnode.context
)
}
}
if (vnode.tag === 'select') {
const cb = () => {
setSelected(el, binding, vnode.context)
}
cb()
/* istanbul ignore if */
if (isIE || isEdge) {
setTimeout(cb, 0)
}
} else if (
(vnode.tag === 'textarea' || el.type === 'text') &&
!binding.modifiers.lazy
) {
if (!isAndroid) {
el.addEventListener('compositionstart', onCompositionStart)
el.addEventListener('compositionend', onCompositionEnd)
}
/* istanbul ignore if */
if (isIE9) {
el.vmodel = true
}
}
},
componentUpdated (el, binding, vnode) {
if (vnode.tag === 'select') {
setSelected(el, binding, vnode.context)
// in case the options rendered by v-for have changed,
// it's possible that the value is out-of-sync with the rendered options.
// detect such cases and filter out values that no longer has a matching
// option in the DOM.
const needReset = el.multiple
? binding.value.some(v => hasNoMatchingOption(v, el.options))
: binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, el.options)
if (needReset) {
trigger(el, 'change')
}
}
}
}
function setSelected (el, binding, vm) {
const value = binding.value
const isMultiple = el.multiple
if (isMultiple && !Array.isArray(value)) {
process.env.NODE_ENV !== 'production' && warn(
`<select multiple v-model="${binding.expression}"> ` +
`expects an Array value for its binding, but got ${
Object.prototype.toString.call(value).slice(8, -1)
}`,
vm
)
return
}
let selected, option
for (let i = 0, l = el.options.length; i < l; i++) {
option = el.options[i]
if (isMultiple) {
selected = looseIndexOf(value, getValue(option)) > -1
if (option.selected !== selected) {
option.selected = selected
}
} else {
if (looseEqual(getValue(option), value)) {
if (el.selectedIndex !== i) {
el.selectedIndex = i
}
return
}
}
}
if (!isMultiple) {
el.selectedIndex = -1
}
}
function hasNoMatchingOption (value, options) {
for (let i = 0, l = options.length; i < l; i++) {
if (looseEqual(getValue(options[i]), value)) {
return false
}
}
return true
}
function getValue (option) {
return '_value' in option
? option._value
: option.value
}
function onCompositionStart (e) {
e.target.composing = true
}
function onCompositionEnd (e) {
e.target.composing = false
trigger(e.target, 'input')
}
function trigger (el, type) {
const e = document.createEvent('HTMLEvents')
e.initEvent(type, true, true)
el.dispatchEvent(e)
}
| src/platforms/web/runtime/directives/model.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.00024730642326176167,
0.00018302220269106328,
0.00016568624414503574,
0.00017239057342521846,
0.000026095201974385418
] |
{
"id": 6,
"code_window": [
" })\n",
"\n",
" it('should warn missing property in render fns without `with`', () => {\n",
" new Vue({\n",
" render (h) {\n",
" return h('div', [this.a])\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const render = function (h) {\n",
" return h('div', [this.a])\n",
" }\n",
" render._withStripped = true\n",
" new Vue({\n",
" render\n",
" }).$mount()\n",
" expect(`Property or method \"a\" is not defined`).toHaveBeenWarned()\n",
" })\n",
"\n",
" it('should not warn for hand-written render functions', () => {\n"
],
"file_path": "test/unit/features/instance/render-proxy.spec.js",
"type": "add",
"edit_start_line_idx": 12
} | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Vue.js markdown editor example</title>
<link rel="stylesheet" href="style.css">
<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/[email protected]"></script>
<!-- Delete ".min" for console warnings in development -->
<script src="../../dist/vue.min.js"></script>
</head>
<body>
<div id="editor">
<textarea :value="input" @input="update"></textarea>
<div v-html="compiledMarkdown"></div>
</div>
<script>
new Vue({
el: '#editor',
data: {
input: '# hello'
},
computed: {
compiledMarkdown: function () {
return marked(this.input, { sanitize: true })
}
},
methods: {
update: _.debounce(function (e) {
this.input = e.target.value
}, 300)
}
})
</script>
</body>
</html>
| examples/markdown/index.html | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.0014386147959157825,
0.000485460099298507,
0.0001658003602642566,
0.0001687126641627401,
0.0005503081483766437
] |
{
"id": 6,
"code_window": [
" })\n",
"\n",
" it('should warn missing property in render fns without `with`', () => {\n",
" new Vue({\n",
" render (h) {\n",
" return h('div', [this.a])\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const render = function (h) {\n",
" return h('div', [this.a])\n",
" }\n",
" render._withStripped = true\n",
" new Vue({\n",
" render\n",
" }).$mount()\n",
" expect(`Property or method \"a\" is not defined`).toHaveBeenWarned()\n",
" })\n",
"\n",
" it('should not warn for hand-written render functions', () => {\n"
],
"file_path": "test/unit/features/instance/render-proxy.spec.js",
"type": "add",
"edit_start_line_idx": 12
} | import { parse } from 'compiler/parser/index'
import { optimize } from 'compiler/optimizer'
import { generate } from 'compiler/codegen'
import { isObject } from 'shared/util'
import { isReservedTag } from 'web/util/index'
import { baseOptions } from 'web/compiler/index'
function assertCodegen (template, generatedCode, ...args) {
let staticRenderFnCodes = []
let generateOptions = baseOptions
let proc = null
let len = args.length
while (len--) {
const arg = args[len]
if (Array.isArray(arg)) {
staticRenderFnCodes = arg
} else if (isObject(arg)) {
generateOptions = arg
} else if (typeof arg === 'function') {
proc = arg
}
}
const ast = parse(template, baseOptions)
optimize(ast, baseOptions)
proc && proc(ast)
const res = generate(ast, generateOptions)
expect(res.render).toBe(generatedCode)
expect(res.staticRenderFns).toEqual(staticRenderFnCodes)
}
/* eslint-disable quotes */
describe('codegen', () => {
it('generate directive', () => {
assertCodegen(
'<p v-custom1:arg1.modifier="value1" v-custom2><p>',
`with(this){return _h('p',{directives:[{name:"custom1",rawName:"v-custom1:arg1.modifier",value:(value1),expression:"value1",arg:"arg1",modifiers:{"modifier":true}},{name:"custom2",rawName:"v-custom2",arg:"arg1"}]})}`
)
})
it('generate filters', () => {
assertCodegen(
'<div :id="a | b | c">{{ d | e | f }}</div>',
`with(this){return _h('div',{attrs:{"id":_f("c")(_f("b")(a))}},[_s(_f("f")(_f("e")(d)))])}`
)
})
it('generate v-for directive', () => {
assertCodegen(
'<li v-for="item in items" :key="item.uid"></li>',
`with(this){return _l((items),function(item){return _h('li',{key:item.uid})})}`
)
// iterator syntax
assertCodegen(
'<li v-for="(item, i) in items"></li>',
`with(this){return _l((items),function(item,i){return _h('li')})}`
)
assertCodegen(
'<li v-for="(item, key, index) in items"></li>',
`with(this){return _l((items),function(item,key,index){return _h('li')})}`
)
// destructuring
assertCodegen(
'<li v-for="{ a, b } in items"></li>',
`with(this){return _l((items),function({ a, b }){return _h('li')})}`
)
assertCodegen(
'<li v-for="({ a, b }, key, index) in items"></li>',
`with(this){return _l((items),function({ a, b },key,index){return _h('li')})}`
)
})
it('generate v-if directive', () => {
assertCodegen(
'<p v-if="show">hello</p>',
`with(this){return (show)?_h('p',["hello"]):_e()}`
)
})
it('generate v-else directive', () => {
assertCodegen(
'<div><p v-if="show">hello</p><p v-else>world</p></div>',
`with(this){return _h('div',[(show)?_h('p',["hello"]):_h('p',["world"])])}`
)
})
it('generate v-else-if directive', () => {
assertCodegen(
'<div><p v-if="show">hello</p><p v-else-if="hide">world</p></div>',
`with(this){return _h('div',[(show)?_h('p',["hello"]):(hide)?_h('p',["world"]):_e()])}`
)
})
it('generate v-else-if with v-else directive', () => {
assertCodegen(
'<div><p v-if="show">hello</p><p v-else-if="hide">world</p><p v-else>bye</p></div>',
`with(this){return _h('div',[(show)?_h('p',["hello"]):(hide)?_h('p',["world"]):_h('p',["bye"])])}`
)
})
it('generate mutli v-else-if with v-else directive', () => {
assertCodegen(
'<div><p v-if="show">hello</p><p v-else-if="hide">world</p><p v-else-if="3">elseif</p><p v-else>bye</p></div>',
`with(this){return _h('div',[(show)?_h('p',["hello"]):(hide)?_h('p',["world"]):(3)?_h('p',["elseif"]):_h('p',["bye"])])}`
)
})
it('generate ref', () => {
assertCodegen(
'<p ref="component1"></p>',
`with(this){return _h('p',{ref:"component1"})}`
)
})
it('generate ref on v-for', () => {
assertCodegen(
'<ul><li v-for="item in items" ref="component1"></li></ul>',
`with(this){return _h('ul',[_l((items),function(item){return _h('li',{ref:"component1",refInFor:true})})])}`
)
})
it('generate v-bind directive', () => {
assertCodegen(
'<p v-bind="test"></p>',
`with(this){return _h('p',_b({},'p',test))}`
)
})
it('generate template tag', () => {
assertCodegen(
'<template><p>{{hello}}</p></template>',
`with(this){return [_h('p',[_s(hello)])]}`
)
})
it('generate single slot', () => {
assertCodegen(
'<slot></slot>',
`with(this){return _t("default")}`
)
})
it('generate named slot', () => {
assertCodegen(
'<slot name="one"></slot>',
`with(this){return _t("one")}`
)
})
it('generate slot fallback content', () => {
assertCodegen(
'<slot><div>hi</div></slot>',
`with(this){return _t("default",[_h('div',["hi"])])}`
)
})
it('generate slot target', () => {
assertCodegen(
'<p slot="one">hello world</p>',
`with(this){return _h('p',{slot:"one"},["hello world"])}`
)
})
it('generate class binding', () => {
// static
assertCodegen(
'<p class="class1">hello world</p>',
`with(this){return _h('p',{staticClass:"class1"},["hello world"])}`,
)
// dynamic
assertCodegen(
'<p :class="class1">hello world</p>',
`with(this){return _h('p',{class:class1},["hello world"])}`
)
})
it('generate style binding', () => {
assertCodegen(
'<p :style="error">hello world</p>',
`with(this){return _h('p',{style:(error)},["hello world"])}`
)
})
it('generate v-show directive', () => {
assertCodegen(
'<p v-show="shown">hello world</p>',
`with(this){return _h('p',{directives:[{name:"show",rawName:"v-show",value:(shown),expression:"shown"}]},["hello world"])}`
)
})
it('generate DOM props with v-bind directive', () => {
// input + value
assertCodegen(
'<input :value="msg">',
`with(this){return _h('input',{domProps:{"value":msg}})}`
)
// non input
assertCodegen(
'<p :value="msg">',
`with(this){return _h('p',{attrs:{"value":msg}})}`
)
})
it('generate attrs with v-bind directive', () => {
assertCodegen(
'<input :name="field1">',
`with(this){return _h('input',{attrs:{"name":field1}})}`
)
})
it('generate static attrs', () => {
assertCodegen(
'<input name="field1">',
`with(this){return _h('input',{attrs:{"name":"field1"}})}`
)
})
it('generate events with v-on directive', () => {
assertCodegen(
'<input @input="onInput">',
`with(this){return _h('input',{on:{"input":onInput}})}`
)
})
it('generate events with keycode', () => {
assertCodegen(
'<input @input.enter="onInput">',
`with(this){return _h('input',{on:{"input":function($event){if($event.keyCode!==13)return;onInput($event)}}})}`
)
// multiple keycodes (delete)
assertCodegen(
'<input @input.delete="onInput">',
`with(this){return _h('input',{on:{"input":function($event){if($event.keyCode!==8&&$event.keyCode!==46)return;onInput($event)}}})}`
)
// multiple keycodes (chained)
assertCodegen(
'<input @keydown.enter.delete="onInput">',
`with(this){return _h('input',{on:{"keydown":function($event){if($event.keyCode!==13&&$event.keyCode!==8&&$event.keyCode!==46)return;onInput($event)}}})}`
)
// number keycode
assertCodegen(
'<input @input.13="onInput">',
`with(this){return _h('input',{on:{"input":function($event){if($event.keyCode!==13)return;onInput($event)}}})}`
)
// custom keycode
assertCodegen(
'<input @input.custom="onInput">',
`with(this){return _h('input',{on:{"input":function($event){if($event.keyCode!==_k("custom"))return;onInput($event)}}})}`
)
})
it('generate events with generic modifiers', () => {
assertCodegen(
'<input @input.stop="onInput">',
`with(this){return _h('input',{on:{"input":function($event){$event.stopPropagation();onInput($event)}}})}`
)
assertCodegen(
'<input @input.prevent="onInput">',
`with(this){return _h('input',{on:{"input":function($event){$event.preventDefault();onInput($event)}}})}`
)
assertCodegen(
'<input @input.self="onInput">',
`with(this){return _h('input',{on:{"input":function($event){if($event.target !== $event.currentTarget)return;onInput($event)}}})}`
)
})
it('generate events with mouse event modifiers', () => {
assertCodegen(
'<input @click.ctrl="onClick">',
`with(this){return _h('input',{on:{"click":function($event){if(!$event.ctrlKey)return;onClick($event)}}})}`
)
assertCodegen(
'<input @click.shift="onClick">',
`with(this){return _h('input',{on:{"click":function($event){if(!$event.shiftKey)return;onClick($event)}}})}`
)
assertCodegen(
'<input @click.alt="onClick">',
`with(this){return _h('input',{on:{"click":function($event){if(!$event.altKey)return;onClick($event)}}})}`
)
assertCodegen(
'<input @click.meta="onClick">',
`with(this){return _h('input',{on:{"click":function($event){if(!$event.metaKey)return;onClick($event)}}})}`
)
})
it('generate events with multiple modifers', () => {
assertCodegen(
'<input @input.stop.prevent.self="onInput">',
`with(this){return _h('input',{on:{"input":function($event){$event.stopPropagation();$event.preventDefault();if($event.target !== $event.currentTarget)return;onInput($event)}}})}`
)
})
it('generate events with capture modifier', () => {
assertCodegen(
'<input @input.capture="onInput">',
`with(this){return _h('input',{on:{"!input":function($event){onInput($event)}}})}`
)
})
it('generate events with inline statement', () => {
assertCodegen(
'<input @input="curent++">',
`with(this){return _h('input',{on:{"input":function($event){curent++}}})}`
)
})
it('generate events with inline function expression', () => {
// normal function
assertCodegen(
'<input @input="function () { current++ }">',
`with(this){return _h('input',{on:{"input":function () { current++ }}})}`
)
// arrow with no args
assertCodegen(
'<input @input="()=>current++">',
`with(this){return _h('input',{on:{"input":()=>current++}})}`
)
// arrow with parens, single arg
assertCodegen(
'<input @input="(e) => current++">',
`with(this){return _h('input',{on:{"input":(e) => current++}})}`
)
// arrow with parens, multi args
assertCodegen(
'<input @input="(a, b, c) => current++">',
`with(this){return _h('input',{on:{"input":(a, b, c) => current++}})}`
)
// arrow with destructuring
assertCodegen(
'<input @input="({ a, b }) => current++">',
`with(this){return _h('input',{on:{"input":({ a, b }) => current++}})}`
)
// arrow single arg no parens
assertCodegen(
'<input @input="e=>current++">',
`with(this){return _h('input',{on:{"input":e=>current++}})}`
)
})
// #3893
it('should not treat handler with unexpected whitespace as inline statement', () => {
assertCodegen(
'<input @input=" onInput ">',
`with(this){return _h('input',{on:{"input": onInput }})}`
)
})
it('generate unhandled events', () => {
assertCodegen(
'<input @input="curent++">',
`with(this){return _h('input',{on:{"input":function(){}}})}`,
ast => {
ast.events.input = undefined
}
)
})
it('generate multiple event handlers', () => {
assertCodegen(
'<input @input="curent++" @input="onInput">',
`with(this){return _h('input',{on:{"input":[function($event){curent++},onInput]}})}`
)
})
it('generate component', () => {
assertCodegen(
'<my-component name="mycomponent1" :msg="msg" @notify="onNotify"><div>hi</div></my-component>',
`with(this){return _h('my-component',{attrs:{"name":"mycomponent1","msg":msg},on:{"notify":onNotify}},[_h('div',["hi"])])}`
)
})
it('generate svg component with children', () => {
assertCodegen(
'<svg><my-comp><circle :r="10"></circle></my-comp></svg>',
`with(this){return _h('svg',[_h('my-comp',[_h('circle',{attrs:{"r":10}})])])}`
)
})
it('generate is attribute', () => {
assertCodegen(
'<div is="component1"></div>',
`with(this){return _h("component1",{tag:"div"})}`
)
assertCodegen(
'<div :is="component1"></div>',
`with(this){return _h(component1,{tag:"div"})}`
)
})
it('generate component with inline-template', () => {
// have "inline-template'"
assertCodegen(
'<my-component inline-template><p><span>hello world</span></p></my-component>',
`with(this){return _h('my-component',{inlineTemplate:{render:function(){with(this){return _m(0)}},staticRenderFns:[function(){with(this){return _h('p',[_h('span',["hello world"])])}}]}})}`
)
// "have inline-template attrs, but not having extactly one child element
assertCodegen(
'<my-component inline-template><hr><hr></my-component>',
`with(this){return _h('my-component',{inlineTemplate:{render:function(){with(this){return _h('hr')}},staticRenderFns:[]}})}`
)
expect('Inline-template components must have exactly one child element.').toHaveBeenWarned()
})
it('generate static trees inside v-for', () => {
assertCodegen(
`<div><div v-for="i in 10"><p><span></span></p></div></div>`,
`with(this){return _h('div',[_l((10),function(i){return _h('div',[_m(0,true)])})])}`,
[`with(this){return _h('p',[_h('span')])}`]
)
})
it('not specified ast type', () => {
const res = generate(null, baseOptions)
expect(res.render).toBe(`with(this){return _h("div")}`)
expect(res.staticRenderFns).toEqual([])
})
it('not specified directives option', () => {
assertCodegen(
'<p v-if="show">hello world</p>',
`with(this){return (show)?_h('p',["hello world"]):_e()}`,
{ isReservedTag }
)
})
})
/* eslint-enable quotes */
| test/unit/modules/compiler/codegen.spec.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.0004946152912452817,
0.00018801177793648094,
0.00016162468818947673,
0.00016873300774022937,
0.0000612519434071146
] |
{
"id": 7,
"code_window": [
" new Vue({\n",
" render (h) {\n",
" return h('div', [this.a])\n",
" }\n",
" }).$mount()\n",
" expect(`Property or method \"a\" is not defined`).toHaveBeenWarned()\n",
" })\n",
" })\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(`Property or method \"a\" is not defined`).not.toHaveBeenWarned()\n"
],
"file_path": "test/unit/features/instance/render-proxy.spec.js",
"type": "replace",
"edit_start_line_idx": 17
} | /* not type checking this file because flow doesn't play well with Proxy */
import { warn, makeMap } from '../util/index'
let hasProxy, proxyHandlers, initProxy
if (process.env.NODE_ENV !== 'production') {
const allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
)
const warnNonPresent = (target, key) => {
warn(
`Property or method "${key}" is not defined on the instance but ` +
`referenced during render. Make sure to declare reactive data ` +
`properties in the data option.`,
target
)
}
hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/)
proxyHandlers = {
has (target, key) {
const has = key in target
const isAllowed = allowedGlobals(key) || key.charAt(0) === '_'
if (!has && !isAllowed) {
warnNonPresent(target, key)
}
return has || !isAllowed
},
get (target, key) {
if (typeof key === 'string' && !(key in target)) {
warnNonPresent(target, key)
}
return target[key]
}
}
initProxy = function initProxy (vm) {
if (hasProxy) {
vm._renderProxy = new Proxy(vm, proxyHandlers)
} else {
vm._renderProxy = vm
}
}
}
export { initProxy }
| src/core/instance/proxy.js | 1 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.0005690904217772186,
0.00023559243709314615,
0.00016583925753366202,
0.00016888965910766274,
0.00014917549560777843
] |
{
"id": 7,
"code_window": [
" new Vue({\n",
" render (h) {\n",
" return h('div', [this.a])\n",
" }\n",
" }).$mount()\n",
" expect(`Property or method \"a\" is not defined`).toHaveBeenWarned()\n",
" })\n",
" })\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(`Property or method \"a\" is not defined`).not.toHaveBeenWarned()\n"
],
"file_path": "test/unit/features/instance/render-proxy.spec.js",
"type": "replace",
"edit_start_line_idx": 17
} | import Vue from 'vue'
describe('Options parent', () => {
it('should work', () => {
const parent = new Vue({}).$mount()
const child = new Vue({
parent: parent
}).$mount()
// this option is straight-forward
// it should register 'parent' as a $parent for 'child'
// and push 'child' to $children array on 'parent'
expect(child.$options.parent).toBeDefined()
expect(child.$options.parent).toEqual(parent)
expect(child.$parent).toBeDefined()
expect(child.$parent).toEqual(parent)
expect(parent.$children).toContain(child)
// destroy 'child' and check if it was removed from 'parent' $children
child.$destroy()
expect(parent.$children.length).toEqual(0)
parent.$destroy()
})
})
| test/unit/features/options/parent.spec.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.003574817208573222,
0.0013083461672067642,
0.000173918844666332,
0.00017630246293265373,
0.0016026373486965895
] |
{
"id": 7,
"code_window": [
" new Vue({\n",
" render (h) {\n",
" return h('div', [this.a])\n",
" }\n",
" }).$mount()\n",
" expect(`Property or method \"a\" is not defined`).toHaveBeenWarned()\n",
" })\n",
" })\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(`Property or method \"a\" is not defined`).not.toHaveBeenWarned()\n"
],
"file_path": "test/unit/features/instance/render-proxy.spec.js",
"type": "replace",
"edit_start_line_idx": 17
} | <!--
Please make sure to read the Pull Request Guidelines:
https://github.com/vuejs/vue/blob/dev/.github/CONTRIBUTING.md#pull-request-guidelines
-->
| .github/PULL_REQUEST_TEMPLATE.md | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.00016487762331962585,
0.00016487762331962585,
0.00016487762331962585,
0.00016487762331962585,
0
] |
{
"id": 7,
"code_window": [
" new Vue({\n",
" render (h) {\n",
" return h('div', [this.a])\n",
" }\n",
" }).$mount()\n",
" expect(`Property or method \"a\" is not defined`).toHaveBeenWarned()\n",
" })\n",
" })\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(`Property or method \"a\" is not defined`).not.toHaveBeenWarned()\n"
],
"file_path": "test/unit/features/instance/render-proxy.spec.js",
"type": "replace",
"edit_start_line_idx": 17
} | // Full spec-compliant TodoMVC with localStorage persistence
// and hash-based routing in ~150 lines.
// localStorage persistence
var STORAGE_KEY = 'todos-vuejs-2.0'
var todoStorage = {
fetch: function () {
var todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
todos.forEach(function (todo, index) {
todo.id = index
})
todoStorage.uid = todos.length
return todos
},
save: function (todos) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(todos))
}
}
// visibility filters
var filters = {
all: function (todos) {
return todos
},
active: function (todos) {
return todos.filter(function (todo) {
return !todo.completed
})
},
completed: function (todos) {
return todos.filter(function (todo) {
return todo.completed
})
}
}
// app Vue instance
var app = new Vue({
// app initial state
data: {
todos: todoStorage.fetch(),
newTodo: '',
editedTodo: null,
visibility: 'all'
},
// watch todos change for localStorage persistence
watch: {
todos: {
handler: function (todos) {
todoStorage.save(todos)
},
deep: true
}
},
// computed properties
// https://vuejs.org/guide/computed.html
computed: {
filteredTodos: function () {
return filters[this.visibility](this.todos)
},
remaining: function () {
return filters.active(this.todos).length
},
allDone: {
get: function () {
return this.remaining === 0
},
set: function (value) {
this.todos.forEach(function (todo) {
todo.completed = value
})
}
}
},
filters: {
pluralize: function (n) {
return n === 1 ? 'item' : 'items'
}
},
// methods that implement data logic.
// note there's no DOM manipulation here at all.
methods: {
addTodo: function () {
var value = this.newTodo && this.newTodo.trim()
if (!value) {
return
}
this.todos.push({
id: todoStorage.uid++,
title: value,
completed: false
})
this.newTodo = ''
},
removeTodo: function (todo) {
this.todos.splice(this.todos.indexOf(todo), 1)
},
editTodo: function (todo) {
this.beforeEditCache = todo.title
this.editedTodo = todo
},
doneEdit: function (todo) {
if (!this.editedTodo) {
return
}
this.editedTodo = null
todo.title = todo.title.trim()
if (!todo.title) {
this.removeTodo(todo)
}
},
cancelEdit: function (todo) {
this.editedTodo = null
todo.title = this.beforeEditCache
},
removeCompleted: function () {
this.todos = filters.active(this.todos)
}
},
// a custom directive to wait for the DOM to be updated
// before focusing on the input field.
// https://vuejs.org/guide/custom-directive.html
directives: {
'todo-focus': function (el, value) {
if (value) {
el.focus()
}
}
}
})
// handle routing
function onHashChange () {
var visibility = window.location.hash.replace(/#\/?/, '')
if (filters[visibility]) {
app.visibility = visibility
} else {
window.location.hash = ''
app.visibility = 'all'
}
}
window.addEventListener('hashchange', onHashChange)
onHashChange()
// mount
app.$mount('.todoapp')
| examples/todomvc/app.js | 0 | https://github.com/vuejs/vue/commit/b2b9d1c2729c13e80feadebf9664f78914417129 | [
0.016549088060855865,
0.0011963433353230357,
0.0001663834846112877,
0.00017332148854620755,
0.003964063245803118
] |
{
"id": 0,
"code_window": [
"import { serviceWorkerPlugin } from './serverPluginServiceWorker'\n",
"import { htmlRewritePlugin } from './serverPluginHtml'\n",
"import { proxyPlugin } from './serverPluginProxy'\n",
"import { createCertificate } from '../utils/createCertificate'\n",
"import { envPlugin } from './serverPluginEnv'\n",
"export { rewriteImports } from './serverPluginModuleRewrite'\n",
"import { sourceMapPlugin, SourceMap } from './serverPluginSourceMap'\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { cachedRead } from '../utils'\n"
],
"file_path": "src/node/server/index.ts",
"type": "add",
"edit_start_line_idx": 22
} | import { ServerPlugin } from '.'
import {
tjsxRE,
transform,
resolveJsxOptions,
vueJsxPublicPath,
vueJsxFilePath
} from '../esbuildService'
import { readBody, cachedRead } from '../utils'
export const esbuildPlugin: ServerPlugin = ({ app, config }) => {
const jsxConfig = resolveJsxOptions(config.jsx)
app.use(async (ctx, next) => {
// intercept and return vue jsx helper import
if (ctx.path === vueJsxPublicPath) {
await cachedRead(ctx, vueJsxFilePath)
}
await next()
if (ctx.body && tjsxRE.test(ctx.path)) {
ctx.type = 'js'
const src = await readBody(ctx.body)
const { code, map } = await transform(
src!,
ctx.url,
jsxConfig,
config.jsx
)
ctx.body = code
if (map) {
ctx.map = JSON.parse(map)
}
}
})
}
| src/node/server/serverPluginEsbuild.ts | 1 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.00025433237897232175,
0.00021167493832763284,
0.00017223981558345258,
0.0002100637648254633,
0.00003880461008520797
] |
{
"id": 0,
"code_window": [
"import { serviceWorkerPlugin } from './serverPluginServiceWorker'\n",
"import { htmlRewritePlugin } from './serverPluginHtml'\n",
"import { proxyPlugin } from './serverPluginProxy'\n",
"import { createCertificate } from '../utils/createCertificate'\n",
"import { envPlugin } from './serverPluginEnv'\n",
"export { rewriteImports } from './serverPluginModuleRewrite'\n",
"import { sourceMapPlugin, SourceMap } from './serverPluginSourceMap'\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { cachedRead } from '../utils'\n"
],
"file_path": "src/node/server/index.ts",
"type": "add",
"edit_start_line_idx": 22
} | .sfc-style-at-import {
color: red;
}
| playground/css-@import/testCssAtImportFromStyle.css | 0 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.00017310271505266428,
0.00017310271505266428,
0.00017310271505266428,
0.00017310271505266428,
0
] |
{
"id": 0,
"code_window": [
"import { serviceWorkerPlugin } from './serverPluginServiceWorker'\n",
"import { htmlRewritePlugin } from './serverPluginHtml'\n",
"import { proxyPlugin } from './serverPluginProxy'\n",
"import { createCertificate } from '../utils/createCertificate'\n",
"import { envPlugin } from './serverPluginEnv'\n",
"export { rewriteImports } from './serverPluginModuleRewrite'\n",
"import { sourceMapPlugin, SourceMap } from './serverPluginSourceMap'\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { cachedRead } from '../utils'\n"
],
"file_path": "src/node/server/index.ts",
"type": "add",
"edit_start_line_idx": 22
} | import { ServerPlugin } from '.'
import { readBody, isImportRequest } from '../utils'
export const jsonPlugin: ServerPlugin = ({ app }) => {
app.use(async (ctx, next) => {
await next()
// handle .json imports
// note ctx.body could be null if upstream set status to 304
if (ctx.path.endsWith('.json') && isImportRequest(ctx) && ctx.body) {
ctx.type = 'js'
ctx.body = `export default ${await readBody(ctx.body)}`
}
})
}
| src/node/server/serverPluginJson.ts | 0 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.00020963068527635187,
0.000188873425940983,
0.00016811616660561413,
0.000188873425940983,
0.00002075725933536887
] |
{
"id": 0,
"code_window": [
"import { serviceWorkerPlugin } from './serverPluginServiceWorker'\n",
"import { htmlRewritePlugin } from './serverPluginHtml'\n",
"import { proxyPlugin } from './serverPluginProxy'\n",
"import { createCertificate } from '../utils/createCertificate'\n",
"import { envPlugin } from './serverPluginEnv'\n",
"export { rewriteImports } from './serverPluginModuleRewrite'\n",
"import { sourceMapPlugin, SourceMap } from './serverPluginSourceMap'\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { cachedRead } from '../utils'\n"
],
"file_path": "src/node/server/index.ts",
"type": "add",
"edit_start_line_idx": 22
} | .sfc-script-css-module-at-import {
color: green;
}
| playground/css-@import/imported.module.css | 0 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.00017316675803158432,
0.00017316675803158432,
0.00017316675803158432,
0.00017316675803158432,
0
] |
{
"id": 1,
"code_window": [
" server,\n",
" watcher,\n",
" resolver,\n",
" config\n",
" }\n",
"\n",
" // attach server context to koa context\n",
" app.use((ctx, next) => {\n",
" Object.assign(ctx, context)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" config,\n",
" read: cachedRead\n"
],
"file_path": "src/node/server/index.ts",
"type": "replace",
"edit_start_line_idx": 68
} | import qs from 'querystring'
import chalk from 'chalk'
import path from 'path'
import { Context, ServerPlugin } from '.'
import {
SFCBlock,
SFCDescriptor,
SFCTemplateBlock,
SFCStyleBlock,
SFCStyleCompileResults,
CompilerOptions,
SFCStyleCompileOptions
} from '@vue/compiler-sfc'
import { resolveCompiler, resolveVue } from '../utils/resolveVue'
import hash_sum from 'hash-sum'
import LRUCache from 'lru-cache'
import { debugHmr, importerMap, ensureMapEntry } from './serverPluginHmr'
import {
resolveFrom,
cachedRead,
cleanUrl,
watchFileIfOutOfRoot
} from '../utils'
import { transform } from '../esbuildService'
import { InternalResolver } from '../resolver'
import { seenUrls } from './serverPluginServeStatic'
import { codegenCss, compileCss, rewriteCssUrls } from '../utils/cssUtils'
import { parse } from '../utils/babelParse'
import MagicString from 'magic-string'
import { resolveImport } from './serverPluginModuleRewrite'
import { SourceMap, mergeSourceMap } from './serverPluginSourceMap'
const debug = require('debug')('vite:sfc')
const getEtag = require('etag')
export const srcImportMap = new Map()
interface CacheEntry {
descriptor?: SFCDescriptor
template?: ResultWithMap
script?: ResultWithMap
styles: SFCStyleCompileResults[]
customs: string[]
}
interface ResultWithMap {
code: string
map: SourceMap | null | undefined
}
export const vueCache = new LRUCache<string, CacheEntry>({
max: 65535
})
export const vuePlugin: ServerPlugin = ({
root,
app,
resolver,
watcher,
config
}) => {
const etagCacheCheck = (ctx: Context) => {
ctx.etag = getEtag(ctx.body)
// only add 304 tag check if not using service worker to cache user code
if (!config.serviceWorker) {
ctx.status =
seenUrls.has(ctx.url) && ctx.etag === ctx.get('If-None-Match')
? 304
: 200
seenUrls.add(ctx.url)
}
}
app.use(async (ctx, next) => {
if (!ctx.path.endsWith('.vue') && !ctx.vue) {
return next()
}
const query = ctx.query
const publicPath = ctx.path
let filePath = resolver.requestToFile(publicPath)
// upstream plugins could've already read the file
const descriptor = await parseSFC(root, filePath, ctx.body)
if (!descriptor) {
debug(`${ctx.url} - 404`)
ctx.status = 404
return
}
if (!query.type) {
// watch potentially out of root vue file since we do a custom read here
watchFileIfOutOfRoot(watcher, root, filePath)
if (descriptor.script && descriptor.script.src) {
filePath = await resolveSrcImport(
root,
descriptor.script,
ctx,
resolver
)
}
ctx.type = 'js'
const { code, map } = await compileSFCMain(
descriptor,
filePath,
publicPath
)
ctx.body = code
ctx.map = map
return etagCacheCheck(ctx)
}
if (query.type === 'template') {
const templateBlock = descriptor.template!
if (templateBlock.src) {
filePath = await resolveSrcImport(root, templateBlock, ctx, resolver)
}
ctx.type = 'js'
const { code, map } = compileSFCTemplate(
root,
templateBlock,
filePath,
publicPath,
descriptor.styles.some((s) => s.scoped),
config.vueCompilerOptions
)
ctx.body = code
ctx.map = map
return etagCacheCheck(ctx)
}
if (query.type === 'style') {
const index = Number(query.index)
const styleBlock = descriptor.styles[index]
if (styleBlock.src) {
filePath = await resolveSrcImport(root, styleBlock, ctx, resolver)
}
const id = hash_sum(publicPath)
const result = await compileSFCStyle(
root,
styleBlock,
index,
filePath,
publicPath,
config.cssPreprocessOptions
)
ctx.type = 'js'
ctx.body = codegenCss(`${id}-${index}`, result.code, result.modules)
return etagCacheCheck(ctx)
}
if (query.type === 'custom') {
const index = Number(query.index)
const customBlock = descriptor.customBlocks[index]
if (customBlock.src) {
filePath = await resolveSrcImport(root, customBlock, ctx, resolver)
}
const result = resolveCustomBlock(
customBlock,
index,
filePath,
publicPath
)
ctx.type = 'js'
ctx.body = result
return etagCacheCheck(ctx)
}
})
const handleVueReload = (watcher.handleVueReload = async (
filePath: string,
timestamp: number = Date.now(),
content?: string
) => {
const publicPath = resolver.fileToRequest(filePath)
const cacheEntry = vueCache.get(filePath)
const { send } = watcher
debugHmr(`busting Vue cache for ${filePath}`)
vueCache.del(filePath)
const descriptor = await parseSFC(root, filePath, content)
if (!descriptor) {
// read failed
return
}
const prevDescriptor = cacheEntry && cacheEntry.descriptor
if (!prevDescriptor) {
// the file has never been accessed yet
debugHmr(`no existing descriptor found for ${filePath}`)
return
}
// check which part of the file changed
let needRerender = false
const sendReload = () => {
send({
type: 'vue-reload',
path: publicPath,
timestamp
})
console.log(
chalk.green(`[vite:hmr] `) +
`${path.relative(root, filePath)} updated. (reload)`
)
}
if (!isEqualBlock(descriptor.script, prevDescriptor.script)) {
return sendReload()
}
if (!isEqualBlock(descriptor.template, prevDescriptor.template)) {
needRerender = true
}
let didUpdateStyle = false
const styleId = hash_sum(publicPath)
const prevStyles = prevDescriptor.styles || []
const nextStyles = descriptor.styles || []
// css modules update causes a reload because the $style object is changed
// and it may be used in JS. It also needs to trigger a vue-style-update
// event so the client busts the sw cache.
if (
prevStyles.some((s) => s.module != null) ||
nextStyles.some((s) => s.module != null)
) {
return sendReload()
}
// force reload if scoped status has changed
if (prevStyles.some((s) => s.scoped) !== nextStyles.some((s) => s.scoped)) {
return sendReload()
}
// only need to update styles if not reloading, since reload forces
// style updates as well.
nextStyles.forEach((_, i) => {
if (!prevStyles[i] || !isEqualBlock(prevStyles[i], nextStyles[i])) {
didUpdateStyle = true
send({
type: 'style-update',
path: `${publicPath}?type=style&index=${i}`,
timestamp
})
}
})
// stale styles always need to be removed
prevStyles.slice(nextStyles.length).forEach((_, i) => {
didUpdateStyle = true
send({
type: 'style-remove',
path: publicPath,
id: `${styleId}-${i + nextStyles.length}`,
timestamp
})
})
const prevCustoms = prevDescriptor.customBlocks || []
const nextCustoms = descriptor.customBlocks || []
// custom blocks update causes a reload
// because the custom block contents is changed and it may be used in JS.
if (
nextCustoms.some(
(_, i) =>
!prevCustoms[i] || !isEqualBlock(prevCustoms[i], nextCustoms[i])
)
) {
return sendReload()
}
if (needRerender) {
send({
type: 'vue-rerender',
path: publicPath,
timestamp
})
}
let updateType = []
if (needRerender) {
updateType.push(`template`)
}
if (didUpdateStyle) {
updateType.push(`style`)
}
if (updateType.length) {
console.log(
chalk.green(`[vite:hmr] `) +
`${path.relative(root, filePath)} updated. (${updateType.join(
' & '
)})`
)
}
})
watcher.on('change', (file) => {
if (file.endsWith('.vue')) {
handleVueReload(file)
}
})
}
function isEqualBlock(a: SFCBlock | null, b: SFCBlock | null) {
if (!a && !b) return true
if (!a || !b) return false
// src imports will trigger their own updates
if (a.src && b.src && a.src === b.src) return true
if (a.content !== b.content) return false
const keysA = Object.keys(a.attrs)
const keysB = Object.keys(b.attrs)
if (keysA.length !== keysB.length) {
return false
}
return keysA.every((key) => a.attrs[key] === b.attrs[key])
}
async function resolveSrcImport(
root: string,
block: SFCBlock,
ctx: Context,
resolver: InternalResolver
) {
const importer = ctx.path
const importee = cleanUrl(resolveImport(root, importer, block.src!, resolver))
const filePath = resolver.requestToFile(importee)
await cachedRead(ctx, filePath)
block.content = (ctx.body as Buffer).toString()
// register HMR import relationship
debugHmr(` ${importer} imports ${importee}`)
ensureMapEntry(importerMap, importee).add(ctx.path)
srcImportMap.set(filePath, ctx.url)
return filePath
}
async function parseSFC(
root: string,
filePath: string,
content?: string | Buffer
): Promise<SFCDescriptor | undefined> {
let cached = vueCache.get(filePath)
if (cached && cached.descriptor) {
debug(`${filePath} parse cache hit`)
return cached.descriptor
}
if (!content) {
try {
content = await cachedRead(null, filePath)
} catch (e) {
return
}
}
if (typeof content !== 'string') {
content = content.toString()
}
const start = Date.now()
const { parse, generateCodeFrame } = resolveCompiler(root)
const { descriptor, errors } = parse(content, {
filename: filePath,
sourceMap: true
})
if (errors.length) {
console.error(chalk.red(`\n[vite] SFC parse error: `))
errors.forEach((e) => {
const locString = e.loc
? `:${e.loc.start.line}:${e.loc.start.column}`
: ``
console.error(chalk.underline(filePath + locString))
console.error(chalk.yellow(e.message))
if (e.loc) {
console.error(
generateCodeFrame(
content as string,
e.loc.start.offset,
e.loc.end.offset
) + `\n`
)
}
})
}
cached = cached || { styles: [], customs: [] }
cached.descriptor = descriptor
vueCache.set(filePath, cached)
debug(`${filePath} parsed in ${Date.now() - start}ms.`)
return descriptor
}
const defaultExportRE = /((?:^|\n|;)\s*)export default/
async function compileSFCMain(
descriptor: SFCDescriptor,
filePath: string,
publicPath: string
): Promise<ResultWithMap> {
let cached = vueCache.get(filePath)
if (cached && cached.script) {
return cached.script
}
const id = hash_sum(publicPath)
let code = ``
if (descriptor.script) {
let content = descriptor.script.content
if (descriptor.script.lang === 'ts') {
const { code, map } = await transform(content, publicPath, {
loader: 'ts'
})
content = code
descriptor.script.map = mergeSourceMap(
descriptor.script.map as SourceMap,
JSON.parse(map!)
) as SourceMap & { version: string }
}
// rewrite export default.
// fast path: simple regex replacement to avoid full-blown babel parse.
let replaced = content.replace(defaultExportRE, '$1const __script =')
// if the script somehow still contains `default export`, it probably has
// multi-line comments or template strings. fallback to a full parse.
if (defaultExportRE.test(replaced)) {
replaced = rewriteDefaultExport(content)
}
code += replaced
} else {
code += `const __script = {}`
}
let hasScoped = false
let hasCSSModules = false
if (descriptor.styles) {
descriptor.styles.forEach((s, i) => {
const styleRequest = publicPath + `?type=style&index=${i}`
if (s.scoped) hasScoped = true
if (s.module) {
if (!hasCSSModules) {
code += `\nconst __cssModules = __script.__cssModules = {}`
hasCSSModules = true
}
const styleVar = `__style${i}`
const moduleName = typeof s.module === 'string' ? s.module : '$style'
code += `\nimport ${styleVar} from ${JSON.stringify(
styleRequest + '&module'
)}`
code += `\n__cssModules[${JSON.stringify(moduleName)}] = ${styleVar}`
} else {
code += `\nimport ${JSON.stringify(styleRequest)}`
}
})
if (hasScoped) {
code += `\n__script.__scopeId = "data-v-${id}"`
}
}
if (descriptor.customBlocks) {
descriptor.customBlocks.forEach((c, i) => {
const attrsQuery = attrsToQuery(c.attrs, c.lang)
const blockTypeQuery = `&blockType=${qs.escape(c.type)}`
let customRequest =
publicPath + `?type=custom&index=${i}${blockTypeQuery}${attrsQuery}`
const customVar = `block${i}`
code += `\nimport ${customVar} from ${JSON.stringify(customRequest)}\n`
code += `if (typeof ${customVar} === 'function') ${customVar}(__script)\n`
})
}
if (descriptor.template) {
const templateRequest = publicPath + `?type=template`
code += `\nimport { render as __render } from ${JSON.stringify(
templateRequest
)}`
code += `\n__script.render = __render`
}
code += `\n__script.__hmrId = ${JSON.stringify(publicPath)}`
code += `\n__script.__file = ${JSON.stringify(filePath)}`
code += `\nexport default __script`
const result: ResultWithMap = {
code,
map: descriptor.script && (descriptor.script.map as SourceMap)
}
cached = cached || { styles: [], customs: [] }
cached.script = result
vueCache.set(filePath, cached)
return result
}
function compileSFCTemplate(
root: string,
template: SFCTemplateBlock,
filePath: string,
publicPath: string,
scoped: boolean,
userOptions: CompilerOptions | undefined
): ResultWithMap {
let cached = vueCache.get(filePath)
if (cached && cached.template) {
debug(`${publicPath} template cache hit`)
return cached.template
}
const start = Date.now()
const { compileTemplate, generateCodeFrame } = resolveCompiler(root)
const { code, map, errors } = compileTemplate({
source: template.content,
filename: filePath,
inMap: template.map,
transformAssetUrls: {
base: path.posix.dirname(publicPath)
},
compilerOptions: {
...userOptions,
scopeId: scoped ? `data-v-${hash_sum(publicPath)}` : null,
runtimeModuleName: resolveVue(root).isLocal
? // in local mode, vue would have been optimized so must be referenced
// with .js postfix
'/@modules/vue.js'
: '/@modules/vue'
},
preprocessLang: template.lang,
preprocessCustomRequire: (id: string) => require(resolveFrom(root, id))
})
if (errors.length) {
console.error(chalk.red(`\n[vite] SFC template compilation error: `))
errors.forEach((e) => {
if (typeof e === 'string') {
console.error(e)
} else {
const locString = e.loc
? `:${e.loc.start.line}:${e.loc.start.column}`
: ``
console.error(chalk.underline(filePath + locString))
console.error(chalk.yellow(e.message))
if (e.loc) {
const original = template.map!.sourcesContent![0]
console.error(
generateCodeFrame(original, e.loc.start.offset, e.loc.end.offset) +
`\n`
)
}
}
})
}
const result = {
code,
map: map as SourceMap
}
cached = cached || { styles: [], customs: [] }
cached.template = result
vueCache.set(filePath, cached)
debug(`${publicPath} template compiled in ${Date.now() - start}ms.`)
return result
}
async function compileSFCStyle(
root: string,
style: SFCStyleBlock,
index: number,
filePath: string,
publicPath: string,
preprocessOptions: SFCStyleCompileOptions['preprocessOptions']
): Promise<SFCStyleCompileResults> {
let cached = vueCache.get(filePath)
const cachedEntry = cached && cached.styles && cached.styles[index]
if (cachedEntry) {
debug(`${publicPath} style cache hit`)
return cachedEntry
}
const start = Date.now()
const { generateCodeFrame } = resolveCompiler(root)
const result = (await compileCss(root, publicPath, {
source: style.content,
filename: filePath + `?type=style&index=${index}`,
id: ``, // will be computed in compileCss
scoped: style.scoped != null,
modules: style.module != null,
preprocessLang: style.lang as SFCStyleCompileOptions['preprocessLang'],
preprocessOptions
})) as SFCStyleCompileResults
if (result.errors.length) {
console.error(chalk.red(`\n[vite] SFC style compilation error: `))
result.errors.forEach((e: any) => {
if (typeof e === 'string') {
console.error(e)
} else {
const lineOffset = style.loc.start.line - 1
if (e.line && e.column) {
console.log(
chalk.underline(`${filePath}:${e.line + lineOffset}:${e.column}`)
)
} else {
console.log(chalk.underline(filePath))
}
const filePathRE = new RegExp(
'.*' +
path.basename(filePath).replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&') +
'(:\\d+:\\d+:\\s*)?'
)
const cleanMsg = e.message.replace(filePathRE, '')
console.error(chalk.yellow(cleanMsg))
if (e.line && e.column && cleanMsg.split(/\n/g).length === 1) {
const original = style.map!.sourcesContent![0]
const offset =
original
.split(/\r?\n/g)
.slice(0, e.line + lineOffset - 1)
.map((l) => l.length)
.reduce((total, l) => total + l + 1, 0) +
e.column -
1
console.error(generateCodeFrame(original, offset, offset + 1)) + `\n`
}
}
})
}
result.code = await rewriteCssUrls(result.code, publicPath)
cached = cached || { styles: [], customs: [] }
cached.styles[index] = result
vueCache.set(filePath, cached)
debug(`${publicPath} style compiled in ${Date.now() - start}ms`)
return result
}
function resolveCustomBlock(
custom: SFCBlock,
index: number,
filePath: string,
publicPath: string
): string {
let cached = vueCache.get(filePath)
const cachedEntry = cached && cached.customs && cached.customs[index]
if (cachedEntry) {
debug(`${publicPath} custom block cache hit`)
return cachedEntry
}
const result = custom.content
cached = cached || { styles: [], customs: [] }
cached.customs[index] = result
vueCache.set(filePath, cached)
return result
}
// these are built-in query parameters so should be ignored
// if the user happen to add them as attrs
const ignoreList = ['id', 'index', 'src', 'type']
function attrsToQuery(attrs: SFCBlock['attrs'], langFallback?: string): string {
let query = ``
for (const name in attrs) {
const value = attrs[name]
if (!ignoreList.includes(name)) {
query += `&${qs.escape(name)}=${value ? qs.escape(String(value)) : ``}`
}
}
if (langFallback && !(`lang` in attrs)) {
query += `&lang=${langFallback}`
}
return query
}
function rewriteDefaultExport(code: string): string {
const s = new MagicString(code)
const ast = parse(code)
ast.forEach((node) => {
if (node.type === 'ExportDefaultDeclaration') {
s.overwrite(node.start!, node.declaration.start!, `const __script = `)
}
})
const ret = s.toString()
return ret
}
| src/node/server/serverPluginVue.ts | 1 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.962982714176178,
0.02780963107943535,
0.0001662580471020192,
0.0001750304945744574,
0.1596011221408844
] |
{
"id": 1,
"code_window": [
" server,\n",
" watcher,\n",
" resolver,\n",
" config\n",
" }\n",
"\n",
" // attach server context to koa context\n",
" app.use((ctx, next) => {\n",
" Object.assign(ctx, context)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" config,\n",
" read: cachedRead\n"
],
"file_path": "src/node/server/index.ts",
"type": "replace",
"edit_start_line_idx": 68
} | const fs = require('fs-extra')
const path = require('path')
const execa = require('execa')
const puppeteer = require('puppeteer')
const moment = require('moment')
jest.setTimeout(100000)
const timeout = (n) => new Promise((r) => setTimeout(r, n))
const binPath = path.resolve(__dirname, '../bin/vite.js')
const fixtureDir = path.join(__dirname, '../playground')
const tempDir = path.join(__dirname, '../temp')
let devServer
let browser
let page
const browserLogs = []
const serverLogs = []
const getEl = async (selectorOrEl) => {
return typeof selectorOrEl === 'string'
? await page.$(selectorOrEl)
: selectorOrEl
}
const getText = async (selectorOrEl) => {
const el = await getEl(selectorOrEl)
return el ? el.evaluate((el) => el.textContent) : null
}
const getComputedColor = async (selectorOrEl) => {
return (await getEl(selectorOrEl)).evaluate(
(el) => getComputedStyle(el).color
)
}
beforeAll(async () => {
try {
await fs.remove(tempDir)
} catch (e) {}
await fs.copy(fixtureDir, tempDir, {
filter: (file) => !/dist|node_modules/.test(file)
})
await execa('yarn', { cwd: tempDir })
await execa('yarn', { cwd: path.join(tempDir, 'optimize-linked') })
})
afterAll(async () => {
try {
await fs.remove(tempDir)
} catch (e) {}
if (browser) await browser.close()
if (devServer) {
devServer.kill('SIGTERM', {
forceKillAfterTimeout: 2000
})
}
// console.log(browserLogs)
// console.log(serverLogs)
})
describe('vite', () => {
beforeAll(async () => {
browser = await puppeteer.launch(
process.env.CI
? { args: ['--no-sandbox', '--disable-setuid-sandbox'] }
: {}
)
})
function declareTests(isBuild) {
test('should render', async () => {
expect(await getText('h1')).toMatch('Vite Playground')
})
test('should generate correct asset paths', async () => {
const has404 = browserLogs.some((msg) => msg.match('404'))
if (has404) {
console.log(browserLogs)
}
expect(has404).toBe(false)
})
test('asset import from js', async () => {
expect(await getText('.asset-import')).toMatch(
isBuild
? // hashed in production
/\/_assets\/testAssets\.([\w\d]+)\.png$/
: // only resolved to absolute in dev
'/testAssets.png'
)
})
test('env variables', async () => {
const mode = isBuild ? 'production' : 'development'
expect(await getText('.base')).toMatch(`BASE_URL: /`)
expect(await getText('.mode')).toMatch(`MODE: ${mode}`)
expect(await getText('.dev')).toMatch(`DEV: ${!isBuild}`)
expect(await getText('.prod')).toMatch(`PROD: ${isBuild}`)
expect(await getText('.custom-env-variable')).toMatch(
'VITE_CUSTOM_ENV_VARIABLE: 9527'
)
expect(await getText('.effective-mode-file-name')).toMatch(
`VITE_EFFECTIVE_MODE_FILE_NAME: ${
isBuild ? `.env.production` : `.env.development`
}`
)
expect(await getText('.node-env')).toMatch(`NODE_ENV: ${mode}`)
})
test('module resolving', async () => {
expect(await getText('.module-resolve-router')).toMatch('ok')
expect(await getText('.module-resolve-store')).toMatch('ok')
expect(await getText('.module-resolve-optimize')).toMatch('ok')
expect(await getText('.index-resolve')).toMatch('ok')
expect(await getText('.dot-resolve')).toMatch('ok')
expect(await getText('.browser-field-resolve')).toMatch('ok')
expect(await getText('.css-entry-resolve')).toMatch('ok')
})
if (!isBuild) {
test('hmr (vue re-render)', async () => {
const button = await page.$('.hmr-increment')
await button.click()
expect(await getText(button)).toMatch('>>> 1 <<<')
await updateFile('TestHmr/TestHmr.vue', (content) =>
content.replace('{{ count }}', 'count is {{ count }}')
)
// note: using the same button to ensure the component did only re-render
// if it's a reload, it would have replaced the button with a new one.
await expectByPolling(() => getText(button), 'count is 1')
})
test('hmr (vue reload)', async () => {
await updateFile('TestHmr/TestHmr.vue', (content) =>
content.replace('count: 0,', 'count: 1337,')
)
await expectByPolling(() => getText('.hmr-increment'), 'count is 1337')
})
test('hmr (js -> vue propagation)', async () => {
const span = await page.$('.hmr-propagation')
expect(await getText(span)).toBe('1')
await updateFile('TestHmr/testHmrPropagation.js', (content) =>
content.replace('return 1', 'return 666')
)
await expectByPolling(() => getText('.hmr-propagation'), '666')
})
test('hmr (js -> vue propagation. dynamic import, static-analyzable)', async () => {
let span = await page.$('.hmr-propagation-dynamic')
expect(await getText(span)).toBe('bar not loaded')
// trigger the dynamic import
let button = await page.$('.hmr-propagation-dynamic-load')
await button.click()
expect(await getText(span)).toBe('bar loading')
await expectByPolling(() => getText(span), 'bar loaded')
// update souce code
await updateFile(
'TestHmr/testHmrPropagationDynamicImport.js',
(content) => content.replace('bar loaded', 'bar updated')
)
// the update trigger the reload of TestHmr component
// all states in it are lost
await expectByPolling(
() => getText('.hmr-propagation-dynamic'),
'bar not loaded'
)
span = await page.$('.hmr-propagation-dynamic')
button = await page.$('.hmr-propagation-dynamic-load')
await button.click()
expect(await getText(span)).toBe('bar loading')
await expectByPolling(() => getText(span), 'bar updated')
})
test('hmr (js -> vue propagation. full dynamic import, non-static-analyzable)', async () => {
let span = await page.$('.hmr-propagation-full-dynamic')
expect(await getText(span)).toBe('baz not loaded')
// trigger the dynamic import
let button = await page.$('.hmr-propagation-full-dynamic-load')
await button.click()
expect(await getText(span)).toBe('baz loading')
await expectByPolling(() => getText(span), 'baz loaded')
// update souce code
await updateFile(
'TestHmr/testHmrPropagationFullDynamicImport.js',
(content) => content.replace('baz loaded', 'baz updated')
)
// the update doesn't trigger hmr
// because it is a non-static-analyzable dynamic import
// and the imported file is not self-accepting
await timeout(200)
expect(await getText('.hmr-propagation-full-dynamic')).toBe(
'baz loaded'
)
// only if we reload the whole page, we can see the new content
await page.reload({ waitUntil: ['networkidle0', 'domcontentloaded'] })
span = await page.$('.hmr-propagation-full-dynamic')
expect(await getText(span)).toBe('baz not loaded')
// trigger the dynamic import
button = await page.$('.hmr-propagation-full-dynamic-load')
await button.click()
expect(await getText(span)).toBe('baz loading')
await expectByPolling(() => getText(span), 'baz updated')
})
test('hmr (js -> vue propagation. full dynamic import, non-static-analyzable, but self-accepting)', async () => {
// reset the sate
await page.reload({ waitUntil: ['networkidle0', 'domcontentloaded'] })
let stateIncrementButton = await page.$('.hmr-increment')
await stateIncrementButton.click()
expect(await getText(stateIncrementButton)).toMatch(
'>>> count is 1338 <<<'
)
let span = await page.$('.hmr-propagation-full-dynamic-self-accepting')
expect(await getText(span)).toBe('qux not loaded')
// trigger the dynamic import
let button = await page.$(
'.hmr-propagation-full-dynamic-load-self-accepting'
)
await button.click()
expect(await getText(span)).toBe('qux loading')
await expectByPolling(() => getText(span), 'qux loaded')
// update souce code
await updateFile(
'TestHmr/testHmrPropagationFullDynamicImportSelfAccepting.js',
(content) => content.replace('qux loaded', 'qux updated')
)
// the update is accepted by the imported file
await expectByPolling(() => getText(span), 'qux updated')
// the state should be the same
// because the TestHmr component is not reloaded
stateIncrementButton = await page.$('.hmr-increment')
expect(await getText(stateIncrementButton)).toMatch(
'>>> count is 1338 <<<'
)
})
test('hmr (manual API, self accepting)', async () => {
await updateFile('testHmrManual.js', (content) =>
content.replace('foo = 1', 'foo = 2')
)
await expectByPolling(
() => browserLogs[browserLogs.length - 1],
'js module hot updated: /testHmrManual.js'
)
expect(
browserLogs.slice(browserLogs.length - 4, browserLogs.length - 1)
).toEqual([
`foo was: 1`,
`(self-accepting)1.foo is now: 2`,
`(self-accepting)2.foo is now: 2`
])
})
test('hmr (manual API, accepting deps)', async () => {
browserLogs.length = 0
await updateFile('testHmrManualDep.js', (content) =>
content.replace('foo = 1', 'foo = 2')
)
await expectByPolling(
() => browserLogs[browserLogs.length - 1],
'js module hot updated: /testHmrManual.js'
)
expect(
browserLogs.slice(browserLogs.length - 8, browserLogs.length - 1)
).toEqual([
// dispose for both dep and self
`foo was: 2`,
`(dep) foo was: 1`,
`(dep) foo from dispose: 10`,
// self callbacks
`(self-accepting)1.foo is now: 2`,
`(self-accepting)2.foo is now: 2`,
// dep callbacks
`(single dep) foo is now: 2`,
`(multiple deps) foo is now: 2`
])
})
}
test('CSS import w/ PostCSS', async () => {
const el = await page.$('.postcss-from-css')
expect(await getComputedColor(el)).toBe('rgb(255, 0, 0)')
// hmr
if (!isBuild) {
await updateFile('testPostCss.css', (content) =>
content.replace('red', 'green')
)
await expectByPolling(() => getComputedColor(el), 'rgb(0, 128, 0)')
}
})
test('SFC <style> w/ PostCSS', async () => {
const el = await page.$('.postcss-from-sfc')
expect(await getComputedColor(el)).toBe('rgb(0, 128, 0)')
// hmr
if (!isBuild) {
await updateFile('TestPostCss.vue', (content) =>
content.replace('color: green;', 'color: red;')
)
await expectByPolling(() => getComputedColor(el), 'rgb(255, 0, 0)')
}
})
test('SFC <style scoped>', async () => {
const el = await page.$('.style-scoped')
expect(await getComputedColor(el)).toBe('rgb(138, 43, 226)')
if (!isBuild) {
await updateFile('TestScopedCss.vue', (content) =>
content.replace('rgb(138, 43, 226)', 'rgb(0, 0, 0)')
)
await expectByPolling(() => getComputedColor(el), 'rgb(0, 0, 0)')
}
})
test('SFC <style module>', async () => {
const el = await page.$('.css-modules-sfc')
expect(await getComputedColor(el)).toBe('rgb(0, 0, 255)')
if (!isBuild) {
await updateFile('TestCssModules.vue', (content) =>
content.replace('color: blue;', 'color: rgb(0, 0, 0);')
)
// css module results in component reload so must use fresh selector
await expectByPolling(
() => getComputedColor('.css-modules-sfc'),
'rgb(0, 0, 0)'
)
}
})
test('CSS @import', async () => {
const el = await page.$('.script-at-import')
expect(await getComputedColor(el)).toBe('rgb(0, 128, 0)')
if (!isBuild) {
await updateFile('css-@import/imported.css', (content) =>
content.replace('green', 'rgb(0, 0, 0)')
)
await expectByPolling(() => getComputedColor(el), 'rgb(0, 0, 0)')
}
})
test('SFC <style> w/ @import', async () => {
const el = await page.$('.sfc-style-at-import')
expect(await getComputedColor(el)).toBe('rgb(255, 0, 0)')
if (!isBuild) {
await updateFile(
'css-@import/testCssAtImportFromStyle.css',
(content) => content.replace('red', 'rgb(0, 0, 0)')
)
await expectByPolling(() => getComputedColor(el), 'rgb(0, 0, 0)')
}
})
test('CSS module @import', async () => {
const el = await page.$('.sfc-script-css-module-at-import')
expect(await getComputedColor(el)).toBe('rgb(0, 128, 0)')
if (!isBuild) {
await updateFile('css-@import/imported.module.css', (content) =>
content.replace('green', 'rgb(0, 0, 0)')
)
await expectByPolling(
() => getComputedColor('.sfc-script-css-module-at-import'),
'rgb(0, 0, 0)'
)
}
})
test('SFC <style module> w/ @import', async () => {
const el = await page.$('.sfc-style-css-module-at-import')
expect(await getComputedColor(el)).toBe('rgb(255, 0, 0)')
if (!isBuild) {
await updateFile(
'css-@import/testCssModuleAtImportFromStyle.module.css',
(content) => content.replace('red', 'rgb(0, 0, 0)')
)
await expectByPolling(() => getComputedColor(el), 'rgb(0, 0, 0)')
}
})
test('import *.module.css', async () => {
const el = await page.$('.css-modules-import')
expect(await getComputedColor(el)).toBe('rgb(255, 140, 0)')
if (!isBuild) {
await updateFile('testCssModules.module.css', (content) =>
content.replace('rgb(255, 140, 0)', 'rgb(0, 0, 1)')
)
// css module results in component reload so must use fresh selector
await expectByPolling(
() => getComputedColor('.css-modules-import'),
'rgb(0, 0, 1)'
)
}
})
test('pre-processors', async () => {
expect(await getText('.pug')).toMatch('template lang="pug"')
expect(await getComputedColor('.pug')).toBe('rgb(255, 0, 255)')
if (!isBuild) {
await updateFile('TestPreprocessors.vue', (c) =>
c.replace('$color: magenta', '$color: black')
)
await expectByPolling(() => getComputedColor('.pug'), 'rgb(0, 0, 0)')
await updateFile('TestPreprocessors.vue', (c) =>
c.replace('rendered from', 'pug with hmr')
)
await expectByPolling(() => getText('.pug'), 'pug with hmr')
}
})
test('SFC src imports', async () => {
expect(await getText('.src-imports-script')).toMatch('src="./script.ts"')
const el = await getEl('.src-imports-style')
expect(await getComputedColor(el)).toBe('rgb(119, 136, 153)')
if (!isBuild) {
// test style first, should not reload the component
await updateFile('src-import/style.css', (c) =>
c.replace('rgb(119, 136, 153)', 'rgb(0, 0, 0)')
)
await expectByPolling(() => getComputedColor(el), 'rgb(0, 0, 0)')
// script
await updateFile('src-import/script.ts', (c) =>
c.replace('hello', 'bye')
)
await expectByPolling(() => getText('.src-imports-script'), 'bye from')
// template
await updateFile('src-import/template.html', (c) =>
c.replace('{{ msg }}', '{{ msg }} changed')
)
await expectByPolling(() => getText('.src-imports-script'), 'changed')
}
})
test('json', async () => {
expect(await getText('.json')).toMatch('this is json')
if (!isBuild) {
await updateFile('testJsonImport.json', (c) =>
c.replace('this is json', 'with hmr')
)
await expectByPolling(() => getText('.json'), 'with hmr')
}
})
test('typescript', async () => {
expect(await getText('.ts-self')).toMatch('from ts')
expect(await getText('.ts-import')).toMatch('1')
if (!isBuild) {
await updateFile('ts/TestTs.vue', (c) =>
c.replace(`m: string = 'from ts'`, `m: number = 123`)
)
await expectByPolling(() => getText('.ts-self'), '123')
await updateFile('ts/testTs.ts', (c) =>
c.replace(`n: number = 1`, `n: number = 2`)
)
await expectByPolling(() => getText('.ts-import'), '2')
}
})
test('jsx', async () => {
const text = await getText('.jsx-root')
expect(text).toMatch('from Preact JSX')
expect(text).toMatch('from Preact TSX')
expect(text).toMatch('count is 1337')
if (!isBuild) {
await updateFile('testJsx.jsx', (c) => c.replace('1337', '2046'))
await expectByPolling(() => getText('.jsx-root'), '2046')
}
})
test('alias', async () => {
expect(await getText('.alias')).toMatch('alias works')
expect(await getText('.dir-alias')).toMatch('directory alias works')
expect(await getText('.dir-alias-index')).toMatch(
'directory alias index works'
)
expect(await getText('.dir-alias-import-outside')).toMatch(
'directory aliased internal import outside works'
)
if (!isBuild) {
await updateFile('aliased/index.js', (c) =>
c.replace('works', 'hmr works')
)
await expectByPolling(() => getText('.alias'), 'alias hmr works')
await updateFile('aliased-dir/named.js', (c) =>
c.replace('works', 'hmr works')
)
await expectByPolling(
() => getText('.dir-alias'),
'directory alias hmr works'
)
await updateFile('aliased-dir/index.js', (c) =>
c.replace('works', 'hmr works')
)
await expectByPolling(
() => getText('.dir-alias-index'),
'directory alias index hmr works'
)
await updateFile('aliased-dir-import.js', (c) =>
c.replace('works', 'hmr works')
)
await expectByPolling(
() => getText('.dir-alias-import-outside'),
'directory aliased internal import outside hmr works'
)
}
})
test('transforms', async () => {
const el = await getEl('.transform-scss')
expect(await getComputedColor(el)).toBe('rgb(0, 255, 255)')
expect(await getText('.transform-js')).toBe('2')
if (!isBuild) {
await updateFile('testTransform.scss', (c) =>
c.replace('cyan', 'rgb(0, 0, 0)')
)
await expectByPolling(() => getComputedColor(el), 'rgb(0, 0, 0)')
await updateFile('testTransform.js', (c) => c.replace('= 1', '= 2'))
await expectByPolling(() => getText('.transform-js'), '3')
}
})
test('async component', async () => {
await expectByPolling(() => getText('.async'), 'should show up')
expect(await getComputedColor('.async')).toBe('rgb(139, 69, 19)')
})
test('rewrite import in optimized deps', async () => {
expect(await getText('.test-rewrite-in-optimized')).toMatch(
moment(1590231082886).format('MMMM Do YYYY, h:mm:ss a')
)
})
test('rewrite import in unoptimized deps', async () => {
expect(await getText('.test-rewrite-in-unoptimized')).toMatch('123')
})
test('monorepo support', async () => {
// linked dep + optimizing linked dep
expect(await getText(`.optimize-linked`)).toMatch(`ok`)
if (!isBuild) {
// test hmr in linked dep
await updateFile(`optimize-linked/index.js`, (c) =>
c.replace(`foo()`, `123`)
)
await expectByPolling(() => getText(`.optimize-linked`), 'error')
}
})
test('SFC custom blocks', async () => {
expect(await getText('.custom-block')).toBe('hello,vite!')
if (!isBuild) {
await updateFile('custom-blocks/TestCustomBlocks.vue', (c) =>
c.replace('hello,vite!', 'hi,vite!')
)
await expectByPolling(() => getText('.custom-block'), 'hi,vite!')
await updateFile('custom-blocks/TestCustomBlocks.vue', (c) =>
c.replace(`useI18n('en')`, `useI18n('ja')`)
)
await expectByPolling(() => getText('.custom-block'), 'こんにちは')
}
})
test('normalize publicPath', async () => {
expect(await getText('.normalize-public-path')).toMatch(
JSON.stringify([2, 4])
)
})
test('dynamic imports with variable interpolation', async () => {
expect(await getText(`.dynamic-import-one`)).toMatch(`One`)
expect(await getText(`.dynamic-import-two`)).toMatch(`Two`)
})
}
// test build first since we are going to edit the fixtures when testing dev
// no need to run build tests when testing service worker mode since it's
// dev only
if (!process.env.USE_SW) {
describe('build', () => {
let staticServer
beforeAll(async () => {
console.log('building...')
const buildOutput = await execa(binPath, ['build'], {
cwd: tempDir
})
expect(buildOutput.stdout).toMatch('Build completed')
expect(buildOutput.stderr).toBe('')
console.log('build complete. running build tests...')
})
afterAll(() => {
console.log('build test done.')
if (staticServer) staticServer.close()
})
describe('assertions', () => {
beforeAll(async () => {
// start a static file server
const app = new (require('koa'))()
app.use(require('koa-static')(path.join(tempDir, 'dist')))
staticServer = require('http').createServer(app.callback())
await new Promise((r) => staticServer.listen(3001, r))
page = await browser.newPage()
await page.goto('http://localhost:3001')
})
declareTests(true)
})
test('css codesplit in async chunks', async () => {
const colorToMatch = /#8B4513/i // from TestAsync.vue
const files = await fs.readdir(path.join(tempDir, 'dist/_assets'))
const cssFile = files.find((f) => f.endsWith('.css'))
const css = await fs.readFile(
path.join(tempDir, 'dist/_assets', cssFile),
'utf-8'
)
// should be extracted from the main css file
expect(css).not.toMatch(colorToMatch)
// should be inside the split chunk file
const asyncChunk = files.find(
(f) => f.startsWith('TestAsync') && f.endsWith('.js')
)
const code = await fs.readFile(
path.join(tempDir, 'dist/_assets', asyncChunk),
'utf-8'
)
// should be inside the async chunk
expect(code).toMatch(colorToMatch)
})
})
}
describe('dev', () => {
beforeAll(async () => {
browserLogs.length = 0
console.log('starting dev server...')
// start dev server
devServer = execa(binPath, {
cwd: tempDir
})
await new Promise((resolve) => {
devServer.stdout.on('data', (data) => {
serverLogs.push(data.toString())
if (data.toString().match('running')) {
console.log('dev server running.')
resolve()
}
})
})
console.log('launching browser')
page = await browser.newPage()
page.on('console', (msg) => {
browserLogs.push(msg.text())
})
await page.goto('http://localhost:3000')
})
declareTests(false)
test('hmr (index.html full-reload)', async () => {
expect(await getText('title')).toMatch('Vite App')
// hmr
const reload = page.waitForNavigation({
waitUntil: 'domcontentloaded'
})
await updateFile('index.html', (content) =>
content.replace('Vite App', 'Vite App Test')
)
await reload
await expectByPolling(() => getText('title'), 'Vite App Test')
})
test('hmr (html full-reload)', async () => {
await page.goto('http://localhost:3000/test.html')
expect(await getText('title')).toMatch('Vite App')
// hmr
const reload = page.waitForNavigation({
waitUntil: 'domcontentloaded'
})
await updateFile('test.html', (content) =>
content.replace('Vite App', 'Vite App Test')
)
await reload
await expectByPolling(() => getText('title'), 'Vite App Test')
})
// Assert that all edited files are reflected on page reload
// i.e. service-worker cache is correctly busted
test('sw cache busting', async () => {
await page.reload()
expect(await getText('.hmr-increment')).toMatch('>>> count is 1337 <<<')
expect(await getText('.hmr-propagation')).toMatch('666')
expect(await getComputedColor('.postcss-from-css')).toBe('rgb(0, 128, 0)')
expect(await getComputedColor('.postcss-from-sfc')).toBe('rgb(255, 0, 0)')
expect(await getComputedColor('.style-scoped')).toBe('rgb(0, 0, 0)')
expect(await getComputedColor('.css-modules-sfc')).toBe('rgb(0, 0, 0)')
expect(await getComputedColor('.css-modules-import')).toBe('rgb(0, 0, 1)')
expect(await getComputedColor('.pug')).toBe('rgb(0, 0, 0)')
expect(await getText('.pug')).toMatch('pug with hmr')
expect(await getComputedColor('.src-imports-style')).toBe('rgb(0, 0, 0)')
expect(await getText('.src-imports-script')).toMatch('bye from')
expect(await getText('.src-imports-script')).toMatch('changed')
expect(await getText('.jsx-root')).toMatch('2046')
expect(await getText('.alias')).toMatch('alias hmr works')
expect(await getComputedColor('.transform-scss')).toBe('rgb(0, 0, 0)')
expect(await getText('.transform-js')).toMatch('3')
expect(await getText('.json')).toMatch('with hmr')
// ensure import graph is still working
await updateFile('testJsonImport.json', (c) =>
c.replace('with hmr', 'with sw reload')
)
await expectByPolling(() => getText('.json'), 'with sw reload')
})
})
})
async function updateFile(file, replacer) {
const compPath = path.join(tempDir, file)
const content = await fs.readFile(compPath, 'utf-8')
await fs.writeFile(compPath, replacer(content))
}
// poll until it updates
async function expectByPolling(poll, expected) {
const maxTries = 20
for (let tries = 0; tries < maxTries; tries++) {
const actual = (await poll()) || ''
if (actual.indexOf(expected) > -1 || tries === maxTries - 1) {
expect(actual).toMatch(expected)
break
} else {
await timeout(50)
}
}
}
| test/test.js | 0 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.0028721634298563004,
0.00021030072821304202,
0.00016762524319346994,
0.00017462208052165806,
0.0003094439744018018
] |
{
"id": 1,
"code_window": [
" server,\n",
" watcher,\n",
" resolver,\n",
" config\n",
" }\n",
"\n",
" // attach server context to koa context\n",
" app.use((ctx, next) => {\n",
" Object.assign(ctx, context)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" config,\n",
" read: cachedRead\n"
],
"file_path": "src/node/server/index.ts",
"type": "replace",
"edit_start_line_idx": 68
} | import { ServerPlugin } from '.'
export const envPublicPath = '/vite/env'
export const envPlugin: ServerPlugin = ({ app, config }) => {
const mode = config.mode || 'development'
const env = JSON.stringify({
...config.env,
BASE_URL: '/',
MODE: mode,
DEV: mode === 'development',
PROD: mode === 'production'
})
app.use((ctx, next) => {
if (ctx.path === envPublicPath) {
ctx.type = 'js'
ctx.body = `export default ${env}`
return
}
return next()
})
}
| src/node/server/serverPluginEnv.ts | 0 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.001839414588175714,
0.0007687818724662066,
0.00022511047427542508,
0.00024182068591471761,
0.0007570823654532433
] |
{
"id": 1,
"code_window": [
" server,\n",
" watcher,\n",
" resolver,\n",
" config\n",
" }\n",
"\n",
" // attach server context to koa context\n",
" app.use((ctx, next) => {\n",
" Object.assign(ctx, context)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" config,\n",
" read: cachedRead\n"
],
"file_path": "src/node/server/index.ts",
"type": "replace",
"edit_start_line_idx": 68
} | VITE_CUSTOM_ENV_VARIABLE=9527
VITE_EFFECTIVE_MODE_FILE_NAME=.env
| playground/.env | 0 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.00016792728274594992,
0.00016792728274594992,
0.00016792728274594992,
0.00016792728274594992,
0
] |
{
"id": 2,
"code_window": [
" transform,\n",
" resolveJsxOptions,\n",
" vueJsxPublicPath,\n",
" vueJsxFilePath\n",
"} from '../esbuildService'\n",
"import { readBody, cachedRead } from '../utils'\n",
"\n",
"export const esbuildPlugin: ServerPlugin = ({ app, config }) => {\n",
" const jsxConfig = resolveJsxOptions(config.jsx)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { readBody } from '../utils'\n"
],
"file_path": "src/node/server/serverPluginEsbuild.ts",
"type": "replace",
"edit_start_line_idx": 8
} | import path from 'path'
import chalk from 'chalk'
import fs from 'fs-extra'
import { ServerPlugin } from '.'
import { resolveVue, cachedRead } from '../utils'
import { URL } from 'url'
import { resolveOptimizedModule, resolveNodeModuleFile } from '../resolver'
const debug = require('debug')('vite:resolve')
export const moduleIdToFileMap = new Map()
export const moduleFileToIdMap = new Map()
export const moduleRE = /^\/@modules\//
const getDebugPath = (root: string, p: string) => {
const relative = path.relative(root, p)
return relative.startsWith('..') ? p : relative
}
// plugin for resolving /@modules/:id requests.
export const moduleResolvePlugin: ServerPlugin = ({ root, app, resolver }) => {
const vueResolved = resolveVue(root)
app.use(async (ctx, next) => {
if (!moduleRE.test(ctx.path)) {
return next()
}
// path maybe contain encode chars
const id = decodeURIComponent(ctx.path.replace(moduleRE, ''))
ctx.type = 'js'
const serve = async (id: string, file: string, type: string) => {
moduleIdToFileMap.set(id, file)
moduleFileToIdMap.set(file, ctx.path)
debug(`(${type}) ${id} -> ${getDebugPath(root, file)}`)
await cachedRead(ctx, file)
return next()
}
// special handling for vue runtime in case it's not installed
if (!vueResolved.isLocal && id in vueResolved) {
return serve(id, (vueResolved as any)[id], 'non-local vue')
}
// already resolved and cached
const cachedPath = moduleIdToFileMap.get(id)
if (cachedPath) {
return serve(id, cachedPath, 'cached')
}
// resolve from vite optimized modules
const optimized = resolveOptimizedModule(root, id)
if (optimized) {
return serve(id, optimized, 'optimized')
}
const referer = ctx.get('referer')
let importer: string | undefined
// this is a map file request from browser dev tool
const isMapFile = ctx.path.endsWith('.map')
if (referer) {
importer = new URL(referer).pathname
} else if (isMapFile) {
// for some reason Chrome doesn't provide referer for source map requests.
// do our best to reverse-infer the importer.
importer = ctx.path.replace(/\.map$/, '')
}
const importerFilePath = importer ? resolver.requestToFile(importer) : root
const nodeModulePath = resolveNodeModuleFile(importerFilePath, id)
if (nodeModulePath) {
return serve(id, nodeModulePath, 'node_modules')
}
if (isMapFile && importer) {
// the resolveNodeModuleFile doesn't work with linked pkg
// our last try: infer from the dir of importer
const inferMapPath = path.join(
path.dirname(importerFilePath),
path.basename(ctx.path)
)
if (fs.existsSync(inferMapPath)) {
return serve(id, inferMapPath, 'map file in linked pkg')
}
}
console.error(
chalk.red(
`[vite] Failed to resolve module import "${id}". ` +
`(imported by ${importer || 'unknown'})`
)
)
ctx.status = 404
})
}
| src/node/server/serverPluginModuleResolve.ts | 1 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.0058379401452839375,
0.0008674783748574555,
0.00016514022718183696,
0.00017365852545481175,
0.0016764061292633414
] |
{
"id": 2,
"code_window": [
" transform,\n",
" resolveJsxOptions,\n",
" vueJsxPublicPath,\n",
" vueJsxFilePath\n",
"} from '../esbuildService'\n",
"import { readBody, cachedRead } from '../utils'\n",
"\n",
"export const esbuildPlugin: ServerPlugin = ({ app, config }) => {\n",
" const jsxConfig = resolveJsxOptions(config.jsx)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { readBody } from '../utils'\n"
],
"file_path": "src/node/server/serverPluginEsbuild.ts",
"type": "replace",
"edit_start_line_idx": 8
} | declare interface ImportMeta {
env: Record<string, string>
}
| src/client/env.d.ts | 0 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.0001741475280141458,
0.0001741475280141458,
0.0001741475280141458,
0.0001741475280141458,
0
] |
{
"id": 2,
"code_window": [
" transform,\n",
" resolveJsxOptions,\n",
" vueJsxPublicPath,\n",
" vueJsxFilePath\n",
"} from '../esbuildService'\n",
"import { readBody, cachedRead } from '../utils'\n",
"\n",
"export const esbuildPlugin: ServerPlugin = ({ app, config }) => {\n",
" const jsxConfig = resolveJsxOptions(config.jsx)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { readBody } from '../utils'\n"
],
"file_path": "src/node/server/serverPluginEsbuild.ts",
"type": "replace",
"edit_start_line_idx": 8
} | <h2>SFC Src Imports</h2>
<div class="src-imports-script">{{ msg }}</div>
<div class="src-imports-style">This should be light gray</div>
| playground/src-import/template.html | 0 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.00017439010844100267,
0.00017439010844100267,
0.00017439010844100267,
0.00017439010844100267,
0
] |
{
"id": 2,
"code_window": [
" transform,\n",
" resolveJsxOptions,\n",
" vueJsxPublicPath,\n",
" vueJsxFilePath\n",
"} from '../esbuildService'\n",
"import { readBody, cachedRead } from '../utils'\n",
"\n",
"export const esbuildPlugin: ServerPlugin = ({ app, config }) => {\n",
" const jsxConfig = resolveJsxOptions(config.jsx)\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { readBody } from '../utils'\n"
],
"file_path": "src/node/server/serverPluginEsbuild.ts",
"type": "replace",
"edit_start_line_idx": 8
} | ---
name: Bug report
about: Create a report to help us improve
title: ''
labels: 'bug: pending triage'
assignees: ''
---
<!--
Before you continue...
If you just upgraded Vite and suddenly everything stops working, try opening the Network tab in your browser devtools, tick "disable cache" and refresh the page.
-->
> Do NOT ignore this template or your issue will have a very high chance to be closed without comment.
## Describe the bug
A clear and concise description of what the bug is.
## Reproduction
Please provide a link to a repo that can reproduce the problem you ran into.
A reproduction is **required** unless you are absolutely sure that the the problem is obvious and the information you provided is enough for us to understand what the problem is. If a report has only vague description (e.g. just a generic error message) and has no reproduction, it will be closed immediately.
## System Info
- **required** `vite` version:
- **required** Operating System:
- **required** Node version:
- Optional:
- npm/yarn version
- Installed `vue` version (from `yarn.lock` or `package-lock.json`)
- Installed `@vue/compiler-sfc` version
## Logs (Optional if provided reproduction)
1. Run `vite` or `vite build` with the `--debug` flag.
2. Provide the error log here.
| .github/ISSUE_TEMPLATE/bug_report.md | 0 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.0001760921295499429,
0.00017304709763266146,
0.00016903560026548803,
0.0001739266444928944,
0.0000023631707790627843
] |
{
"id": 3,
"code_window": [
" const jsxConfig = resolveJsxOptions(config.jsx)\n",
"\n",
" app.use(async (ctx, next) => {\n",
" // intercept and return vue jsx helper import\n",
" if (ctx.path === vueJsxPublicPath) {\n",
" await cachedRead(ctx, vueJsxFilePath)\n",
" }\n",
"\n",
" await next()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await ctx.read(ctx, vueJsxFilePath)\n"
],
"file_path": "src/node/server/serverPluginEsbuild.ts",
"type": "replace",
"edit_start_line_idx": 16
} | import { ServerPlugin } from '.'
import {
tjsxRE,
transform,
resolveJsxOptions,
vueJsxPublicPath,
vueJsxFilePath
} from '../esbuildService'
import { readBody, cachedRead } from '../utils'
export const esbuildPlugin: ServerPlugin = ({ app, config }) => {
const jsxConfig = resolveJsxOptions(config.jsx)
app.use(async (ctx, next) => {
// intercept and return vue jsx helper import
if (ctx.path === vueJsxPublicPath) {
await cachedRead(ctx, vueJsxFilePath)
}
await next()
if (ctx.body && tjsxRE.test(ctx.path)) {
ctx.type = 'js'
const src = await readBody(ctx.body)
const { code, map } = await transform(
src!,
ctx.url,
jsxConfig,
config.jsx
)
ctx.body = code
if (map) {
ctx.map = JSON.parse(map)
}
}
})
}
| src/node/server/serverPluginEsbuild.ts | 1 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.9982560276985168,
0.4999755024909973,
0.00016670745390001684,
0.5007396936416626,
0.49718335270881653
] |
{
"id": 3,
"code_window": [
" const jsxConfig = resolveJsxOptions(config.jsx)\n",
"\n",
" app.use(async (ctx, next) => {\n",
" // intercept and return vue jsx helper import\n",
" if (ctx.path === vueJsxPublicPath) {\n",
" await cachedRead(ctx, vueJsxFilePath)\n",
" }\n",
"\n",
" await next()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await ctx.read(ctx, vueJsxFilePath)\n"
],
"file_path": "src/node/server/serverPluginEsbuild.ts",
"type": "replace",
"edit_start_line_idx": 16
} | ---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
| .github/ISSUE_TEMPLATE/feature_request.md | 0 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.0001728668576106429,
0.00017180507711600512,
0.00016978381609078497,
0.0001727645139908418,
0.0000014298476571639185
] |
{
"id": 3,
"code_window": [
" const jsxConfig = resolveJsxOptions(config.jsx)\n",
"\n",
" app.use(async (ctx, next) => {\n",
" // intercept and return vue jsx helper import\n",
" if (ctx.path === vueJsxPublicPath) {\n",
" await cachedRead(ctx, vueJsxFilePath)\n",
" }\n",
"\n",
" await next()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await ctx.read(ctx, vueJsxFilePath)\n"
],
"file_path": "src/node/server/serverPluginEsbuild.ts",
"type": "replace",
"edit_start_line_idx": 16
} | import { util } from './util'
export default util
| playground/rewrite-optimized/test-package/index.js | 0 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.00016819794836919755,
0.00016819794836919755,
0.00016819794836919755,
0.00016819794836919755,
0
] |
{
"id": 3,
"code_window": [
" const jsxConfig = resolveJsxOptions(config.jsx)\n",
"\n",
" app.use(async (ctx, next) => {\n",
" // intercept and return vue jsx helper import\n",
" if (ctx.path === vueJsxPublicPath) {\n",
" await cachedRead(ctx, vueJsxFilePath)\n",
" }\n",
"\n",
" await next()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" await ctx.read(ctx, vueJsxFilePath)\n"
],
"file_path": "src/node/server/serverPluginEsbuild.ts",
"type": "replace",
"edit_start_line_idx": 16
} | import fs from 'fs-extra'
import path from 'path'
import slash from 'slash'
import {
cleanUrl,
resolveFrom,
queryRE,
lookupFile,
parseNodeModuleId
} from './utils'
import {
moduleRE,
moduleIdToFileMap,
moduleFileToIdMap
} from './server/serverPluginModuleResolve'
import { resolveOptimizedCacheDir } from './optimizer'
import { hmrClientPublicPath } from './server/serverPluginHmr'
import chalk from 'chalk'
const debug = require('debug')('vite:resolve')
export interface Resolver {
requestToFile?(publicPath: string, root: string): string | undefined
fileToRequest?(filePath: string, root: string): string | undefined
alias?: ((id: string) => string | undefined) | Record<string, string>
}
export interface InternalResolver {
requestToFile(publicPath: string): string
fileToRequest(filePath: string): string
normalizePublicPath(publicPath: string): string
alias(id: string): string | undefined
resolveRelativeRequest(
publicPath: string,
relativePublicPath: string
): { pathname: string; query: string }
}
export const supportedExts = ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json']
export const mainFields = ['module', 'jsnext', 'jsnext:main', 'browser', 'main']
const defaultRequestToFile = (publicPath: string, root: string): string => {
if (moduleRE.test(publicPath)) {
const id = publicPath.replace(moduleRE, '')
const cachedNodeModule = moduleIdToFileMap.get(id)
if (cachedNodeModule) {
return cachedNodeModule
}
// try to resolve from optimized modules
const optimizedModule = resolveOptimizedModule(root, id)
if (optimizedModule) {
return optimizedModule
}
// try to resolve from normal node_modules
const nodeModule = resolveNodeModuleFile(root, id)
if (nodeModule) {
moduleIdToFileMap.set(id, nodeModule)
return nodeModule
}
}
const publicDirPath = path.join(root, 'public', publicPath.slice(1))
if (fs.existsSync(publicDirPath)) {
return publicDirPath
}
return path.join(root, publicPath.slice(1))
}
const defaultFileToRequest = (filePath: string, root: string): string => {
const moduleRequest = moduleFileToIdMap.get(filePath)
if (moduleRequest) {
return moduleRequest
}
return `/${slash(path.relative(root, filePath))}`
}
const isFile = (file: string): boolean => {
try {
return fs.statSync(file).isFile()
} catch (e) {
return false
}
}
/**
* this function resolve fuzzy file path. examples:
* /path/file is a fuzzy file path for /path/file.tsx
* /path/dir is a fuzzy file path for /path/dir/index.js
*
* returning undefined indicates the filePath is not fuzzy:
* it is already an exact file path, or it can't match any file
*/
const resolveFilePathPostfix = (filePath: string): string | undefined => {
const cleanPath = cleanUrl(filePath)
if (!isFile(cleanPath)) {
let postfix = ''
for (const ext of supportedExts) {
if (isFile(cleanPath + ext)) {
postfix = ext
break
}
if (isFile(path.join(cleanPath, '/index' + ext))) {
postfix = '/index' + ext
break
}
}
const queryMatch = filePath.match(/\?.*$/)
const query = queryMatch ? queryMatch[0] : ''
const resolved = cleanPath + postfix + query
if (resolved !== filePath) {
debug(`(postfix) ${filePath} -> ${resolved}`)
return postfix
}
}
}
const isDir = (p: string) => fs.existsSync(p) && fs.statSync(p).isDirectory()
export function createResolver(
root: string,
resolvers: Resolver[] = [],
userAlias: Record<string, string> = {}
): InternalResolver {
resolvers = [...resolvers]
const literalAlias: Record<string, string> = {}
const literalDirAlias: Record<string, string> = {}
const resolveAlias = (alias: Record<string, string>) => {
for (const key in alias) {
let target = alias[key]
// aliasing a directory
if (key.startsWith('/') && key.endsWith('/') && path.isAbsolute(target)) {
// check first if this is aliasing to a path from root
const fromRoot = path.join(root, target)
if (isDir(fromRoot)) {
target = fromRoot
} else if (!isDir(target)) {
continue
}
resolvers.push({
requestToFile(publicPath) {
if (publicPath.startsWith(key)) {
return path.join(target, publicPath.slice(key.length))
}
},
fileToRequest(filePath) {
if (filePath.startsWith(target)) {
return slash(key + path.relative(target, filePath))
}
}
})
literalDirAlias[key] = target
} else {
literalAlias[key] = target
}
}
}
resolvers.forEach((r) => {
if (r.alias && typeof r.alias === 'object') {
resolveAlias(r.alias)
}
})
resolveAlias(userAlias)
const requestToFileCache = new Map<string, string>()
const fileToRequestCache = new Map<string, string>()
const resolver: InternalResolver = {
requestToFile(publicPath) {
if (requestToFileCache.has(publicPath)) {
return requestToFileCache.get(publicPath)!
}
let resolved: string | undefined
for (const r of resolvers) {
const filepath = r.requestToFile && r.requestToFile(publicPath, root)
if (filepath) {
resolved = filepath
break
}
}
if (!resolved) {
resolved = defaultRequestToFile(publicPath, root)
}
const postfix = resolveFilePathPostfix(resolved)
if (postfix) {
if (postfix[0] === '/') {
resolved = path.join(resolved, postfix)
} else {
resolved += postfix
}
}
requestToFileCache.set(publicPath, resolved)
return resolved
},
fileToRequest(filePath) {
if (fileToRequestCache.has(filePath)) {
return fileToRequestCache.get(filePath)!
}
for (const r of resolvers) {
const request = r.fileToRequest && r.fileToRequest(filePath, root)
if (request) return request
}
const res = defaultFileToRequest(filePath, root)
fileToRequestCache.set(filePath, res)
return res
},
/**
* Given a fuzzy public path, resolve missing extensions and /index.xxx
*/
normalizePublicPath(publicPath) {
if (publicPath === hmrClientPublicPath) {
return publicPath
}
// preserve query
const queryMatch = publicPath.match(/\?.*$/)
const query = queryMatch ? queryMatch[0] : ''
const cleanPublicPath = cleanUrl(publicPath)
const finalize = (result: string) => {
result += query
if (
resolver.requestToFile(result) !== resolver.requestToFile(publicPath)
) {
throw new Error(
`[vite] normalizePublicPath check fail. please report to vite.`
)
}
return result
}
if (!moduleRE.test(cleanPublicPath)) {
return finalize(
resolver.fileToRequest(resolver.requestToFile(cleanPublicPath))
)
}
const filePath = resolver.requestToFile(cleanPublicPath)
const cacheDir = resolveOptimizedCacheDir(root)
if (cacheDir) {
const relative = path.relative(cacheDir, filePath)
if (!relative.startsWith('..')) {
return finalize(path.posix.join('/@modules/', slash(relative)))
}
}
// fileToRequest doesn't work with files in node_modules
// because of edge cases like symlinks or yarn-aliased-install
// or even aliased-symlinks
// example id: "@babel/runtime/helpers/esm/slicedToArray"
// see the test case: /playground/TestNormalizePublicPath.vue
const id = publicPath.replace(moduleRE, '')
const { scope, name, inPkgPath } = parseNodeModuleId(id)
if (!inPkgPath) return publicPath
let filePathPostFix = ''
let findPkgFrom = filePath
while (!filePathPostFix.startsWith(inPkgPath)) {
// some package contains multi package.json...
// for example: @babel/[email protected]/helpers/esm/package.json
const pkgPath = lookupFile(findPkgFrom, ['package.json'], true)
if (!pkgPath) {
throw new Error(
`[vite] can't find package.json for a node_module file: ` +
`"${publicPath}". something is wrong.`
)
}
filePathPostFix = slash(path.relative(path.dirname(pkgPath), filePath))
findPkgFrom = path.join(path.dirname(pkgPath), '../')
}
return finalize(
['/@modules', scope, name, filePathPostFix].filter(Boolean).join('/')
)
},
alias(id) {
let aliased: string | undefined = literalAlias[id]
if (aliased) {
return aliased
}
for (const r of resolvers) {
aliased =
r.alias && typeof r.alias === 'function' ? r.alias(id) : undefined
if (aliased) {
return aliased
}
}
},
resolveRelativeRequest(publicPath: string, relativePublicPath: string) {
let dirname = path.dirname(publicPath)
const filePath = resolver.requestToFile(publicPath)
for (const alias in literalDirAlias) {
if (publicPath.startsWith(alias)) {
const relativeFilePath = path.relative(
filePath,
literalDirAlias[alias]
)
if (!relativeFilePath.startsWith('..')) {
dirname = '/' + slash(relativeFilePath)
}
break
}
}
const resolved = slash(path.posix.resolve(dirname, relativePublicPath))
const queryMatch = relativePublicPath.match(queryRE)
return {
// path resovle strips ending / which should be preserved
pathname:
cleanUrl(resolved) + (relativePublicPath.endsWith('/') ? '/' : ''),
query: queryMatch ? queryMatch[0] : ''
}
}
}
return resolver
}
export const jsSrcRE = /\.(?:(?:j|t)sx?|vue)$|\.mjs$/
const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//
/**
* Redirects a bare module request to a full path under /@modules/
* It resolves a bare node module id to its full entry path so that relative
* imports from the entry can be correctly resolved.
* e.g.:
* - `import 'foo'` -> `import '/@modules/foo/dist/index.js'`
* - `import 'foo/bar/baz'` -> `import '/@modules/foo/bar/baz.js'`
*/
export function resolveBareModuleRequest(
root: string,
id: string,
importer: string,
resolver: InternalResolver
): string {
const optimized = resolveOptimizedModule(root, id)
if (optimized) {
// ensure optimized module requests always ends with `.js` - this is because
// optimized deps may import one another and in the built bundle their
// relative import paths ends with `.js`. If we don't append `.js` during
// rewrites, it may result in duplicated copies of the same dep.
return path.extname(id) === '.js' ? id : id + '.js'
}
let isEntry = false
const basedir = path.dirname(resolver.requestToFile(importer))
const pkgInfo = resolveNodeModule(basedir, id, resolver)
if (pkgInfo) {
if (!pkgInfo.entry) {
console.error(
chalk.yellow(
`[vite] dependency ${id} does not have default entry defined in ` +
`package.json.`
)
)
} else {
isEntry = true
id = pkgInfo.entry
}
}
if (!isEntry) {
const deepMatch = !isEntry && id.match(deepImportRE)
if (deepMatch) {
// deep import
const depId = deepMatch[1] || deepMatch[2]
// check if this is a deep import to an optimized dep.
if (resolveOptimizedModule(root, depId)) {
if (resolver.alias(depId) === id) {
// this is a deep import but aliased from a bare module id.
// redirect it the optimized copy.
return resolveBareModuleRequest(root, depId, importer, resolver)
}
// warn against deep imports to optimized dep
console.error(
chalk.yellow(
`\n[vite] Avoid deep import "${id}" (imported by ${importer})\n` +
`because "${depId}" has been pre-optimized by vite into a single file.\n` +
`Prefer importing directly from the module entry:\n` +
chalk.cyan(`\n import { ... } from "${depId}" \n\n`) +
`If the dependency requires deep import to function properly, \n` +
`add the deep path to ${chalk.cyan(
`optimizeDeps.include`
)} in vite.config.js.\n`
)
)
}
// resolve ext for deepImport
const filePath = resolveNodeModuleFile(root, id)
if (filePath) {
const deepPath = id.replace(deepImportRE, '')
const normalizedFilePath = slash(filePath)
const postfix = normalizedFilePath.slice(
normalizedFilePath.lastIndexOf(deepPath) + deepPath.length
)
id += postfix
}
}
}
// check and warn deep imports on optimized modules
const ext = path.extname(id)
if (!jsSrcRE.test(ext)) {
// append import query for non-js deep imports
return id + (queryRE.test(id) ? '&import' : '?import')
} else {
return id
}
}
const viteOptimizedMap = new Map()
export function resolveOptimizedModule(
root: string,
id: string
): string | undefined {
const cacheKey = `${root}#${id}`
const cached = viteOptimizedMap.get(cacheKey)
if (cached) {
return cached
}
const cacheDir = resolveOptimizedCacheDir(root)
if (!cacheDir) return
if (!path.extname(id)) id += '.js'
const file = path.join(cacheDir, id)
if (fs.existsSync(file) && fs.statSync(file).isFile()) {
viteOptimizedMap.set(cacheKey, file)
return file
}
}
interface NodeModuleInfo {
entry: string | undefined
entryFilePath: string | undefined
pkg: any
}
const nodeModulesInfoMap = new Map<string, NodeModuleInfo>()
const nodeModulesFileMap = new Map()
export function resolveNodeModule(
root: string,
id: string,
resolver: InternalResolver
): NodeModuleInfo | undefined {
const cacheKey = `${root}#${id}`
const cached = nodeModulesInfoMap.get(cacheKey)
if (cached) {
return cached
}
let pkgPath
try {
// see if the id is a valid package name
pkgPath = resolveFrom(root, `${id}/package.json`)
} catch (e) {
debug(`failed to resolve package.json for ${id}`)
}
if (pkgPath) {
// if yes, this is a entry import. resolve entry file
let pkg
try {
pkg = fs.readJSONSync(pkgPath)
} catch (e) {
return
}
let entryPoint: string | undefined
// TODO properly support conditinal exports
// https://nodejs.org/api/esm.html#esm_conditional_exports
// Note: this would require @rollup/plugin-node-resolve to support it too
// or we will have to implement that logic in vite's own resolve plugin.
if (!entryPoint) {
for (const field of mainFields) {
if (typeof pkg[field] === 'string') {
entryPoint = pkg[field]
break
}
}
}
// resolve object browser field in package.json
// https://github.com/defunctzombie/package-browser-field-spec
const browserField = pkg.browser
if (entryPoint && browserField && typeof browserField === 'object') {
entryPoint = mapWithBrowserField(entryPoint, browserField)
}
debug(`(node_module entry) ${id} -> ${entryPoint}`)
// save resolved entry file path using the deep import path as key
// e.g. foo/dist/foo.js
// this is the path raw imports will be rewritten to, and is what will
// be passed to resolveNodeModuleFile().
let entryFilePath: string | undefined
// respect user manual alias
const aliased = resolver.alias(id)
if (aliased && aliased !== id) {
entryFilePath = resolveNodeModuleFile(root, aliased)
}
if (!entryFilePath && entryPoint) {
// #284 some packages specify entry without extension...
entryFilePath = path.join(path.dirname(pkgPath), entryPoint!)
const postfix = resolveFilePathPostfix(entryFilePath)
if (postfix) {
entryPoint += postfix
entryFilePath += postfix
}
entryPoint = path.posix.join(id, entryPoint!)
// save the resolved file path now so we don't need to do it again in
// resolveNodeModuleFile()
nodeModulesFileMap.set(entryPoint, entryFilePath)
}
const result: NodeModuleInfo = {
entry: entryPoint!,
entryFilePath,
pkg
}
nodeModulesInfoMap.set(cacheKey, result)
return result
}
}
export function resolveNodeModuleFile(
root: string,
id: string
): string | undefined {
const cacheKey = `${root}#${id}`
const cached = nodeModulesFileMap.get(cacheKey)
if (cached) {
return cached
}
try {
const resolved = resolveFrom(root, id)
nodeModulesFileMap.set(cacheKey, resolved)
return resolved
} catch (e) {
// error will be reported downstream
}
}
const normalize = path.posix.normalize
/**
* given a relative path in pkg dir,
* return a relative path in pkg dir,
* mapped with the "map" object
*/
function mapWithBrowserField(
relativePathInPkgDir: string,
map: Record<string, string>
) {
const normalized = normalize(relativePathInPkgDir)
const foundEntry = Object.entries(map).find(([from]) => {
return normalize(from) === normalized
})
if (!foundEntry) {
return normalized
}
const [, to] = foundEntry
return normalize(to)
}
| src/node/resolver.ts | 0 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.0006026283372193575,
0.00018754207121673971,
0.0001634696964174509,
0.00017028684669639915,
0.00007006734813330695
] |
{
"id": 4,
"code_window": [
"import path from 'path'\n",
"import chalk from 'chalk'\n",
"import fs from 'fs-extra'\n",
"import { ServerPlugin } from '.'\n",
"import { resolveVue, cachedRead } from '../utils'\n",
"import { URL } from 'url'\n",
"import { resolveOptimizedModule, resolveNodeModuleFile } from '../resolver'\n",
"\n",
"const debug = require('debug')('vite:resolve')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { resolveVue } from '../utils'\n"
],
"file_path": "src/node/server/serverPluginModuleResolve.ts",
"type": "replace",
"edit_start_line_idx": 4
} | import fs from 'fs'
import path from 'path'
import { ServerPlugin } from '.'
import { isStaticAsset, cachedRead } from '../utils'
import chalk from 'chalk'
const send = require('koa-send')
const debug = require('debug')('vite:history')
export const seenUrls = new Set()
export const serveStaticPlugin: ServerPlugin = ({
root,
app,
resolver,
config,
watcher
}) => {
app.use(async (ctx, next) => {
// short circuit requests that have already been explicitly handled
if (ctx.body || ctx.status !== 404) {
return
}
// warn non-root references to assets under /public/
if (ctx.path.startsWith('/public/') && isStaticAsset(ctx.path)) {
console.error(
chalk.yellow(
`[vite] files in the public directory are served at the root path.\n` +
` ${chalk.blue(ctx.path)} should be changed to ${chalk.blue(
ctx.path.replace(/^\/public\//, '/')
)}.`
)
)
}
// handle possible user request -> file aliases
const expectsHtml =
ctx.headers.accept && ctx.headers.accept.includes('text/html')
if (!expectsHtml) {
const filePath = resolver.requestToFile(ctx.path)
if (
filePath !== ctx.path &&
fs.existsSync(filePath) &&
fs.statSync(filePath).isFile()
) {
await cachedRead(ctx, filePath)
}
}
return next()
})
if (!config.serviceWorker) {
app.use(async (ctx, next) => {
await next()
// the first request to the server should never 304
if (seenUrls.has(ctx.url) && ctx.fresh) {
ctx.status = 304
}
seenUrls.add(ctx.url)
})
}
app.use(require('koa-etag')())
app.use(require('koa-static')(root))
app.use(require('koa-static')(path.join(root, 'public')))
// history API fallback
app.use(async (ctx, next) => {
if (ctx.status !== 404) {
return next()
}
if (ctx.method !== 'GET') {
debug(`not redirecting ${ctx.url} (not GET)`)
return next()
}
const accept = ctx.headers && ctx.headers.accept
if (typeof accept !== 'string') {
debug(`not redirecting ${ctx.url} (no headers.accept)`)
return next()
}
if (accept.includes('application/json')) {
debug(`not redirecting ${ctx.url} (json)`)
return next()
}
if (!accept.includes('text/html')) {
debug(`not redirecting ${ctx.url} (not accepting html)`)
return next()
}
debug(`redirecting ${ctx.url} to /index.html`)
try {
await send(ctx, `index.html`, { root })
} catch (e) {
ctx.url = '/index.html'
ctx.status = 404
return next()
}
})
}
| src/node/server/serverPluginServeStatic.ts | 1 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.05063527449965477,
0.005321902222931385,
0.00016488910478074104,
0.0002663348859641701,
0.01437394693493843
] |
{
"id": 4,
"code_window": [
"import path from 'path'\n",
"import chalk from 'chalk'\n",
"import fs from 'fs-extra'\n",
"import { ServerPlugin } from '.'\n",
"import { resolveVue, cachedRead } from '../utils'\n",
"import { URL } from 'url'\n",
"import { resolveOptimizedModule, resolveNodeModuleFile } from '../resolver'\n",
"\n",
"const debug = require('debug')('vite:resolve')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { resolveVue } from '../utils'\n"
],
"file_path": "src/node/server/serverPluginModuleResolve.ts",
"type": "replace",
"edit_start_line_idx": 4
} | <template>
<h2>JSON</h2>
<pre class="json">Imported JSON: {{ json }}</pre>
</template>
<script>
import json from './testJsonImport.json'
export default {
data: () => ({ json })
}
</script>
| playground/TestJsonImport.vue | 0 | https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268 | [
0.00017413074965588748,
0.00017237599240615964,
0.0001706212351564318,
0.00017237599240615964,
0.0000017547572497278452
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.