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": 10,
"code_window": [
"\t\tpublic name: string,\n",
"\t\treference: number,\n",
"\t\tpublic expensive: boolean,\n",
"\t\tchildrenCount: number\n",
"\t) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tnamedVariables: number,\n",
"\t\tindexedVariables: number\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 339
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"corrupt.commands": "Eccezione imprevista durante l'esecuzione del comando."
} | i18n/ita/src/vs/editor/common/controller/cursor.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0001763914042385295,
0.0001763914042385295,
0.0001763914042385295,
0.0001763914042385295,
0
] |
{
"id": 10,
"code_window": [
"\t\tpublic name: string,\n",
"\t\treference: number,\n",
"\t\tpublic expensive: boolean,\n",
"\t\tchildrenCount: number\n",
"\t) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tnamedVariables: number,\n",
"\t\tindexedVariables: number\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 339
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import NLS = require('vs/nls');
import * as Objects from 'vs/base/common/objects';
import * as Platform from 'vs/base/common/platform';
import { IStringDictionary } from 'vs/base/common/collections';
import * as Types from 'vs/base/common/types';
import { ValidationStatus, ValidationState, ILogger, Parser, ISystemVariables } from 'vs/base/common/parsers';
/**
* Options to be passed to the external program or shell.
*/
export interface CommandOptions {
/**
* The current working directory of the executed program or shell.
* If omitted VSCode's current workspace root is used.
*/
cwd?: string;
/**
* The environment of the executed program or shell. If omitted
* the parent process' environment is used.
*/
env?: { [key:string]: string; };
}
export interface Executable {
/**
* The command to be executed. Can be an external program or a shell
* command.
*/
command: string;
/**
* Specifies whether the command is a shell command and therefore must
* be executed in a shell interpreter (e.g. cmd.exe, bash, ...).
*/
isShellCommand: boolean;
/**
* The arguments passed to the command.
*/
args: string[];
/**
* The command options used when the command is executed. Can be omitted.
*/
options?: CommandOptions;
}
export interface ForkOptions extends CommandOptions {
execArgv?: string[];
}
export enum Source {
stdout,
stderr
}
/**
* The data send via a success callback
*/
export interface SuccessData {
error?:Error;
cmdCode?:number;
terminated?:boolean;
}
/**
* The data send via a error callback
*/
export interface ErrorData {
error?:Error;
terminated?:boolean;
stdout?:string;
stderr?:string;
}
export interface TerminateResponse {
success: boolean;
error?: any;
}
export namespace Config {
/**
* Options to be passed to the external program or shell
*/
export interface CommandOptions {
/**
* The current working directory of the executed program or shell.
* If omitted VSCode's current workspace root is used.
*/
cwd?: string;
/**
* The additional environment of the executed program or shell. If omitted
* the parent process' environment is used.
*/
env?: IStringDictionary<string>;
/**
* Index signature
*/
[key:string]: string | string[] | IStringDictionary<string>;
}
export interface BaseExecutable {
/**
* The command to be executed. Can be an external program or a shell
* command.
*/
command?: string;
/**
* Specifies whether the command is a shell command and therefore must
* be executed in a shell interpreter (e.g. cmd.exe, bash, ...).
*
* Defaults to false if omitted.
*/
isShellCommand?: boolean;
/**
* The arguments passed to the command. Can be omitted.
*/
args?: string[];
/**
* The command options used when the command is executed. Can be omitted.
*/
options?: CommandOptions;
}
export interface Executable extends BaseExecutable {
/**
* Windows specific executable configuration
*/
windows?: BaseExecutable;
/**
* Mac specific executable configuration
*/
osx?: BaseExecutable;
/**
* Linux specific executable configuration
*/
linux?: BaseExecutable;
}
}
export interface ParserOptions {
globals?: Executable;
emptyCommand?: boolean;
noDefaults?: boolean;
}
export class ExecutableParser extends Parser {
constructor(logger: ILogger, validationStatus: ValidationStatus = new ValidationStatus()) {
super(logger, validationStatus);
}
public parse(json: Config.Executable, parserOptions: ParserOptions = { globals: null, emptyCommand: false, noDefaults: false }): Executable {
let result = this.parseExecutable(json, parserOptions.globals);
if (this.status.isFatal()) {
return result;
}
let osExecutable: Executable;
if (json.windows && Platform.platform === Platform.Platform.Windows) {
osExecutable = this.parseExecutable(json.windows);
} else if (json.osx && Platform.platform === Platform.Platform.Mac) {
osExecutable = this.parseExecutable(json.osx);
} else if (json.linux && Platform.platform === Platform.Platform.Linux) {
osExecutable = this.parseExecutable(json.linux);
}
if (osExecutable) {
result = ExecutableParser.mergeExecutable(result, osExecutable);
}
if ((!result || !result.command) && !parserOptions.emptyCommand) {
this.status.state = ValidationState.Fatal;
this.log(NLS.localize('ExecutableParser.commandMissing', 'Error: executable info must define a command of type string.'));
return null;
}
if (!parserOptions.noDefaults) {
Parser.merge(result, {
command: undefined,
isShellCommand: false,
args: [],
options: {}
}, false);
}
return result;
}
public parseExecutable(json: Config.BaseExecutable, globals?: Executable): Executable {
let command: string = undefined;
let isShellCommand: boolean = undefined;
let args: string[] = undefined;
let options: CommandOptions = undefined;
if (this.is(json.command, Types.isString)) {
command = json.command;
}
if (this.is(json.isShellCommand, Types.isBoolean, ValidationState.Warning, NLS.localize('ExecutableParser.isShellCommand', 'Warning: isShellCommand must be of type boolean. Ignoring value {0}.', json.isShellCommand))) {
isShellCommand = json.isShellCommand;
}
if (this.is(json.args, Types.isStringArray, ValidationState.Warning, NLS.localize('ExecutableParser.args', 'Warning: args must be of type string[]. Ignoring value {0}.', json.isShellCommand))) {
args = json.args.slice(0);
}
if (this.is(json.options, Types.isObject)) {
options = this.parseCommandOptions(json.options);
}
return { command, isShellCommand, args, options };
}
private parseCommandOptions(json: Config.CommandOptions): CommandOptions {
let result: CommandOptions = {};
if (!json) {
return result;
}
if (this.is(json.cwd, Types.isString, ValidationState.Warning, NLS.localize('ExecutableParser.invalidCWD', 'Warning: options.cwd must be of type string. Ignoring value {0}.', json.cwd))) {
result.cwd = json.cwd;
}
if (!Types.isUndefined(json.env)) {
result.env = Objects.clone(json.env);
}
return result;
}
public static mergeExecutable(executable: Executable, other: Executable): Executable {
if (!executable) {
return other;
}
Parser.merge(executable, other, true);
return executable;
}
}
export function resolveCommandOptions(options: CommandOptions, variables: ISystemVariables): CommandOptions {
let result = Objects.clone(options);
if (result.cwd) {
result.cwd = variables.resolve(result.cwd);
}
if (result.env) {
result.env = variables.resolve(result.env);
}
return result;
}
export function resolveExecutable(executable: Executable, variables: ISystemVariables): Executable {
let result = Objects.clone(executable);
result.command = variables.resolve(result.command);
result.args = variables.resolve(result.args);
if (result.options) {
result.options = resolveCommandOptions(result.options, variables);
}
return result;
} | src/vs/base/common/processes.ts | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0006840529968030751,
0.0002304258814547211,
0.00016616247012279928,
0.0001753918477334082,
0.00012083598267054185
] |
{
"id": 11,
"code_window": [
"\t) {\n",
"\t\tsuper(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);\n",
"\t}\n",
"}\n",
"\n",
"export class StackFrame implements debug.IStackFrame {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsuper(reference, `scope:${threadId}:${name}:${reference}`, true, namedVariables, indexedVariables);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 341
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.9988982677459717,
0.17408764362335205,
0.00016558202332817018,
0.0001742727472446859,
0.37725695967674255
] |
{
"id": 11,
"code_window": [
"\t) {\n",
"\t\tsuper(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);\n",
"\t}\n",
"}\n",
"\n",
"export class StackFrame implements debug.IStackFrame {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsuper(reference, `scope:${threadId}:${name}:${reference}`, true, namedVariables, indexedVariables);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 341
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"TaskSystemDetector.buildTaskDetected": "Ein Buildtask namens \"{0}\" wurde erkannt.",
"TaskSystemDetector.noGruntProgram": "Grunt ist auf Ihrem System nicht installiert. Führen Sie \"npm install -g grunt\" aus, um die Anwendung zu installieren.",
"TaskSystemDetector.noGulpProgram": "Gulp ist auf Ihrem System nicht installiert. Führen Sie \"npm install -g gulp\" aus, um die Anwendung zu installieren.",
"TaskSystemDetector.noGulpTasks": "Die Ausführung von \"gulp -tasks-simple\" hat keine Tasks aufgelistet. Haben Sie \"npm install\" ausgeführt?",
"TaskSystemDetector.noJakeProgram": "Jake ist auf Ihrem System nicht installiert. Führen Sie \"npm install -g jake\" aus, um die Anwendung zu installieren.",
"TaskSystemDetector.noJakeTasks": "Die Ausführung von \"jake -tasks\" hat keine Tasks aufgelistet. Haben Sie \"npm install\" ausgeführt?",
"TaskSystemDetector.noProgram": "Das Programm {0} wurde nicht gefunden. Die Meldung lautet: {1}",
"TaskSystemDetector.testTaskDetected": "Ein Testtask namens \"{0}\" wurde erkannt."
} | i18n/deu/src/vs/workbench/parts/tasks/node/processRunnerDetector.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017272745026275516,
0.00017260460299439728,
0.0001724817557260394,
0.00017260460299439728,
1.2284726835787296e-7
] |
{
"id": 11,
"code_window": [
"\t) {\n",
"\t\tsuper(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);\n",
"\t}\n",
"}\n",
"\n",
"export class StackFrame implements debug.IStackFrame {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsuper(reference, `scope:${threadId}:${name}:${reference}`, true, namedVariables, indexedVariables);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 341
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"added-char": "A",
"allChanges": "更改",
"ariaLabelChanges": "更改,GIT",
"ariaLabelMerge": "合并,GIT",
"ariaLabelStagedChanges": "暂存的更改,GIT",
"copied-char": "C",
"deleted-char": "D",
"fileStatusAriaLabel": "文件夹 {1} 中的文件 {0} 具有状态: {2},GIT",
"ignored-char": "!",
"mergeChanges": "合并更改",
"modified-char": "M",
"outsideOfWorkspace": "此文件位于当前工作区之外。",
"renamed-char": "R",
"stagedChanges": "暂存的更改",
"title-conflict-added-by-them": "冲突: 已由他们添加",
"title-conflict-added-by-us": "冲突: 已由我们添加",
"title-conflict-both-added": "冲突: 二者均已添加",
"title-conflict-both-deleted": "冲突: 二者均已删除",
"title-conflict-both-modified": "冲突: 二者均已修改",
"title-conflict-deleted-by-them": "冲突: 已由他们删除",
"title-conflict-deleted-by-us": "冲突: 已由我们删除",
"title-deleted": "已删除",
"title-ignored": "已忽略",
"title-index-added": "已添加到索引",
"title-index-copied": "已在索引中复制",
"title-index-deleted": "已在索引中删除",
"title-index-modified": "已在索引中修改",
"title-index-renamed": "已在索引中重新命名",
"title-modified": "已修改",
"title-untracked": "未跟踪的",
"untracked-char": "U"
} | i18n/chs/src/vs/workbench/parts/git/browser/views/changes/changesViewer.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017719062452670187,
0.00017258760635741055,
0.00016827350191306323,
0.00017244313494302332,
0.0000031662327728554374
] |
{
"id": 11,
"code_window": [
"\t) {\n",
"\t\tsuper(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);\n",
"\t}\n",
"}\n",
"\n",
"export class StackFrame implements debug.IStackFrame {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsuper(reference, `scope:${threadId}:${name}:${reference}`, true, namedVariables, indexedVariables);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 341
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import URI from 'vs/base/common/uri';
import {IDisposable, dispose} from 'vs/base/common/lifecycle';
import {TPromise} from 'vs/base/common/winjs.base';
import {IThreadService} from 'vs/workbench/services/thread/common/threadService';
import {EndOfLine} from './extHostTypes';
import {ISingleEditOperation, ISelection, IRange, IEditor, EditorType, ICommonCodeEditor, ICommonDiffEditor, IDecorationRenderOptions, IDecorationOptions} from 'vs/editor/common/editorCommon';
import {ICodeEditorService} from 'vs/editor/common/services/codeEditorService';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService';
import {Position as EditorPosition} from 'vs/platform/editor/common/editor';
import {IModelService} from 'vs/editor/common/services/modelService';
import {MainThreadEditorsTracker, TextEditorRevealType, MainThreadTextEditor, ITextEditorConfigurationUpdate} from 'vs/workbench/api/node/mainThreadEditorsTracker';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {IEventService} from 'vs/platform/event/common/event';
import {equals as arrayEquals} from 'vs/base/common/arrays';
import {equals as objectEquals} from 'vs/base/common/objects';
import {ExtHostContext, MainThreadEditorsShape, ExtHostEditorsShape, ITextEditorPositionData} from './extHost.protocol';
export class MainThreadEditors extends MainThreadEditorsShape {
private _proxy: ExtHostEditorsShape;
private _workbenchEditorService: IWorkbenchEditorService;
private _telemetryService: ITelemetryService;
private _editorTracker: MainThreadEditorsTracker;
private _toDispose: IDisposable[];
private _textEditorsListenersMap: { [editorId: string]: IDisposable[]; };
private _textEditorsMap: { [editorId: string]: MainThreadTextEditor; };
private _activeTextEditor: string;
private _visibleEditors: string[];
private _editorPositionData: ITextEditorPositionData;
constructor(
@IThreadService threadService: IThreadService,
@IWorkbenchEditorService workbenchEditorService: IWorkbenchEditorService,
@IEditorGroupService editorGroupService: IEditorGroupService,
@ITelemetryService telemetryService: ITelemetryService,
@ICodeEditorService editorService: ICodeEditorService,
@IEventService eventService: IEventService,
@IModelService modelService: IModelService
) {
super();
this._proxy = threadService.get(ExtHostContext.ExtHostEditors);
this._workbenchEditorService = workbenchEditorService;
this._telemetryService = telemetryService;
this._toDispose = [];
this._textEditorsListenersMap = Object.create(null);
this._textEditorsMap = Object.create(null);
this._activeTextEditor = null;
this._visibleEditors = [];
this._editorPositionData = null;
this._editorTracker = new MainThreadEditorsTracker(editorService, modelService);
this._toDispose.push(this._editorTracker);
this._toDispose.push(this._editorTracker.onTextEditorAdd((textEditor) => this._onTextEditorAdd(textEditor)));
this._toDispose.push(this._editorTracker.onTextEditorRemove((textEditor) => this._onTextEditorRemove(textEditor)));
this._toDispose.push(this._editorTracker.onDidUpdateTextEditors(() => this._updateActiveAndVisibleTextEditors()));
this._toDispose.push(this._editorTracker.onChangedFocusedTextEditor((focusedTextEditorId) => this._updateActiveAndVisibleTextEditors()));
this._toDispose.push(editorGroupService.onEditorsChanged(() => this._updateActiveAndVisibleTextEditors()));
this._toDispose.push(editorGroupService.onEditorsMoved(() => this._updateActiveAndVisibleTextEditors()));
}
public dispose(): void {
Object.keys(this._textEditorsListenersMap).forEach((editorId) => {
dispose(this._textEditorsListenersMap[editorId]);
});
this._textEditorsListenersMap = Object.create(null);
this._toDispose = dispose(this._toDispose);
}
private _onTextEditorAdd(textEditor: MainThreadTextEditor): void {
let id = textEditor.getId();
let toDispose: IDisposable[] = [];
toDispose.push(textEditor.onConfigurationChanged((opts) => {
this._proxy.$acceptOptionsChanged(id, opts);
}));
toDispose.push(textEditor.onSelectionChanged((event) => {
this._proxy.$acceptSelectionsChanged(id, event);
}));
this._proxy.$acceptTextEditorAdd({
id: id,
document: textEditor.getModel().uri,
options: textEditor.getConfiguration(),
selections: textEditor.getSelections(),
editorPosition: this._findEditorPosition(textEditor)
});
this._textEditorsListenersMap[id] = toDispose;
this._textEditorsMap[id] = textEditor;
}
private _onTextEditorRemove(textEditor: MainThreadTextEditor): void {
let id = textEditor.getId();
dispose(this._textEditorsListenersMap[id]);
delete this._textEditorsListenersMap[id];
delete this._textEditorsMap[id];
this._proxy.$acceptTextEditorRemove(id);
}
private _updateActiveAndVisibleTextEditors(): void {
// active and visible editors
let visibleEditors = this._editorTracker.getVisibleTextEditorIds();
let activeEditor = this._findActiveTextEditorId();
if (activeEditor !== this._activeTextEditor || !arrayEquals(this._visibleEditors, visibleEditors, (a, b) => a === b)) {
this._activeTextEditor = activeEditor;
this._visibleEditors = visibleEditors;
this._proxy.$acceptActiveEditorAndVisibleEditors(this._activeTextEditor, this._visibleEditors);
}
// editor columns
let editorPositionData = this._getTextEditorPositionData();
if (!objectEquals(this._editorPositionData, editorPositionData)) {
this._editorPositionData = editorPositionData;
this._proxy.$acceptEditorPositionData(this._editorPositionData);
}
}
private _findActiveTextEditorId(): string {
let focusedTextEditorId = this._editorTracker.getFocusedTextEditorId();
if (focusedTextEditorId) {
return focusedTextEditorId;
}
let activeEditor = this._workbenchEditorService.getActiveEditor();
if (!activeEditor) {
return null;
}
let editor = <IEditor>activeEditor.getControl();
// Substitute for (editor instanceof ICodeEditor)
if (!editor || typeof editor.getEditorType !== 'function') {
// Not a text editor...
return null;
}
if (editor.getEditorType() === EditorType.ICodeEditor) {
return this._editorTracker.findTextEditorIdFor(<ICommonCodeEditor>editor);
}
// Must be a diff editor => use the modified side
return this._editorTracker.findTextEditorIdFor((<ICommonDiffEditor>editor).getModifiedEditor());
}
private _findEditorPosition(editor: MainThreadTextEditor): EditorPosition {
for (let workbenchEditor of this._workbenchEditorService.getVisibleEditors()) {
if (editor.matches(workbenchEditor)) {
return workbenchEditor.position;
}
}
}
private _getTextEditorPositionData(): ITextEditorPositionData {
let result: ITextEditorPositionData = Object.create(null);
for (let workbenchEditor of this._workbenchEditorService.getVisibleEditors()) {
let editor = <IEditor>workbenchEditor.getControl();
// Substitute for (editor instanceof ICodeEditor)
if (!editor || typeof editor.getEditorType !== 'function') {
// Not a text editor...
continue;
}
if (editor.getEditorType() === EditorType.ICodeEditor) {
let id = this._editorTracker.findTextEditorIdFor(<ICommonCodeEditor>editor);
if (id) {
result[id] = workbenchEditor.position;
}
}
}
return result;
}
// --- from extension host process
$tryShowTextDocument(resource: URI, position: EditorPosition, preserveFocus: boolean): TPromise<string> {
const input = {
resource,
options: { preserveFocus }
};
return this._workbenchEditorService.openEditor(input, position).then(editor => {
if (!editor) {
return;
}
return new TPromise<void>(c => {
// not very nice but the way it is: changes to the editor state aren't
// send to the ext host as they happen but stuff is delayed a little. in
// order to provide the real editor on #openTextEditor we need to sync on
// that update
let subscription: IDisposable;
let handle: number;
function contd() {
subscription.dispose();
clearTimeout(handle);
c(undefined);
}
subscription = this._editorTracker.onDidUpdateTextEditors(() => {
contd();
});
handle = setTimeout(() => {
contd();
}, 1000);
}).then(() => {
// find the editor we have just opened and return the
// id we have assigned to it.
for (let id in this._textEditorsMap) {
if (this._textEditorsMap[id].matches(editor)) {
return id;
}
}
});
});
}
$tryShowEditor(id: string, position: EditorPosition): TPromise<void> {
// check how often this is used
this._telemetryService.publicLog('api.deprecated', { function: 'TextEditor.show' });
let mainThreadEditor = this._textEditorsMap[id];
if (mainThreadEditor) {
let model = mainThreadEditor.getModel();
return this._workbenchEditorService.openEditor({
resource: model.uri,
options: { preserveFocus: false }
}, position).then(() => { return; });
}
}
$tryHideEditor(id: string): TPromise<void> {
// check how often this is used
this._telemetryService.publicLog('api.deprecated', { function: 'TextEditor.hide' });
let mainThreadEditor = this._textEditorsMap[id];
if (mainThreadEditor) {
let editors = this._workbenchEditorService.getVisibleEditors();
for (let editor of editors) {
if (mainThreadEditor.matches(editor)) {
return this._workbenchEditorService.closeEditor(editor.position, editor.input).then(() => { return; });
}
}
}
}
$trySetSelections(id: string, selections: ISelection[]): TPromise<any> {
if (!this._textEditorsMap[id]) {
return TPromise.wrapError('TextEditor disposed');
}
this._textEditorsMap[id].setSelections(selections);
return TPromise.as(null);
}
$trySetDecorations(id: string, key: string, ranges: IDecorationOptions[]): TPromise<any> {
if (!this._textEditorsMap[id]) {
return TPromise.wrapError('TextEditor disposed');
}
this._textEditorsMap[id].setDecorations(key, ranges);
return TPromise.as(null);
}
$tryRevealRange(id: string, range: IRange, revealType: TextEditorRevealType): TPromise<any> {
if (!this._textEditorsMap[id]) {
return TPromise.wrapError('TextEditor disposed');
}
this._textEditorsMap[id].revealRange(range, revealType);
}
$trySetOptions(id: string, options: ITextEditorConfigurationUpdate): TPromise<any> {
if (!this._textEditorsMap[id]) {
return TPromise.wrapError('TextEditor disposed');
}
this._textEditorsMap[id].setConfiguration(options);
return TPromise.as(null);
}
$tryApplyEdits(id: string, modelVersionId: number, edits: ISingleEditOperation[], setEndOfLine:EndOfLine): TPromise<boolean> {
if (!this._textEditorsMap[id]) {
return TPromise.wrapError('TextEditor disposed');
}
return TPromise.as(this._textEditorsMap[id].applyEdits(modelVersionId, edits, setEndOfLine));
}
$registerTextEditorDecorationType(key: string, options: IDecorationRenderOptions): void {
this._editorTracker.registerTextEditorDecorationType(key, options);
}
$removeTextEditorDecorationType(key: string): void {
this._editorTracker.removeTextEditorDecorationType(key);
}
}
| src/vs/workbench/api/node/mainThreadEditors.ts | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0002150457730749622,
0.00017365816165693104,
0.0001663798320805654,
0.00017291006224695593,
0.000008136925316648558
] |
{
"id": 12,
"code_window": [
"\t}\n",
"\n",
"\tpublic getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {\n",
"\t\tif (!this.scopes) {\n",
"\t\t\tthis.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {\n",
"\t\t\t\treturn response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));\n",
"\t\t\t}, err => []);\n",
"\t\t}\n",
"\n",
"\t\treturn this.scopes;\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\treturn response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables));\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 367
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.9967994689941406,
0.012790222652256489,
0.00016048489487729967,
0.00017213213141076267,
0.11071377992630005
] |
{
"id": 12,
"code_window": [
"\t}\n",
"\n",
"\tpublic getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {\n",
"\t\tif (!this.scopes) {\n",
"\t\t\tthis.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {\n",
"\t\t\t\treturn response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));\n",
"\t\t\t}, err => []);\n",
"\t\t}\n",
"\n",
"\t\treturn this.scopes;\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\treturn response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables));\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 367
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import nls = require('vs/nls');
export function since(date: Date): string {
var seconds = (new Date().getTime() - date.getTime()) / 1000;
if (seconds < 60) {
return nls.localize('diff.seconds.verbose', "just now");
}
var minutes = seconds / 60;
if (minutes < 60) {
return Math.floor(minutes) === 1 ? nls.localize('diff.minute.verbose', "1 minute ago") : nls.localize('diff.minutes.verbose', "{0} minutes ago", Math.floor(minutes));
}
var hours = minutes / 60;
if (hours < 24) {
return Math.floor(hours) === 1 ? nls.localize('diff.hour.verbose', "1 hour ago") : nls.localize('diff.hours.verbose', "{0} hours ago", Math.floor(hours));
}
var days = hours / 24;
if (Math.floor(days) === 1) {
return nls.localize('diff.days.yesterday', "yesterday");
}
if (days > 6 && days < 8) {
return nls.localize('diff.days.week', "a week ago");
}
if (days > 30 && days < 40) {
return nls.localize('diff.days.month', "a month ago");
}
return nls.localize('diff.days.verbose', "{0} days ago", Math.floor(days));
} | src/vs/base/common/dates.ts | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017799512716010213,
0.0001756371493684128,
0.00017430284060537815,
0.00017512532940600067,
0.0000015140713003347628
] |
{
"id": 12,
"code_window": [
"\t}\n",
"\n",
"\tpublic getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {\n",
"\t\tif (!this.scopes) {\n",
"\t\t\tthis.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {\n",
"\t\t\t\treturn response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));\n",
"\t\t\t}, err => []);\n",
"\t\t}\n",
"\n",
"\t\treturn this.scopes;\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\treturn response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables));\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 367
} | // ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS:
[{
"name": "textmate/make.tmbundle",
"version": "0.0.0",
"license": "TextMate Bundle License",
"repositoryURL": "https://github.com/textmate/make.tmbundle",
"licenseDetail": [
"Copyright (c) textmate-make.tmbundle project authors",
"",
"If not otherwise specified (see below), files in this repository fall under the following license:",
"",
"Permission to copy, use, modify, sell and distribute this",
"software is granted. This software is provided \"as is\" without",
"express or implied warranty, and with no claim as to its",
"suitability for any purpose.",
"",
"An exception is made for files in readable text which contain their own license information,",
"or files where an accompanying file exists (in the same directory) with a \"-license\" suffix added",
"to the base-name name of the original file, and an extension of txt, html, or similar. For example",
"\"tidy\" is accompanied by \"tidy-license.txt\"."
]
}]
| extensions/make/OSSREADME.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017597981786821038,
0.00017575260426383466,
0.00017550929624121636,
0.00017576869868207723,
1.9242646942529973e-7
] |
{
"id": 12,
"code_window": [
"\t}\n",
"\n",
"\tpublic getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {\n",
"\t\tif (!this.scopes) {\n",
"\t\t\tthis.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {\n",
"\t\t\t\treturn response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));\n",
"\t\t\t}, err => []);\n",
"\t\t}\n",
"\n",
"\t\treturn this.scopes;\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\treturn response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables));\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 367
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"navigateNext": "Далее",
"navigatePrevious": "Назад"
} | i18n/rus/src/vs/workbench/browser/actions/triggerNavigation.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017627052147872746,
0.00017627052147872746,
0.00017627052147872746,
0.00017627052147872746,
0
] |
{
"id": 13,
"code_window": [
"\t\tconst type = 'node';\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(new debugmodel.Expression(null, false), type), null);\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(new debugmodel.Expression('son', false), type), 'son');\n",
"\n",
"\t\tconst scope = new debugmodel.Scope(1, 'myscope', 1, false, 1);\n",
"\t\tconst son = new debugmodel.Variable(new debugmodel.Variable(new debugmodel.Variable(scope, 0, 'grandfather', '75', 1), 0, 'father', '45', 1), 0, 'son', '20', 1);\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(son, type), 'grandfather.father.son');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tconst scope = new debugmodel.Scope(1, 'myscope', 1, false, 1, 0);\n",
"\t\tconst son = new debugmodel.Variable(new debugmodel.Variable(new debugmodel.Variable(scope, 0, 'grandfather', '75', 1, 0), 0, 'father', '45', 1, 0), 0, 'son', '20', 1, 0);\n"
],
"file_path": "src/vs/workbench/parts/debug/test/node/debugModel.test.ts",
"type": "replace",
"edit_start_line_idx": 354
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0010803970508277416,
0.0002079776459140703,
0.00016309821512550116,
0.0001742575695971027,
0.00015556893777102232
] |
{
"id": 13,
"code_window": [
"\t\tconst type = 'node';\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(new debugmodel.Expression(null, false), type), null);\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(new debugmodel.Expression('son', false), type), 'son');\n",
"\n",
"\t\tconst scope = new debugmodel.Scope(1, 'myscope', 1, false, 1);\n",
"\t\tconst son = new debugmodel.Variable(new debugmodel.Variable(new debugmodel.Variable(scope, 0, 'grandfather', '75', 1), 0, 'father', '45', 1), 0, 'son', '20', 1);\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(son, type), 'grandfather.father.son');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tconst scope = new debugmodel.Scope(1, 'myscope', 1, false, 1, 0);\n",
"\t\tconst son = new debugmodel.Variable(new debugmodel.Variable(new debugmodel.Variable(scope, 0, 'grandfather', '75', 1, 0), 0, 'father', '45', 1, 0), 0, 'son', '20', 1, 0);\n"
],
"file_path": "src/vs/workbench/parts/debug/test/node/debugModel.test.ts",
"type": "replace",
"edit_start_line_idx": 354
} | <svg xmlns="http://www.w3.org/2000/svg" width="58" height="36"><path fill="#F0EFF1" d="M54 32v-28h-50v28h50zm-16-2h-18v-6h18v6zm6 0h-4v-6h4v6zm8 0h-6v-6h6v6zm-4-24h4v4h-4v-4zm0 6h4v4h-4v-4zm0 6h4v4h-4v-4zm-6-12h4v4h-4v-4zm0 6h4v4h-4v-4zm0 6h4v4h-4v-4zm-6-12h4v4h-4v-4zm0 6h4v4h-4v-4zm0 6h4v4h-4v-4zm-6-12h4v4h-4v-4zm0 6h4v4h-4v-4zm0 6h4v4h-4v-4zm-6-12h4v4h-4v-4zm0 6h4v4h-4v-4zm0 6h4v4h-4v-4zm-6-12h4v4h-4v-4zm0 6h4v4h-4v-4zm0 6h4v4h-4v-4zm0 12h-4v-6h4v6zm-6-24h4v4h-4v-4zm0 6h4v4h-4v-4zm0 6h4v4h-4v-4zm-6-12h4v4h-4v-4zm0 6h4v4h-4v-4zm0 6h4v4h-4v-4zm0 6h6v6h-6v-6z"/><path fill="#424242" d="M55.336 0h-53.285c-1.344 0-2.051.656-2.051 2v32c0 1.344.707 1.965 2.051 1.965l53.949.035c1.344 0 2-.656 2-2v-32c0-1.344-1.32-2-2.664-2zm-1.336 32h-50v-28h50v28z"/><rect x="6" y="12" fill="#424242" width="4" height="4"/><rect x="12" y="12" fill="#424242" width="4" height="4"/><rect x="18" y="12" fill="#424242" width="4" height="4"/><rect x="24" y="12" fill="#424242" width="4" height="4"/><rect x="30" y="12" fill="#424242" width="4" height="4"/><rect x="36" y="12" fill="#424242" width="4" height="4"/><rect x="42" y="12" fill="#424242" width="4" height="4"/><rect x="48" y="12" fill="#424242" width="4" height="4"/><rect x="6" y="6" fill="#424242" width="4" height="4"/><rect x="12" y="6" fill="#424242" width="4" height="4"/><rect x="18" y="6" fill="#424242" width="4" height="4"/><rect x="24" y="6" fill="#424242" width="4" height="4"/><rect x="30" y="6" fill="#424242" width="4" height="4"/><rect x="36" y="6" fill="#424242" width="4" height="4"/><rect x="42" y="6" fill="#424242" width="4" height="4"/><rect x="48" y="6" fill="#424242" width="4" height="4"/><rect x="6" y="18" fill="#424242" width="4" height="4"/><rect x="12" y="18" fill="#424242" width="4" height="4"/><rect x="18" y="18" fill="#424242" width="4" height="4"/><rect x="24" y="18" fill="#424242" width="4" height="4"/><rect x="30" y="18" fill="#424242" width="4" height="4"/><rect x="36" y="18" fill="#424242" width="4" height="4"/><rect x="42" y="18" fill="#424242" width="4" height="4"/><rect x="48" y="18" fill="#424242" width="4" height="4"/><rect x="6" y="24" fill="#424242" width="6" height="6"/><rect x="46" y="24" fill="#424242" width="6" height="6"/><rect x="20" y="24" fill="#424242" width="18" height="6"/><rect x="14" y="24" fill="#424242" width="4" height="6"/><rect x="40" y="24" fill="#424242" width="4" height="6"/></svg> | src/vs/editor/contrib/iPadShowKeyboard/browser/keyboard.svg | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00030964866164140403,
0.00030964866164140403,
0.00030964866164140403,
0.00030964866164140403,
0
] |
{
"id": 13,
"code_window": [
"\t\tconst type = 'node';\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(new debugmodel.Expression(null, false), type), null);\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(new debugmodel.Expression('son', false), type), 'son');\n",
"\n",
"\t\tconst scope = new debugmodel.Scope(1, 'myscope', 1, false, 1);\n",
"\t\tconst son = new debugmodel.Variable(new debugmodel.Variable(new debugmodel.Variable(scope, 0, 'grandfather', '75', 1), 0, 'father', '45', 1), 0, 'son', '20', 1);\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(son, type), 'grandfather.father.son');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tconst scope = new debugmodel.Scope(1, 'myscope', 1, false, 1, 0);\n",
"\t\tconst son = new debugmodel.Variable(new debugmodel.Variable(new debugmodel.Variable(scope, 0, 'grandfather', '75', 1, 0), 0, 'father', '45', 1, 0), 0, 'son', '20', 1, 0);\n"
],
"file_path": "src/vs/workbench/parts/debug/test/node/debugModel.test.ts",
"type": "replace",
"edit_start_line_idx": 354
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import {ModelBuilder, computeHash} from 'vs/editor/node/model/modelBuilder';
import {ITextModelCreationOptions, IRawText} from 'vs/editor/common/editorCommon';
import {TextModel} from 'vs/editor/common/model/textModel';
import * as strings from 'vs/base/common/strings';
export function testModelBuilder(chunks:string[], opts:ITextModelCreationOptions = TextModel.DEFAULT_CREATION_OPTIONS): string {
let expectedRawText = TextModel.toRawText(chunks.join(''), opts);
let expectedHash = computeHash(expectedRawText);
let builder = new ModelBuilder();
for (let i = 0, len = chunks.length; i < len; i++) {
builder.acceptChunk(chunks[i]);
}
let actual = builder.finish(opts);
assert.deepEqual({
rawText: expectedRawText,
hash: expectedHash
}, actual);
return expectedHash;
}
function toRawText(lines:string[]): IRawText {
return {
BOM: '',
lines: lines,
EOL: '\n',
length: 0,
options: null
};
}
export function testDifferentHash(lines1:string[], lines2:string[]): void {
let hash1 = computeHash(toRawText(lines1));
let hash2 = computeHash(toRawText(lines2));
assert.notEqual(hash1, hash2);
}
suite('ModelBuilder', () => {
test('uses sha1', () => {
// These are the sha1s of the string + \n
assert.equal(computeHash(toRawText([''])), 'adc83b19e793491b1c6ea0fd8b46cd9f32e592fc');
assert.equal(computeHash(toRawText(['hello world'])), '22596363b3de40b06f981fb85d82312e8c0ed511');
});
test('no chunks', () => {
testModelBuilder([]);
});
test('single empty chunk', () => {
testModelBuilder(['']);
});
test('single line in one chunk', () => {
testModelBuilder(['Hello world']);
});
test('single line in multiple chunks', () => {
testModelBuilder(['Hello', ' ', 'world']);
});
test('two lines in single chunk', () => {
testModelBuilder(['Hello world\nHow are you?']);
});
test('two lines in multiple chunks 1', () => {
testModelBuilder(['Hello worl', 'd\nHow are you?']);
});
test('two lines in multiple chunks 2', () => {
testModelBuilder(['Hello worl', 'd' , '\n', 'H', 'ow are you?']);
});
test('two lines in multiple chunks 3', () => {
testModelBuilder(['Hello worl', 'd' , '\nHow are you?']);
});
test('multiple lines in single chunks', () => {
testModelBuilder(['Hello world\nHow are you?\nIs everything good today?\nDo you enjoy the weather?']);
});
test('multiple lines in multiple chunks 1', () => {
testModelBuilder(['Hello world\nHow are you', '?\nIs everything good today?\nDo you enjoy the weather?']);
});
test('multiple lines in multiple chunks 1', () => {
testModelBuilder(['Hello world', '\nHow are you', '?\nIs everything good today?', '\nDo you enjoy the weather?']);
});
test('multiple lines in multiple chunks 1', () => {
testModelBuilder(['Hello world\n', 'How are you', '?\nIs everything good today?', '\nDo you enjoy the weather?']);
});
test('carriage return detection (1 \r\n 2 \n)', () => {
testModelBuilder(['Hello world\r\n', 'How are you', '?\nIs everything good today?', '\nDo you enjoy the weather?']);
});
test('carriage return detection (2 \r\n 1 \n)', () => {
testModelBuilder(['Hello world\r\n', 'How are you', '?\r\nIs everything good today?', '\nDo you enjoy the weather?']);
});
test('carriage return detection (3 \r\n 0 \n)', () => {
testModelBuilder(['Hello world\r\n', 'How are you', '?\r\nIs everything good today?', '\r\nDo you enjoy the weather?']);
});
test('carriage return detection (isolated \r)', () => {
testModelBuilder(['Hello world', '\r', '\n', 'How are you', '?', '\r', '\n', 'Is everything good today?', '\r', '\n', 'Do you enjoy the weather?']);
});
test('BOM handling', () => {
testModelBuilder([strings.UTF8_BOM_CHARACTER + 'Hello world!']);
});
});
| src/vs/editor/test/node/model/modelBuilder.test.ts | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0001767276116879657,
0.00017504974675830454,
0.0001725012989481911,
0.00017556099919602275,
0.0000013642256817547604
] |
{
"id": 13,
"code_window": [
"\t\tconst type = 'node';\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(new debugmodel.Expression(null, false), type), null);\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(new debugmodel.Expression('son', false), type), 'son');\n",
"\n",
"\t\tconst scope = new debugmodel.Scope(1, 'myscope', 1, false, 1);\n",
"\t\tconst son = new debugmodel.Variable(new debugmodel.Variable(new debugmodel.Variable(scope, 0, 'grandfather', '75', 1), 0, 'father', '45', 1), 0, 'son', '20', 1);\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(son, type), 'grandfather.father.son');\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tconst scope = new debugmodel.Scope(1, 'myscope', 1, false, 1, 0);\n",
"\t\tconst son = new debugmodel.Variable(new debugmodel.Variable(new debugmodel.Variable(scope, 0, 'grandfather', '75', 1, 0), 0, 'father', '45', 1, 0), 0, 'son', '20', 1, 0);\n"
],
"file_path": "src/vs/workbench/parts/debug/test/node/debugModel.test.ts",
"type": "replace",
"edit_start_line_idx": 354
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"cancel": "취소",
"close": "닫기"
} | i18n/kor/src/vs/platform/message/common/message.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017607348854653537,
0.00017607348854653537,
0.00017607348854653537,
0.00017607348854653537,
0
] |
{
"id": 14,
"code_window": [
"\t\tassert.equal(debugmodel.getFullExpressionName(son, type), 'grandfather.father.son');\n",
"\n",
"\t\tconst grandson = new debugmodel.Variable(son, 0, '/weird_name', '1', 0);\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(grandson, type), 'grandfather.father.son[\\'/weird_name\\']');\n",
"\t});\n",
"});"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst grandson = new debugmodel.Variable(son, 0, '/weird_name', '1', 0, 0);\n"
],
"file_path": "src/vs/workbench/parts/debug/test/node/debugModel.test.ts",
"type": "replace",
"edit_start_line_idx": 358
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0010560875525698066,
0.0001935432810569182,
0.00016140630759764463,
0.00017327108071185648,
0.00013179123925510794
] |
{
"id": 14,
"code_window": [
"\t\tassert.equal(debugmodel.getFullExpressionName(son, type), 'grandfather.father.son');\n",
"\n",
"\t\tconst grandson = new debugmodel.Variable(son, 0, '/weird_name', '1', 0);\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(grandson, type), 'grandfather.father.son[\\'/weird_name\\']');\n",
"\t});\n",
"});"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst grandson = new debugmodel.Variable(son, 0, '/weird_name', '1', 0, 0);\n"
],
"file_path": "src/vs/workbench/parts/debug/test/node/debugModel.test.ts",
"type": "replace",
"edit_start_line_idx": 358
} | // Type definitions for semver v2.2.1
// Project: https://github.com/isaacs/node-semver
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module SemVerModule {
/**
* Return the parsed version, or null if it's not valid.
*/
function valid(v: string, loose?: boolean): string;
/**
* Return the version incremented by the release type (major, minor, patch, or prerelease), or null if it's not valid.
*/
function inc(v: string, release: string, loose?: boolean): string;
// Comparison
/**
* v1 > v2
*/
function gt(v1: string, v2: string, loose?: boolean): boolean;
/**
* v1 >= v2
*/
function gte(v1: string, v2: string, loose?: boolean): boolean;
/**
* v1 < v2
*/
function lt(v1: string, v2: string, loose?: boolean): boolean;
/**
* v1 <= v2
*/
function lte(v1: string, v2: string, loose?: boolean): boolean;
/**
* v1 == v2 This is true if they're logically equivalent, even if they're not the exact same string. You already know how to compare strings.
*/
function eq(v1: string, v2: string, loose?: boolean): boolean;
/**
* v1 != v2 The opposite of eq.
*/
function neq(v1: string, v2: string, loose?: boolean): boolean;
/**
* Pass in a comparison string, and it'll call the corresponding semver comparison function. "===" and "!==" do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided.
*/
function cmp(v1: string, comparator: any, v2: string, loose?: boolean): boolean;
/**
* Return 0 if v1 == v2, or 1 if v1 is greater, or -1 if v2 is greater. Sorts in ascending order if passed to Array.sort().
*/
function compare(v1: string, v2: string, loose?: boolean): number;
/**
* The reverse of compare. Sorts an array of versions in descending order when passed to Array.sort().
*/
function rcompare(v1: string, v2: string, loose?: boolean): number;
// Ranges
/**
* Return the valid range or null if it's not valid
*/
function validRange(range: string, loose?: boolean): string;
/**
* Return true if the version satisfies the range.
*/
function satisfies(version: string, range: string, loose?: boolean): boolean;
/**
* Return the highest version in the list that satisfies the range, or null if none of them do.
*/
function maxSatisfying(versions: string[], range: string, loose?: boolean): string;
/**
* Return true if version is greater than all the versions possible in the range.
*/
function gtr(version: string, range: string, loose?: boolean): boolean;
/**
* Return true if version is less than all the versions possible in the range.
*/
function ltr(version: string, range: string, loose?: boolean): boolean;
/**
* Return true if the version is outside the bounds of the range in either the high or low direction. The hilo argument must be either the string '>' or '<'. (This is the function called by gtr and ltr.)
*/
function outside(version: string, range: string, hilo: string, loose?: boolean): boolean;
class SemVerBase {
raw: string;
loose: boolean;
format(): string;
inspect(): string;
toString(): string;
}
class SemVer extends SemVerBase {
constructor(version: string, loose?: boolean);
major: number;
minor: number;
patch: number;
version: string;
build: string[];
prerelease: string[];
compare(other:SemVer): number;
compareMain(other:SemVer): number;
comparePre(other:SemVer): number;
inc(release: string): SemVer;
}
class Comparator extends SemVerBase {
constructor(comp: string, loose?: boolean);
semver: SemVer;
operator: string;
value: boolean;
parse(comp: string): void;
test(version:SemVer): boolean;
}
class Range extends SemVerBase {
constructor(range: string, loose?: boolean);
set: Comparator[][];
parseRange(range: string): Comparator[];
test(version: SemVer): boolean;
}
}
declare module "semver" {
export = SemVerModule;
}
| src/typings/semver.d.ts | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017848493007477373,
0.0001746992493281141,
0.00016522733494639397,
0.00017579871928319335,
0.0000035939203826274024
] |
{
"id": 14,
"code_window": [
"\t\tassert.equal(debugmodel.getFullExpressionName(son, type), 'grandfather.father.son');\n",
"\n",
"\t\tconst grandson = new debugmodel.Variable(son, 0, '/weird_name', '1', 0);\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(grandson, type), 'grandfather.father.son[\\'/weird_name\\']');\n",
"\t});\n",
"});"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst grandson = new debugmodel.Variable(son, 0, '/weird_name', '1', 0, 0);\n"
],
"file_path": "src/vs/workbench/parts/debug/test/node/debugModel.test.ts",
"type": "replace",
"edit_start_line_idx": 358
} | THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
Do Not Translate or Localize
This project incorporates components from the projects listed below. The original copyright notices and the licenses
under which Microsoft received such components are set forth below. Microsoft reserves all rights not expressly granted
herein, whether by implication, estoppel or otherwise.
%% HTML 5.1 W3C Working Draft version 08 October 2015 (http://www.w3.org/TR/2015/WD-html51-20151008/)
=========================================
Copyright © 2015 W3C® (MIT, ERCIM, Keio, Beihang). This software or document includes material copied
from or derived from HTML 5.1 W3C Working Draft (http://www.w3.org/TR/2015/WD-html51-20151008/.)
THIS DOCUMENT IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT
NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE; THAT THE CONTENTS OF
THE DOCUMENT ARE SUITABLE FOR ANY PURPOSE; NOR THAT THE IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY
PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE
DOCUMENT OR THE PERFORMANCE OR IMPLEMENTATION OF THE CONTENTS THEREOF.
The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to this document or its contents
without specific, written prior permission. Title to copyright in this document will at all times remain with copyright holders.
=========================================
END OF HTML 5.1 W3C Working Draft NOTICES AND INFORMATION
%% js-beautify version 1.5.10 (https://github.com/beautify-web/js-beautify)
=========================================
The MIT License (MIT)
Copyright (c) 2007-2013 Einar Lielmanis and contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=========================================
END OF js-beautify NOTICES AND INFORMATION
%% string_scorer version 0.1.20 (https://github.com/joshaven/string_score)
=========================================
This software is released under the MIT license:
Copyright (c) Joshaven Potter
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=========================================
END OF string_scorer NOTICES AND INFORMATION
%% chjj-marked NOTICES AND INFORMATION BEGIN HERE
=========================================
The MIT License (MIT)
Copyright (c) 2011-2014, Christopher Jeffrey (https://github.com/chjj/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=========================================
END OF chjj-marked NOTICES AND INFORMATION
| build/monaco/ThirdPartyNotices.txt | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017635273979976773,
0.00017191773804370314,
0.00016395548300351948,
0.00017382699297741055,
0.00000415876502302126
] |
{
"id": 14,
"code_window": [
"\t\tassert.equal(debugmodel.getFullExpressionName(son, type), 'grandfather.father.son');\n",
"\n",
"\t\tconst grandson = new debugmodel.Variable(son, 0, '/weird_name', '1', 0);\n",
"\t\tassert.equal(debugmodel.getFullExpressionName(grandson, type), 'grandfather.father.son[\\'/weird_name\\']');\n",
"\t});\n",
"});"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst grandson = new debugmodel.Variable(son, 0, '/weird_name', '1', 0, 0);\n"
],
"file_path": "src/vs/workbench/parts/debug/test/node/debugModel.test.ts",
"type": "replace",
"edit_start_line_idx": 358
} | <svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><g fill="#E51400"><circle cx="8" cy="8" r="5"/></g></g></svg> | src/vs/workbench/parts/debug/browser/media/breakpoint.svg | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017391520668752491,
0.00017391520668752491,
0.00017391520668752491,
0.00017391520668752491,
0
] |
{
"id": 0,
"code_window": [
"/dist\n",
"/emails/dist\n",
"/public_gen\n",
"/tmp\n",
"\n",
"docs/AWS_S3_BUCKET\n",
"docs/GIT_BRANCH\n",
"docs/VERSION\n",
"docs/GITCOMMIT\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"vendor/phantomjs/phantomjs\n"
],
"file_path": ".gitignore",
"type": "add",
"edit_start_line_idx": 8
} | module.exports = function(config,grunt) {
'use strict';
grunt.registerTask('phantomjs', 'Copy phantomjs binary from node', function() {
var dest = './vendor/phantomjs/phantomjs';
var confDir = './node_modules/karma-phantomjs-launcher/node_modules/phantomjs/lib/'
if (!grunt.file.exists(dest)){
var m=grunt.file.read(confDir+"location.js")
var src=/= \"([^\"]*)\"/.exec(m)[1];
if (!grunt.file.isPathAbsolute(src)) {
src = confDir+src;
}
var exec = require('child_process').execFileSync;
try {
var ph=exec(src,['-v'], { stdio: 'ignore' });
grunt.verbose.writeln('Using '+ src);
grunt.file.copy(src, dest, { encoding: null });
} catch (err) {
grunt.verbose.writeln(err);
grunt.fail.warn('No working Phantomjs binary available')
}
} else {
grunt.log.writeln('Phantomjs already imported from node');
}
});
};
| tasks/options/phantomjs.js | 1 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.00017403629317414016,
0.00017209583893418312,
0.00016921249334700406,
0.00017256729188375175,
0.0000018139949133910704
] |
{
"id": 0,
"code_window": [
"/dist\n",
"/emails/dist\n",
"/public_gen\n",
"/tmp\n",
"\n",
"docs/AWS_S3_BUCKET\n",
"docs/GIT_BRANCH\n",
"docs/VERSION\n",
"docs/GITCOMMIT\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"vendor/phantomjs/phantomjs\n"
],
"file_path": ".gitignore",
"type": "add",
"edit_start_line_idx": 8
} | (function(angular) {
'use strict';
function isDnDsSupported() {
return 'ondrag' in document.createElement('a');
}
function determineEffectAllowed(e) {
// Chrome doesn't set dropEffect, so we have to work it out ourselves
if (e.dataTransfer && e.dataTransfer.dropEffect === 'none') {
if (e.dataTransfer.effectAllowed === 'copy' ||
e.dataTransfer.effectAllowed === 'move') {
e.dataTransfer.dropEffect = e.dataTransfer.effectAllowed;
} else if (e.dataTransfer.effectAllowed === 'copyMove' || e.dataTransfer.effectAllowed === 'copymove') {
e.dataTransfer.dropEffect = e.ctrlKey ? 'copy' : 'move';
}
}
}
if (!isDnDsSupported()) {
angular.module('ang-drag-drop', []);
return;
}
if (window.jQuery && (-1 === window.jQuery.event.props.indexOf('dataTransfer'))) {
window.jQuery.event.props.push('dataTransfer');
}
var module = angular.module('ang-drag-drop', []);
module.directive('uiDraggable', ['$parse', '$rootScope', '$dragImage', function($parse, $rootScope, $dragImage) {
return function(scope, element, attrs) {
var isDragHandleUsed = false,
dragHandleClass,
draggingClass = attrs.draggingClass || 'on-dragging',
dragTarget;
element.attr('draggable', false);
scope.$watch(attrs.uiDraggable, function(newValue) {
if (newValue) {
element.attr('draggable', newValue);
element.bind('dragend', dragendHandler);
element.bind('dragstart', dragstartHandler);
}
else {
element.removeAttr('draggable');
element.unbind('dragend', dragendHandler);
element.unbind('dragstart', dragstartHandler);
}
});
if (angular.isString(attrs.dragHandleClass)) {
isDragHandleUsed = true;
dragHandleClass = attrs.dragHandleClass.trim() || 'drag-handle';
element.bind('mousedown', function(e) {
dragTarget = e.target;
});
}
function dragendHandler(e) {
setTimeout(function() {
element.unbind('$destroy', dragendHandler);
}, 0);
var sendChannel = attrs.dragChannel || 'defaultchannel';
$rootScope.$broadcast('ANGULAR_DRAG_END', e, sendChannel);
determineEffectAllowed(e);
if (e.dataTransfer && e.dataTransfer.dropEffect !== 'none') {
if (attrs.onDropSuccess) {
var onDropSuccessFn = $parse(attrs.onDropSuccess);
scope.$evalAsync(function() {
onDropSuccessFn(scope, {$event: e});
});
} else {
if (attrs.onDropFailure) {
var onDropFailureFn = $parse(attrs.onDropFailure);
scope.$evalAsync(function() {
onDropFailureFn(scope, {$event: e});
});
}
}
}
element.removeClass(draggingClass);
}
function dragstartHandler(e) {
var isDragAllowed = !isDragHandleUsed || dragTarget.classList.contains(dragHandleClass);
if (dragTarget.classList.contains("resize-panel-handle")) {
return;
}
if (isDragAllowed) {
var sendChannel = attrs.dragChannel || 'defaultchannel';
var dragData = '';
if (attrs.drag) {
dragData = scope.$eval(attrs.drag);
}
var dragImage = attrs.dragImage || null;
element.addClass(draggingClass);
element.bind('$destroy', dragendHandler);
//Code to make sure that the setDragImage is available. IE 10, 11, and Opera do not support setDragImage.
var hasNativeDraggable = !(document.uniqueID || window.opera);
//If there is a draggable image passed in, then set the image to be dragged.
if (dragImage && hasNativeDraggable) {
var dragImageFn = $parse(attrs.dragImage);
scope.$apply(function() {
var dragImageParameters = dragImageFn(scope, {$event: e});
if (dragImageParameters) {
if (angular.isString(dragImageParameters)) {
dragImageParameters = $dragImage.generate(dragImageParameters);
}
if (dragImageParameters.image) {
var xOffset = dragImageParameters.xOffset || 0,
yOffset = dragImageParameters.yOffset || 0;
e.dataTransfer.setDragImage(dragImageParameters.image, xOffset, yOffset);
}
}
});
}
var transferDataObject = {data: dragData, channel: sendChannel}
var transferDataText = angular.toJson(transferDataObject);
e.dataTransfer.setData('text', transferDataText);
e.dataTransfer.effectAllowed = 'copyMove';
$rootScope.$broadcast('ANGULAR_DRAG_START', e, sendChannel, transferDataObject);
}
else {
e.preventDefault();
}
}
};
}
]);
module.directive('uiOnDrop', ['$parse', '$rootScope', function($parse, $rootScope) {
return function(scope, element, attr) {
var dragging = 0; //Ref. http://stackoverflow.com/a/10906204
var dropChannel = attr.dropChannel || 'defaultchannel';
var dragChannel = '';
var dragEnterClass = attr.dragEnterClass || 'on-drag-enter';
var dragHoverClass = attr.dragHoverClass || 'on-drag-hover';
var customDragEnterEvent = $parse(attr.onDragEnter);
var customDragLeaveEvent = $parse(attr.onDragLeave);
function onDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
if (e.stopPropagation) {
e.stopPropagation();
}
var uiOnDragOverFn = $parse(attr.uiOnDragOver);
scope.$evalAsync(function() {
uiOnDragOverFn(scope, {$event: e, $channel: dropChannel});
});
return false;
}
function onDragLeave(e) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
dragging--;
if (dragging === 0) {
scope.$evalAsync(function() {
customDragLeaveEvent(scope, {$event: e, $channel: dropChannel});
});
element.addClass(dragEnterClass);
element.removeClass(dragHoverClass);
}
var uiOnDragLeaveFn = $parse(attr.uiOnDragLeave);
scope.$evalAsync(function() {
uiOnDragLeaveFn(scope, {$event: e, $channel: dropChannel});
});
}
function onDragEnter(e) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
if (dragging === 0) {
scope.$evalAsync(function() {
customDragEnterEvent(scope, {$event: e, $channel: dropChannel});
});
element.removeClass(dragEnterClass);
element.addClass(dragHoverClass);
}
dragging++;
var uiOnDragEnterFn = $parse(attr.uiOnDragEnter);
scope.$evalAsync(function() {
uiOnDragEnterFn(scope, {$event: e, $channel: dropChannel});
});
$rootScope.$broadcast('ANGULAR_HOVER', dragChannel);
}
function onDrop(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
if (e.stopPropagation) {
e.stopPropagation(); // Necessary. Allows us to drop.
}
var sendData = e.dataTransfer.getData('text');
sendData = angular.fromJson(sendData);
determineEffectAllowed(e);
var uiOnDropFn = $parse(attr.uiOnDrop);
scope.$evalAsync(function() {
uiOnDropFn(scope, {$data: sendData.data, $event: e, $channel: sendData.channel});
});
element.removeClass(dragEnterClass);
dragging = 0;
}
function isDragChannelAccepted(dragChannel, dropChannel) {
if (dropChannel === '*') {
return true;
}
var channelMatchPattern = new RegExp('(\\s|[,])+(' + dragChannel + ')(\\s|[,])+', 'i');
return channelMatchPattern.test(',' + dropChannel + ',');
}
function preventNativeDnD(e) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.dataTransfer.dropEffect = 'none';
return false;
}
var deregisterDragStart = $rootScope.$on('ANGULAR_DRAG_START', function(_, e, channel, transferDataObject) {
dragChannel = channel;
var valid = true;
if (!isDragChannelAccepted(channel, dropChannel)) {
valid = false;
}
if (valid && attr.dropValidate) {
var validateFn = $parse(attr.dropValidate);
valid = validateFn(scope, {
$drop: {scope: scope, element: element},
$event: e,
$data: transferDataObject.data,
$channel: transferDataObject.channel
});
}
if (valid) {
element.bind('dragover', onDragOver);
element.bind('dragenter', onDragEnter);
element.bind('dragleave', onDragLeave);
element.bind('drop', onDrop);
element.addClass(dragEnterClass);
} else {
element.bind('dragover', preventNativeDnD);
element.bind('dragenter', preventNativeDnD);
element.bind('dragleave', preventNativeDnD);
element.bind('drop', preventNativeDnD);
element.removeClass(dragEnterClass);
}
});
var deregisterDragEnd = $rootScope.$on('ANGULAR_DRAG_END', function(_, e, channel) {
element.unbind('dragover', onDragOver);
element.unbind('dragenter', onDragEnter);
element.unbind('dragleave', onDragLeave);
element.unbind('drop', onDrop);
element.removeClass(dragHoverClass);
element.removeClass(dragEnterClass);
element.unbind('dragover', preventNativeDnD);
element.unbind('dragenter', preventNativeDnD);
element.unbind('dragleave', preventNativeDnD);
element.unbind('drop', preventNativeDnD);
});
scope.$on('$destroy', function() {
deregisterDragStart();
deregisterDragEnd();
});
attr.$observe('dropChannel', function(value) {
if (value) {
dropChannel = value;
}
});
};
}
]);
module.constant('$dragImageConfig', {
height: 20,
width: 200,
padding: 10,
font: 'bold 11px Arial',
fontColor: '#eee8d5',
backgroundColor: '#93a1a1',
xOffset: 0,
yOffset: 0
});
module.service('$dragImage', ['$dragImageConfig', function(defaultConfig) {
var ELLIPSIS = '…';
function fitString(canvas, text, config) {
var width = canvas.measureText(text).width;
if (width < config.width) {
return text;
}
while (width + config.padding > config.width) {
text = text.substring(0, text.length - 1);
width = canvas.measureText(text + ELLIPSIS).width;
}
return text + ELLIPSIS;
}
this.generate = function(text, options) {
var config = angular.extend({}, defaultConfig, options || {});
var el = document.createElement('canvas');
el.height = config.height;
el.width = config.width;
var canvas = el.getContext('2d');
canvas.fillStyle = config.backgroundColor;
canvas.fillRect(0, 0, config.width, config.height);
canvas.font = config.font;
canvas.fillStyle = config.fontColor;
var title = fitString(canvas, text, config);
canvas.fillText(title, 4, config.padding + 4);
var image = new Image();
image.src = el.toDataURL();
return {
image: image,
xOffset: config.xOffset,
yOffset: config.yOffset
};
};
}
]);
}(angular));
| public/vendor/angular-native-dragdrop/draganddrop.js | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.00017774700245354325,
0.0001704804162727669,
0.00016435525321867317,
0.0001699702988844365,
0.000002824061539286049
] |
{
"id": 0,
"code_window": [
"/dist\n",
"/emails/dist\n",
"/public_gen\n",
"/tmp\n",
"\n",
"docs/AWS_S3_BUCKET\n",
"docs/GIT_BRANCH\n",
"docs/VERSION\n",
"docs/GITCOMMIT\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"vendor/phantomjs/phantomjs\n"
],
"file_path": ".gitignore",
"type": "add",
"edit_start_line_idx": 8
} | define([
'angular',
'lodash',
'config',
'store',
'filesaver'
],
function (angular, _) {
'use strict';
var module = angular.module('grafana.controllers');
module.controller('DashboardNavCtrl', function($scope, $rootScope, alertSrv, $location, playlistSrv, backendSrv, $timeout) {
$scope.init = function() {
$scope.onAppEvent('save-dashboard', $scope.saveDashboard);
$scope.onAppEvent('delete-dashboard', $scope.deleteDashboard);
};
$scope.openEditView = function(editview) {
var search = _.extend($location.search(), {editview: editview});
$location.search(search);
};
$scope.starDashboard = function() {
if ($scope.dashboardMeta.isStarred) {
backendSrv.delete('/api/user/stars/dashboard/' + $scope.dashboard.id).then(function() {
$scope.dashboardMeta.isStarred = false;
});
}
else {
backendSrv.post('/api/user/stars/dashboard/' + $scope.dashboard.id).then(function() {
$scope.dashboardMeta.isStarred = true;
});
}
};
$scope.shareDashboard = function() {
$scope.appEvent('show-modal', {
src: './app/features/dashboard/partials/shareModal.html',
scope: $scope.$new(),
});
};
$scope.openSearch = function() {
$scope.appEvent('show-dash-search');
};
$scope.hideTooltip = function(evt) {
angular.element(evt.currentTarget).tooltip('hide');
$scope.appEvent('hide-dash-search');
};
$scope.saveDashboard = function(options) {
if ($scope.dashboardMeta.canSave === false) {
return;
}
var clone = $scope.dashboard.getSaveModelClone();
backendSrv.saveDashboard(clone, options).then(function(data) {
$scope.dashboard.version = data.version;
$scope.appEvent('dashboard-saved', $scope.dashboard);
var dashboardUrl = '/dashboard/db/' + data.slug;
if (dashboardUrl !== $location.path()) {
$location.url(dashboardUrl);
}
$scope.appEvent('alert-success', ['Dashboard saved', 'Saved as ' + clone.title]);
}, $scope.handleSaveDashError);
};
$scope.handleSaveDashError = function(err) {
if (err.data && err.data.status === "version-mismatch") {
err.isHandled = true;
$scope.appEvent('confirm-modal', {
title: 'Someone else has updated this dashboard!',
text: "Would you still like to save this dashboard?",
yesText: "Save & Overwrite",
icon: "fa-warning",
onConfirm: function() {
$scope.saveDashboard({overwrite: true});
}
});
}
if (err.data && err.data.status === "name-exists") {
err.isHandled = true;
$scope.appEvent('confirm-modal', {
title: 'Another dashboard with the same name exists',
text: "Would you still like to save this dashboard?",
yesText: "Save & Overwrite",
icon: "fa-warning",
onConfirm: function() {
$scope.saveDashboard({overwrite: true});
}
});
}
};
$scope.deleteDashboard = function() {
$scope.appEvent('confirm-modal', {
title: 'Do you want to delete dashboard ' + $scope.dashboard.title + '?',
icon: 'fa-trash',
yesText: 'Delete',
onConfirm: function() {
$scope.deleteDashboardConfirmed();
}
});
};
$scope.deleteDashboardConfirmed = function() {
backendSrv.delete('/api/dashboards/db/' + $scope.dashboardMeta.slug).then(function() {
$scope.appEvent('alert-success', ['Dashboard Deleted', $scope.dashboard.title + ' has been deleted']);
$location.url('/');
});
};
$scope.saveDashboardAs = function() {
var newScope = $rootScope.$new();
newScope.clone = $scope.dashboard.getSaveModelClone();
newScope.clone.editable = true;
newScope.clone.hideControls = false;
$scope.appEvent('show-modal', {
src: './app/features/dashboard/partials/saveDashboardAs.html',
scope: newScope,
});
};
$scope.exportDashboard = function() {
var clone = $scope.dashboard.getSaveModelClone();
var blob = new Blob([angular.toJson(clone, true)], { type: "application/json;charset=utf-8" });
window.saveAs(blob, $scope.dashboard.title + '-' + new Date().getTime());
};
$scope.snapshot = function() {
$scope.dashboard.snapshot = true;
$rootScope.$broadcast('refresh');
$timeout(function() {
$scope.exportDashboard();
$scope.dashboard.snapshot = false;
$scope.appEvent('dashboard-snapshot-cleanup');
}, 1000);
};
$scope.editJson = function() {
var clone = $scope.dashboard.getSaveModelClone();
$scope.appEvent('show-json-editor', { object: clone });
};
$scope.stopPlaylist = function() {
playlistSrv.stop(1);
};
});
});
| public/app/features/dashboard/dashboardNavCtrl.js | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.00017704383935779333,
0.00017125846352428198,
0.0001642170682316646,
0.000171221952768974,
0.000003231342361686984
] |
{
"id": 0,
"code_window": [
"/dist\n",
"/emails/dist\n",
"/public_gen\n",
"/tmp\n",
"\n",
"docs/AWS_S3_BUCKET\n",
"docs/GIT_BRANCH\n",
"docs/VERSION\n",
"docs/GITCOMMIT\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"vendor/phantomjs/phantomjs\n"
],
"file_path": ".gitignore",
"type": "add",
"edit_start_line_idx": 8
} | define([
"./core",
"./var/rnotwhite",
"./core/access",
"./data/var/data_priv",
"./data/var/data_user"
], function( jQuery, rnotwhite, access, data_priv, data_user ) {
// Implementation Summary
//
// 1. Enforce API surface and semantic compatibility with 1.9.x branch
// 2. Improve the module's maintainability by reducing the storage
// paths to a single mechanism.
// 3. Use the same single mechanism to support "private" and "user" data.
// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
// 5. Avoid exposing implementation details on user objects (eg. expando properties)
// 6. Provide a clear path for implementation upgrade to WeakMap in 2014
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
return jQuery;
});
| public/vendor/jquery/src/data.js | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.00017622851009946316,
0.0001710544020170346,
0.00016422678891103715,
0.00017126384773291647,
0.0000030534133657056373
] |
{
"id": 1,
"code_window": [
"\n",
" var m=grunt.file.read(confDir+\"location.js\")\n",
" var src=/= \\\"([^\\\"]*)\\\"/.exec(m)[1];\n",
" \n",
" if (!grunt.file.isPathAbsolute(src)) {\n",
" src = confDir+src;\n",
" }\n",
"\n",
" var exec = require('child_process').execFileSync;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 12
} | module.exports = function(config,grunt) {
'use strict';
grunt.registerTask('phantomjs', 'Copy phantomjs binary from node', function() {
var dest = './vendor/phantomjs/phantomjs';
var confDir = './node_modules/karma-phantomjs-launcher/node_modules/phantomjs/lib/'
if (!grunt.file.exists(dest)){
var m=grunt.file.read(confDir+"location.js")
var src=/= \"([^\"]*)\"/.exec(m)[1];
if (!grunt.file.isPathAbsolute(src)) {
src = confDir+src;
}
var exec = require('child_process').execFileSync;
try {
var ph=exec(src,['-v'], { stdio: 'ignore' });
grunt.verbose.writeln('Using '+ src);
grunt.file.copy(src, dest, { encoding: null });
} catch (err) {
grunt.verbose.writeln(err);
grunt.fail.warn('No working Phantomjs binary available')
}
} else {
grunt.log.writeln('Phantomjs already imported from node');
}
});
};
| tasks/options/phantomjs.js | 1 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.9984111785888672,
0.49914228916168213,
0.00017205203766934574,
0.4989929795265198,
0.49829280376434326
] |
{
"id": 1,
"code_window": [
"\n",
" var m=grunt.file.read(confDir+\"location.js\")\n",
" var src=/= \\\"([^\\\"]*)\\\"/.exec(m)[1];\n",
" \n",
" if (!grunt.file.isPathAbsolute(src)) {\n",
" src = confDir+src;\n",
" }\n",
"\n",
" var exec = require('child_process').execFileSync;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 12
} | // Type definitions for Moment.js 2.8.0
// Project: https://github.com/timrwood/moment
// Definitions by: Michael Lakerveld <https://github.com/Lakerfield>, Aaron King <https://github.com/kingdango>, Hiroki Horiuchi <https://github.com/horiuchi>, Dick van den Brink <https://github.com/DickvdBrink>, Adi Dahiya <https://github.com/adidahiya>, Matt Brooks <https://github.com/EnableSoftware>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="moment-node.d.ts" />
| public/app/headers/moment/moment.d.ts | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.00017264166672248393,
0.00017264166672248393,
0.00017264166672248393,
0.00017264166672248393,
0
] |
{
"id": 1,
"code_window": [
"\n",
" var m=grunt.file.read(confDir+\"location.js\")\n",
" var src=/= \\\"([^\\\"]*)\\\"/.exec(m)[1];\n",
" \n",
" if (!grunt.file.isPathAbsolute(src)) {\n",
" src = confDir+src;\n",
" }\n",
"\n",
" var exec = require('child_process').execFileSync;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 12
} | // Command tomlv validates TOML documents and prints each key's type.
package main
import (
"flag"
"fmt"
"log"
"os"
"path"
"strings"
"text/tabwriter"
"github.com/BurntSushi/toml"
)
var (
flagTypes = false
)
func init() {
log.SetFlags(0)
flag.BoolVar(&flagTypes, "types", flagTypes,
"When set, the types of every defined key will be shown.")
flag.Usage = usage
flag.Parse()
}
func usage() {
log.Printf("Usage: %s toml-file [ toml-file ... ]\n",
path.Base(os.Args[0]))
flag.PrintDefaults()
os.Exit(1)
}
func main() {
if flag.NArg() < 1 {
flag.Usage()
}
for _, f := range flag.Args() {
var tmp interface{}
md, err := toml.DecodeFile(f, &tmp)
if err != nil {
log.Fatalf("Error in '%s': %s", f, err)
}
if flagTypes {
printTypes(md)
}
}
}
func printTypes(md toml.MetaData) {
tabw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
for _, key := range md.Keys() {
fmt.Fprintf(tabw, "%s%s\t%s\n",
strings.Repeat(" ", len(key)-1), key, md.Type(key...))
}
tabw.Flush()
}
| Godeps/_workspace/src/github.com/BurntSushi/toml/cmd/tomlv/main.go | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.00017323018983006477,
0.0001690403587417677,
0.0001616239023860544,
0.00016954859893303365,
0.0000038058751670178026
] |
{
"id": 1,
"code_window": [
"\n",
" var m=grunt.file.read(confDir+\"location.js\")\n",
" var src=/= \\\"([^\\\"]*)\\\"/.exec(m)[1];\n",
" \n",
" if (!grunt.file.isPathAbsolute(src)) {\n",
" src = confDir+src;\n",
" }\n",
"\n",
" var exec = require('child_process').execFileSync;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 12
} | // Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: [email protected] (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers
// Any returns a matcher that matches any value.
func Any() Matcher {
return &anyMatcher{}
}
type anyMatcher struct {
}
func (m *anyMatcher) Description() string {
return "is anything"
}
func (m *anyMatcher) Matches(c interface{}) error {
return nil
}
| Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/assertions/oglematchers/any.go | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.00017727223166730255,
0.00017303175991401076,
0.00016821960161905736,
0.00017331758863292634,
0.000003837082658719737
] |
{
"id": 2,
"code_window": [
" var exec = require('child_process').execFileSync;\n",
"\n",
" try {\n",
" var ph=exec(src,['-v'], { stdio: 'ignore' });\n",
" grunt.verbose.writeln('Using '+ src);\n",
" grunt.file.copy(src, dest, { encoding: null });\n",
" } catch (err) {\n",
" grunt.verbose.writeln(err);\n",
" grunt.fail.warn('No working Phantomjs binary available')\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" grunt.config('copy.phantom_bin', {\n",
" src: src,\n",
" dest: dest,\n",
" options: { mode: true},\n",
" });\n",
" grunt.task.run('copy:phantom_bin');\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 20
} | module.exports = function(config,grunt) {
'use strict';
grunt.registerTask('phantomjs', 'Copy phantomjs binary from node', function() {
var dest = './vendor/phantomjs/phantomjs';
var confDir = './node_modules/karma-phantomjs-launcher/node_modules/phantomjs/lib/'
if (!grunt.file.exists(dest)){
var m=grunt.file.read(confDir+"location.js")
var src=/= \"([^\"]*)\"/.exec(m)[1];
if (!grunt.file.isPathAbsolute(src)) {
src = confDir+src;
}
var exec = require('child_process').execFileSync;
try {
var ph=exec(src,['-v'], { stdio: 'ignore' });
grunt.verbose.writeln('Using '+ src);
grunt.file.copy(src, dest, { encoding: null });
} catch (err) {
grunt.verbose.writeln(err);
grunt.fail.warn('No working Phantomjs binary available')
}
} else {
grunt.log.writeln('Phantomjs already imported from node');
}
});
};
| tasks/options/phantomjs.js | 1 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.9985055923461914,
0.49926745891571045,
0.00017264430061914027,
0.4991958439350128,
0.4984639286994934
] |
{
"id": 2,
"code_window": [
" var exec = require('child_process').execFileSync;\n",
"\n",
" try {\n",
" var ph=exec(src,['-v'], { stdio: 'ignore' });\n",
" grunt.verbose.writeln('Using '+ src);\n",
" grunt.file.copy(src, dest, { encoding: null });\n",
" } catch (err) {\n",
" grunt.verbose.writeln(err);\n",
" grunt.fail.warn('No working Phantomjs binary available')\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" grunt.config('copy.phantom_bin', {\n",
" src: src,\n",
" dest: dest,\n",
" options: { mode: true},\n",
" });\n",
" grunt.task.run('copy:phantom_bin');\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 20
} | package rest
import "reflect"
// PayloadMember returns the payload field member of i if there is one, or nil.
func PayloadMember(i interface{}) interface{} {
if i == nil {
return nil
}
v := reflect.ValueOf(i).Elem()
if !v.IsValid() {
return nil
}
if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok {
if payloadName := field.Tag.Get("payload"); payloadName != "" {
field, _ := v.Type().FieldByName(payloadName)
if field.Tag.Get("type") != "structure" {
return nil
}
payload := v.FieldByName(payloadName)
if payload.IsValid() || (payload.Kind() == reflect.Ptr && !payload.IsNil()) {
return payload.Interface()
}
}
}
return nil
}
// PayloadType returns the type of a payload field member of i if there is one, or "".
func PayloadType(i interface{}) string {
v := reflect.Indirect(reflect.ValueOf(i))
if !v.IsValid() {
return ""
}
if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok {
if payloadName := field.Tag.Get("payload"); payloadName != "" {
if member, ok := v.Type().FieldByName(payloadName); ok {
return member.Tag.Get("type")
}
}
}
return ""
}
| Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/payload.go | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.00023439826327376068,
0.0001838282769313082,
0.00016574915207456797,
0.0001725712209008634,
0.000025467577870585956
] |
{
"id": 2,
"code_window": [
" var exec = require('child_process').execFileSync;\n",
"\n",
" try {\n",
" var ph=exec(src,['-v'], { stdio: 'ignore' });\n",
" grunt.verbose.writeln('Using '+ src);\n",
" grunt.file.copy(src, dest, { encoding: null });\n",
" } catch (err) {\n",
" grunt.verbose.writeln(err);\n",
" grunt.fail.warn('No working Phantomjs binary available')\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" grunt.config('copy.phantom_bin', {\n",
" src: src,\n",
" dest: dest,\n",
" options: { mode: true},\n",
" });\n",
" grunt.task.run('copy:phantom_bin');\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 20
} |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/assertions/oglematchers/LICENSE | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.00017991490312851965,
0.00017772754654288292,
0.00017480716633144766,
0.00017812721489463001,
0.000001429775579708803
] |
{
"id": 2,
"code_window": [
" var exec = require('child_process').execFileSync;\n",
"\n",
" try {\n",
" var ph=exec(src,['-v'], { stdio: 'ignore' });\n",
" grunt.verbose.writeln('Using '+ src);\n",
" grunt.file.copy(src, dest, { encoding: null });\n",
" } catch (err) {\n",
" grunt.verbose.writeln(err);\n",
" grunt.fail.warn('No working Phantomjs binary available')\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" grunt.config('copy.phantom_bin', {\n",
" src: src,\n",
" dest: dest,\n",
" options: { mode: true},\n",
" });\n",
" grunt.task.run('copy:phantom_bin');\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 20
} | ----
page_title: Graphite query guide
page_description: Graphite query guide
page_keywords: grafana, graphite, metrics, query, documentation
---
# Graphite
Grafana has an advanced Graphite query editor that lets you quickly navigate the metric space, add functions,
change function parameters and much more. The editor can handle all types of graphite queries. It can even handle complex nested
queries through the use of query references.
## Adding the data source to Grafana

1. Open the side menu by clicking the the Grafana icon in the top header.
2. In the side menu under the `Dashboards` link you should find a link named `Data Sources`.
> NOTE: If this link is missing in the side menu it means that your current user does not have the `Admin` role for the current organization.
3. Click the `Add new` link in the top header.
4. Select `Graphite` from the dropdown.
Name | Description
------------ | -------------
Name | The data source name, important that this is the same as in Grafana v1.x if you plan to import old dashboards.
Default | Default data source means that it will be pre-selected for new panels.
Url | The http protocol, ip and port of you graphite-web or graphite-api install.
Access | Proxy = access via Grafana backend, Direct = access directory from browser.
Proxy access means that the Grafana backend will proxy all requests from the browser, and send them on to the Data Source. This is useful because it can eliminate CORS (Cross Origin Site Resource) issues, as well as eliminate the need to disseminate authentication details to the Data Source to the brower.
Direct access is still supported because in some cases it may be useful to access a Data Source directly depending on the use case and topology of Grafana, the user, and the Data Source.
## Metric editor
### Navigate metric segments
Click the ``Select metric`` link to start navigating the metric space. One you start you can continue using the mouse
or keyboard arrow keys. You can select a wildcard and still continue.

### Functions
Click the plus icon to the right to add a function. You can search for the function or select it from the menu. Once
a function is selected it will be added and your focus will be in the text box of the first parameter. To later change
a parameter just click on it and it will turn into a text box. To delete a function click the function name followed
by the x icon.

### Optional parameters
Some functions like aliasByNode support an optional second argument. To add this parameter specify for example 3,-2 as the first parameter and the function editor will adapt and move the -2 to a second parameter. To remove the second optional parameter just click on it and leave it blank and the editor will remove it.

## Point consolidation
All Graphite metrics are consolidated so that Graphite doesn't return more data points than there are pixels in the graph. By default
this consolidation is done using `avg` function. You can how Graphite consolidates metrics by adding the Graphite consolidateBy function.
> *Notice* This means that legend summary values (max, min, total) cannot be all correct at the same time. They are calculated
> client side by Grafana. And depending on your consolidation function only one or two can be correct at the same time.
## Templating
You can create a template variable in Grafana and have that variable filled with values from any Graphite metric exploration query.
You can then use this variable in your Graphite queries, either as part of a metric path or as arguments to functions.
For example a query like `prod.servers.*` will fill the variable with all possible
values that exists in the wildcard position.
You can also create nested variables that use other variables in their definition. For example
`apps.$app.servers.*` uses the variable `$app` in its query definition.

## Query Reference
You can reference queries by the row “letter” that they’re on (similar to Microsoft Excel). If you add a second query to graph, you can reference the first query simply by typing in #A. This provides an easy and convenient way to build compounded queries. | docs/sources/datasources/graphite.md | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.0001766100322129205,
0.00017214879335369915,
0.00016329815844073892,
0.00017310320981778204,
0.0000036929193356627366
] |
{
"id": 3,
"code_window": [
" grunt.verbose.writeln(err);\n",
" grunt.fail.warn('No working Phantomjs binary available')\n",
" }\n",
" \n",
" } else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 27
} | module.exports = function(config,grunt) {
'use strict';
grunt.registerTask('phantomjs', 'Copy phantomjs binary from node', function() {
var dest = './vendor/phantomjs/phantomjs';
var confDir = './node_modules/karma-phantomjs-launcher/node_modules/phantomjs/lib/'
if (!grunt.file.exists(dest)){
var m=grunt.file.read(confDir+"location.js")
var src=/= \"([^\"]*)\"/.exec(m)[1];
if (!grunt.file.isPathAbsolute(src)) {
src = confDir+src;
}
var exec = require('child_process').execFileSync;
try {
var ph=exec(src,['-v'], { stdio: 'ignore' });
grunt.verbose.writeln('Using '+ src);
grunt.file.copy(src, dest, { encoding: null });
} catch (err) {
grunt.verbose.writeln(err);
grunt.fail.warn('No working Phantomjs binary available')
}
} else {
grunt.log.writeln('Phantomjs already imported from node');
}
});
};
| tasks/options/phantomjs.js | 1 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.9464315176010132,
0.23680171370506287,
0.00016728036280255765,
0.00030402347329072654,
0.4097049832344055
] |
{
"id": 3,
"code_window": [
" grunt.verbose.writeln(err);\n",
" grunt.fail.warn('No working Phantomjs binary available')\n",
" }\n",
" \n",
" } else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 27
} | define([
'./alertSrv',
'./utilSrv',
'./datasourceSrv',
'./contextSrv',
'./timer',
'./keyboardManager',
'./analytics',
'./popoverSrv',
'./uiSegmentSrv',
'./backendSrv',
],
function () {});
| public/app/services/all.js | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.00017096713418141007,
0.0001686784962657839,
0.0001663898437982425,
0.0001686784962657839,
0.0000022886451915837824
] |
{
"id": 3,
"code_window": [
" grunt.verbose.writeln(err);\n",
" grunt.fail.warn('No working Phantomjs binary available')\n",
" }\n",
" \n",
" } else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 27
} | -----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDjjAaacFRR0TQ0gznNolkPBe2N2A400JL0CU3ujHhVSST4POA0
WAKy55RYwejlu9Gv9lTBQLGQcHkNNVScjxbpwvCS5mRJOMF2+EdmxFtKtqlDzsi+
bE0rlJc8VbzR0G63U66JXEtrhkC+wa4eZM6crocKaeXIIRK+rh32Rd8WpwIDAQAB
AoGAM5dM6/kp9P700i8qjOgRPym96Zoh5nGfz/rIE5z/r36NBkdvIg8OVZfR96nH
b0b9TOMR5lsPp0sI9yivTWvX6qyvLJRWy2vvx17hXK9NxXUNTAm0PYZUTvCtcPeX
RnJpzQKNZQPkFzF0uXBc4CtPK2Vz0+FGvAelrhYAxnw1dIkCQQD+9qaW5QhXjsjb
Nl85CmXgxPmGROcgLQCO+omfrjf9UXrituU9Dz6auym5lDGEdMFnkzfr+wpasEy9
mf5ZZOhDAkEA5HjXfVGaCtpydOt6hDon/uZsyssCK2lQ7NSuE3vP+sUsYMzIpEoy
t3VWXqKbo+g9KNDTP4WEliqp1aiSIylzzQJANPeqzihQnlgEdD4MdD4rwhFJwVIp
Le8Lcais1KaN7StzOwxB/XhgSibd2TbnPpw+3bSg5n5lvUdo+e62/31OHwJAU1jS
I+F09KikQIr28u3UUWT2IzTT4cpVv1AHAQyV3sG3YsjSGT0IK20eyP9BEBZU2WL0
7aNjrvR5aHxKc5FXsQJABsFtyGpgI5X4xufkJZVZ+Mklz2n7iXa+XPatMAHFxAtb
EEMt60rngwMjXAzBSC6OYuYogRRAY3UCacNC5VhLYQ==
-----END RSA PRIVATE KEY-----
| Godeps/_workspace/src/github.com/lib/pq/certs/postgresql.key | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.0035710588563233614,
0.001869247411377728,
0.00016743595188017935,
0.001869247411377728,
0.0017018114449456334
] |
{
"id": 3,
"code_window": [
" grunt.verbose.writeln(err);\n",
" grunt.fail.warn('No working Phantomjs binary available')\n",
" }\n",
" \n",
" } else {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 27
} | 本包提供了 Go 语言中读写 INI 文件的功能。
## 功能特性
- 支持覆盖加载多个数据源(`[]byte` 或文件)
- 支持递归读取键值
- 支持读取父子分区
- 支持读取自增键名
- 支持读取多行的键值
- 支持大量辅助方法
- 支持在读取时直接转换为 Go 语言类型
- 支持读取和 **写入** 分区和键的注释
- 轻松操作分区、键值和注释
- 在保存文件时分区和键值会保持原有的顺序
## 下载安装
go get gopkg.in/ini.v1
## 开始使用
### 从数据源加载
一个 **数据源** 可以是 `[]byte` 类型的原始数据,或 `string` 类型的文件路径。您可以加载 **任意多个** 数据源。如果您传递其它类型的数据源,则会直接返回错误。
```go
cfg, err := ini.Load([]byte("raw data"), "filename")
```
或者从一个空白的文件开始:
```go
cfg := ini.Empty()
```
当您在一开始无法决定需要加载哪些数据源时,仍可以使用 **Append()** 在需要的时候加载它们。
```go
err := cfg.Append("other file", []byte("other raw data"))
```
### 操作分区(Section)
获取指定分区:
```go
section, err := cfg.GetSection("section name")
```
如果您想要获取默认分区,则可以用空字符串代替分区名:
```go
section, err := cfg.GetSection("")
```
当您非常确定某个分区是存在的,可以使用以下简便方法:
```go
section := cfg.Section("")
```
如果不小心判断错了,要获取的分区其实是不存在的,那会发生什么呢?没事的,它会自动创建并返回一个对应的分区对象给您。
创建一个分区:
```go
err := cfg.NewSection("new section")
```
获取所有分区对象或名称:
```go
sections := cfg.Sections()
names := cfg.SectionStrings()
```
### 操作键(Key)
获取某个分区下的键:
```go
key, err := cfg.Section("").GetKey("key name")
```
和分区一样,您也可以直接获取键而忽略错误处理:
```go
key := cfg.Section("").Key("key name")
```
创建一个新的键:
```go
err := cfg.Section("").NewKey("name", "value")
```
获取分区下的所有键或键名:
```go
keys := cfg.Section().Keys()
names := cfg.Section().KeyStrings()
```
获取分区下的所有键值对的克隆:
```go
hash := cfg.GetSection("").KeysHash()
```
### 操作键值(Value)
获取一个类型为字符串(string)的值:
```go
val := cfg.Section("").Key("key name").String()
```
获取其它类型的值:
```go
// 布尔值的规则:
// true 当值为:1, t, T, TRUE, true, True, YES, yes, Yes, ON, on, On
// false 当值为:0, f, F, FALSE, false, False, NO, no, No, OFF, off, Off
v, err = cfg.Section("").Key("BOOL").Bool()
v, err = cfg.Section("").Key("FLOAT64").Float64()
v, err = cfg.Section("").Key("INT").Int()
v, err = cfg.Section("").Key("INT64").Int64()
v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339)
v, err = cfg.Section("").Key("TIME").Time() // RFC3339
v = cfg.Section("").Key("BOOL").MustBool()
v = cfg.Section("").Key("FLOAT64").MustFloat64()
v = cfg.Section("").Key("INT").MustInt()
v = cfg.Section("").Key("INT64").MustInt64()
v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339)
v = cfg.Section("").Key("TIME").MustTime() // RFC3339
// 由 Must 开头的方法名允许接收一个相同类型的参数来作为默认值,
// 当键不存在或者转换失败时,则会直接返回该默认值。
// 但是,MustString 方法必须传递一个默认值。
v = cfg.Seciont("").Key("String").MustString("default")
v = cfg.Section("").Key("BOOL").MustBool(true)
v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25)
v = cfg.Section("").Key("INT").MustInt(10)
v = cfg.Section("").Key("INT64").MustInt64(99)
v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now())
v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339
```
如果我的值有好多行怎么办?
```ini
[advance]
ADDRESS = """404 road,
NotFound, State, 5000
Earth"""
```
嗯哼?小 case!
```go
cfg.Section("advance").Key("ADDRESS").String()
/* --- start ---
404 road,
NotFound, State, 5000
Earth
------ end --- */
```
这就是全部了?哈哈,当然不是。
#### 操作键值的辅助方法
获取键值时设定候选值:
```go
v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"})
v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75})
v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30})
v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30})
v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3})
v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339
```
如果获取到的值不是候选值的任意一个,则会返回默认值,而默认值不需要是候选值中的一员。
验证获取的值是否在指定范围内:
```go
vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2)
vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20)
vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20)
vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime)
vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339
```
自动分割键值为切片(slice):
```go
vals = cfg.Section("").Key("STRINGS").Strings(",")
vals = cfg.Section("").Key("FLOAT64S").Float64s(",")
vals = cfg.Section("").Key("INTS").Ints(",")
vals = cfg.Section("").Key("INT64S").Int64s(",")
vals = cfg.Section("").Key("TIMES").Times(",")
```
### 高级用法
#### 递归读取键值
在获取所有键值的过程中,特殊语法 `%(<name>)s` 会被应用,其中 `<name>` 可以是相同分区或者默认分区下的键名。字符串 `%(<name>)s` 会被相应的键值所替代,如果指定的键不存在,则会用空字符串替代。您可以最多使用 99 层的递归嵌套。
```ini
NAME = ini
[author]
NAME = Unknwon
GITHUB = https://github.com/%(NAME)s
[package]
FULL_NAME = github.com/go-ini/%(NAME)s
```
```go
cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon
cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini
```
#### 读取父子分区
您可以在分区名称中使用 `.` 来表示两个或多个分区之间的父子关系。如果某个键在子分区中不存在,则会去它的父分区中再次寻找,直到没有父分区为止。
```ini
NAME = ini
VERSION = v1
IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s
[package]
CLONE_URL = https://%(IMPORT_PATH)s
[package.sub]
```
```go
cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1
```
#### 读取自增键名
如果数据源中的键名为 `-`,则认为该键使用了自增键名的特殊语法。计数器从 1 开始,并且分区之间是相互独立的。
```ini
[features]
-: Support read/write comments of keys and sections
-: Support auto-increment of key names
-: Support load multiple files to overwrite key values
```
```go
cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"}
```
### 映射到结构
想要使用更加面向对象的方式玩转 INI 吗?好主意。
```ini
Name = Unknwon
age = 21
Male = true
Born = 1993-01-01T20:17:05Z
[Note]
Content = Hi is a good man!
Cities = HangZhou, Boston
```
```go
type Note struct {
Content string
Cities []string
}
type Person struct {
Name string
Age int `ini:"age"`
Male bool
Born time.Time
Note
Created time.Time `ini:"-"`
}
func main() {
cfg, err := ini.Load("path/to/ini")
// ...
p := new(Person)
err = cfg.MapTo(p)
// ...
// 一切竟可以如此的简单。
err = ini.MapTo(p, "path/to/ini")
// ...
// 嗯哼?只需要映射一个分区吗?
n := new(Note)
err = cfg.Section("Note").MapTo(n)
// ...
}
```
结构的字段怎么设置默认值呢?很简单,只要在映射之前对指定字段进行赋值就可以了。如果键未找到或者类型错误,该值不会发生改变。
```go
// ...
p := &Person{
Name: "Joe",
}
// ...
```
#### 名称映射器(Name Mapper)
为了节省您的时间并简化代码,本库支持类型为 [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) 的名称映射器,该映射器负责结构字段名与分区名和键名之间的映射。
目前有 2 款内置的映射器:
- `AllCapsUnderscore`:该映射器将字段名转换至格式 `ALL_CAPS_UNDERSCORE` 后再去匹配分区名和键名。
- `TitleUnderscore`:该映射器将字段名转换至格式 `title_underscore` 后再去匹配分区名和键名。
使用方法:
```go
type Info struct{
PackageName string
}
func main() {
err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("packag_name=ini"))
// ...
cfg, err := ini.Load("PACKAGE_NAME=ini")
// ...
info := new(Info)
cfg.NameMapper = ini.AllCapsUnderscore
err = cfg.MapTo(info)
// ...
}
```
## 获取帮助
- [API 文档](https://gowalker.org/gopkg.in/ini.v1)
- [创建工单](https://github.com/go-ini/ini/issues/new)
## 常见问题
### 字段 `BlockMode` 是什么?
默认情况下,本库会在您进行读写操作时采用锁机制来确保数据时间。但在某些情况下,您非常确定只进行读操作。此时,您可以通过设置 `cfg.BlockMode = false` 来将读操作提升大约 **50-70%** 的性能。
### 为什么要写另一个 INI 解析库?
许多人都在使用我的 [goconfig](https://github.com/Unknwon/goconfig) 来完成对 INI 文件的操作,但我希望使用更加 Go 风格的代码。并且当您设置 `cfg.BlockMode = false` 时,会有大约 **10-30%** 的性能提升。
为了做出这些改变,我必须对 API 进行破坏,所以新开一个仓库是最安全的做法。除此之外,本库直接使用 `gopkg.in` 来进行版本化发布。(其实真相是导入路径更短了)
| Godeps/_workspace/src/gopkg.in/ini.v1/README_ZH.md | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.009514340199530125,
0.0008714391151443124,
0.00016264502482954413,
0.00016969317221082747,
0.001639505964703858
] |
{
"id": 4,
"code_window": [
" } else {\n",
" grunt.log.writeln('Phantomjs already imported from node');\n",
" }\n",
" });\n",
"};"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" grunt.log.writeln('Phantomjs already imported from node');\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 29
} | module.exports = function(config,grunt) {
'use strict';
grunt.registerTask('phantomjs', 'Copy phantomjs binary from node', function() {
var dest = './vendor/phantomjs/phantomjs';
var confDir = './node_modules/karma-phantomjs-launcher/node_modules/phantomjs/lib/'
if (!grunt.file.exists(dest)){
var m=grunt.file.read(confDir+"location.js")
var src=/= \"([^\"]*)\"/.exec(m)[1];
if (!grunt.file.isPathAbsolute(src)) {
src = confDir+src;
}
var exec = require('child_process').execFileSync;
try {
var ph=exec(src,['-v'], { stdio: 'ignore' });
grunt.verbose.writeln('Using '+ src);
grunt.file.copy(src, dest, { encoding: null });
} catch (err) {
grunt.verbose.writeln(err);
grunt.fail.warn('No working Phantomjs binary available')
}
} else {
grunt.log.writeln('Phantomjs already imported from node');
}
});
};
| tasks/options/phantomjs.js | 1 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.9970447421073914,
0.2502966821193695,
0.00016849071835167706,
0.001986740157008171,
0.43113774061203003
] |
{
"id": 4,
"code_window": [
" } else {\n",
" grunt.log.writeln('Phantomjs already imported from node');\n",
" }\n",
" });\n",
"};"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" grunt.log.writeln('Phantomjs already imported from node');\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 29
} | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bufio_test
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"strings"
"testing"
"testing/iotest"
"time"
"unicode/utf8"
. "gopkg.in/bufio.v1"
)
// Reads from a reader and rot13s the result.
type rot13Reader struct {
r io.Reader
}
func newRot13Reader(r io.Reader) *rot13Reader {
r13 := new(rot13Reader)
r13.r = r
return r13
}
func (r13 *rot13Reader) Read(p []byte) (int, error) {
n, err := r13.r.Read(p)
if err != nil {
return n, err
}
for i := 0; i < n; i++ {
c := p[i] | 0x20 // lowercase byte
if 'a' <= c && c <= 'm' {
p[i] += 13
} else if 'n' <= c && c <= 'z' {
p[i] -= 13
}
}
return n, nil
}
// Call ReadByte to accumulate the text of a file
func readBytes(buf *Reader) string {
var b [1000]byte
nb := 0
for {
c, err := buf.ReadByte()
if err == io.EOF {
break
}
if err == nil {
b[nb] = c
nb++
} else if err != iotest.ErrTimeout {
panic("Data: " + err.Error())
}
}
return string(b[0:nb])
}
func TestReaderSimple(t *testing.T) {
data := "hello world"
b := NewReader(strings.NewReader(data))
if s := readBytes(b); s != "hello world" {
t.Errorf("simple hello world test failed: got %q", s)
}
b = NewReader(newRot13Reader(strings.NewReader(data)))
if s := readBytes(b); s != "uryyb jbeyq" {
t.Errorf("rot13 hello world test failed: got %q", s)
}
}
type readMaker struct {
name string
fn func(io.Reader) io.Reader
}
var readMakers = []readMaker{
{"full", func(r io.Reader) io.Reader { return r }},
{"byte", iotest.OneByteReader},
{"half", iotest.HalfReader},
{"data+err", iotest.DataErrReader},
{"timeout", iotest.TimeoutReader},
}
// Call ReadString (which ends up calling everything else)
// to accumulate the text of a file.
func readLines(b *Reader) string {
s := ""
for {
s1, err := b.ReadString('\n')
if err == io.EOF {
break
}
if err != nil && err != iotest.ErrTimeout {
panic("GetLines: " + err.Error())
}
s += s1
}
return s
}
// Call Read to accumulate the text of a file
func reads(buf *Reader, m int) string {
var b [1000]byte
nb := 0
for {
n, err := buf.Read(b[nb : nb+m])
nb += n
if err == io.EOF {
break
}
}
return string(b[0:nb])
}
type bufReader struct {
name string
fn func(*Reader) string
}
var bufreaders = []bufReader{
{"1", func(b *Reader) string { return reads(b, 1) }},
{"2", func(b *Reader) string { return reads(b, 2) }},
{"3", func(b *Reader) string { return reads(b, 3) }},
{"4", func(b *Reader) string { return reads(b, 4) }},
{"5", func(b *Reader) string { return reads(b, 5) }},
{"7", func(b *Reader) string { return reads(b, 7) }},
{"bytes", readBytes},
{"lines", readLines},
}
const minReadBufferSize = 16
var bufsizes = []int{
0, minReadBufferSize, 23, 32, 46, 64, 93, 128, 1024, 4096,
}
func TestReader(t *testing.T) {
var texts [31]string
str := ""
all := ""
for i := 0; i < len(texts)-1; i++ {
texts[i] = str + "\n"
all += texts[i]
str += string(i%26 + 'a')
}
texts[len(texts)-1] = all
for h := 0; h < len(texts); h++ {
text := texts[h]
for i := 0; i < len(readMakers); i++ {
for j := 0; j < len(bufreaders); j++ {
for k := 0; k < len(bufsizes); k++ {
readmaker := readMakers[i]
bufreader := bufreaders[j]
bufsize := bufsizes[k]
read := readmaker.fn(strings.NewReader(text))
buf := NewReaderSize(read, bufsize)
s := bufreader.fn(buf)
if s != text {
t.Errorf("reader=%s fn=%s bufsize=%d want=%q got=%q",
readmaker.name, bufreader.name, bufsize, text, s)
}
}
}
}
}
}
type zeroReader struct{}
func (zeroReader) Read(p []byte) (int, error) {
return 0, nil
}
func TestZeroReader(t *testing.T) {
var z zeroReader
r := NewReader(z)
c := make(chan error)
go func() {
_, err := r.ReadByte()
c <- err
}()
select {
case err := <-c:
if err == nil {
t.Error("error expected")
} else if err != io.ErrNoProgress {
t.Error("unexpected error:", err)
}
case <-time.After(time.Second):
t.Error("test timed out (endless loop in ReadByte?)")
}
}
// A StringReader delivers its data one string segment at a time via Read.
type StringReader struct {
data []string
step int
}
func (r *StringReader) Read(p []byte) (n int, err error) {
if r.step < len(r.data) {
s := r.data[r.step]
n = copy(p, s)
r.step++
} else {
err = io.EOF
}
return
}
func readRuneSegments(t *testing.T, segments []string) {
got := ""
want := strings.Join(segments, "")
r := NewReader(&StringReader{data: segments})
for {
r, _, err := r.ReadRune()
if err != nil {
if err != io.EOF {
return
}
break
}
got += string(r)
}
if got != want {
t.Errorf("segments=%v got=%s want=%s", segments, got, want)
}
}
var segmentList = [][]string{
{},
{""},
{"日", "本語"},
{"\u65e5", "\u672c", "\u8a9e"},
{"\U000065e5", "\U0000672c", "\U00008a9e"},
{"\xe6", "\x97\xa5\xe6", "\x9c\xac\xe8\xaa\x9e"},
{"Hello", ", ", "World", "!"},
{"Hello", ", ", "", "World", "!"},
}
func TestReadRune(t *testing.T) {
for _, s := range segmentList {
readRuneSegments(t, s)
}
}
func TestUnreadRune(t *testing.T) {
segments := []string{"Hello, world:", "日本語"}
r := NewReader(&StringReader{data: segments})
got := ""
want := strings.Join(segments, "")
// Normal execution.
for {
r1, _, err := r.ReadRune()
if err != nil {
if err != io.EOF {
t.Error("unexpected error on ReadRune:", err)
}
break
}
got += string(r1)
// Put it back and read it again.
if err = r.UnreadRune(); err != nil {
t.Fatal("unexpected error on UnreadRune:", err)
}
r2, _, err := r.ReadRune()
if err != nil {
t.Fatal("unexpected error reading after unreading:", err)
}
if r1 != r2 {
t.Fatalf("incorrect rune after unread: got %c, want %c", r1, r2)
}
}
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestReaderUnreadByte(t *testing.T) {
segments := []string{"Hello, ", "world"}
r := NewReader(&StringReader{data: segments})
got := ""
want := strings.Join(segments, "")
// Normal execution.
for {
b1, err := r.ReadByte()
if err != nil {
if err != io.EOF {
t.Error("unexpected error on ReadByte:", err)
}
break
}
got += string(b1)
// Put it back and read it again.
if err = r.UnreadByte(); err != nil {
t.Fatal("unexpected error on UnreadByte:", err)
}
b2, err := r.ReadByte()
if err != nil {
t.Fatal("unexpected error reading after unreading:", err)
}
if b1 != b2 {
t.Fatalf("incorrect byte after unread: got %q, want %q", b1, b2)
}
}
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestUnreadByteMultiple(t *testing.T) {
segments := []string{"Hello, ", "world"}
data := strings.Join(segments, "")
for n := 0; n <= len(data); n++ {
r := NewReader(&StringReader{data: segments})
// Read n bytes.
for i := 0; i < n; i++ {
b, err := r.ReadByte()
if err != nil {
t.Fatalf("n = %d: unexpected error on ReadByte: %v", n, err)
}
if b != data[i] {
t.Fatalf("n = %d: incorrect byte returned from ReadByte: got %q, want %q", n, b, data[i])
}
}
// Unread one byte if there is one.
if n > 0 {
if err := r.UnreadByte(); err != nil {
t.Errorf("n = %d: unexpected error on UnreadByte: %v", n, err)
}
}
// Test that we cannot unread any further.
if err := r.UnreadByte(); err == nil {
t.Errorf("n = %d: expected error on UnreadByte", n)
}
}
}
func TestUnreadByteOthers(t *testing.T) {
// A list of readers to use in conjunction with UnreadByte.
var readers = []func(*Reader, byte) ([]byte, error){
(*Reader).ReadBytes,
(*Reader).ReadSlice,
func(r *Reader, delim byte) ([]byte, error) {
data, err := r.ReadString(delim)
return []byte(data), err
},
// ReadLine doesn't fit the data/pattern easily
// so we leave it out. It should be covered via
// the ReadSlice test since ReadLine simply calls
// ReadSlice, and it's that function that handles
// the last byte.
}
// Try all readers with UnreadByte.
for rno, read := range readers {
// Some input data that is longer than the minimum reader buffer size.
const n = 10
var buf bytes.Buffer
for i := 0; i < n; i++ {
buf.WriteString("abcdefg")
}
r := NewReaderSize(&buf, minReadBufferSize)
readTo := func(delim byte, want string) {
data, err := read(r, delim)
if err != nil {
t.Fatalf("#%d: unexpected error reading to %c: %v", rno, delim, err)
}
if got := string(data); got != want {
t.Fatalf("#%d: got %q, want %q", rno, got, want)
}
}
// Read the data with occasional UnreadByte calls.
for i := 0; i < n; i++ {
readTo('d', "abcd")
for j := 0; j < 3; j++ {
if err := r.UnreadByte(); err != nil {
t.Fatalf("#%d: unexpected error on UnreadByte: %v", rno, err)
}
readTo('d', "d")
}
readTo('g', "efg")
}
// All data should have been read.
_, err := r.ReadByte()
if err != io.EOF {
t.Errorf("#%d: got error %v; want EOF", rno, err)
}
}
}
// Test that UnreadRune fails if the preceding operation was not a ReadRune.
func TestUnreadRuneError(t *testing.T) {
buf := make([]byte, 3) // All runes in this test are 3 bytes long
r := NewReader(&StringReader{data: []string{"日本語日本語日本語"}})
if r.UnreadRune() == nil {
t.Error("expected error on UnreadRune from fresh buffer")
}
_, _, err := r.ReadRune()
if err != nil {
t.Error("unexpected error on ReadRune (1):", err)
}
if err = r.UnreadRune(); err != nil {
t.Error("unexpected error on UnreadRune (1):", err)
}
if r.UnreadRune() == nil {
t.Error("expected error after UnreadRune (1)")
}
// Test error after Read.
_, _, err = r.ReadRune() // reset state
if err != nil {
t.Error("unexpected error on ReadRune (2):", err)
}
_, err = r.Read(buf)
if err != nil {
t.Error("unexpected error on Read (2):", err)
}
if r.UnreadRune() == nil {
t.Error("expected error after Read (2)")
}
// Test error after ReadByte.
_, _, err = r.ReadRune() // reset state
if err != nil {
t.Error("unexpected error on ReadRune (2):", err)
}
for _ = range buf {
_, err = r.ReadByte()
if err != nil {
t.Error("unexpected error on ReadByte (2):", err)
}
}
if r.UnreadRune() == nil {
t.Error("expected error after ReadByte")
}
// Test error after UnreadByte.
_, _, err = r.ReadRune() // reset state
if err != nil {
t.Error("unexpected error on ReadRune (3):", err)
}
_, err = r.ReadByte()
if err != nil {
t.Error("unexpected error on ReadByte (3):", err)
}
err = r.UnreadByte()
if err != nil {
t.Error("unexpected error on UnreadByte (3):", err)
}
if r.UnreadRune() == nil {
t.Error("expected error after UnreadByte (3)")
}
}
func TestUnreadRuneAtEOF(t *testing.T) {
// UnreadRune/ReadRune should error at EOF (was a bug; used to panic)
r := NewReader(strings.NewReader("x"))
r.ReadRune()
r.ReadRune()
r.UnreadRune()
_, _, err := r.ReadRune()
if err == nil {
t.Error("expected error at EOF")
} else if err != io.EOF {
t.Error("expected EOF; got", err)
}
}
func TestReadWriteRune(t *testing.T) {
const NRune = 1000
byteBuf := new(bytes.Buffer)
w := NewWriter(byteBuf)
// Write the runes out using WriteRune
buf := make([]byte, utf8.UTFMax)
for r := rune(0); r < NRune; r++ {
size := utf8.EncodeRune(buf, r)
nbytes, err := w.WriteRune(r)
if err != nil {
t.Fatalf("WriteRune(0x%x) error: %s", r, err)
}
if nbytes != size {
t.Fatalf("WriteRune(0x%x) expected %d, got %d", r, size, nbytes)
}
}
w.Flush()
r := NewReader(byteBuf)
// Read them back with ReadRune
for r1 := rune(0); r1 < NRune; r1++ {
size := utf8.EncodeRune(buf, r1)
nr, nbytes, err := r.ReadRune()
if nr != r1 || nbytes != size || err != nil {
t.Fatalf("ReadRune(0x%x) got 0x%x,%d not 0x%x,%d (err=%s)", r1, nr, nbytes, r1, size, err)
}
}
}
func TestWriter(t *testing.T) {
var data [8192]byte
for i := 0; i < len(data); i++ {
data[i] = byte(' ' + i%('~'-' '))
}
w := new(bytes.Buffer)
for i := 0; i < len(bufsizes); i++ {
for j := 0; j < len(bufsizes); j++ {
nwrite := bufsizes[i]
bs := bufsizes[j]
// Write nwrite bytes using buffer size bs.
// Check that the right amount makes it out
// and that the data is correct.
w.Reset()
buf := NewWriterSize(w, bs)
context := fmt.Sprintf("nwrite=%d bufsize=%d", nwrite, bs)
n, e1 := buf.Write(data[0:nwrite])
if e1 != nil || n != nwrite {
t.Errorf("%s: buf.Write %d = %d, %v", context, nwrite, n, e1)
continue
}
if e := buf.Flush(); e != nil {
t.Errorf("%s: buf.Flush = %v", context, e)
}
written := w.Bytes()
if len(written) != nwrite {
t.Errorf("%s: %d bytes written", context, len(written))
}
for l := 0; l < len(written); l++ {
if written[i] != data[i] {
t.Errorf("wrong bytes written")
t.Errorf("want=%q", data[0:len(written)])
t.Errorf("have=%q", written)
}
}
}
}
}
// Check that write errors are returned properly.
type errorWriterTest struct {
n, m int
err error
expect error
}
func (w errorWriterTest) Write(p []byte) (int, error) {
return len(p) * w.n / w.m, w.err
}
var errorWriterTests = []errorWriterTest{
{0, 1, nil, io.ErrShortWrite},
{1, 2, nil, io.ErrShortWrite},
{1, 1, nil, nil},
{0, 1, io.ErrClosedPipe, io.ErrClosedPipe},
{1, 2, io.ErrClosedPipe, io.ErrClosedPipe},
{1, 1, io.ErrClosedPipe, io.ErrClosedPipe},
}
func TestWriteErrors(t *testing.T) {
for _, w := range errorWriterTests {
buf := NewWriter(w)
_, e := buf.Write([]byte("hello world"))
if e != nil {
t.Errorf("Write hello to %v: %v", w, e)
continue
}
// Two flushes, to verify the error is sticky.
for i := 0; i < 2; i++ {
e = buf.Flush()
if e != w.expect {
t.Errorf("Flush %d/2 %v: got %v, wanted %v", i+1, w, e, w.expect)
}
}
}
}
func TestNewReaderSizeIdempotent(t *testing.T) {
const BufSize = 1000
b := NewReaderSize(strings.NewReader("hello world"), BufSize)
// Does it recognize itself?
b1 := NewReaderSize(b, BufSize)
if b1 != b {
t.Error("NewReaderSize did not detect underlying Reader")
}
// Does it wrap if existing buffer is too small?
b2 := NewReaderSize(b, 2*BufSize)
if b2 == b {
t.Error("NewReaderSize did not enlarge buffer")
}
}
func TestNewWriterSizeIdempotent(t *testing.T) {
const BufSize = 1000
b := NewWriterSize(new(bytes.Buffer), BufSize)
// Does it recognize itself?
b1 := NewWriterSize(b, BufSize)
if b1 != b {
t.Error("NewWriterSize did not detect underlying Writer")
}
// Does it wrap if existing buffer is too small?
b2 := NewWriterSize(b, 2*BufSize)
if b2 == b {
t.Error("NewWriterSize did not enlarge buffer")
}
}
func TestWriteString(t *testing.T) {
const BufSize = 8
buf := new(bytes.Buffer)
b := NewWriterSize(buf, BufSize)
b.WriteString("0") // easy
b.WriteString("123456") // still easy
b.WriteString("7890") // easy after flush
b.WriteString("abcdefghijklmnopqrstuvwxy") // hard
b.WriteString("z")
if err := b.Flush(); err != nil {
t.Error("WriteString", err)
}
s := "01234567890abcdefghijklmnopqrstuvwxyz"
if string(buf.Bytes()) != s {
t.Errorf("WriteString wants %q gets %q", s, string(buf.Bytes()))
}
}
func TestBufferFull(t *testing.T) {
const longString = "And now, hello, world! It is the time for all good men to come to the aid of their party"
buf := NewReaderSize(strings.NewReader(longString), minReadBufferSize)
line, err := buf.ReadSlice('!')
if string(line) != "And now, hello, " || err != ErrBufferFull {
t.Errorf("first ReadSlice(,) = %q, %v", line, err)
}
line, err = buf.ReadSlice('!')
if string(line) != "world!" || err != nil {
t.Errorf("second ReadSlice(,) = %q, %v", line, err)
}
}
func TestPeek(t *testing.T) {
p := make([]byte, 10)
// string is 16 (minReadBufferSize) long.
buf := NewReaderSize(strings.NewReader("abcdefghijklmnop"), minReadBufferSize)
if s, err := buf.Peek(1); string(s) != "a" || err != nil {
t.Fatalf("want %q got %q, err=%v", "a", string(s), err)
}
if s, err := buf.Peek(4); string(s) != "abcd" || err != nil {
t.Fatalf("want %q got %q, err=%v", "abcd", string(s), err)
}
if _, err := buf.Peek(-1); err != ErrNegativeCount {
t.Fatalf("want ErrNegativeCount got %v", err)
}
if _, err := buf.Peek(32); err != ErrBufferFull {
t.Fatalf("want ErrBufFull got %v", err)
}
if _, err := buf.Read(p[0:3]); string(p[0:3]) != "abc" || err != nil {
t.Fatalf("want %q got %q, err=%v", "abc", string(p[0:3]), err)
}
if s, err := buf.Peek(1); string(s) != "d" || err != nil {
t.Fatalf("want %q got %q, err=%v", "d", string(s), err)
}
if s, err := buf.Peek(2); string(s) != "de" || err != nil {
t.Fatalf("want %q got %q, err=%v", "de", string(s), err)
}
if _, err := buf.Read(p[0:3]); string(p[0:3]) != "def" || err != nil {
t.Fatalf("want %q got %q, err=%v", "def", string(p[0:3]), err)
}
if s, err := buf.Peek(4); string(s) != "ghij" || err != nil {
t.Fatalf("want %q got %q, err=%v", "ghij", string(s), err)
}
if _, err := buf.Read(p[0:]); string(p[0:]) != "ghijklmnop" || err != nil {
t.Fatalf("want %q got %q, err=%v", "ghijklmnop", string(p[0:minReadBufferSize]), err)
}
if s, err := buf.Peek(0); string(s) != "" || err != nil {
t.Fatalf("want %q got %q, err=%v", "", string(s), err)
}
if _, err := buf.Peek(1); err != io.EOF {
t.Fatalf("want EOF got %v", err)
}
// Test for issue 3022, not exposing a reader's error on a successful Peek.
buf = NewReaderSize(dataAndEOFReader("abcd"), 32)
if s, err := buf.Peek(2); string(s) != "ab" || err != nil {
t.Errorf(`Peek(2) on "abcd", EOF = %q, %v; want "ab", nil`, string(s), err)
}
if s, err := buf.Peek(4); string(s) != "abcd" || err != nil {
t.Errorf(`Peek(4) on "abcd", EOF = %q, %v; want "abcd", nil`, string(s), err)
}
if n, err := buf.Read(p[0:5]); string(p[0:n]) != "abcd" || err != nil {
t.Fatalf("Read after peek = %q, %v; want abcd, EOF", p[0:n], err)
}
if n, err := buf.Read(p[0:1]); string(p[0:n]) != "" || err != io.EOF {
t.Fatalf(`second Read after peek = %q, %v; want "", EOF`, p[0:n], err)
}
}
type dataAndEOFReader string
func (r dataAndEOFReader) Read(p []byte) (int, error) {
return copy(p, r), io.EOF
}
func TestPeekThenUnreadRune(t *testing.T) {
// This sequence used to cause a crash.
r := NewReader(strings.NewReader("x"))
r.ReadRune()
r.Peek(1)
r.UnreadRune()
r.ReadRune() // Used to panic here
}
var testOutput = []byte("0123456789abcdefghijklmnopqrstuvwxy")
var testInput = []byte("012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy")
var testInputrn = []byte("012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\nuvw\r\nxy\r\n\n\r\n")
// TestReader wraps a []byte and returns reads of a specific length.
type testReader struct {
data []byte
stride int
}
func (t *testReader) Read(buf []byte) (n int, err error) {
n = t.stride
if n > len(t.data) {
n = len(t.data)
}
if n > len(buf) {
n = len(buf)
}
copy(buf, t.data)
t.data = t.data[n:]
if len(t.data) == 0 {
err = io.EOF
}
return
}
func testReadLine(t *testing.T, input []byte) {
//for stride := 1; stride < len(input); stride++ {
for stride := 1; stride < 2; stride++ {
done := 0
reader := testReader{input, stride}
l := NewReaderSize(&reader, len(input)+1)
for {
line, isPrefix, err := l.ReadLine()
if len(line) > 0 && err != nil {
t.Errorf("ReadLine returned both data and error: %s", err)
}
if isPrefix {
t.Errorf("ReadLine returned prefix")
}
if err != nil {
if err != io.EOF {
t.Fatalf("Got unknown error: %s", err)
}
break
}
if want := testOutput[done : done+len(line)]; !bytes.Equal(want, line) {
t.Errorf("Bad line at stride %d: want: %x got: %x", stride, want, line)
}
done += len(line)
}
if done != len(testOutput) {
t.Errorf("ReadLine didn't return everything: got: %d, want: %d (stride: %d)", done, len(testOutput), stride)
}
}
}
func TestReadLine(t *testing.T) {
testReadLine(t, testInput)
testReadLine(t, testInputrn)
}
func TestLineTooLong(t *testing.T) {
data := make([]byte, 0)
for i := 0; i < minReadBufferSize*5/2; i++ {
data = append(data, '0'+byte(i%10))
}
buf := bytes.NewReader(data)
l := NewReaderSize(buf, minReadBufferSize)
line, isPrefix, err := l.ReadLine()
if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
t.Errorf("bad result for first line: got %q want %q %v", line, data[:minReadBufferSize], err)
}
data = data[len(line):]
line, isPrefix, err = l.ReadLine()
if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
t.Errorf("bad result for second line: got %q want %q %v", line, data[:minReadBufferSize], err)
}
data = data[len(line):]
line, isPrefix, err = l.ReadLine()
if isPrefix || !bytes.Equal(line, data[:minReadBufferSize/2]) || err != nil {
t.Errorf("bad result for third line: got %q want %q %v", line, data[:minReadBufferSize/2], err)
}
line, isPrefix, err = l.ReadLine()
if isPrefix || err == nil {
t.Errorf("expected no more lines: %x %s", line, err)
}
}
func TestReadAfterLines(t *testing.T) {
line1 := "this is line1"
restData := "this is line2\nthis is line 3\n"
inbuf := bytes.NewReader([]byte(line1 + "\n" + restData))
outbuf := new(bytes.Buffer)
maxLineLength := len(line1) + len(restData)/2
l := NewReaderSize(inbuf, maxLineLength)
line, isPrefix, err := l.ReadLine()
if isPrefix || err != nil || string(line) != line1 {
t.Errorf("bad result for first line: isPrefix=%v err=%v line=%q", isPrefix, err, string(line))
}
n, err := io.Copy(outbuf, l)
if int(n) != len(restData) || err != nil {
t.Errorf("bad result for Read: n=%d err=%v", n, err)
}
if outbuf.String() != restData {
t.Errorf("bad result for Read: got %q; expected %q", outbuf.String(), restData)
}
}
func TestReadEmptyBuffer(t *testing.T) {
l := NewReaderSize(new(bytes.Buffer), minReadBufferSize)
line, isPrefix, err := l.ReadLine()
if err != io.EOF {
t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
}
}
func TestLinesAfterRead(t *testing.T) {
l := NewReaderSize(bytes.NewReader([]byte("foo")), minReadBufferSize)
_, err := ioutil.ReadAll(l)
if err != nil {
t.Error(err)
return
}
line, isPrefix, err := l.ReadLine()
if err != io.EOF {
t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
}
}
func TestReadLineNonNilLineOrError(t *testing.T) {
r := NewReader(strings.NewReader("line 1\n"))
for i := 0; i < 2; i++ {
l, _, err := r.ReadLine()
if l != nil && err != nil {
t.Fatalf("on line %d/2; ReadLine=%#v, %v; want non-nil line or Error, but not both",
i+1, l, err)
}
}
}
type readLineResult struct {
line []byte
isPrefix bool
err error
}
var readLineNewlinesTests = []struct {
input string
expect []readLineResult
}{
{"012345678901234\r\n012345678901234\r\n", []readLineResult{
{[]byte("012345678901234"), true, nil},
{nil, false, nil},
{[]byte("012345678901234"), true, nil},
{nil, false, nil},
{nil, false, io.EOF},
}},
{"0123456789012345\r012345678901234\r", []readLineResult{
{[]byte("0123456789012345"), true, nil},
{[]byte("\r012345678901234"), true, nil},
{[]byte("\r"), false, nil},
{nil, false, io.EOF},
}},
}
func TestReadLineNewlines(t *testing.T) {
for _, e := range readLineNewlinesTests {
testReadLineNewlines(t, e.input, e.expect)
}
}
func testReadLineNewlines(t *testing.T, input string, expect []readLineResult) {
b := NewReaderSize(strings.NewReader(input), minReadBufferSize)
for i, e := range expect {
line, isPrefix, err := b.ReadLine()
if !bytes.Equal(line, e.line) {
t.Errorf("%q call %d, line == %q, want %q", input, i, line, e.line)
return
}
if isPrefix != e.isPrefix {
t.Errorf("%q call %d, isPrefix == %v, want %v", input, i, isPrefix, e.isPrefix)
return
}
if err != e.err {
t.Errorf("%q call %d, err == %v, want %v", input, i, err, e.err)
return
}
}
}
func createTestInput(n int) []byte {
input := make([]byte, n)
for i := range input {
// 101 and 251 are arbitrary prime numbers.
// The idea is to create an input sequence
// which doesn't repeat too frequently.
input[i] = byte(i % 251)
if i%101 == 0 {
input[i] ^= byte(i / 101)
}
}
return input
}
func TestReaderWriteTo(t *testing.T) {
input := createTestInput(8192)
r := NewReader(onlyReader{bytes.NewReader(input)})
w := new(bytes.Buffer)
if n, err := r.WriteTo(w); err != nil || n != int64(len(input)) {
t.Fatalf("r.WriteTo(w) = %d, %v, want %d, nil", n, err, len(input))
}
for i, val := range w.Bytes() {
if val != input[i] {
t.Errorf("after write: out[%d] = %#x, want %#x", i, val, input[i])
}
}
}
type errorWriterToTest struct {
rn, wn int
rerr, werr error
expected error
}
func (r errorWriterToTest) Read(p []byte) (int, error) {
return len(p) * r.rn, r.rerr
}
func (w errorWriterToTest) Write(p []byte) (int, error) {
return len(p) * w.wn, w.werr
}
var errorWriterToTests = []errorWriterToTest{
{1, 0, nil, io.ErrClosedPipe, io.ErrClosedPipe},
{0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe},
{0, 0, io.ErrUnexpectedEOF, io.ErrClosedPipe, io.ErrClosedPipe},
{0, 1, io.EOF, nil, nil},
}
func TestReaderWriteToErrors(t *testing.T) {
for i, rw := range errorWriterToTests {
r := NewReader(rw)
if _, err := r.WriteTo(rw); err != rw.expected {
t.Errorf("r.WriteTo(errorWriterToTests[%d]) = _, %v, want _,%v", i, err, rw.expected)
}
}
}
func TestWriterReadFrom(t *testing.T) {
ws := []func(io.Writer) io.Writer{
func(w io.Writer) io.Writer { return onlyWriter{w} },
func(w io.Writer) io.Writer { return w },
}
rs := []func(io.Reader) io.Reader{
iotest.DataErrReader,
func(r io.Reader) io.Reader { return r },
}
for ri, rfunc := range rs {
for wi, wfunc := range ws {
input := createTestInput(8192)
b := new(bytes.Buffer)
w := NewWriter(wfunc(b))
r := rfunc(bytes.NewReader(input))
if n, err := w.ReadFrom(r); err != nil || n != int64(len(input)) {
t.Errorf("ws[%d],rs[%d]: w.ReadFrom(r) = %d, %v, want %d, nil", wi, ri, n, err, len(input))
continue
}
if err := w.Flush(); err != nil {
t.Errorf("Flush returned %v", err)
continue
}
if got, want := b.String(), string(input); got != want {
t.Errorf("ws[%d], rs[%d]:\ngot %q\nwant %q\n", wi, ri, got, want)
}
}
}
}
type errorReaderFromTest struct {
rn, wn int
rerr, werr error
expected error
}
func (r errorReaderFromTest) Read(p []byte) (int, error) {
return len(p) * r.rn, r.rerr
}
func (w errorReaderFromTest) Write(p []byte) (int, error) {
return len(p) * w.wn, w.werr
}
var errorReaderFromTests = []errorReaderFromTest{
{0, 1, io.EOF, nil, nil},
{1, 1, io.EOF, nil, nil},
{0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe},
{0, 0, io.ErrClosedPipe, io.ErrShortWrite, io.ErrClosedPipe},
{1, 0, nil, io.ErrShortWrite, io.ErrShortWrite},
}
func TestWriterReadFromErrors(t *testing.T) {
for i, rw := range errorReaderFromTests {
w := NewWriter(rw)
if _, err := w.ReadFrom(rw); err != rw.expected {
t.Errorf("w.ReadFrom(errorReaderFromTests[%d]) = _, %v, want _,%v", i, err, rw.expected)
}
}
}
// TestWriterReadFromCounts tests that using io.Copy to copy into a
// bufio.Writer does not prematurely flush the buffer. For example, when
// buffering writes to a network socket, excessive network writes should be
// avoided.
func TestWriterReadFromCounts(t *testing.T) {
var w0 writeCountingDiscard
b0 := NewWriterSize(&w0, 1234)
b0.WriteString(strings.Repeat("x", 1000))
if w0 != 0 {
t.Fatalf("write 1000 'x's: got %d writes, want 0", w0)
}
b0.WriteString(strings.Repeat("x", 200))
if w0 != 0 {
t.Fatalf("write 1200 'x's: got %d writes, want 0", w0)
}
io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 30))})
if w0 != 0 {
t.Fatalf("write 1230 'x's: got %d writes, want 0", w0)
}
io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 9))})
if w0 != 1 {
t.Fatalf("write 1239 'x's: got %d writes, want 1", w0)
}
var w1 writeCountingDiscard
b1 := NewWriterSize(&w1, 1234)
b1.WriteString(strings.Repeat("x", 1200))
b1.Flush()
if w1 != 1 {
t.Fatalf("flush 1200 'x's: got %d writes, want 1", w1)
}
b1.WriteString(strings.Repeat("x", 89))
if w1 != 1 {
t.Fatalf("write 1200 + 89 'x's: got %d writes, want 1", w1)
}
io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 700))})
if w1 != 1 {
t.Fatalf("write 1200 + 789 'x's: got %d writes, want 1", w1)
}
io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 600))})
if w1 != 2 {
t.Fatalf("write 1200 + 1389 'x's: got %d writes, want 2", w1)
}
b1.Flush()
if w1 != 3 {
t.Fatalf("flush 1200 + 1389 'x's: got %d writes, want 3", w1)
}
}
// A writeCountingDiscard is like ioutil.Discard and counts the number of times
// Write is called on it.
type writeCountingDiscard int
func (w *writeCountingDiscard) Write(p []byte) (int, error) {
*w++
return len(p), nil
}
type negativeReader int
func (r *negativeReader) Read([]byte) (int, error) { return -1, nil }
func TestNegativeRead(t *testing.T) {
// should panic with a description pointing at the reader, not at itself.
// (should NOT panic with slice index error, for example.)
b := NewReader(new(negativeReader))
defer func() {
switch err := recover().(type) {
case nil:
t.Fatal("read did not panic")
case error:
if !strings.Contains(err.Error(), "reader returned negative count from Read") {
t.Fatalf("wrong panic: %v", err)
}
default:
t.Fatalf("unexpected panic value: %T(%v)", err, err)
}
}()
b.Read(make([]byte, 100))
}
var errFake = errors.New("fake error")
type errorThenGoodReader struct {
didErr bool
nread int
}
func (r *errorThenGoodReader) Read(p []byte) (int, error) {
r.nread++
if !r.didErr {
r.didErr = true
return 0, errFake
}
return len(p), nil
}
func TestReaderClearError(t *testing.T) {
r := &errorThenGoodReader{}
b := NewReader(r)
buf := make([]byte, 1)
if _, err := b.Read(nil); err != nil {
t.Fatalf("1st nil Read = %v; want nil", err)
}
if _, err := b.Read(buf); err != errFake {
t.Fatalf("1st Read = %v; want errFake", err)
}
if _, err := b.Read(nil); err != nil {
t.Fatalf("2nd nil Read = %v; want nil", err)
}
if _, err := b.Read(buf); err != nil {
t.Fatalf("3rd Read with buffer = %v; want nil", err)
}
if r.nread != 2 {
t.Errorf("num reads = %d; want 2", r.nread)
}
}
// Test for golang.org/issue/5947
func TestWriterReadFromWhileFull(t *testing.T) {
buf := new(bytes.Buffer)
w := NewWriterSize(buf, 10)
// Fill buffer exactly.
n, err := w.Write([]byte("0123456789"))
if n != 10 || err != nil {
t.Fatalf("Write returned (%v, %v), want (10, nil)", n, err)
}
// Use ReadFrom to read in some data.
n2, err := w.ReadFrom(strings.NewReader("abcdef"))
if n2 != 6 || err != nil {
t.Fatalf("ReadFrom returned (%v, %v), want (6, nil)", n2, err)
}
}
type emptyThenNonEmptyReader struct {
r io.Reader
n int
}
func (r *emptyThenNonEmptyReader) Read(p []byte) (int, error) {
if r.n <= 0 {
return r.r.Read(p)
}
r.n--
return 0, nil
}
// Test for golang.org/issue/7611
func TestWriterReadFromUntilEOF(t *testing.T) {
buf := new(bytes.Buffer)
w := NewWriterSize(buf, 5)
// Partially fill buffer
n, err := w.Write([]byte("0123"))
if n != 4 || err != nil {
t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err)
}
// Use ReadFrom to read in some data.
r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 3}
n2, err := w.ReadFrom(r)
if n2 != 4 || err != nil {
t.Fatalf("ReadFrom returned (%v, %v), want (4, nil)", n2, err)
}
w.Flush()
if got, want := string(buf.Bytes()), "0123abcd"; got != want {
t.Fatalf("buf.Bytes() returned %q, want %q", got, want)
}
}
func TestWriterReadFromErrNoProgress(t *testing.T) {
buf := new(bytes.Buffer)
w := NewWriterSize(buf, 5)
// Partially fill buffer
n, err := w.Write([]byte("0123"))
if n != 4 || err != nil {
t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err)
}
// Use ReadFrom to read in some data.
r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 100}
n2, err := w.ReadFrom(r)
if n2 != 0 || err != io.ErrNoProgress {
t.Fatalf("buf.Bytes() returned (%v, %v), want (0, io.ErrNoProgress)", n2, err)
}
}
func TestReaderReset(t *testing.T) {
r := NewReader(strings.NewReader("foo foo"))
buf := make([]byte, 3)
r.Read(buf)
if string(buf) != "foo" {
t.Errorf("buf = %q; want foo", buf)
}
r.Reset(strings.NewReader("bar bar"))
all, err := ioutil.ReadAll(r)
if err != nil {
t.Fatal(err)
}
if string(all) != "bar bar" {
t.Errorf("ReadAll = %q; want bar bar", all)
}
}
func TestWriterReset(t *testing.T) {
var buf1, buf2 bytes.Buffer
w := NewWriter(&buf1)
w.WriteString("foo")
w.Reset(&buf2) // and not flushed
w.WriteString("bar")
w.Flush()
if buf1.String() != "" {
t.Errorf("buf1 = %q; want empty", buf1.String())
}
if buf2.String() != "bar" {
t.Errorf("buf2 = %q; want bar", buf2.String())
}
}
// An onlyReader only implements io.Reader, no matter what other methods the underlying implementation may have.
type onlyReader struct {
io.Reader
}
// An onlyWriter only implements io.Writer, no matter what other methods the underlying implementation may have.
type onlyWriter struct {
io.Writer
}
func BenchmarkReaderCopyOptimal(b *testing.B) {
// Optimal case is where the underlying reader implements io.WriterTo
srcBuf := bytes.NewBuffer(make([]byte, 8192))
src := NewReader(srcBuf)
dstBuf := new(bytes.Buffer)
dst := onlyWriter{dstBuf}
for i := 0; i < b.N; i++ {
srcBuf.Reset()
src.Reset(srcBuf)
dstBuf.Reset()
io.Copy(dst, src)
}
}
func BenchmarkReaderCopyUnoptimal(b *testing.B) {
// Unoptimal case is where the underlying reader doesn't implement io.WriterTo
srcBuf := bytes.NewBuffer(make([]byte, 8192))
src := NewReader(onlyReader{srcBuf})
dstBuf := new(bytes.Buffer)
dst := onlyWriter{dstBuf}
for i := 0; i < b.N; i++ {
srcBuf.Reset()
src.Reset(onlyReader{srcBuf})
dstBuf.Reset()
io.Copy(dst, src)
}
}
func BenchmarkReaderCopyNoWriteTo(b *testing.B) {
srcBuf := bytes.NewBuffer(make([]byte, 8192))
srcReader := NewReader(srcBuf)
src := onlyReader{srcReader}
dstBuf := new(bytes.Buffer)
dst := onlyWriter{dstBuf}
for i := 0; i < b.N; i++ {
srcBuf.Reset()
srcReader.Reset(srcBuf)
dstBuf.Reset()
io.Copy(dst, src)
}
}
func BenchmarkReaderWriteToOptimal(b *testing.B) {
const bufSize = 16 << 10
buf := make([]byte, bufSize)
r := bytes.NewReader(buf)
srcReader := NewReaderSize(onlyReader{r}, 1<<10)
if _, ok := ioutil.Discard.(io.ReaderFrom); !ok {
b.Fatal("ioutil.Discard doesn't support ReaderFrom")
}
for i := 0; i < b.N; i++ {
r.Seek(0, 0)
srcReader.Reset(onlyReader{r})
n, err := srcReader.WriteTo(ioutil.Discard)
if err != nil {
b.Fatal(err)
}
if n != bufSize {
b.Fatalf("n = %d; want %d", n, bufSize)
}
}
}
func BenchmarkWriterCopyOptimal(b *testing.B) {
// Optimal case is where the underlying writer implements io.ReaderFrom
srcBuf := bytes.NewBuffer(make([]byte, 8192))
src := onlyReader{srcBuf}
dstBuf := new(bytes.Buffer)
dst := NewWriter(dstBuf)
for i := 0; i < b.N; i++ {
srcBuf.Reset()
dstBuf.Reset()
dst.Reset(dstBuf)
io.Copy(dst, src)
}
}
func BenchmarkWriterCopyUnoptimal(b *testing.B) {
srcBuf := bytes.NewBuffer(make([]byte, 8192))
src := onlyReader{srcBuf}
dstBuf := new(bytes.Buffer)
dst := NewWriter(onlyWriter{dstBuf})
for i := 0; i < b.N; i++ {
srcBuf.Reset()
dstBuf.Reset()
dst.Reset(onlyWriter{dstBuf})
io.Copy(dst, src)
}
}
func BenchmarkWriterCopyNoReadFrom(b *testing.B) {
srcBuf := bytes.NewBuffer(make([]byte, 8192))
src := onlyReader{srcBuf}
dstBuf := new(bytes.Buffer)
dstWriter := NewWriter(dstBuf)
dst := onlyWriter{dstWriter}
for i := 0; i < b.N; i++ {
srcBuf.Reset()
dstBuf.Reset()
dstWriter.Reset(dstBuf)
io.Copy(dst, src)
}
}
func BenchmarkReaderEmpty(b *testing.B) {
b.ReportAllocs()
str := strings.Repeat("x", 16<<10)
for i := 0; i < b.N; i++ {
br := NewReader(strings.NewReader(str))
n, err := io.Copy(ioutil.Discard, br)
if err != nil {
b.Fatal(err)
}
if n != int64(len(str)) {
b.Fatal("wrong length")
}
}
}
func BenchmarkWriterEmpty(b *testing.B) {
b.ReportAllocs()
str := strings.Repeat("x", 1<<10)
bs := []byte(str)
for i := 0; i < b.N; i++ {
bw := NewWriter(ioutil.Discard)
bw.Flush()
bw.WriteByte('a')
bw.Flush()
bw.WriteRune('B')
bw.Flush()
bw.Write(bs)
bw.Flush()
bw.WriteString(str)
bw.Flush()
}
}
func BenchmarkWriterFlush(b *testing.B) {
b.ReportAllocs()
bw := NewWriter(ioutil.Discard)
str := strings.Repeat("x", 50)
for i := 0; i < b.N; i++ {
bw.WriteString(str)
bw.Flush()
}
}
| Godeps/_workspace/src/gopkg.in/bufio.v1/bufio_test.go | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.0016051633283495903,
0.00019090258865617216,
0.00016435854195151478,
0.00016890751430764794,
0.0001432024728273973
] |
{
"id": 4,
"code_window": [
" } else {\n",
" grunt.log.writeln('Phantomjs already imported from node');\n",
" }\n",
" });\n",
"};"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" grunt.log.writeln('Phantomjs already imported from node');\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 29
} | 2.1.0
| docs/VERSION | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.00017338468751404434,
0.00017338468751404434,
0.00017338468751404434,
0.00017338468751404434,
0
] |
{
"id": 4,
"code_window": [
" } else {\n",
" grunt.log.writeln('Phantomjs already imported from node');\n",
" }\n",
" });\n",
"};"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" grunt.log.writeln('Phantomjs already imported from node');\n"
],
"file_path": "tasks/options/phantomjs.js",
"type": "replace",
"edit_start_line_idx": 29
} | ----
page_title: Sharing
page_description: Sharing
page_keywords: grafana, sharing, guide, documentation
---
# Sharing features
Grafana provides a number of ways to share a dashboard or a specfic panel to other users within your
organization. It also provides ways to publish interactive snapshots that can be accessed by external partners.
## Share dashboard
Share a dashboard via the share icon in the top nav. This opens the share dialog where you
can get a link to the current dashboard with the current selected time range and template variables. If you have
made changes to the dashboard, make sure those are saved before sending the link.
### Dashboard snapshot
A dashboard snapshot is an instant way to share an interactive dashboard publicly. When created, we <strong>strip sensitive data</strong> like queries
(metric, template and annotation) and panel links, leaving only the visible metric data and series names embedded into your dashboard. Dashboard
snapshots can be accessed by anyone who has the link and can reach the URL.

### Publish snapshots
You can publish snapshots to you local instance or to [snapshot.raintank.io](http://snapshot.raintank.io). The later is a free service
that is provided by [Raintank](http://raintank.io) that allows you to publish dashboard snapshots to an external grafana instance.
The same rules still apply, anyone with the link can view it. You can set an expiration time if you want the snapshot to be removed
after a certain time period.
## Share Panel
Click a panel title to open the panel menu, then click share in the panel menu to open the Share Panel dialog. Here you
have access to a link that will take you to exactly this panel with the current time range and selected template variables.
You also get a link to service side rendered PNG of the panel. Useful if you want to share an image of the panel.
Please note that for OSX and Windows, you will need to ensure that a `phantomjs` binary is available under `vendor/phantomjs/phantomjs`. For Linux, a `phantomjs` binary is included - however, you should ensure that any requisite libraries (e.g. libfontconfig) are available.
### Embed Panel
You can embed a panel using an iframe on another web site. This tab will show you the html that you need to use.
Example:
```html
<iframe src="http://snapshot.raintank.io/dashboard/solo/snapshot/UtvRYDv650fHOV2jV5QlAQhLnNOhB5ZN?panelId=4&fullscreen&from=1427385145990&to=1427388745990" width="650" height="300" frameborder="0"></iframe>
```
Below there should be an interactive Grafana graph embedded in an iframe:
<iframe src="https://snapshot.raintank.io/dashboard-solo/snapshot/4IKyWYNEQll1B9FXcN3RIgx4M2VGgU8d?panelId=4&fullscreen" width="650" height="300" frameborder="0"></iframe>
| docs/sources/reference/sharing.md | 0 | https://github.com/grafana/grafana/commit/81a660eae4bb434f99d54d6c5cd98c8c42e99501 | [
0.00017353967996314168,
0.00016726893954910338,
0.00016432374832220376,
0.00016610560123808682,
0.0000032319503588951193
] |
{
"id": 0,
"code_window": [
"import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from 'vue'\n",
"import type { Ref, WatchSource } from 'vue'\n",
"import { NuxtApp, useNuxtApp } from '../nuxt'\n",
"\n",
"export type _Transform<Input = any, Output = any> = (input: Input) => Output\n",
"\n",
"export type PickFrom<T, K extends Array<string>> = T extends Array<any>\n",
" ? T\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createError } from './error'\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "add",
"edit_start_line_idx": 3
} | import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from 'vue'
import type { Ref, WatchSource } from 'vue'
import { NuxtApp, useNuxtApp } from '../nuxt'
export type _Transform<Input = any, Output = any> = (input: Input) => Output
export type PickFrom<T, K extends Array<string>> = T extends Array<any>
? T
: T extends Record<string, any>
? keyof T extends K[number]
? T // Exact same keys as the target, skip Pick
: Pick<T, K[number]>
: T
export type KeysOf<T> = Array<keyof T extends string ? keyof T : string>
export type KeyOfRes<Transform extends _Transform> = KeysOf<ReturnType<Transform>>
type MultiWatchSources = (WatchSource<unknown> | object)[]
export interface AsyncDataOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<_Transform> = KeyOfRes<Transform>
> {
server?: boolean
lazy?: boolean
default?: () => DataT | Ref<DataT> | null
transform?: Transform
pick?: PickKeys
watch?: MultiWatchSources
initialCache?: boolean
immediate?: boolean
}
export interface AsyncDataExecuteOptions {
_initial?: boolean
/**
* Force a refresh, even if there is already a pending request. Previous requests will
* not be cancelled, but their result will not affect the data/pending state - and any
* previously awaited promises will not resolve until this new request resolves.
*/
dedupe?: boolean
}
export interface _AsyncData<DataT, ErrorT> {
data: Ref<DataT | null>
pending: Ref<boolean>
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>
error: Ref<ErrorT | null>
}
export type AsyncData<Data, Error> = _AsyncData<Data, Error> & Promise<_AsyncData<Data, Error>>
const getDefault = () => null
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
// eslint-disable-next-line prefer-const
let [key, handler, options = {}] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// Validate arguments
if (typeof key !== 'string') {
throw new TypeError('[nuxt] [asyncData] key must be a string.')
}
if (typeof handler !== 'function') {
throw new TypeError('[nuxt] [asyncData] handler must be a function.')
}
// Apply defaults
options.server = options.server ?? true
options.default = options.default ?? getDefault
// TODO: remove support for `defer` in Nuxt 3 RC
if ((options as any).defer) {
console.warn('[useAsyncData] `defer` has been renamed to `lazy`. Support for `defer` will be removed in RC.')
}
options.lazy = options.lazy ?? (options as any).defer ?? false
options.initialCache = options.initialCache ?? true
options.immediate = options.immediate ?? true
// Setup nuxt instance payload
const nuxt = useNuxtApp()
const useInitialCache = () => (nuxt.isHydrating || options.initialCache) && nuxt.payload.data[key] !== undefined
// Create or use a shared asyncData entity
if (!nuxt._asyncData[key]) {
nuxt._asyncData[key] = {
data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),
pending: ref(!useInitialCache()),
error: ref(nuxt.payload._errors[key] ?? null)
}
}
// TODO: Else, Soemhow check for confliciting keys with different defaults or fetcher
const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>
asyncData.refresh = asyncData.execute = (opts = {}) => {
if (nuxt._asyncDataPromises[key]) {
if (opts.dedupe === false) {
// Avoid fetching same key more than once at a time
return nuxt._asyncDataPromises[key]
}
(nuxt._asyncDataPromises[key] as any).cancelled = true
}
// Avoid fetching same key that is already fetched
if (opts._initial && useInitialCache()) {
return nuxt.payload.data[key]
}
asyncData.pending.value = true
// TODO: Cancel previous promise
const promise = new Promise<DataT>(
(resolve, reject) => {
try {
resolve(handler(nuxt))
} catch (err) {
reject(err)
}
})
.then((result) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
if (options.transform) {
result = options.transform(result)
}
if (options.pick) {
result = pick(result as any, options.pick) as DataT
}
asyncData.data.value = result
asyncData.error.value = null
})
.catch((error: any) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
asyncData.error.value = error
asyncData.data.value = unref(options.default?.() ?? null)
})
.finally(() => {
if ((promise as any).cancelled) { return }
asyncData.pending.value = false
nuxt.payload.data[key] = asyncData.data.value
if (asyncData.error.value) {
nuxt.payload._errors[key] = true
}
delete nuxt._asyncDataPromises[key]
})
nuxt._asyncDataPromises[key] = promise
return nuxt._asyncDataPromises[key]
}
const initialFetch = () => asyncData.refresh({ _initial: true })
const fetchOnServer = options.server !== false && nuxt.payload.serverRendered
// Server side
if (process.server && fetchOnServer && options.immediate) {
const promise = initialFetch()
onServerPrefetch(() => promise)
}
// Client side
if (process.client) {
// Setup hook callbacks once per instance
const instance = getCurrentInstance()
if (instance && !instance._nuxtOnBeforeMountCbs) {
instance._nuxtOnBeforeMountCbs = []
const cbs = instance._nuxtOnBeforeMountCbs
if (instance) {
onBeforeMount(() => {
cbs.forEach((cb) => { cb() })
cbs.splice(0, cbs.length)
})
onUnmounted(() => cbs.splice(0, cbs.length))
}
}
if (fetchOnServer && nuxt.isHydrating && key in nuxt.payload.data) {
// 1. Hydration (server: true): no fetch
asyncData.pending.value = false
} else if (instance && ((nuxt.payload.serverRendered && nuxt.isHydrating) || options.lazy) && options.immediate) {
// 2. Initial load (server: false): fetch on mounted
// 3. Initial load or navigation (lazy: true): fetch on mounted
instance._nuxtOnBeforeMountCbs.push(initialFetch)
} else if (options.immediate) {
// 4. Navigation (lazy: false) - or plugin usage: await fetch
initialFetch()
}
if (options.watch) {
watch(options.watch, () => asyncData.refresh())
}
const off = nuxt.hook('app:data:refresh', (keys) => {
if (!keys || keys.includes(key)) {
return asyncData.refresh()
}
})
if (instance) {
onUnmounted(off)
}
}
// Allow directly awaiting on asyncData
const asyncDataPromise = Promise.resolve(nuxt._asyncDataPromises[key]).then(() => asyncData) as AsyncData<DataT, DataE>
Object.assign(asyncDataPromise, asyncData)
return asyncDataPromise as AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE>
}
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// @ts-ignore
return useAsyncData(key, handler, { ...options, lazy: true }, null)
}
export async function refreshNuxtData (keys?: string | string[]): Promise<void> {
if (process.server) {
return Promise.resolve()
}
const _keys = keys ? Array.isArray(keys) ? keys : [keys] : undefined
await useNuxtApp().hooks.callHookParallel('app:data:refresh', _keys)
}
export function clearNuxtData (keys?: string | string[] | ((key: string) => boolean)): void {
const nuxtApp = useNuxtApp()
const _allKeys = Object.keys(nuxtApp.payload.data)
const _keys: string[] = !keys
? _allKeys
: typeof keys === 'function'
? _allKeys.filter(keys)
: Array.isArray(keys) ? keys : [keys]
for (const key of _keys) {
if (key in nuxtApp.payload.data) {
nuxtApp.payload.data[key] = undefined
}
if (key in nuxtApp.payload._errors) {
nuxtApp.payload._errors[key] = undefined
}
if (nuxtApp._asyncData[key]) {
nuxtApp._asyncData[key]!.data.value = undefined
nuxtApp._asyncData[key]!.error.value = undefined
nuxtApp._asyncData[key]!.pending.value = false
}
if (key in nuxtApp._asyncDataPromises) {
nuxtApp._asyncDataPromises[key] = undefined
}
}
}
function pick (obj: Record<string, any>, keys: string[]) {
const newObj = {}
for (const key of keys) {
(newObj as any)[key] = obj[key]
}
return newObj
}
| packages/nuxt/src/app/composables/asyncData.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.9978871941566467,
0.29248496890068054,
0.0001658498658798635,
0.0008689201204106212,
0.4191191792488098
] |
{
"id": 0,
"code_window": [
"import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from 'vue'\n",
"import type { Ref, WatchSource } from 'vue'\n",
"import { NuxtApp, useNuxtApp } from '../nuxt'\n",
"\n",
"export type _Transform<Input = any, Output = any> = (input: Input) => Output\n",
"\n",
"export type PickFrom<T, K extends Array<string>> = T extends Array<any>\n",
" ? T\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createError } from './error'\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "add",
"edit_start_line_idx": 3
} | {
"extends": "./.nuxt/tsconfig.json"
}
| examples/routing/universal-router/tsconfig.json | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.0001658544351812452,
0.0001658544351812452,
0.0001658544351812452,
0.0001658544351812452,
0
] |
{
"id": 0,
"code_window": [
"import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from 'vue'\n",
"import type { Ref, WatchSource } from 'vue'\n",
"import { NuxtApp, useNuxtApp } from '../nuxt'\n",
"\n",
"export type _Transform<Input = any, Output = any> = (input: Input) => Output\n",
"\n",
"export type PickFrom<T, K extends Array<string>> = T extends Array<any>\n",
" ? T\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createError } from './error'\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "add",
"edit_start_line_idx": 3
} | titleTemplate: 'Migrate to Bridge: %s'
| docs/content/6.bridge/_dir.yml | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.000171040344866924,
0.000171040344866924,
0.000171040344866924,
0.000171040344866924,
0
] |
{
"id": 0,
"code_window": [
"import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from 'vue'\n",
"import type { Ref, WatchSource } from 'vue'\n",
"import { NuxtApp, useNuxtApp } from '../nuxt'\n",
"\n",
"export type _Transform<Input = any, Output = any> = (input: Input) => Output\n",
"\n",
"export type PickFrom<T, K extends Array<string>> = T extends Array<any>\n",
" ? T\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createError } from './error'\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "add",
"edit_start_line_idx": 3
} | ---
title: "Module Author Guide"
description: "Learn how to create a Nuxt module."
---
# Module Author Guide
A powerful configuration and hooks system makes it possible to customize almost every aspect of Nuxt Framework and add endless possible integrations when it comes to customization.
Nuxt provides a zero-config experience with a preset of integrations and best practices to develop Web applications.
A powerful configuration and hooks system makes it possible to customize almost every aspect of Nuxt Framework and add endless possible integrations when it comes to customization. You can learn more about how Nuxt works in the [Nuxt internals](/guide/going-further/internals) section.
Nuxt exposes a powerful API called **Nuxt Modules**. Nuxt modules are simple async functions that sequentially run when starting Nuxt in development mode using `nuxi dev` or building a project for production with `nuxi build`.
Using Nuxt Modules, we can encapsulate, properly test and share custom solutions as npm packages without adding unnecessary boilerplate to the Nuxt project itself.
Nuxt Modules can hook into lifecycle events of Nuxt builder, provide runtime app templates, update the configuration or do any other custom action based on needs.
## Quick Start
For the impatient ones, You can quickly start with [module-builder](https://github.com/nuxt/module-builder) and [module starter template](https://github.com/nuxt/starter/tree/module):
```bash
npx nuxi init -t module my-module
```
Starter template and module starter is a standard path of creating a Nuxt module.
**Next steps:**
1. Open `my-module` in the IDE of your choice (Visual Studio Code is recommended)
2. Install dependencies using the package manager of your choice (Yarn is recommended)
3. Ensure local files are generated using `npm run dev:prepare`
4. Start playground using `npm run dev`
5. Follow this document to learn more about Nuxt modules
::alert{type=info icon=🚧}
This is an under-the-progress guide. Please regularly check for updates.
::
## Module Anatomy
A Nuxt module is a simple function accepting inline user options and `nuxt` arguments.
It is totally up to you, as the module author, how to handle the rest of the logic.
Starting with Nuxt 3, modules can benefit all [Nuxt Kit](/api/advanced/kit) utilities.
```ts [modules/example.ts]
// modules/module.mjs
export default async (inlineOptions, nuxt) => {
// You can do whatever you like here..
console.log(inlineOptions.token) // `123`
console.log(nuxt.options.dev) // `true` or `false`
nuxt.hook('ready', async nuxt => {
console.log('Nuxt is ready')
})
}
```
```ts [nuxt.config]
export default defineNuxtConfig({
modules: [
// Using package name (recommended usage)
'@nuxtjs/example',
// Load a local module
'./modules/example',
// Add module with inline-options
['./modules/example', { token: '123' }]
// Inline module definition
async (inlineOptions, nuxt) => { }
]
})
```
## Defining Nuxt Modules
Creating Nuxt modules involves tedious and common tasks. [Nuxt Kit](/api/advanced/kit), provides a convenient and standard API to define Nuxt modules using `defineNuxtModule`:
```js
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
meta: {
// Usually npm package name of your module
name: '@nuxtjs/example',
// The key in `nuxt.config` that holds your module options
configKey: 'sample',
// Compatibility constraints
compatibility: {
// Semver version of supported nuxt versions
nuxt: '^3.0.0'
}
},
// Default configuration options for your module
defaults: {},
hooks: {},
async setup(moduleOptions, nuxt) {
// -- Add your module logic here --
}
})
```
The result of `defineNuxtModule` is a wrapper function with an `(inlineOptions, nuxt)` signature. It applies defaults and other necessary steps and calls the `setup` function when called.
**`defineNuxtModule` features:**
::list
- Support `defaults` and `meta.configKey` for automatically merging module options
- Type hints and automated type inference
- Add shims for basic Nuxt 2 compatibility
- Ensure module gets installed only once using a unique key computed from `meta.name` or `meta.configKey`
- Automatically register Nuxt hooks
- Automatically check for compatibility issues based on module meta
- Expose `getOptions` and `getMeta` for internal usage of Nuxt
- Ensuring backward and upward compatibility as long as the module is using `defineNuxtModule` from the latest version of `@nuxt/kit`
- Integration with module builder tooling
::
## Best Practices
### Async Modules
Nuxt Modules can do asynchronous operations. For example, you may want to develop a module that needs fetching some API or calling an async function.
::alert{type="warning"}
Be careful that `nuxi dev` waits for your module setup before going to the next module and starting the development server. Do time-consuming logic using deferred Nuxt hooks.
::
### Always Prefix Exposed Interfaces
Nuxt Modules should provide an explicit prefix for any exposed configuration, plugin, API, composable, or component to avoid conflict with other modules and internals.
Ideally, you should prefix them with your module's name (e.g. if your module is called `nuxt-foo`, expose `<FooButton>` and `useFooBar()` and **not** `<Button>` and `useBar()`).
### Be TypeScript Friendly
Nuxt 3, has first-class typescript integration for the best developer experience.
Exposing types and using typescript to develop modules can benefit users even when not using typescript directly.
### Avoid CommonJS Syntax
Nuxt 3, relies on native ESM. Please read [Native ES Modules](/guide/going-further/esm) for more information.
## Modules Ecosystem
Nuxt tends to have a healthy and rich ecosystem of Nuxt modules and integrations. Here are some best practices if you want to jump in and contribute!
### Document Module Usage
Consider documenting module usage in the readme file:
- Why use this module
- How to use this module
- What this module does?
Linking to the integration website and documentation is always a good idea.
### Use `nuxt-` Prefix for npm Packages
To make your modules discoverable, use `nuxt-` prefix for the npm package name. This is always the best starting point to draft and try an idea!
### Listing Module on modules.nuxtjs.org
Do you have a working Module and want it listed on [modules.nuxtjs.org](https://modules.nuxtjs.org)? Open an issue in [nuxt/modules](https://github.com/nuxt/modules/issues/new) repository.
Nuxt team can help you to apply best practices before listing.
### Do Not Advertize With a Specific Nuxt Version
Nuxt 3, Nuxt Kit, and other new toolings are made to have both forward and backward compatibility in mind.
Please use "X for Nuxt" instead of "X for Nuxt 3" to avoid fragmentation in the ecosystem and prefer using `meta.compatibility` to set Nuxt version constraints.
### Joining nuxt-community
By moving your modules to [nuxt-community](https://github.com/nuxt-community), there is always someone else to help, and this way, we can join forces to make one perfect solution.
If you have an already published and working module and want to transfer it to nuxt-community, open an issue in [nuxt/modules](https://github.com/nuxt/modules/issues/new).
## Testing
### `@nuxt/test-utils`
#### Fixture Setup
To test the modules we create, we could set up some Nuxt apps as fixtures and test their behaviors. For example, we can create a simple Nuxt app under `./test/fixture` with the configuration like:
```ts
// nuxt.config.js
import MyModule from '../../src'
export default defineNuxtConfig({
modules: [
MyModule
]
})
```
#### Tests Setup
We can create a test file and use the `rootDir` to test the fixture.
```ts
// basic.test.js
import { describe, it, expect } from 'vitest'
import { fileURLToPath } from 'node:url'
import { setup, $fetch } from '@nuxt/test-utils-edge'
describe('ssr', async () => {
await setup({
rootDir: fileURLToPath(new URL('./fixture', import.meta.url)),
})
it('renders the index page', async () => {
// Get response to a server-rendered page with `$fetch`.
const html = await $fetch('/')
expect(html).toContain('<a>A Link</a>')
})
})
```
For more usage, please refer to our [tests for Nuxt 3 framework](https://github.com/nuxt/framework/blob/main/test/basic.test.ts).
### Mock utils
- `mockFn()`: Returns a mocked function based on test runner.
- `mockLogger()`: Mocks logger using [`consola.mockTypes`](https://github.com/unjs/consola#mocktypes) and `mockFn()`. Returns an object of mocked logger types.
### Testing Externally
If you wish to test your module outside of the module playground before publishing to npm, you can use [`npm pack`](https://docs.npmjs.com/cli/v7/commands/npm-pack) command, or your package manager equivalent, to create a tarball from your module. Then in your test project, you can add your module to `package.json` packages as: `"nuxt-module-name": "file:/path/to/tarball.tgz"`.
After that, you should be able to reference `nuxt-module-name` like in any regular project.
## Examples
### Provide Nuxt Plugins
Commonly, modules provide one or more run plugins to add runtime logic.
```ts
import { defineNuxtModule, addPlugin, createResolver } from '@nuxt/kit'
export default defineNuxtModule<ModuleOptions>({
setup (options, nuxt) {
// Create resolver to resolve relative paths
const { resolve } = createResolver(import.meta.url)
addPlugin(resolve('./runtime/plugin'))
}
})
```
::ReadMore{link="/api/advanced/kit" title="API > Advanced > Kit"}
::
### Add a CSS Library
If your module will provide a CSS library, make sure to check if the user already included the library to avoid duplicates and add an option to disable the CSS library in the module.
```ts
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
nuxt.options.css.push('font-awesome/css/font-awesome.css')
}
})
```
### Adding Vue Components
If your module should provide Vue components, you can use the `addComponent` utility to add them as auto-imports for Nuxt to resolve.
```ts
import { defineNuxtModule, addComponent } from '@nuxt/kit'
export default defineNuxtModule({
setup(options, nuxt) {
addComponent({
name: 'MyComponent', // name of the component to be used in vue templates
export: 'MyAwesomeComponent', // (optional) if the component is a named (rather than default) export
// filePath should be package name or resolved path
// if the component is created locally, preferably in `runtime` dir
filePath: '@vue/awesome-components' // resolve(runtimeDir, 'components', 'MyComponent.vue')
})
}
})
```
### Clean Up Module
If your module opens, handles or starts a watcher, you should close it when the Nuxt lifecycle is done. For this, use the `close` hook:
```ts
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
nuxt.hook('close', async nuxt => {
// Your custom code here
})
}
})
```
| docs/content/2.guide/4.going-further/3.modules.md | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00022339526913128793,
0.0001716172555461526,
0.0001622457057237625,
0.0001691860961727798,
0.00001131493627326563
] |
{
"id": 1,
"code_window": [
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: AsyncDataOptions<DataT, Transform, PickKeys>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useAsyncData<\n",
" DataT,\n",
" DataE = Error,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 63
} | import { expectTypeOf } from 'expect-type'
import { describe, it } from 'vitest'
import type { Ref } from 'vue'
import type { AppConfig } from '@nuxt/schema'
import type { FetchError } from 'ohmyfetch'
import { NavigationFailure, RouteLocationNormalizedLoaded, RouteLocationRaw, useRouter as vueUseRouter } from 'vue-router'
import { defineNuxtConfig } from '~~/../../../packages/nuxt/config'
import type { NavigateToOptions } from '~~/../../../packages/nuxt/dist/app/composables/router'
// eslint-disable-next-line import/order
import { isVue3 } from '#app'
import { useRouter } from '#imports'
interface TestResponse { message: string }
describe('API routes', () => {
it('generates types for routes', () => {
expectTypeOf($fetch('/api/hello')).toEqualTypeOf<Promise<string>>()
expectTypeOf($fetch('/api/hey')).toEqualTypeOf<Promise<{ foo: string, baz: string }>>()
expectTypeOf($fetch('/api/other')).toEqualTypeOf<Promise<unknown>>()
expectTypeOf($fetch<TestResponse>('/test')).toEqualTypeOf<Promise<TestResponse>>()
})
it('works with useAsyncData', () => {
expectTypeOf(useAsyncData('api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useAsyncData('api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useAsyncData('api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useAsyncData('api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useAsyncData<TestResponse>('api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
expectTypeOf(useLazyAsyncData('lazy-api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyAsyncData<TestResponse>('lazy-api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
})
it('works with useFetch', () => {
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
})
})
describe('aliases', () => {
it('allows importing from path aliases', () => {
expectTypeOf(useRouter).toEqualTypeOf<typeof vueUseRouter>()
expectTypeOf(isVue3).toEqualTypeOf<boolean>()
})
})
describe('middleware', () => {
it('recognizes named middleware', () => {
definePageMeta({ middleware: 'inject-auth' })
// @ts-expect-error ignore global middleware
definePageMeta({ middleware: 'redirect' })
// @ts-expect-error Invalid middleware
definePageMeta({ middleware: 'invalid-middleware' })
})
it('handles adding middleware', () => {
addRouteMiddleware('example', (to, from) => {
expectTypeOf(to).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(from).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(navigateTo).toEqualTypeOf<(to: RouteLocationRaw, options?: NavigateToOptions) => RouteLocationRaw | Promise<void | NavigationFailure>>()
navigateTo('/')
abortNavigation()
abortNavigation('error string')
abortNavigation(new Error('my error'))
// @ts-expect-error Must return error or string
abortNavigation(true)
}, { global: true })
})
})
describe('layouts', () => {
it('recognizes named layouts', () => {
definePageMeta({ layout: 'custom' })
definePageMeta({ layout: 'pascal-case' })
// @ts-expect-error Invalid layout
definePageMeta({ layout: 'invalid-layout' })
})
})
describe('modules', () => {
it('augments schema automatically', () => {
defineNuxtConfig({ sampleModule: { enabled: false } })
// @ts-expect-error
defineNuxtConfig({ sampleModule: { other: false } })
// @ts-expect-error
defineNuxtConfig({ undeclaredKey: { other: false } })
})
})
describe('runtimeConfig', () => {
it('generated runtimeConfig types', () => {
const runtimeConfig = useRuntimeConfig()
expectTypeOf(runtimeConfig.testConfig).toEqualTypeOf<number>()
expectTypeOf(runtimeConfig.privateConfig).toEqualTypeOf<string>()
expectTypeOf(runtimeConfig.unknown).toEqualTypeOf<any>()
})
})
describe('head', () => {
it('correctly types nuxt.config options', () => {
// @ts-expect-error
defineNuxtConfig({ app: { head: { titleTemplate: () => 'test' } } })
defineNuxtConfig({
app: {
head: {
meta: [{ key: 'key', name: 'description', content: 'some description ' }],
titleTemplate: 'test %s'
}
}
})
})
it('types useHead', () => {
useHead({
base: { href: '/base' },
link: computed(() => []),
meta: [
{ key: 'key', name: 'description', content: 'some description ' },
() => ({ key: 'key', name: 'description', content: 'some description ' })
],
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - Site Title` : 'Site Title'
}
})
})
})
describe('composables', () => {
it('allows providing default refs', () => {
expectTypeOf(useState('test', () => ref('hello'))).toEqualTypeOf<Ref<string>>()
expectTypeOf(useState('test', () => 'hello')).toEqualTypeOf<Ref<string>>()
expectTypeOf(useCookie('test', { default: () => ref(500) })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useCookie('test', { default: () => 500 })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
})
it('infer request url string literal from server/api routes', () => {
// request can accept dynamic string type
const dynamicStringUrl: string = 'https://example.com/api'
expectTypeOf(useFetch(dynamicStringUrl).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
// request param should infer string literal type / show auto-complete hint base on server routes, ex: '/api/hello'
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
// request can accept string literal and Request object type
expectTypeOf(useFetch('https://example.com/api').data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
expectTypeOf(useFetch(new Request('test')).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
})
it('provides proper type support when using overloads', () => {
expectTypeOf(useState('test')).toEqualTypeOf(useState())
expectTypeOf(useState('test', () => ({ foo: Math.random() }))).toEqualTypeOf(useState(() => ({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
})
})
describe('app config', () => {
it('merges app config as expected', () => {
interface ExpectedMergedAppConfig {
fromLayer: boolean,
fromNuxtConfig: boolean,
nested: {
val: number
},
userConfig: number
}
expectTypeOf<AppConfig>().toMatchTypeOf<ExpectedMergedAppConfig>()
})
})
describe('extends type declarations', () => {
it('correctly adds references to tsconfig', () => {
expectTypeOf<import('bing').BingInterface>().toEqualTypeOf<{ foo: 'bar' }>()
})
})
| test/fixtures/basic/types.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.9951621890068054,
0.2661477327346802,
0.00016656190564390272,
0.00017134923837147653,
0.434444785118103
] |
{
"id": 1,
"code_window": [
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: AsyncDataOptions<DataT, Transform, PickKeys>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useAsyncData<\n",
" DataT,\n",
" DataE = Error,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 63
} | import { resolve } from 'node:path'
import { ComponentsDir } from '@nuxt/schema'
import { expect, it, vi } from 'vitest'
import { scanComponents } from '../src/components/scan'
const fixtureDir = resolve(__dirname, 'fixture')
const rFixture = (...p: string[]) => resolve(fixtureDir, ...p)
vi.mock('@nuxt/kit', () => ({
isIgnored: () => false
}))
const dirs: ComponentsDir[] = [
{
path: rFixture('components'),
enabled: true,
extensions: [
'vue'
],
pattern: '**/*.{vue,}',
ignore: [
'**/*.stories.{js,ts,jsx,tsx}',
'**/*{M,.m,-m}ixin.{js,ts,jsx,tsx}',
'**/*.d.ts'
],
transpile: false
},
{
path: rFixture('components'),
enabled: true,
extensions: [
'vue'
],
pattern: '**/*.{vue,}',
ignore: [
'**/*.stories.{js,ts,jsx,tsx}',
'**/*{M,.m,-m}ixin.{js,ts,jsx,tsx}',
'**/*.d.ts'
],
transpile: false
},
{
path: rFixture('components'),
extensions: [
'vue'
],
prefix: 'nuxt',
enabled: true,
pattern: '**/*.{vue,}',
ignore: [
'**/*.stories.{js,ts,jsx,tsx}',
'**/*{M,.m,-m}ixin.{js,ts,jsx,tsx}',
'**/*.d.ts'
],
transpile: false
}
]
const expectedComponents = [
{
mode: 'all',
pascalName: 'HelloWorld',
kebabName: 'hello-world',
chunkName: 'components/hello-world',
shortPath: 'components/HelloWorld.vue',
export: 'default',
global: undefined,
prefetch: false,
preload: false
},
{
mode: 'client',
pascalName: 'Nuxt3',
kebabName: 'nuxt3',
chunkName: 'components/nuxt3-client',
shortPath: 'components/Nuxt3.client.vue',
export: 'default',
global: undefined,
prefetch: false,
preload: false
},
{
mode: 'server',
pascalName: 'Nuxt3',
kebabName: 'nuxt3',
chunkName: 'components/nuxt3-server',
shortPath: 'components/Nuxt3.server.vue',
export: 'default',
global: undefined,
prefetch: false,
preload: false
},
{
mode: 'server',
pascalName: 'ParentFolder',
kebabName: 'parent-folder',
chunkName: 'components/parent-folder-server',
shortPath: 'components/parent-folder/index.server.vue',
export: 'default',
global: undefined,
prefetch: false,
preload: false
}
]
const srcDir = rFixture('.')
it('components:scanComponents', async () => {
const scannedComponents = await scanComponents(dirs, srcDir)
for (const c of scannedComponents) {
// @ts-ignore
delete c.filePath
}
expect(scannedComponents).deep.eq(expectedComponents)
})
| packages/nuxt/test/scan-components.test.ts | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017762230709195137,
0.000173107604496181,
0.00016597039939370006,
0.00017344122170470655,
0.0000030623773454863112
] |
{
"id": 1,
"code_window": [
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: AsyncDataOptions<DataT, Transform, PickKeys>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useAsyncData<\n",
" DataT,\n",
" DataE = Error,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 63
} | titleTemplate: 'Migrate to Nuxt 3: %s'
| docs/content/7.migration/_dir.yml | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.0001676286046858877,
0.0001676286046858877,
0.0001676286046858877,
0.0001676286046858877,
0
] |
{
"id": 1,
"code_window": [
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: AsyncDataOptions<DataT, Transform, PickKeys>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useAsyncData<\n",
" DataT,\n",
" DataE = Error,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 63
} | title: Deploy
navigation.icon: uil:cloud-check
| docs/content/2.guide/3.deploy/_dir.yml | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017657518037594855,
0.00017657518037594855,
0.00017657518037594855,
0.00017657518037594855,
0
] |
{
"id": 2,
"code_window": [
"> (\n",
" key: string,\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: AsyncDataOptions<DataT, Transform, PickKeys>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useAsyncData<\n",
" DataT,\n",
" DataE = Error,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 73
} | import { expectTypeOf } from 'expect-type'
import { describe, it } from 'vitest'
import type { Ref } from 'vue'
import type { AppConfig } from '@nuxt/schema'
import type { FetchError } from 'ohmyfetch'
import { NavigationFailure, RouteLocationNormalizedLoaded, RouteLocationRaw, useRouter as vueUseRouter } from 'vue-router'
import { defineNuxtConfig } from '~~/../../../packages/nuxt/config'
import type { NavigateToOptions } from '~~/../../../packages/nuxt/dist/app/composables/router'
// eslint-disable-next-line import/order
import { isVue3 } from '#app'
import { useRouter } from '#imports'
interface TestResponse { message: string }
describe('API routes', () => {
it('generates types for routes', () => {
expectTypeOf($fetch('/api/hello')).toEqualTypeOf<Promise<string>>()
expectTypeOf($fetch('/api/hey')).toEqualTypeOf<Promise<{ foo: string, baz: string }>>()
expectTypeOf($fetch('/api/other')).toEqualTypeOf<Promise<unknown>>()
expectTypeOf($fetch<TestResponse>('/test')).toEqualTypeOf<Promise<TestResponse>>()
})
it('works with useAsyncData', () => {
expectTypeOf(useAsyncData('api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useAsyncData('api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useAsyncData('api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useAsyncData('api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useAsyncData<TestResponse>('api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
expectTypeOf(useLazyAsyncData('lazy-api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyAsyncData<TestResponse>('lazy-api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
})
it('works with useFetch', () => {
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
})
})
describe('aliases', () => {
it('allows importing from path aliases', () => {
expectTypeOf(useRouter).toEqualTypeOf<typeof vueUseRouter>()
expectTypeOf(isVue3).toEqualTypeOf<boolean>()
})
})
describe('middleware', () => {
it('recognizes named middleware', () => {
definePageMeta({ middleware: 'inject-auth' })
// @ts-expect-error ignore global middleware
definePageMeta({ middleware: 'redirect' })
// @ts-expect-error Invalid middleware
definePageMeta({ middleware: 'invalid-middleware' })
})
it('handles adding middleware', () => {
addRouteMiddleware('example', (to, from) => {
expectTypeOf(to).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(from).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(navigateTo).toEqualTypeOf<(to: RouteLocationRaw, options?: NavigateToOptions) => RouteLocationRaw | Promise<void | NavigationFailure>>()
navigateTo('/')
abortNavigation()
abortNavigation('error string')
abortNavigation(new Error('my error'))
// @ts-expect-error Must return error or string
abortNavigation(true)
}, { global: true })
})
})
describe('layouts', () => {
it('recognizes named layouts', () => {
definePageMeta({ layout: 'custom' })
definePageMeta({ layout: 'pascal-case' })
// @ts-expect-error Invalid layout
definePageMeta({ layout: 'invalid-layout' })
})
})
describe('modules', () => {
it('augments schema automatically', () => {
defineNuxtConfig({ sampleModule: { enabled: false } })
// @ts-expect-error
defineNuxtConfig({ sampleModule: { other: false } })
// @ts-expect-error
defineNuxtConfig({ undeclaredKey: { other: false } })
})
})
describe('runtimeConfig', () => {
it('generated runtimeConfig types', () => {
const runtimeConfig = useRuntimeConfig()
expectTypeOf(runtimeConfig.testConfig).toEqualTypeOf<number>()
expectTypeOf(runtimeConfig.privateConfig).toEqualTypeOf<string>()
expectTypeOf(runtimeConfig.unknown).toEqualTypeOf<any>()
})
})
describe('head', () => {
it('correctly types nuxt.config options', () => {
// @ts-expect-error
defineNuxtConfig({ app: { head: { titleTemplate: () => 'test' } } })
defineNuxtConfig({
app: {
head: {
meta: [{ key: 'key', name: 'description', content: 'some description ' }],
titleTemplate: 'test %s'
}
}
})
})
it('types useHead', () => {
useHead({
base: { href: '/base' },
link: computed(() => []),
meta: [
{ key: 'key', name: 'description', content: 'some description ' },
() => ({ key: 'key', name: 'description', content: 'some description ' })
],
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - Site Title` : 'Site Title'
}
})
})
})
describe('composables', () => {
it('allows providing default refs', () => {
expectTypeOf(useState('test', () => ref('hello'))).toEqualTypeOf<Ref<string>>()
expectTypeOf(useState('test', () => 'hello')).toEqualTypeOf<Ref<string>>()
expectTypeOf(useCookie('test', { default: () => ref(500) })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useCookie('test', { default: () => 500 })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
})
it('infer request url string literal from server/api routes', () => {
// request can accept dynamic string type
const dynamicStringUrl: string = 'https://example.com/api'
expectTypeOf(useFetch(dynamicStringUrl).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
// request param should infer string literal type / show auto-complete hint base on server routes, ex: '/api/hello'
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
// request can accept string literal and Request object type
expectTypeOf(useFetch('https://example.com/api').data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
expectTypeOf(useFetch(new Request('test')).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
})
it('provides proper type support when using overloads', () => {
expectTypeOf(useState('test')).toEqualTypeOf(useState())
expectTypeOf(useState('test', () => ({ foo: Math.random() }))).toEqualTypeOf(useState(() => ({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
})
})
describe('app config', () => {
it('merges app config as expected', () => {
interface ExpectedMergedAppConfig {
fromLayer: boolean,
fromNuxtConfig: boolean,
nested: {
val: number
},
userConfig: number
}
expectTypeOf<AppConfig>().toMatchTypeOf<ExpectedMergedAppConfig>()
})
})
describe('extends type declarations', () => {
it('correctly adds references to tsconfig', () => {
expectTypeOf<import('bing').BingInterface>().toEqualTypeOf<{ foo: 'bar' }>()
})
})
| test/fixtures/basic/types.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.9969327449798584,
0.14511042833328247,
0.00016550516011193395,
0.00017508331802673638,
0.3138427436351776
] |
{
"id": 2,
"code_window": [
"> (\n",
" key: string,\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: AsyncDataOptions<DataT, Transform, PickKeys>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useAsyncData<\n",
" DataT,\n",
" DataE = Error,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 73
} | ---
title: "navigateTo"
description: navigateTo is a helper function that programmatically navigates users.
---
# `navigateTo`
`navigateTo` is a router helper function that allows programmatically navigating users through your Nuxt application.
`navigateTo` is available on both server side and client side. It can be used within plugins, middleware or can be called directly to perform page navigation.
## Type
```ts
navigateTo(to: RouteLocationRaw | undefined | null, options?: NavigateToOptions) => Promise<void | NavigationFailure> | RouteLocationRaw
interface NavigateToOptions {
replace?: boolean
redirectCode?: number
external?: boolean
}
```
::alert{type="warning"}
Make sure to always use `await` or `return` on result of `navigateTo` when calling it.
::
## Parameters
### `to`
**Type**: [`RouteLocationRaw`](https://router.vuejs.org/api/#routelocationraw) | `undefined` | `null`
**Default**: `'/'`
`to` can be a plain string or a route object to redirect to. When passed as `undefined` or `null`, it will default to `'/'`.
### `options` (optional)
**Type**: `NavigateToOptions`
An object accepting the following properties:
- `replace` (optional)
**Type**: `boolean`
**Default**: `false`
By default, `navigateTo` pushes the given route into the Vue Router's instance on the client side.
This behavior can be changed by setting `replace` to `true`, to indicate that given route should be replaced.
- `redirectCode` (optional)
**Type**: `number`
**Default**: `302`
`navigateTo` redirects to the given path and sets the redirect code to [`302 Found`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302) by default when the redirection takes place on the server side.
This default behavior can be modified by providing different `redirectCode`. Commonly, [`301 Moved Permanently`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/301) can be used for permanent redirections.
- `external` (optional)
**Type**: `boolean`
**Default**: `false`
Allows navigating to an external URL when set to `true`. Otherwise, `navigateTo` will throw an error, as external navigation is not allowed by default.
## Examples
### Navigating Within a Vue Component
```vue
<script setup>
// passing 'to' as a string
await navigateTo('/search')
// ... or as a route object
await navigateTo({ path: '/search' })
// ... or as a route object with query parameters
await navigateTo({
path: '/search',
query: {
page: 1,
sort: 'asc'
}
})
</script>
```
### Navigating Within Route Middleware
```ts
export default defineNuxtRouteMiddleware((to, from) => {
// setting the redirect code to '301 Moved Permanently'
return navigateTo('/search', { redirectCode: 301 })
})
```
::ReadMore{link="/guide/directory-structure/middleware"}
::
### Navigating to an External URL
```vue
<script setup>
// will throw an error;
// navigating to an external URL is not allowed by default
await navigateTo('https://v3.nuxtjs.org')
// will redirect successfully with the 'external' parameter set to 'true'
await navigateTo('https://v3.nuxtjs.org', {
external: true
})
</script>
```
| docs/content/3.api/3.utils/navigate-to.md | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.000369350629625842,
0.00019003282068297267,
0.00016481822240166366,
0.00016981489898171276,
0.00005514919030247256
] |
{
"id": 2,
"code_window": [
"> (\n",
" key: string,\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: AsyncDataOptions<DataT, Transform, PickKeys>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useAsyncData<\n",
" DataT,\n",
" DataE = Error,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 73
} | ---
navigation: false
redirect: /guide/going-further/tooling
---
| docs/content/2.guide/4.going-further/index.md | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017522468988317996,
0.00017522468988317996,
0.00017522468988317996,
0.00017522468988317996,
0
] |
{
"id": 2,
"code_window": [
"> (\n",
" key: string,\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: AsyncDataOptions<DataT, Transform, PickKeys>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useAsyncData<\n",
" DataT,\n",
" DataE = Error,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 73
} | ---
title: "Edge Channel"
description: "Edge channel allows to use latest commits from the repository."
---
# Edge Release Channel
Nuxt 3 is landing commits, improvements, and bug fixes every day. You can opt-in to test them earlier before the next release.
After each commit is merged into the `main` branch of [nuxt/framework](https://github.com/nuxt/framework) and **passing all tests**, we trigger an automated npm release using Github Actions publishing Nuxt 3 packages.
You can opt in to use this release channel and avoid waiting for the next release and helping Nuxt by beta testing changes.
The build and publishing method and quality of edge releases are the same as stable ones. The only difference is that you should often check the GitHub repository for updates. There is a slight chance of regressions not being caught during the review process and by the automated tests. Therefore, we internally use this channel to double-check everything before each release.
:::Alert
Features only available on the edge channel are marked with an alert in the documentation.
:::
## Opting Into the Edge Channel
Update `nuxt` dependency inside `package.json`:
```diff [package.json]
{
"devDependencies": {
-- "nuxt": "^3.0.0-rc.1"
++ "nuxt": "npm:nuxt3@latest"
}
}
```
Remove lockfile (`package-lock.json`, `yarn.lock`, or `pnpm-lock.yaml`) and reinstall dependencies.
## Opting Out From the Edge Channel
Update `nuxt` dependency inside `package.json`:
```diff [package.json]
{
"devDependencies": {
-- "nuxt": "npm:nuxt3@latest"
++ "nuxt": "^3.0.0-rc.1"
}
}
```
Remove lockfile (`package-lock.json`, `yarn.lock`, or `pnpm-lock.yaml`) and reinstall dependencies.
## Using Latest `nuxi` CLI From Edge
:::Alert
All cli dependencies are bundled because of the building method for reducing `nuxi` package size. You can get dependency updates and CLI improvements using the edge channel.
:::
You can use `npx nuxi-edge@latest [command]` to try the latest version of the nuxi CLI.
| docs/content/2.guide/4.going-further/11.edge-channel.md | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017077276424970478,
0.0001673437509452924,
0.00016527742263861,
0.000166995421750471,
0.0000018923535662906943
] |
{
"id": 3,
"code_window": [
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {\n",
" const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined\n",
" if (typeof args[0] !== 'string') { args.unshift(autoKey) }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> {\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 79
} | import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from 'vue'
import type { Ref, WatchSource } from 'vue'
import { NuxtApp, useNuxtApp } from '../nuxt'
export type _Transform<Input = any, Output = any> = (input: Input) => Output
export type PickFrom<T, K extends Array<string>> = T extends Array<any>
? T
: T extends Record<string, any>
? keyof T extends K[number]
? T // Exact same keys as the target, skip Pick
: Pick<T, K[number]>
: T
export type KeysOf<T> = Array<keyof T extends string ? keyof T : string>
export type KeyOfRes<Transform extends _Transform> = KeysOf<ReturnType<Transform>>
type MultiWatchSources = (WatchSource<unknown> | object)[]
export interface AsyncDataOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<_Transform> = KeyOfRes<Transform>
> {
server?: boolean
lazy?: boolean
default?: () => DataT | Ref<DataT> | null
transform?: Transform
pick?: PickKeys
watch?: MultiWatchSources
initialCache?: boolean
immediate?: boolean
}
export interface AsyncDataExecuteOptions {
_initial?: boolean
/**
* Force a refresh, even if there is already a pending request. Previous requests will
* not be cancelled, but their result will not affect the data/pending state - and any
* previously awaited promises will not resolve until this new request resolves.
*/
dedupe?: boolean
}
export interface _AsyncData<DataT, ErrorT> {
data: Ref<DataT | null>
pending: Ref<boolean>
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>
error: Ref<ErrorT | null>
}
export type AsyncData<Data, Error> = _AsyncData<Data, Error> & Promise<_AsyncData<Data, Error>>
const getDefault = () => null
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
// eslint-disable-next-line prefer-const
let [key, handler, options = {}] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// Validate arguments
if (typeof key !== 'string') {
throw new TypeError('[nuxt] [asyncData] key must be a string.')
}
if (typeof handler !== 'function') {
throw new TypeError('[nuxt] [asyncData] handler must be a function.')
}
// Apply defaults
options.server = options.server ?? true
options.default = options.default ?? getDefault
// TODO: remove support for `defer` in Nuxt 3 RC
if ((options as any).defer) {
console.warn('[useAsyncData] `defer` has been renamed to `lazy`. Support for `defer` will be removed in RC.')
}
options.lazy = options.lazy ?? (options as any).defer ?? false
options.initialCache = options.initialCache ?? true
options.immediate = options.immediate ?? true
// Setup nuxt instance payload
const nuxt = useNuxtApp()
const useInitialCache = () => (nuxt.isHydrating || options.initialCache) && nuxt.payload.data[key] !== undefined
// Create or use a shared asyncData entity
if (!nuxt._asyncData[key]) {
nuxt._asyncData[key] = {
data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),
pending: ref(!useInitialCache()),
error: ref(nuxt.payload._errors[key] ?? null)
}
}
// TODO: Else, Soemhow check for confliciting keys with different defaults or fetcher
const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>
asyncData.refresh = asyncData.execute = (opts = {}) => {
if (nuxt._asyncDataPromises[key]) {
if (opts.dedupe === false) {
// Avoid fetching same key more than once at a time
return nuxt._asyncDataPromises[key]
}
(nuxt._asyncDataPromises[key] as any).cancelled = true
}
// Avoid fetching same key that is already fetched
if (opts._initial && useInitialCache()) {
return nuxt.payload.data[key]
}
asyncData.pending.value = true
// TODO: Cancel previous promise
const promise = new Promise<DataT>(
(resolve, reject) => {
try {
resolve(handler(nuxt))
} catch (err) {
reject(err)
}
})
.then((result) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
if (options.transform) {
result = options.transform(result)
}
if (options.pick) {
result = pick(result as any, options.pick) as DataT
}
asyncData.data.value = result
asyncData.error.value = null
})
.catch((error: any) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
asyncData.error.value = error
asyncData.data.value = unref(options.default?.() ?? null)
})
.finally(() => {
if ((promise as any).cancelled) { return }
asyncData.pending.value = false
nuxt.payload.data[key] = asyncData.data.value
if (asyncData.error.value) {
nuxt.payload._errors[key] = true
}
delete nuxt._asyncDataPromises[key]
})
nuxt._asyncDataPromises[key] = promise
return nuxt._asyncDataPromises[key]
}
const initialFetch = () => asyncData.refresh({ _initial: true })
const fetchOnServer = options.server !== false && nuxt.payload.serverRendered
// Server side
if (process.server && fetchOnServer && options.immediate) {
const promise = initialFetch()
onServerPrefetch(() => promise)
}
// Client side
if (process.client) {
// Setup hook callbacks once per instance
const instance = getCurrentInstance()
if (instance && !instance._nuxtOnBeforeMountCbs) {
instance._nuxtOnBeforeMountCbs = []
const cbs = instance._nuxtOnBeforeMountCbs
if (instance) {
onBeforeMount(() => {
cbs.forEach((cb) => { cb() })
cbs.splice(0, cbs.length)
})
onUnmounted(() => cbs.splice(0, cbs.length))
}
}
if (fetchOnServer && nuxt.isHydrating && key in nuxt.payload.data) {
// 1. Hydration (server: true): no fetch
asyncData.pending.value = false
} else if (instance && ((nuxt.payload.serverRendered && nuxt.isHydrating) || options.lazy) && options.immediate) {
// 2. Initial load (server: false): fetch on mounted
// 3. Initial load or navigation (lazy: true): fetch on mounted
instance._nuxtOnBeforeMountCbs.push(initialFetch)
} else if (options.immediate) {
// 4. Navigation (lazy: false) - or plugin usage: await fetch
initialFetch()
}
if (options.watch) {
watch(options.watch, () => asyncData.refresh())
}
const off = nuxt.hook('app:data:refresh', (keys) => {
if (!keys || keys.includes(key)) {
return asyncData.refresh()
}
})
if (instance) {
onUnmounted(off)
}
}
// Allow directly awaiting on asyncData
const asyncDataPromise = Promise.resolve(nuxt._asyncDataPromises[key]).then(() => asyncData) as AsyncData<DataT, DataE>
Object.assign(asyncDataPromise, asyncData)
return asyncDataPromise as AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE>
}
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// @ts-ignore
return useAsyncData(key, handler, { ...options, lazy: true }, null)
}
export async function refreshNuxtData (keys?: string | string[]): Promise<void> {
if (process.server) {
return Promise.resolve()
}
const _keys = keys ? Array.isArray(keys) ? keys : [keys] : undefined
await useNuxtApp().hooks.callHookParallel('app:data:refresh', _keys)
}
export function clearNuxtData (keys?: string | string[] | ((key: string) => boolean)): void {
const nuxtApp = useNuxtApp()
const _allKeys = Object.keys(nuxtApp.payload.data)
const _keys: string[] = !keys
? _allKeys
: typeof keys === 'function'
? _allKeys.filter(keys)
: Array.isArray(keys) ? keys : [keys]
for (const key of _keys) {
if (key in nuxtApp.payload.data) {
nuxtApp.payload.data[key] = undefined
}
if (key in nuxtApp.payload._errors) {
nuxtApp.payload._errors[key] = undefined
}
if (nuxtApp._asyncData[key]) {
nuxtApp._asyncData[key]!.data.value = undefined
nuxtApp._asyncData[key]!.error.value = undefined
nuxtApp._asyncData[key]!.pending.value = false
}
if (key in nuxtApp._asyncDataPromises) {
nuxtApp._asyncDataPromises[key] = undefined
}
}
}
function pick (obj: Record<string, any>, keys: string[]) {
const newObj = {}
for (const key of keys) {
(newObj as any)[key] = obj[key]
}
return newObj
}
| packages/nuxt/src/app/composables/asyncData.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.999201238155365,
0.293916791677475,
0.0001646862510824576,
0.0004268415505066514,
0.4446032643318176
] |
{
"id": 3,
"code_window": [
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {\n",
" const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined\n",
" if (typeof args[0] !== 'string') { args.unshift(autoKey) }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> {\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 79
} | ---
title: "useCookie"
description: "This example shows how to use the useCookie API to persist small amounts of data that both client and server can use."
toc: false
---
::ReadMore{link="/api/composables/use-cookie"}
::
::sandbox{repo="nuxt/framework" branch="main" dir="examples/composables/use-cookie" file="app.vue"}
::
| docs/content/4.examples/3.composables/use-cookie.md | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.0001729192736092955,
0.00017275733989663422,
0.00017259542073588818,
0.00017275733989663422,
1.6192643670365214e-7
] |
{
"id": 3,
"code_window": [
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {\n",
" const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined\n",
" if (typeof args[0] !== 'string') { args.unshift(autoKey) }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> {\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 79
} | {
"extends": "./.nuxt/tsconfig.json"
}
| examples/advanced/jsx/tsconfig.json | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017350113193970174,
0.00017350113193970174,
0.00017350113193970174,
0.00017350113193970174,
0
] |
{
"id": 3,
"code_window": [
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {\n",
" const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined\n",
" if (typeof args[0] !== 'string') { args.unshift(autoKey) }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> {\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 79
} | <script setup lang="ts">
function exposedFunc () {
console.log('ok')
}
defineExpose({ exposedFunc })
await new Promise(resolve => setTimeout(resolve, 300))
onMounted(() => { console.log('mounted') })
</script>
<template>
<div>
client-only component
</div>
</template>
| test/fixtures/basic/components/ClientWrapped.client.vue | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017473033221904188,
0.0001738739520078525,
0.0001730175717966631,
0.0001738739520078525,
8.563802111893892e-7
] |
{
"id": 4,
"code_window": [
" if (!nuxt._asyncData[key]) {\n",
" nuxt._asyncData[key] = {\n",
" data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),\n",
" pending: ref(!useInitialCache()),\n",
" error: ref(nuxt.payload._errors[key] ?? null)\n",
" }\n",
" }\n",
" // TODO: Else, Soemhow check for confliciting keys with different defaults or fetcher\n",
" const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error: ref(nuxt.payload._errors[key] ? createError(nuxt.payload._errors[key]) : null)\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 116
} | import { expectTypeOf } from 'expect-type'
import { describe, it } from 'vitest'
import type { Ref } from 'vue'
import type { AppConfig } from '@nuxt/schema'
import type { FetchError } from 'ohmyfetch'
import { NavigationFailure, RouteLocationNormalizedLoaded, RouteLocationRaw, useRouter as vueUseRouter } from 'vue-router'
import { defineNuxtConfig } from '~~/../../../packages/nuxt/config'
import type { NavigateToOptions } from '~~/../../../packages/nuxt/dist/app/composables/router'
// eslint-disable-next-line import/order
import { isVue3 } from '#app'
import { useRouter } from '#imports'
interface TestResponse { message: string }
describe('API routes', () => {
it('generates types for routes', () => {
expectTypeOf($fetch('/api/hello')).toEqualTypeOf<Promise<string>>()
expectTypeOf($fetch('/api/hey')).toEqualTypeOf<Promise<{ foo: string, baz: string }>>()
expectTypeOf($fetch('/api/other')).toEqualTypeOf<Promise<unknown>>()
expectTypeOf($fetch<TestResponse>('/test')).toEqualTypeOf<Promise<TestResponse>>()
})
it('works with useAsyncData', () => {
expectTypeOf(useAsyncData('api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useAsyncData('api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useAsyncData('api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useAsyncData('api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useAsyncData<TestResponse>('api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
expectTypeOf(useLazyAsyncData('lazy-api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyAsyncData<TestResponse>('lazy-api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
})
it('works with useFetch', () => {
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
})
})
describe('aliases', () => {
it('allows importing from path aliases', () => {
expectTypeOf(useRouter).toEqualTypeOf<typeof vueUseRouter>()
expectTypeOf(isVue3).toEqualTypeOf<boolean>()
})
})
describe('middleware', () => {
it('recognizes named middleware', () => {
definePageMeta({ middleware: 'inject-auth' })
// @ts-expect-error ignore global middleware
definePageMeta({ middleware: 'redirect' })
// @ts-expect-error Invalid middleware
definePageMeta({ middleware: 'invalid-middleware' })
})
it('handles adding middleware', () => {
addRouteMiddleware('example', (to, from) => {
expectTypeOf(to).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(from).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(navigateTo).toEqualTypeOf<(to: RouteLocationRaw, options?: NavigateToOptions) => RouteLocationRaw | Promise<void | NavigationFailure>>()
navigateTo('/')
abortNavigation()
abortNavigation('error string')
abortNavigation(new Error('my error'))
// @ts-expect-error Must return error or string
abortNavigation(true)
}, { global: true })
})
})
describe('layouts', () => {
it('recognizes named layouts', () => {
definePageMeta({ layout: 'custom' })
definePageMeta({ layout: 'pascal-case' })
// @ts-expect-error Invalid layout
definePageMeta({ layout: 'invalid-layout' })
})
})
describe('modules', () => {
it('augments schema automatically', () => {
defineNuxtConfig({ sampleModule: { enabled: false } })
// @ts-expect-error
defineNuxtConfig({ sampleModule: { other: false } })
// @ts-expect-error
defineNuxtConfig({ undeclaredKey: { other: false } })
})
})
describe('runtimeConfig', () => {
it('generated runtimeConfig types', () => {
const runtimeConfig = useRuntimeConfig()
expectTypeOf(runtimeConfig.testConfig).toEqualTypeOf<number>()
expectTypeOf(runtimeConfig.privateConfig).toEqualTypeOf<string>()
expectTypeOf(runtimeConfig.unknown).toEqualTypeOf<any>()
})
})
describe('head', () => {
it('correctly types nuxt.config options', () => {
// @ts-expect-error
defineNuxtConfig({ app: { head: { titleTemplate: () => 'test' } } })
defineNuxtConfig({
app: {
head: {
meta: [{ key: 'key', name: 'description', content: 'some description ' }],
titleTemplate: 'test %s'
}
}
})
})
it('types useHead', () => {
useHead({
base: { href: '/base' },
link: computed(() => []),
meta: [
{ key: 'key', name: 'description', content: 'some description ' },
() => ({ key: 'key', name: 'description', content: 'some description ' })
],
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - Site Title` : 'Site Title'
}
})
})
})
describe('composables', () => {
it('allows providing default refs', () => {
expectTypeOf(useState('test', () => ref('hello'))).toEqualTypeOf<Ref<string>>()
expectTypeOf(useState('test', () => 'hello')).toEqualTypeOf<Ref<string>>()
expectTypeOf(useCookie('test', { default: () => ref(500) })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useCookie('test', { default: () => 500 })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
})
it('infer request url string literal from server/api routes', () => {
// request can accept dynamic string type
const dynamicStringUrl: string = 'https://example.com/api'
expectTypeOf(useFetch(dynamicStringUrl).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
// request param should infer string literal type / show auto-complete hint base on server routes, ex: '/api/hello'
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
// request can accept string literal and Request object type
expectTypeOf(useFetch('https://example.com/api').data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
expectTypeOf(useFetch(new Request('test')).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
})
it('provides proper type support when using overloads', () => {
expectTypeOf(useState('test')).toEqualTypeOf(useState())
expectTypeOf(useState('test', () => ({ foo: Math.random() }))).toEqualTypeOf(useState(() => ({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
})
})
describe('app config', () => {
it('merges app config as expected', () => {
interface ExpectedMergedAppConfig {
fromLayer: boolean,
fromNuxtConfig: boolean,
nested: {
val: number
},
userConfig: number
}
expectTypeOf<AppConfig>().toMatchTypeOf<ExpectedMergedAppConfig>()
})
})
describe('extends type declarations', () => {
it('correctly adds references to tsconfig', () => {
expectTypeOf<import('bing').BingInterface>().toEqualTypeOf<{ foo: 'bar' }>()
})
})
| test/fixtures/basic/types.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00018157140584662557,
0.00016969330317806453,
0.00016256890376098454,
0.00016965638496913016,
0.000004192258529656101
] |
{
"id": 4,
"code_window": [
" if (!nuxt._asyncData[key]) {\n",
" nuxt._asyncData[key] = {\n",
" data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),\n",
" pending: ref(!useInitialCache()),\n",
" error: ref(nuxt.payload._errors[key] ?? null)\n",
" }\n",
" }\n",
" // TODO: Else, Soemhow check for confliciting keys with different defaults or fetcher\n",
" const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error: ref(nuxt.payload._errors[key] ? createError(nuxt.payload._errors[key]) : null)\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 116
} | <template>
<b style="color: #00C58E">
From Nuxt 3
</b>
</template>
| packages/nuxt/test/fixture/components/Nuxt3.client.vue | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00016731146024540067,
0.00016731146024540067,
0.00016731146024540067,
0.00016731146024540067,
0
] |
{
"id": 4,
"code_window": [
" if (!nuxt._asyncData[key]) {\n",
" nuxt._asyncData[key] = {\n",
" data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),\n",
" pending: ref(!useInitialCache()),\n",
" error: ref(nuxt.payload._errors[key] ?? null)\n",
" }\n",
" }\n",
" // TODO: Else, Soemhow check for confliciting keys with different defaults or fetcher\n",
" const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error: ref(nuxt.payload._errors[key] ? createError(nuxt.payload._errors[key]) : null)\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 116
} | declare module 'bing' {
interface BingInterface {
foo: 'bar'
}
}
| test/fixtures/basic/extends/bar/index.d.ts | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00016936859174165875,
0.00016936859174165875,
0.00016936859174165875,
0.00016936859174165875,
0
] |
{
"id": 4,
"code_window": [
" if (!nuxt._asyncData[key]) {\n",
" nuxt._asyncData[key] = {\n",
" data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),\n",
" pending: ref(!useInitialCache()),\n",
" error: ref(nuxt.payload._errors[key] ?? null)\n",
" }\n",
" }\n",
" // TODO: Else, Soemhow check for confliciting keys with different defaults or fetcher\n",
" const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error: ref(nuxt.payload._errors[key] ? createError(nuxt.payload._errors[key]) : null)\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 116
} | <template>
<div>
You should never see this page
</div>
</template>
<script setup>
definePageMeta({
middleware: 'redirect-me'
})
</script>
| examples/routing/middleware/pages/redirect.vue | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00016956881154328585,
0.000168964485055767,
0.00016836015856824815,
0.000168964485055767,
6.04326487518847e-7
] |
{
"id": 5,
"code_window": [
" asyncData.pending.value = false\n",
" nuxt.payload.data[key] = asyncData.data.value\n",
" if (asyncData.error.value) {\n",
" nuxt.payload._errors[key] = true\n",
" }\n",
" delete nuxt._asyncDataPromises[key]\n",
" })\n",
" nuxt._asyncDataPromises[key] = promise\n",
" return nuxt._asyncDataPromises[key]\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // We use `createError` and its .toJSON() property to normalize the error\n",
" nuxt.payload._errors[key] = createError(asyncData.error.value)\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 170
} | import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from 'vue'
import type { Ref, WatchSource } from 'vue'
import { NuxtApp, useNuxtApp } from '../nuxt'
export type _Transform<Input = any, Output = any> = (input: Input) => Output
export type PickFrom<T, K extends Array<string>> = T extends Array<any>
? T
: T extends Record<string, any>
? keyof T extends K[number]
? T // Exact same keys as the target, skip Pick
: Pick<T, K[number]>
: T
export type KeysOf<T> = Array<keyof T extends string ? keyof T : string>
export type KeyOfRes<Transform extends _Transform> = KeysOf<ReturnType<Transform>>
type MultiWatchSources = (WatchSource<unknown> | object)[]
export interface AsyncDataOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<_Transform> = KeyOfRes<Transform>
> {
server?: boolean
lazy?: boolean
default?: () => DataT | Ref<DataT> | null
transform?: Transform
pick?: PickKeys
watch?: MultiWatchSources
initialCache?: boolean
immediate?: boolean
}
export interface AsyncDataExecuteOptions {
_initial?: boolean
/**
* Force a refresh, even if there is already a pending request. Previous requests will
* not be cancelled, but their result will not affect the data/pending state - and any
* previously awaited promises will not resolve until this new request resolves.
*/
dedupe?: boolean
}
export interface _AsyncData<DataT, ErrorT> {
data: Ref<DataT | null>
pending: Ref<boolean>
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>
error: Ref<ErrorT | null>
}
export type AsyncData<Data, Error> = _AsyncData<Data, Error> & Promise<_AsyncData<Data, Error>>
const getDefault = () => null
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
// eslint-disable-next-line prefer-const
let [key, handler, options = {}] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// Validate arguments
if (typeof key !== 'string') {
throw new TypeError('[nuxt] [asyncData] key must be a string.')
}
if (typeof handler !== 'function') {
throw new TypeError('[nuxt] [asyncData] handler must be a function.')
}
// Apply defaults
options.server = options.server ?? true
options.default = options.default ?? getDefault
// TODO: remove support for `defer` in Nuxt 3 RC
if ((options as any).defer) {
console.warn('[useAsyncData] `defer` has been renamed to `lazy`. Support for `defer` will be removed in RC.')
}
options.lazy = options.lazy ?? (options as any).defer ?? false
options.initialCache = options.initialCache ?? true
options.immediate = options.immediate ?? true
// Setup nuxt instance payload
const nuxt = useNuxtApp()
const useInitialCache = () => (nuxt.isHydrating || options.initialCache) && nuxt.payload.data[key] !== undefined
// Create or use a shared asyncData entity
if (!nuxt._asyncData[key]) {
nuxt._asyncData[key] = {
data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),
pending: ref(!useInitialCache()),
error: ref(nuxt.payload._errors[key] ?? null)
}
}
// TODO: Else, Soemhow check for confliciting keys with different defaults or fetcher
const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>
asyncData.refresh = asyncData.execute = (opts = {}) => {
if (nuxt._asyncDataPromises[key]) {
if (opts.dedupe === false) {
// Avoid fetching same key more than once at a time
return nuxt._asyncDataPromises[key]
}
(nuxt._asyncDataPromises[key] as any).cancelled = true
}
// Avoid fetching same key that is already fetched
if (opts._initial && useInitialCache()) {
return nuxt.payload.data[key]
}
asyncData.pending.value = true
// TODO: Cancel previous promise
const promise = new Promise<DataT>(
(resolve, reject) => {
try {
resolve(handler(nuxt))
} catch (err) {
reject(err)
}
})
.then((result) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
if (options.transform) {
result = options.transform(result)
}
if (options.pick) {
result = pick(result as any, options.pick) as DataT
}
asyncData.data.value = result
asyncData.error.value = null
})
.catch((error: any) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
asyncData.error.value = error
asyncData.data.value = unref(options.default?.() ?? null)
})
.finally(() => {
if ((promise as any).cancelled) { return }
asyncData.pending.value = false
nuxt.payload.data[key] = asyncData.data.value
if (asyncData.error.value) {
nuxt.payload._errors[key] = true
}
delete nuxt._asyncDataPromises[key]
})
nuxt._asyncDataPromises[key] = promise
return nuxt._asyncDataPromises[key]
}
const initialFetch = () => asyncData.refresh({ _initial: true })
const fetchOnServer = options.server !== false && nuxt.payload.serverRendered
// Server side
if (process.server && fetchOnServer && options.immediate) {
const promise = initialFetch()
onServerPrefetch(() => promise)
}
// Client side
if (process.client) {
// Setup hook callbacks once per instance
const instance = getCurrentInstance()
if (instance && !instance._nuxtOnBeforeMountCbs) {
instance._nuxtOnBeforeMountCbs = []
const cbs = instance._nuxtOnBeforeMountCbs
if (instance) {
onBeforeMount(() => {
cbs.forEach((cb) => { cb() })
cbs.splice(0, cbs.length)
})
onUnmounted(() => cbs.splice(0, cbs.length))
}
}
if (fetchOnServer && nuxt.isHydrating && key in nuxt.payload.data) {
// 1. Hydration (server: true): no fetch
asyncData.pending.value = false
} else if (instance && ((nuxt.payload.serverRendered && nuxt.isHydrating) || options.lazy) && options.immediate) {
// 2. Initial load (server: false): fetch on mounted
// 3. Initial load or navigation (lazy: true): fetch on mounted
instance._nuxtOnBeforeMountCbs.push(initialFetch)
} else if (options.immediate) {
// 4. Navigation (lazy: false) - or plugin usage: await fetch
initialFetch()
}
if (options.watch) {
watch(options.watch, () => asyncData.refresh())
}
const off = nuxt.hook('app:data:refresh', (keys) => {
if (!keys || keys.includes(key)) {
return asyncData.refresh()
}
})
if (instance) {
onUnmounted(off)
}
}
// Allow directly awaiting on asyncData
const asyncDataPromise = Promise.resolve(nuxt._asyncDataPromises[key]).then(() => asyncData) as AsyncData<DataT, DataE>
Object.assign(asyncDataPromise, asyncData)
return asyncDataPromise as AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE>
}
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// @ts-ignore
return useAsyncData(key, handler, { ...options, lazy: true }, null)
}
export async function refreshNuxtData (keys?: string | string[]): Promise<void> {
if (process.server) {
return Promise.resolve()
}
const _keys = keys ? Array.isArray(keys) ? keys : [keys] : undefined
await useNuxtApp().hooks.callHookParallel('app:data:refresh', _keys)
}
export function clearNuxtData (keys?: string | string[] | ((key: string) => boolean)): void {
const nuxtApp = useNuxtApp()
const _allKeys = Object.keys(nuxtApp.payload.data)
const _keys: string[] = !keys
? _allKeys
: typeof keys === 'function'
? _allKeys.filter(keys)
: Array.isArray(keys) ? keys : [keys]
for (const key of _keys) {
if (key in nuxtApp.payload.data) {
nuxtApp.payload.data[key] = undefined
}
if (key in nuxtApp.payload._errors) {
nuxtApp.payload._errors[key] = undefined
}
if (nuxtApp._asyncData[key]) {
nuxtApp._asyncData[key]!.data.value = undefined
nuxtApp._asyncData[key]!.error.value = undefined
nuxtApp._asyncData[key]!.pending.value = false
}
if (key in nuxtApp._asyncDataPromises) {
nuxtApp._asyncDataPromises[key] = undefined
}
}
}
function pick (obj: Record<string, any>, keys: string[]) {
const newObj = {}
for (const key of keys) {
(newObj as any)[key] = obj[key]
}
return newObj
}
| packages/nuxt/src/app/composables/asyncData.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.9965672492980957,
0.07499752938747406,
0.00016822088218759745,
0.0018369805766269565,
0.2435292750597
] |
{
"id": 5,
"code_window": [
" asyncData.pending.value = false\n",
" nuxt.payload.data[key] = asyncData.data.value\n",
" if (asyncData.error.value) {\n",
" nuxt.payload._errors[key] = true\n",
" }\n",
" delete nuxt._asyncDataPromises[key]\n",
" })\n",
" nuxt._asyncDataPromises[key] = promise\n",
" return nuxt._asyncDataPromises[key]\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // We use `createError` and its .toJSON() property to normalize the error\n",
" nuxt.payload._errors[key] = createError(asyncData.error.value)\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 170
} | ---
title: "NuxtApp"
description: "In Nuxt 3, you can access runtime app context within composables, components and plugins."
---
# NuxtApp
In Nuxt 3, you can access runtime app context within composables, components and plugins. In Nuxt 2, this was referred to as [Nuxt context](https://nuxtjs.org/docs/internals-glossary/context#the-context).
## Accessing NuxtApp
Within composables, plugins and components you can access `nuxtApp` with `useNuxtApp`:
```js
function useMyComposable () {
const nuxtApp = useNuxtApp()
// access runtime nuxt app instance
}
```
Plugins also receive `nuxtApp` as the first argument for convenience. [Read more about plugins.](/guide/directory-structure/plugins)
::alert{icon=👉}
**`useNuxtApp` (on the server) only works during `setup`, inside Nuxt plugins or `Lifecycle Hooks`**.
::
## Providing Helpers
You can provide helpers to be usable across all composables and application. This usually happens within a Nuxt plugin.
```js
const nuxtApp = useNuxtApp()
nuxtApp.provide('hello', (name) => `Hello ${name}!`)
console.log(nuxtApp.$hello('name')) // Prints "Hello name!"
```
In Nuxt 2 plugins, this was referred to as [inject function](https://nuxtjs.org/docs/directory-structure/plugins#inject-in-root--context).
::alert{icon=👉}
It is possible to inject helpers by returning an object with a `provide` key. See the [plugins documentation](/guide/directory-structure/plugins) for more information.
::
| docs/content/2.guide/4.going-further/6.nuxt-app.md | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.0014342244248837233,
0.00043475901475176215,
0.00015963024634402245,
0.0001690963690634817,
0.0005007059080526233
] |
{
"id": 5,
"code_window": [
" asyncData.pending.value = false\n",
" nuxt.payload.data[key] = asyncData.data.value\n",
" if (asyncData.error.value) {\n",
" nuxt.payload._errors[key] = true\n",
" }\n",
" delete nuxt._asyncDataPromises[key]\n",
" })\n",
" nuxt._asyncDataPromises[key] = promise\n",
" return nuxt._asyncDataPromises[key]\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // We use `createError` and its .toJSON() property to normalize the error\n",
" nuxt.payload._errors[key] = createError(asyncData.error.value)\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 170
} | <script setup lang="ts">
const count = ref(0)
function inc () {
count.value++
}
function dec () {
count.value--
}
</script>
<template>
<NuxtExampleLayout example="experimental/vite-node">
<div>
{{ count }}
<div class="flex gap-1 justify-center">
<NButton @click="inc()">
Inc
</NButton>
<NButton @click="dec()">
Dec
</NButton>
</div>
</div>
</NuxtExampleLayout>
</template>
| examples/experimental/vite-node/app.vue | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017376203322783113,
0.00017297995509579778,
0.0001715239486657083,
0.0001736538833938539,
0.0000010304983106834698
] |
{
"id": 5,
"code_window": [
" asyncData.pending.value = false\n",
" nuxt.payload.data[key] = asyncData.data.value\n",
" if (asyncData.error.value) {\n",
" nuxt.payload._errors[key] = true\n",
" }\n",
" delete nuxt._asyncDataPromises[key]\n",
" })\n",
" nuxt._asyncDataPromises[key] = promise\n",
" return nuxt._asyncDataPromises[key]\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // We use `createError` and its .toJSON() property to normalize the error\n",
" nuxt.payload._errors[key] = createError(asyncData.error.value)\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 170
} | ---
navigation: false
redirect: /guide/going-further/tooling
---
| docs/content/2.guide/4.going-further/index.md | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00016822986071929336,
0.00016822986071929336,
0.00016822986071929336,
0.00016822986071929336,
0
] |
{
"id": 6,
"code_window": [
"> (\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useLazyAsyncData<\n",
" DataT,\n",
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 242
} | import { expectTypeOf } from 'expect-type'
import { describe, it } from 'vitest'
import type { Ref } from 'vue'
import type { AppConfig } from '@nuxt/schema'
import type { FetchError } from 'ohmyfetch'
import { NavigationFailure, RouteLocationNormalizedLoaded, RouteLocationRaw, useRouter as vueUseRouter } from 'vue-router'
import { defineNuxtConfig } from '~~/../../../packages/nuxt/config'
import type { NavigateToOptions } from '~~/../../../packages/nuxt/dist/app/composables/router'
// eslint-disable-next-line import/order
import { isVue3 } from '#app'
import { useRouter } from '#imports'
interface TestResponse { message: string }
describe('API routes', () => {
it('generates types for routes', () => {
expectTypeOf($fetch('/api/hello')).toEqualTypeOf<Promise<string>>()
expectTypeOf($fetch('/api/hey')).toEqualTypeOf<Promise<{ foo: string, baz: string }>>()
expectTypeOf($fetch('/api/other')).toEqualTypeOf<Promise<unknown>>()
expectTypeOf($fetch<TestResponse>('/test')).toEqualTypeOf<Promise<TestResponse>>()
})
it('works with useAsyncData', () => {
expectTypeOf(useAsyncData('api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useAsyncData('api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useAsyncData('api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useAsyncData('api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useAsyncData<TestResponse>('api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
expectTypeOf(useLazyAsyncData('lazy-api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyAsyncData<TestResponse>('lazy-api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
})
it('works with useFetch', () => {
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
})
})
describe('aliases', () => {
it('allows importing from path aliases', () => {
expectTypeOf(useRouter).toEqualTypeOf<typeof vueUseRouter>()
expectTypeOf(isVue3).toEqualTypeOf<boolean>()
})
})
describe('middleware', () => {
it('recognizes named middleware', () => {
definePageMeta({ middleware: 'inject-auth' })
// @ts-expect-error ignore global middleware
definePageMeta({ middleware: 'redirect' })
// @ts-expect-error Invalid middleware
definePageMeta({ middleware: 'invalid-middleware' })
})
it('handles adding middleware', () => {
addRouteMiddleware('example', (to, from) => {
expectTypeOf(to).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(from).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(navigateTo).toEqualTypeOf<(to: RouteLocationRaw, options?: NavigateToOptions) => RouteLocationRaw | Promise<void | NavigationFailure>>()
navigateTo('/')
abortNavigation()
abortNavigation('error string')
abortNavigation(new Error('my error'))
// @ts-expect-error Must return error or string
abortNavigation(true)
}, { global: true })
})
})
describe('layouts', () => {
it('recognizes named layouts', () => {
definePageMeta({ layout: 'custom' })
definePageMeta({ layout: 'pascal-case' })
// @ts-expect-error Invalid layout
definePageMeta({ layout: 'invalid-layout' })
})
})
describe('modules', () => {
it('augments schema automatically', () => {
defineNuxtConfig({ sampleModule: { enabled: false } })
// @ts-expect-error
defineNuxtConfig({ sampleModule: { other: false } })
// @ts-expect-error
defineNuxtConfig({ undeclaredKey: { other: false } })
})
})
describe('runtimeConfig', () => {
it('generated runtimeConfig types', () => {
const runtimeConfig = useRuntimeConfig()
expectTypeOf(runtimeConfig.testConfig).toEqualTypeOf<number>()
expectTypeOf(runtimeConfig.privateConfig).toEqualTypeOf<string>()
expectTypeOf(runtimeConfig.unknown).toEqualTypeOf<any>()
})
})
describe('head', () => {
it('correctly types nuxt.config options', () => {
// @ts-expect-error
defineNuxtConfig({ app: { head: { titleTemplate: () => 'test' } } })
defineNuxtConfig({
app: {
head: {
meta: [{ key: 'key', name: 'description', content: 'some description ' }],
titleTemplate: 'test %s'
}
}
})
})
it('types useHead', () => {
useHead({
base: { href: '/base' },
link: computed(() => []),
meta: [
{ key: 'key', name: 'description', content: 'some description ' },
() => ({ key: 'key', name: 'description', content: 'some description ' })
],
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - Site Title` : 'Site Title'
}
})
})
})
describe('composables', () => {
it('allows providing default refs', () => {
expectTypeOf(useState('test', () => ref('hello'))).toEqualTypeOf<Ref<string>>()
expectTypeOf(useState('test', () => 'hello')).toEqualTypeOf<Ref<string>>()
expectTypeOf(useCookie('test', { default: () => ref(500) })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useCookie('test', { default: () => 500 })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
})
it('infer request url string literal from server/api routes', () => {
// request can accept dynamic string type
const dynamicStringUrl: string = 'https://example.com/api'
expectTypeOf(useFetch(dynamicStringUrl).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
// request param should infer string literal type / show auto-complete hint base on server routes, ex: '/api/hello'
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
// request can accept string literal and Request object type
expectTypeOf(useFetch('https://example.com/api').data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
expectTypeOf(useFetch(new Request('test')).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
})
it('provides proper type support when using overloads', () => {
expectTypeOf(useState('test')).toEqualTypeOf(useState())
expectTypeOf(useState('test', () => ({ foo: Math.random() }))).toEqualTypeOf(useState(() => ({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
})
})
describe('app config', () => {
it('merges app config as expected', () => {
interface ExpectedMergedAppConfig {
fromLayer: boolean,
fromNuxtConfig: boolean,
nested: {
val: number
},
userConfig: number
}
expectTypeOf<AppConfig>().toMatchTypeOf<ExpectedMergedAppConfig>()
})
})
describe('extends type declarations', () => {
it('correctly adds references to tsconfig', () => {
expectTypeOf<import('bing').BingInterface>().toEqualTypeOf<{ foo: 'bar' }>()
})
})
| test/fixtures/basic/types.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.9962430000305176,
0.13513803482055664,
0.0001657203829381615,
0.00017237861175090075,
0.3396450877189636
] |
{
"id": 6,
"code_window": [
"> (\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useLazyAsyncData<\n",
" DataT,\n",
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 242
} | import { defineUntypedSchema } from 'untyped'
export default defineUntypedSchema({
generate: {
/**
* The routes to generate.
*
* If you are using the crawler, this will be only the starting point for route generation.
* This is often necessary when using dynamic routes.
*
* It can be an array or a function.
*
* @example
* ```js
* routes: ['/users/1', '/users/2', '/users/3']
* ```
*
* You can pass a function that returns a promise or a function that takes a callback. It should
* return an array of strings or objects with `route` and (optional) `payload` keys.
*
* @example
* ```js
* export default {
* generate: {
* async routes() {
* const res = await axios.get('https://my-api/users')
* return res.data.map(user => ({ route: '/users/' + user.id, payload: user }))
* }
* }
* }
* ```
* Or instead:
* ```js
* export default {
* generate: {
* routes(callback) {
* axios
* .get('https://my-api/users')
* .then(res => {
* const routes = res.data.map(user => '/users/' + user.id)
* callback(null, routes)
* })
* .catch(callback)
* }
* }
* }
* ```
*
* If `routes()` returns a payload, it can be accessed from the Nuxt context.
* @example
* ```js
* export default {
* async useAsyncData ({ params, error, payload }) {
* if (payload) return { user: payload }
* else return { user: await backend.fetchUser(params.id) }
* }
* }
* ```
*/
routes: [],
/**
* An array of string or regular expressions that will prevent generation
* of routes matching them. The routes will still be accessible when `fallback` is set.
*/
exclude: []
}
})
| packages/schema/src/config/generate.ts | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.0003672545135486871,
0.000201132454094477,
0.00016459502512589097,
0.00016753033560235053,
0.00006935146666364744
] |
{
"id": 6,
"code_window": [
"> (\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useLazyAsyncData<\n",
" DataT,\n",
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 242
} | {
"name": "@nuxt/vite-builder",
"version": "3.0.0-rc.12",
"repository": "nuxt/framework",
"license": "MIT",
"type": "module",
"types": "./dist/index.d.ts",
"exports": "./dist/index.mjs",
"files": [
"dist"
],
"scripts": {
"prepack": "unbuild"
},
"devDependencies": {
"@nuxt/schema": "3.0.0-rc.12",
"@types/cssnano": "^5",
"unbuild": "latest",
"vue": "3.2.41"
},
"dependencies": {
"@nuxt/kit": "3.0.0-rc.12",
"@rollup/plugin-replace": "^5.0.1",
"@vitejs/plugin-vue": "^3.2.0",
"@vitejs/plugin-vue-jsx": "^2.1.0",
"autoprefixer": "^10.4.13",
"chokidar": "^3.5.3",
"cssnano": "^5.1.14",
"defu": "^6.1.0",
"esbuild": "^0.15.12",
"escape-string-regexp": "^5.0.0",
"estree-walker": "^3.0.1",
"externality": "^0.2.2",
"fs-extra": "^10.1.0",
"get-port-please": "^2.6.1",
"h3": "^0.8.6",
"knitwork": "^0.1.2",
"magic-string": "^0.26.7",
"mlly": "^0.5.16",
"ohash": "^0.1.5",
"pathe": "^0.3.9",
"perfect-debounce": "^0.1.3",
"pkg-types": "^0.3.6",
"postcss": "^8.4.18",
"postcss-import": "^15.0.0",
"postcss-url": "^10.1.3",
"rollup": "^2.79.1",
"rollup-plugin-visualizer": "^5.8.3",
"ufo": "^0.8.6",
"unplugin": "^0.10.2",
"vite": "~3.2.2",
"vite-node": "^0.24.5",
"vite-plugin-checker": "^0.5.1",
"vue-bundle-renderer": "^0.4.4"
},
"peerDependencies": {
"vue": "^3.2.41"
},
"engines": {
"node": "^14.16.0 || ^16.10.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
}
| packages/vite/package.json | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017518342065159231,
0.00017343413492199033,
0.00017123910947702825,
0.000173480439116247,
0.0000012650335747821373
] |
{
"id": 6,
"code_window": [
"> (\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useLazyAsyncData<\n",
" DataT,\n",
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 242
} | {
"name": "nuxt-framework",
"private": true,
"repository": "nuxt/framework",
"license": "MIT",
"type": "module",
"scripts": {
"build": "FORCE_COLOR=1 pnpm --filter './packages/**' prepack",
"build:stub": "pnpm --filter './packages/**' prepack --stub",
"cleanup": "rimraf 'packages/**/node_modules' 'examples/**/node_modules' 'docs/node_modules' 'playground/node_modules' 'node_modules'",
"dev": "pnpm play",
"example": "./scripts/example.sh dev",
"example:build": "./scripts/example.sh build",
"lint": "eslint --ext .vue,.ts,.js,.mjs .",
"lint:docs": "markdownlint ./docs/content && case-police 'docs/content**/*.md'",
"lint:docs:fix": "markdownlint ./docs/content --fix && case-police 'docs/content**/*.md' --fix",
"nuxi": "NUXT_TELEMETRY_DISABLED=1 JITI_ESM_RESOLVE=1 nuxi",
"nuxt": "NUXT_TELEMETRY_DISABLED=1 JITI_ESM_RESOLVE=1 nuxi",
"play": "pnpm nuxi dev playground",
"play:build": "pnpm nuxi build playground",
"play:preview": "pnpm nuxi preview playground",
"test:fixtures": "NUXT_TELEMETRY_DISABLED=1 pnpm nuxi prepare test/fixtures/basic && JITI_ESM_RESOLVE=1 vitest run --dir test",
"test:fixtures:dev": "NUXT_TELEMETRY_DISABLED=1 NUXT_TEST_DEV=true pnpm test:fixtures",
"test:fixtures:webpack": "NUXT_TELEMETRY_DISABLED=1 TEST_WITH_WEBPACK=1 pnpm test:fixtures",
"test:types": "pnpm nuxi prepare test/fixtures/basic && cd test/fixtures/basic && npx vue-tsc --noEmit",
"test:unit": "JITI_ESM_RESOLVE=1 vitest run --dir packages",
"typecheck": "tsc --noEmit"
},
"resolutions": {
"@nuxt/kit": "workspace:*",
"@nuxt/schema": "workspace:*",
"@nuxt/test-utils": "workspace:*",
"@nuxt/vite-builder": "workspace:*",
"@nuxt/webpack-builder": "workspace:*",
"nuxi": "workspace:*",
"nuxt": "workspace:*",
"nuxt3": "workspace:nuxt@*",
"unbuild": "^0.9.4",
"vite": "^3.2.2",
"vue": "3.2.41"
},
"devDependencies": {
"@actions/core": "^1.10.0",
"@nuxt/kit": "workspace:*",
"@nuxt/schema": "workspace:*",
"@nuxt/test-utils": "workspace:*",
"@nuxt/vite-builder": "workspace:*",
"@nuxt/webpack-builder": "workspace:*",
"@nuxtjs/eslint-config-typescript": "^11.0.0",
"@types/crawler": "^1.2.2",
"@types/node": "^18.11.9",
"@types/rimraf": "^3",
"@types/semver": "^7",
"@unocss/reset": "^0.46.2",
"case-police": "^0.5.10",
"changelogen": "^0.3.5",
"crawler": "^1.3.0",
"eslint": "^8.26.0",
"eslint-plugin-jsdoc": "^39.5.0",
"execa": "^6.1.0",
"expect-type": "^0.15.0",
"globby": "^13.1.2",
"jiti": "^1.16.0",
"markdownlint-cli": "^0.32.2",
"nuxi": "workspace:*",
"nuxt": "workspace:*",
"ohmyfetch": "^0.4.20",
"pathe": "^0.3.9",
"rimraf": "^3.0.2",
"semver": "^7.3.8",
"std-env": "^3.3.0",
"typescript": "^4.8.4",
"ufo": "^0.8.6",
"unbuild": "^0.9.4",
"vite": "^3.2.2",
"vitest": "^0.24.5",
"vue-tsc": "^1.0.9"
},
"packageManager": "[email protected]",
"engines": {
"node": "^14.16.0 || ^16.10.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
}
| package.json | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.0001759048318490386,
0.0001735769328661263,
0.00017137009126599878,
0.00017414402100257576,
0.0000014725852679475793
] |
{
"id": 7,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" key: string,\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useLazyAsyncData<\n",
" DataT,\n",
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 252
} | import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from 'vue'
import type { Ref, WatchSource } from 'vue'
import { NuxtApp, useNuxtApp } from '../nuxt'
export type _Transform<Input = any, Output = any> = (input: Input) => Output
export type PickFrom<T, K extends Array<string>> = T extends Array<any>
? T
: T extends Record<string, any>
? keyof T extends K[number]
? T // Exact same keys as the target, skip Pick
: Pick<T, K[number]>
: T
export type KeysOf<T> = Array<keyof T extends string ? keyof T : string>
export type KeyOfRes<Transform extends _Transform> = KeysOf<ReturnType<Transform>>
type MultiWatchSources = (WatchSource<unknown> | object)[]
export interface AsyncDataOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<_Transform> = KeyOfRes<Transform>
> {
server?: boolean
lazy?: boolean
default?: () => DataT | Ref<DataT> | null
transform?: Transform
pick?: PickKeys
watch?: MultiWatchSources
initialCache?: boolean
immediate?: boolean
}
export interface AsyncDataExecuteOptions {
_initial?: boolean
/**
* Force a refresh, even if there is already a pending request. Previous requests will
* not be cancelled, but their result will not affect the data/pending state - and any
* previously awaited promises will not resolve until this new request resolves.
*/
dedupe?: boolean
}
export interface _AsyncData<DataT, ErrorT> {
data: Ref<DataT | null>
pending: Ref<boolean>
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>
error: Ref<ErrorT | null>
}
export type AsyncData<Data, Error> = _AsyncData<Data, Error> & Promise<_AsyncData<Data, Error>>
const getDefault = () => null
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
// eslint-disable-next-line prefer-const
let [key, handler, options = {}] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// Validate arguments
if (typeof key !== 'string') {
throw new TypeError('[nuxt] [asyncData] key must be a string.')
}
if (typeof handler !== 'function') {
throw new TypeError('[nuxt] [asyncData] handler must be a function.')
}
// Apply defaults
options.server = options.server ?? true
options.default = options.default ?? getDefault
// TODO: remove support for `defer` in Nuxt 3 RC
if ((options as any).defer) {
console.warn('[useAsyncData] `defer` has been renamed to `lazy`. Support for `defer` will be removed in RC.')
}
options.lazy = options.lazy ?? (options as any).defer ?? false
options.initialCache = options.initialCache ?? true
options.immediate = options.immediate ?? true
// Setup nuxt instance payload
const nuxt = useNuxtApp()
const useInitialCache = () => (nuxt.isHydrating || options.initialCache) && nuxt.payload.data[key] !== undefined
// Create or use a shared asyncData entity
if (!nuxt._asyncData[key]) {
nuxt._asyncData[key] = {
data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),
pending: ref(!useInitialCache()),
error: ref(nuxt.payload._errors[key] ?? null)
}
}
// TODO: Else, Soemhow check for confliciting keys with different defaults or fetcher
const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>
asyncData.refresh = asyncData.execute = (opts = {}) => {
if (nuxt._asyncDataPromises[key]) {
if (opts.dedupe === false) {
// Avoid fetching same key more than once at a time
return nuxt._asyncDataPromises[key]
}
(nuxt._asyncDataPromises[key] as any).cancelled = true
}
// Avoid fetching same key that is already fetched
if (opts._initial && useInitialCache()) {
return nuxt.payload.data[key]
}
asyncData.pending.value = true
// TODO: Cancel previous promise
const promise = new Promise<DataT>(
(resolve, reject) => {
try {
resolve(handler(nuxt))
} catch (err) {
reject(err)
}
})
.then((result) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
if (options.transform) {
result = options.transform(result)
}
if (options.pick) {
result = pick(result as any, options.pick) as DataT
}
asyncData.data.value = result
asyncData.error.value = null
})
.catch((error: any) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
asyncData.error.value = error
asyncData.data.value = unref(options.default?.() ?? null)
})
.finally(() => {
if ((promise as any).cancelled) { return }
asyncData.pending.value = false
nuxt.payload.data[key] = asyncData.data.value
if (asyncData.error.value) {
nuxt.payload._errors[key] = true
}
delete nuxt._asyncDataPromises[key]
})
nuxt._asyncDataPromises[key] = promise
return nuxt._asyncDataPromises[key]
}
const initialFetch = () => asyncData.refresh({ _initial: true })
const fetchOnServer = options.server !== false && nuxt.payload.serverRendered
// Server side
if (process.server && fetchOnServer && options.immediate) {
const promise = initialFetch()
onServerPrefetch(() => promise)
}
// Client side
if (process.client) {
// Setup hook callbacks once per instance
const instance = getCurrentInstance()
if (instance && !instance._nuxtOnBeforeMountCbs) {
instance._nuxtOnBeforeMountCbs = []
const cbs = instance._nuxtOnBeforeMountCbs
if (instance) {
onBeforeMount(() => {
cbs.forEach((cb) => { cb() })
cbs.splice(0, cbs.length)
})
onUnmounted(() => cbs.splice(0, cbs.length))
}
}
if (fetchOnServer && nuxt.isHydrating && key in nuxt.payload.data) {
// 1. Hydration (server: true): no fetch
asyncData.pending.value = false
} else if (instance && ((nuxt.payload.serverRendered && nuxt.isHydrating) || options.lazy) && options.immediate) {
// 2. Initial load (server: false): fetch on mounted
// 3. Initial load or navigation (lazy: true): fetch on mounted
instance._nuxtOnBeforeMountCbs.push(initialFetch)
} else if (options.immediate) {
// 4. Navigation (lazy: false) - or plugin usage: await fetch
initialFetch()
}
if (options.watch) {
watch(options.watch, () => asyncData.refresh())
}
const off = nuxt.hook('app:data:refresh', (keys) => {
if (!keys || keys.includes(key)) {
return asyncData.refresh()
}
})
if (instance) {
onUnmounted(off)
}
}
// Allow directly awaiting on asyncData
const asyncDataPromise = Promise.resolve(nuxt._asyncDataPromises[key]).then(() => asyncData) as AsyncData<DataT, DataE>
Object.assign(asyncDataPromise, asyncData)
return asyncDataPromise as AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE>
}
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// @ts-ignore
return useAsyncData(key, handler, { ...options, lazy: true }, null)
}
export async function refreshNuxtData (keys?: string | string[]): Promise<void> {
if (process.server) {
return Promise.resolve()
}
const _keys = keys ? Array.isArray(keys) ? keys : [keys] : undefined
await useNuxtApp().hooks.callHookParallel('app:data:refresh', _keys)
}
export function clearNuxtData (keys?: string | string[] | ((key: string) => boolean)): void {
const nuxtApp = useNuxtApp()
const _allKeys = Object.keys(nuxtApp.payload.data)
const _keys: string[] = !keys
? _allKeys
: typeof keys === 'function'
? _allKeys.filter(keys)
: Array.isArray(keys) ? keys : [keys]
for (const key of _keys) {
if (key in nuxtApp.payload.data) {
nuxtApp.payload.data[key] = undefined
}
if (key in nuxtApp.payload._errors) {
nuxtApp.payload._errors[key] = undefined
}
if (nuxtApp._asyncData[key]) {
nuxtApp._asyncData[key]!.data.value = undefined
nuxtApp._asyncData[key]!.error.value = undefined
nuxtApp._asyncData[key]!.pending.value = false
}
if (key in nuxtApp._asyncDataPromises) {
nuxtApp._asyncDataPromises[key] = undefined
}
}
}
function pick (obj: Record<string, any>, keys: string[]) {
const newObj = {}
for (const key of keys) {
(newObj as any)[key] = obj[key]
}
return newObj
}
| packages/nuxt/src/app/composables/asyncData.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.9979559183120728,
0.16406363248825073,
0.00016522291116416454,
0.002117469906806946,
0.36394259333610535
] |
{
"id": 7,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" key: string,\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useLazyAsyncData<\n",
" DataT,\n",
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 252
} | <script setup lang="ts">
// explicit import to bypass client import protection
import BreaksServer from '../components/BreaksServer.client'
onMounted(() => import('~/components/BreaksServer.client'))
onBeforeMount(() => import('~/components/BreaksServer.client'))
onBeforeUpdate(() => import('~/components/BreaksServer.client'))
onRenderTracked(() => import('~/components/BreaksServer.client'))
onRenderTriggered(() => import('~/components/BreaksServer.client'))
onActivated(() => import('~/components/BreaksServer.client'))
onDeactivated(() => import('~/components/BreaksServer.client'))
onBeforeUnmount(() => import('~/components/BreaksServer.client'))
</script>
<template>
<div>
This page should not crash when rendered.
<ClientOnly class="something">
test
<BreaksServer />
<BreaksServer>Some slot content</BreaksServer>
</ClientOnly>
This should render.
<div>
<ClientOnly class="another">
test
<BreaksServer />
</ClientOnly>
</div>
</div>
</template>
| test/fixtures/basic/pages/client.vue | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017663816106505692,
0.00017498547094874084,
0.00017287574883084744,
0.0001752139942254871,
0.0000013972861552247196
] |
{
"id": 7,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" key: string,\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useLazyAsyncData<\n",
" DataT,\n",
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 252
} | export type Props = Readonly<Record<string, any>>
export type FetchPriority = 'high' | 'low' | 'auto'
export type CrossOrigin = '' | 'anonymous' | 'use-credentials'
export type HTTPEquiv =
| 'content-security-policy'
| 'content-type'
| 'default-style'
| 'refresh'
| 'x-ua-compatible'
export type ReferrerPolicy =
| ''
| 'no-referrer'
| 'no-referrer-when-downgrade'
| 'same-origin'
| 'origin'
| 'strict-origin'
| 'origin-when-cross-origin'
| 'strict-origin-when-cross-origin'
| 'unsafe-url'
export type LinkRelationship =
| 'alternate'
| 'author'
| 'canonical'
| 'dns-prefetch'
| 'help'
| 'icon'
| 'license'
| 'manifest'
| 'me'
| 'modulepreload'
| 'next'
| 'pingback'
| 'preconnect'
| 'prefetch'
| 'preload'
| 'prerender'
| 'prev'
| 'search'
| 'stylesheet'
| (string & {})
export type Target = '_blank' | '_self' | '_parent' | '_top' | (string & {})
| packages/nuxt/src/head/runtime/types.ts | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.0001798487064661458,
0.00017312895215582103,
0.0001670766359893605,
0.0001730588119244203,
0.000004097681539860787
] |
{
"id": 7,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" key: string,\n",
" handler: (ctx?: NuxtApp) => Promise<DataT>,\n",
" options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>\n",
"export function useLazyAsyncData<\n",
" DataT,\n",
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 252
} | export default defineNuxtConfig({})
| test/fixtures/minimal/nuxt.config.ts | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00018541800091043115,
0.00018541800091043115,
0.00018541800091043115,
0.00018541800091043115,
0
] |
{
"id": 8,
"code_window": [
"export function useLazyAsyncData<\n",
" DataT,\n",
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {\n",
" const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined\n",
" if (typeof args[0] !== 'string') { args.unshift(autoKey) }\n",
" const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]\n",
" // @ts-ignore\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> {\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 258
} | import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from 'vue'
import type { Ref, WatchSource } from 'vue'
import { NuxtApp, useNuxtApp } from '../nuxt'
export type _Transform<Input = any, Output = any> = (input: Input) => Output
export type PickFrom<T, K extends Array<string>> = T extends Array<any>
? T
: T extends Record<string, any>
? keyof T extends K[number]
? T // Exact same keys as the target, skip Pick
: Pick<T, K[number]>
: T
export type KeysOf<T> = Array<keyof T extends string ? keyof T : string>
export type KeyOfRes<Transform extends _Transform> = KeysOf<ReturnType<Transform>>
type MultiWatchSources = (WatchSource<unknown> | object)[]
export interface AsyncDataOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<_Transform> = KeyOfRes<Transform>
> {
server?: boolean
lazy?: boolean
default?: () => DataT | Ref<DataT> | null
transform?: Transform
pick?: PickKeys
watch?: MultiWatchSources
initialCache?: boolean
immediate?: boolean
}
export interface AsyncDataExecuteOptions {
_initial?: boolean
/**
* Force a refresh, even if there is already a pending request. Previous requests will
* not be cancelled, but their result will not affect the data/pending state - and any
* previously awaited promises will not resolve until this new request resolves.
*/
dedupe?: boolean
}
export interface _AsyncData<DataT, ErrorT> {
data: Ref<DataT | null>
pending: Ref<boolean>
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>
error: Ref<ErrorT | null>
}
export type AsyncData<Data, Error> = _AsyncData<Data, Error> & Promise<_AsyncData<Data, Error>>
const getDefault = () => null
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
// eslint-disable-next-line prefer-const
let [key, handler, options = {}] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// Validate arguments
if (typeof key !== 'string') {
throw new TypeError('[nuxt] [asyncData] key must be a string.')
}
if (typeof handler !== 'function') {
throw new TypeError('[nuxt] [asyncData] handler must be a function.')
}
// Apply defaults
options.server = options.server ?? true
options.default = options.default ?? getDefault
// TODO: remove support for `defer` in Nuxt 3 RC
if ((options as any).defer) {
console.warn('[useAsyncData] `defer` has been renamed to `lazy`. Support for `defer` will be removed in RC.')
}
options.lazy = options.lazy ?? (options as any).defer ?? false
options.initialCache = options.initialCache ?? true
options.immediate = options.immediate ?? true
// Setup nuxt instance payload
const nuxt = useNuxtApp()
const useInitialCache = () => (nuxt.isHydrating || options.initialCache) && nuxt.payload.data[key] !== undefined
// Create or use a shared asyncData entity
if (!nuxt._asyncData[key]) {
nuxt._asyncData[key] = {
data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),
pending: ref(!useInitialCache()),
error: ref(nuxt.payload._errors[key] ?? null)
}
}
// TODO: Else, Soemhow check for confliciting keys with different defaults or fetcher
const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>
asyncData.refresh = asyncData.execute = (opts = {}) => {
if (nuxt._asyncDataPromises[key]) {
if (opts.dedupe === false) {
// Avoid fetching same key more than once at a time
return nuxt._asyncDataPromises[key]
}
(nuxt._asyncDataPromises[key] as any).cancelled = true
}
// Avoid fetching same key that is already fetched
if (opts._initial && useInitialCache()) {
return nuxt.payload.data[key]
}
asyncData.pending.value = true
// TODO: Cancel previous promise
const promise = new Promise<DataT>(
(resolve, reject) => {
try {
resolve(handler(nuxt))
} catch (err) {
reject(err)
}
})
.then((result) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
if (options.transform) {
result = options.transform(result)
}
if (options.pick) {
result = pick(result as any, options.pick) as DataT
}
asyncData.data.value = result
asyncData.error.value = null
})
.catch((error: any) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
asyncData.error.value = error
asyncData.data.value = unref(options.default?.() ?? null)
})
.finally(() => {
if ((promise as any).cancelled) { return }
asyncData.pending.value = false
nuxt.payload.data[key] = asyncData.data.value
if (asyncData.error.value) {
nuxt.payload._errors[key] = true
}
delete nuxt._asyncDataPromises[key]
})
nuxt._asyncDataPromises[key] = promise
return nuxt._asyncDataPromises[key]
}
const initialFetch = () => asyncData.refresh({ _initial: true })
const fetchOnServer = options.server !== false && nuxt.payload.serverRendered
// Server side
if (process.server && fetchOnServer && options.immediate) {
const promise = initialFetch()
onServerPrefetch(() => promise)
}
// Client side
if (process.client) {
// Setup hook callbacks once per instance
const instance = getCurrentInstance()
if (instance && !instance._nuxtOnBeforeMountCbs) {
instance._nuxtOnBeforeMountCbs = []
const cbs = instance._nuxtOnBeforeMountCbs
if (instance) {
onBeforeMount(() => {
cbs.forEach((cb) => { cb() })
cbs.splice(0, cbs.length)
})
onUnmounted(() => cbs.splice(0, cbs.length))
}
}
if (fetchOnServer && nuxt.isHydrating && key in nuxt.payload.data) {
// 1. Hydration (server: true): no fetch
asyncData.pending.value = false
} else if (instance && ((nuxt.payload.serverRendered && nuxt.isHydrating) || options.lazy) && options.immediate) {
// 2. Initial load (server: false): fetch on mounted
// 3. Initial load or navigation (lazy: true): fetch on mounted
instance._nuxtOnBeforeMountCbs.push(initialFetch)
} else if (options.immediate) {
// 4. Navigation (lazy: false) - or plugin usage: await fetch
initialFetch()
}
if (options.watch) {
watch(options.watch, () => asyncData.refresh())
}
const off = nuxt.hook('app:data:refresh', (keys) => {
if (!keys || keys.includes(key)) {
return asyncData.refresh()
}
})
if (instance) {
onUnmounted(off)
}
}
// Allow directly awaiting on asyncData
const asyncDataPromise = Promise.resolve(nuxt._asyncDataPromises[key]).then(() => asyncData) as AsyncData<DataT, DataE>
Object.assign(asyncDataPromise, asyncData)
return asyncDataPromise as AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE>
}
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// @ts-ignore
return useAsyncData(key, handler, { ...options, lazy: true }, null)
}
export async function refreshNuxtData (keys?: string | string[]): Promise<void> {
if (process.server) {
return Promise.resolve()
}
const _keys = keys ? Array.isArray(keys) ? keys : [keys] : undefined
await useNuxtApp().hooks.callHookParallel('app:data:refresh', _keys)
}
export function clearNuxtData (keys?: string | string[] | ((key: string) => boolean)): void {
const nuxtApp = useNuxtApp()
const _allKeys = Object.keys(nuxtApp.payload.data)
const _keys: string[] = !keys
? _allKeys
: typeof keys === 'function'
? _allKeys.filter(keys)
: Array.isArray(keys) ? keys : [keys]
for (const key of _keys) {
if (key in nuxtApp.payload.data) {
nuxtApp.payload.data[key] = undefined
}
if (key in nuxtApp.payload._errors) {
nuxtApp.payload._errors[key] = undefined
}
if (nuxtApp._asyncData[key]) {
nuxtApp._asyncData[key]!.data.value = undefined
nuxtApp._asyncData[key]!.error.value = undefined
nuxtApp._asyncData[key]!.pending.value = false
}
if (key in nuxtApp._asyncDataPromises) {
nuxtApp._asyncDataPromises[key] = undefined
}
}
}
function pick (obj: Record<string, any>, keys: string[]) {
const newObj = {}
for (const key of keys) {
(newObj as any)[key] = obj[key]
}
return newObj
}
| packages/nuxt/src/app/composables/asyncData.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.9981495141983032,
0.4907557964324951,
0.00017115911759901792,
0.49541953206062317,
0.4712858200073242
] |
{
"id": 8,
"code_window": [
"export function useLazyAsyncData<\n",
" DataT,\n",
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {\n",
" const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined\n",
" if (typeof args[0] !== 'string') { args.unshift(autoKey) }\n",
" const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]\n",
" // @ts-ignore\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> {\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 258
} | import { WebpackConfigContext } from '../utils/config'
export function pug (ctx: WebpackConfigContext) {
ctx.config.module!.rules!.push({
test: /\.pug$/i,
oneOf: [
{
resourceQuery: /^\?vue/i,
use: [{
loader: 'pug-plain-loader',
options: ctx.options.webpack.loaders.pugPlain
}]
},
{
use: [
'raw-loader',
{
loader: 'pug-plain-loader',
options: ctx.options.webpack.loaders.pugPlain
}
]
}
]
})
}
| packages/webpack/src/presets/pug.ts | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017436034977436066,
0.00017244741320610046,
0.00017081137048080564,
0.00017217053391505033,
0.0000014620333104176098
] |
{
"id": 8,
"code_window": [
"export function useLazyAsyncData<\n",
" DataT,\n",
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {\n",
" const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined\n",
" if (typeof args[0] !== 'string') { args.unshift(autoKey) }\n",
" const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]\n",
" // @ts-ignore\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> {\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 258
} | <template>
<NuxtExampleLayout example="auto-imports/composables">
<p>Named export <code>useA</code> : {{ a }}</p>
<p>Named export <code>useB</code> : {{ b }}</p>
<p>Named export <code>useC</code> : {{ c }}</p>
<p>Named export <code>useD</code> : {{ d }}</p>
<p>Default export <code>useFoo</code> : {{ foo }}</p>
</NuxtExampleLayout>
</template>
<script setup>
const a = useA()
const b = useB()
const c = useC()
const d = useD()
const foo = useFoo()
</script>
| examples/auto-imports/composables/app.vue | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017264742928091437,
0.00017235046834684908,
0.00017205352196469903,
0.00017235046834684908,
2.9695365810766816e-7
] |
{
"id": 8,
"code_window": [
"export function useLazyAsyncData<\n",
" DataT,\n",
" DataE = Error,\n",
" Transform extends _Transform<DataT> = _Transform<DataT, DataT>,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {\n",
" const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined\n",
" if (typeof args[0] !== 'string') { args.unshift(autoKey) }\n",
" const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]\n",
" // @ts-ignore\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null> {\n"
],
"file_path": "packages/nuxt/src/app/composables/asyncData.ts",
"type": "replace",
"edit_start_line_idx": 258
} | import { defineComponent } from 'vue'
export default defineComponent({
name: 'NuxtPage',
setup (_, props) {
if (process.dev) {
console.warn('Create a Vue component in the `pages/` directory to enable `<NuxtPage>`')
}
return () => props.slots.default?.()
}
})
| packages/nuxt/src/pages/runtime/page-placeholder.ts | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017350359121337533,
0.00017080522957257926,
0.00016810688248369843,
0.00017080522957257926,
0.000002698354364838451
] |
{
"id": 9,
"code_window": [
" Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" request: Ref<ReqT> | ReqT | (() => ReqT),\n",
" opts?: UseFetchOptions<_ResT, Transform, PickKeys>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null | true>\n",
"export function useFetch<\n",
" ResT = void,\n",
" ErrorT = FetchError,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 32
} | import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from 'vue'
import type { Ref, WatchSource } from 'vue'
import { NuxtApp, useNuxtApp } from '../nuxt'
export type _Transform<Input = any, Output = any> = (input: Input) => Output
export type PickFrom<T, K extends Array<string>> = T extends Array<any>
? T
: T extends Record<string, any>
? keyof T extends K[number]
? T // Exact same keys as the target, skip Pick
: Pick<T, K[number]>
: T
export type KeysOf<T> = Array<keyof T extends string ? keyof T : string>
export type KeyOfRes<Transform extends _Transform> = KeysOf<ReturnType<Transform>>
type MultiWatchSources = (WatchSource<unknown> | object)[]
export interface AsyncDataOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<_Transform> = KeyOfRes<Transform>
> {
server?: boolean
lazy?: boolean
default?: () => DataT | Ref<DataT> | null
transform?: Transform
pick?: PickKeys
watch?: MultiWatchSources
initialCache?: boolean
immediate?: boolean
}
export interface AsyncDataExecuteOptions {
_initial?: boolean
/**
* Force a refresh, even if there is already a pending request. Previous requests will
* not be cancelled, but their result will not affect the data/pending state - and any
* previously awaited promises will not resolve until this new request resolves.
*/
dedupe?: boolean
}
export interface _AsyncData<DataT, ErrorT> {
data: Ref<DataT | null>
pending: Ref<boolean>
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>
error: Ref<ErrorT | null>
}
export type AsyncData<Data, Error> = _AsyncData<Data, Error> & Promise<_AsyncData<Data, Error>>
const getDefault = () => null
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
// eslint-disable-next-line prefer-const
let [key, handler, options = {}] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// Validate arguments
if (typeof key !== 'string') {
throw new TypeError('[nuxt] [asyncData] key must be a string.')
}
if (typeof handler !== 'function') {
throw new TypeError('[nuxt] [asyncData] handler must be a function.')
}
// Apply defaults
options.server = options.server ?? true
options.default = options.default ?? getDefault
// TODO: remove support for `defer` in Nuxt 3 RC
if ((options as any).defer) {
console.warn('[useAsyncData] `defer` has been renamed to `lazy`. Support for `defer` will be removed in RC.')
}
options.lazy = options.lazy ?? (options as any).defer ?? false
options.initialCache = options.initialCache ?? true
options.immediate = options.immediate ?? true
// Setup nuxt instance payload
const nuxt = useNuxtApp()
const useInitialCache = () => (nuxt.isHydrating || options.initialCache) && nuxt.payload.data[key] !== undefined
// Create or use a shared asyncData entity
if (!nuxt._asyncData[key]) {
nuxt._asyncData[key] = {
data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),
pending: ref(!useInitialCache()),
error: ref(nuxt.payload._errors[key] ?? null)
}
}
// TODO: Else, Soemhow check for confliciting keys with different defaults or fetcher
const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>
asyncData.refresh = asyncData.execute = (opts = {}) => {
if (nuxt._asyncDataPromises[key]) {
if (opts.dedupe === false) {
// Avoid fetching same key more than once at a time
return nuxt._asyncDataPromises[key]
}
(nuxt._asyncDataPromises[key] as any).cancelled = true
}
// Avoid fetching same key that is already fetched
if (opts._initial && useInitialCache()) {
return nuxt.payload.data[key]
}
asyncData.pending.value = true
// TODO: Cancel previous promise
const promise = new Promise<DataT>(
(resolve, reject) => {
try {
resolve(handler(nuxt))
} catch (err) {
reject(err)
}
})
.then((result) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
if (options.transform) {
result = options.transform(result)
}
if (options.pick) {
result = pick(result as any, options.pick) as DataT
}
asyncData.data.value = result
asyncData.error.value = null
})
.catch((error: any) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
asyncData.error.value = error
asyncData.data.value = unref(options.default?.() ?? null)
})
.finally(() => {
if ((promise as any).cancelled) { return }
asyncData.pending.value = false
nuxt.payload.data[key] = asyncData.data.value
if (asyncData.error.value) {
nuxt.payload._errors[key] = true
}
delete nuxt._asyncDataPromises[key]
})
nuxt._asyncDataPromises[key] = promise
return nuxt._asyncDataPromises[key]
}
const initialFetch = () => asyncData.refresh({ _initial: true })
const fetchOnServer = options.server !== false && nuxt.payload.serverRendered
// Server side
if (process.server && fetchOnServer && options.immediate) {
const promise = initialFetch()
onServerPrefetch(() => promise)
}
// Client side
if (process.client) {
// Setup hook callbacks once per instance
const instance = getCurrentInstance()
if (instance && !instance._nuxtOnBeforeMountCbs) {
instance._nuxtOnBeforeMountCbs = []
const cbs = instance._nuxtOnBeforeMountCbs
if (instance) {
onBeforeMount(() => {
cbs.forEach((cb) => { cb() })
cbs.splice(0, cbs.length)
})
onUnmounted(() => cbs.splice(0, cbs.length))
}
}
if (fetchOnServer && nuxt.isHydrating && key in nuxt.payload.data) {
// 1. Hydration (server: true): no fetch
asyncData.pending.value = false
} else if (instance && ((nuxt.payload.serverRendered && nuxt.isHydrating) || options.lazy) && options.immediate) {
// 2. Initial load (server: false): fetch on mounted
// 3. Initial load or navigation (lazy: true): fetch on mounted
instance._nuxtOnBeforeMountCbs.push(initialFetch)
} else if (options.immediate) {
// 4. Navigation (lazy: false) - or plugin usage: await fetch
initialFetch()
}
if (options.watch) {
watch(options.watch, () => asyncData.refresh())
}
const off = nuxt.hook('app:data:refresh', (keys) => {
if (!keys || keys.includes(key)) {
return asyncData.refresh()
}
})
if (instance) {
onUnmounted(off)
}
}
// Allow directly awaiting on asyncData
const asyncDataPromise = Promise.resolve(nuxt._asyncDataPromises[key]).then(() => asyncData) as AsyncData<DataT, DataE>
Object.assign(asyncDataPromise, asyncData)
return asyncDataPromise as AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE>
}
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// @ts-ignore
return useAsyncData(key, handler, { ...options, lazy: true }, null)
}
export async function refreshNuxtData (keys?: string | string[]): Promise<void> {
if (process.server) {
return Promise.resolve()
}
const _keys = keys ? Array.isArray(keys) ? keys : [keys] : undefined
await useNuxtApp().hooks.callHookParallel('app:data:refresh', _keys)
}
export function clearNuxtData (keys?: string | string[] | ((key: string) => boolean)): void {
const nuxtApp = useNuxtApp()
const _allKeys = Object.keys(nuxtApp.payload.data)
const _keys: string[] = !keys
? _allKeys
: typeof keys === 'function'
? _allKeys.filter(keys)
: Array.isArray(keys) ? keys : [keys]
for (const key of _keys) {
if (key in nuxtApp.payload.data) {
nuxtApp.payload.data[key] = undefined
}
if (key in nuxtApp.payload._errors) {
nuxtApp.payload._errors[key] = undefined
}
if (nuxtApp._asyncData[key]) {
nuxtApp._asyncData[key]!.data.value = undefined
nuxtApp._asyncData[key]!.error.value = undefined
nuxtApp._asyncData[key]!.pending.value = false
}
if (key in nuxtApp._asyncDataPromises) {
nuxtApp._asyncDataPromises[key] = undefined
}
}
}
function pick (obj: Record<string, any>, keys: string[]) {
const newObj = {}
for (const key of keys) {
(newObj as any)[key] = obj[key]
}
return newObj
}
| packages/nuxt/src/app/composables/asyncData.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.8031103610992432,
0.03938419744372368,
0.0001647195458645001,
0.00032284928602166474,
0.1423235833644867
] |
{
"id": 9,
"code_window": [
" Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" request: Ref<ReqT> | ReqT | (() => ReqT),\n",
" opts?: UseFetchOptions<_ResT, Transform, PickKeys>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null | true>\n",
"export function useFetch<\n",
" ResT = void,\n",
" ErrorT = FetchError,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 32
} | {
"name": "example-jsx",
"private": true,
"scripts": {
"build": "nuxi build",
"dev": "nuxi dev",
"start": "nuxi preview"
},
"devDependencies": {
"@nuxt/ui": "^0.3.3",
"nuxt": "^3.0.0-rc.12"
}
}
| examples/advanced/jsx/package.json | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017531594494357705,
0.00017394614405930042,
0.00017257632862310857,
0.00017394614405930042,
0.0000013698081602342427
] |
{
"id": 9,
"code_window": [
" Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" request: Ref<ReqT> | ReqT | (() => ReqT),\n",
" opts?: UseFetchOptions<_ResT, Transform, PickKeys>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null | true>\n",
"export function useFetch<\n",
" ResT = void,\n",
" ErrorT = FetchError,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 32
} | import { Agent as HTTPSAgent } from 'node:https'
import { $fetch } from 'ohmyfetch'
export const viteNodeOptions = JSON.parse(process.env.NUXT_VITE_NODE_OPTIONS || '{}')
export const viteNodeFetch = $fetch.create({
baseURL: viteNodeOptions.baseURL,
agent: viteNodeOptions.baseURL.startsWith('https://')
? new HTTPSAgent({ rejectUnauthorized: false })
: null
})
| packages/vite/src/runtime/vite-node-shared.mjs | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.000176704692421481,
0.00017561559798195958,
0.00017452651809435338,
0.00017561559798195958,
0.0000010890871635638177
] |
{
"id": 9,
"code_window": [
" Transform extends (res: _ResT) => any = (res: _ResT) => _ResT,\n",
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" request: Ref<ReqT> | ReqT | (() => ReqT),\n",
" opts?: UseFetchOptions<_ResT, Transform, PickKeys>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null | true>\n",
"export function useFetch<\n",
" ResT = void,\n",
" ErrorT = FetchError,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 32
} | # Server
In a built Nuxt 3 application, there is no runtime Nuxt dependency. That means your site will be highly performant, and ultra-slim. But it also means you can no longer hook into runtime Nuxt server hooks.
[Read more about the Nitro server engine](/guide/concepts/server-engine).
## Steps
1. Remove the `render` key in your `nuxt.config`.
1. Any files in `~/server/api` and `~/server/middleware` will be automatically registered; you can remove them from your `serverMiddleware` array.
1. Update any other items in your `serverMiddleware` array to point to files or npm packages directly, rather than using inline functions.
1. If you are adding any server hooks, such as `server:` or `vue-renderer:` you will need to remove these and wait for [nitropack](https://github.com/unjs/nitropack) support for runtime hooks and plugins.
| docs/content/7.migration/11.server.md | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00016485185187775642,
0.00016359574510715902,
0.00016233963833656162,
0.00016359574510715902,
0.0000012561067705973983
] |
{
"id": 10,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" request: Ref<ReqT> | ReqT | (() => ReqT),\n",
" opts?: Omit<UseFetchOptions<_ResT, Transform, PickKeys>, 'lazy'>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null | true>\n",
"export function useLazyFetch<\n",
" ResT = void,\n",
" ErrorT = FetchError,\n",
" ReqT extends NitroFetchRequest = NitroFetchRequest,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 116
} | import { expectTypeOf } from 'expect-type'
import { describe, it } from 'vitest'
import type { Ref } from 'vue'
import type { AppConfig } from '@nuxt/schema'
import type { FetchError } from 'ohmyfetch'
import { NavigationFailure, RouteLocationNormalizedLoaded, RouteLocationRaw, useRouter as vueUseRouter } from 'vue-router'
import { defineNuxtConfig } from '~~/../../../packages/nuxt/config'
import type { NavigateToOptions } from '~~/../../../packages/nuxt/dist/app/composables/router'
// eslint-disable-next-line import/order
import { isVue3 } from '#app'
import { useRouter } from '#imports'
interface TestResponse { message: string }
describe('API routes', () => {
it('generates types for routes', () => {
expectTypeOf($fetch('/api/hello')).toEqualTypeOf<Promise<string>>()
expectTypeOf($fetch('/api/hey')).toEqualTypeOf<Promise<{ foo: string, baz: string }>>()
expectTypeOf($fetch('/api/other')).toEqualTypeOf<Promise<unknown>>()
expectTypeOf($fetch<TestResponse>('/test')).toEqualTypeOf<Promise<TestResponse>>()
})
it('works with useAsyncData', () => {
expectTypeOf(useAsyncData('api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useAsyncData('api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useAsyncData('api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useAsyncData('api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useAsyncData<TestResponse>('api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
expectTypeOf(useLazyAsyncData('lazy-api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyAsyncData<TestResponse>('lazy-api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
})
it('works with useFetch', () => {
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
})
})
describe('aliases', () => {
it('allows importing from path aliases', () => {
expectTypeOf(useRouter).toEqualTypeOf<typeof vueUseRouter>()
expectTypeOf(isVue3).toEqualTypeOf<boolean>()
})
})
describe('middleware', () => {
it('recognizes named middleware', () => {
definePageMeta({ middleware: 'inject-auth' })
// @ts-expect-error ignore global middleware
definePageMeta({ middleware: 'redirect' })
// @ts-expect-error Invalid middleware
definePageMeta({ middleware: 'invalid-middleware' })
})
it('handles adding middleware', () => {
addRouteMiddleware('example', (to, from) => {
expectTypeOf(to).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(from).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(navigateTo).toEqualTypeOf<(to: RouteLocationRaw, options?: NavigateToOptions) => RouteLocationRaw | Promise<void | NavigationFailure>>()
navigateTo('/')
abortNavigation()
abortNavigation('error string')
abortNavigation(new Error('my error'))
// @ts-expect-error Must return error or string
abortNavigation(true)
}, { global: true })
})
})
describe('layouts', () => {
it('recognizes named layouts', () => {
definePageMeta({ layout: 'custom' })
definePageMeta({ layout: 'pascal-case' })
// @ts-expect-error Invalid layout
definePageMeta({ layout: 'invalid-layout' })
})
})
describe('modules', () => {
it('augments schema automatically', () => {
defineNuxtConfig({ sampleModule: { enabled: false } })
// @ts-expect-error
defineNuxtConfig({ sampleModule: { other: false } })
// @ts-expect-error
defineNuxtConfig({ undeclaredKey: { other: false } })
})
})
describe('runtimeConfig', () => {
it('generated runtimeConfig types', () => {
const runtimeConfig = useRuntimeConfig()
expectTypeOf(runtimeConfig.testConfig).toEqualTypeOf<number>()
expectTypeOf(runtimeConfig.privateConfig).toEqualTypeOf<string>()
expectTypeOf(runtimeConfig.unknown).toEqualTypeOf<any>()
})
})
describe('head', () => {
it('correctly types nuxt.config options', () => {
// @ts-expect-error
defineNuxtConfig({ app: { head: { titleTemplate: () => 'test' } } })
defineNuxtConfig({
app: {
head: {
meta: [{ key: 'key', name: 'description', content: 'some description ' }],
titleTemplate: 'test %s'
}
}
})
})
it('types useHead', () => {
useHead({
base: { href: '/base' },
link: computed(() => []),
meta: [
{ key: 'key', name: 'description', content: 'some description ' },
() => ({ key: 'key', name: 'description', content: 'some description ' })
],
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - Site Title` : 'Site Title'
}
})
})
})
describe('composables', () => {
it('allows providing default refs', () => {
expectTypeOf(useState('test', () => ref('hello'))).toEqualTypeOf<Ref<string>>()
expectTypeOf(useState('test', () => 'hello')).toEqualTypeOf<Ref<string>>()
expectTypeOf(useCookie('test', { default: () => ref(500) })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useCookie('test', { default: () => 500 })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
})
it('infer request url string literal from server/api routes', () => {
// request can accept dynamic string type
const dynamicStringUrl: string = 'https://example.com/api'
expectTypeOf(useFetch(dynamicStringUrl).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
// request param should infer string literal type / show auto-complete hint base on server routes, ex: '/api/hello'
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
// request can accept string literal and Request object type
expectTypeOf(useFetch('https://example.com/api').data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
expectTypeOf(useFetch(new Request('test')).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
})
it('provides proper type support when using overloads', () => {
expectTypeOf(useState('test')).toEqualTypeOf(useState())
expectTypeOf(useState('test', () => ({ foo: Math.random() }))).toEqualTypeOf(useState(() => ({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
})
})
describe('app config', () => {
it('merges app config as expected', () => {
interface ExpectedMergedAppConfig {
fromLayer: boolean,
fromNuxtConfig: boolean,
nested: {
val: number
},
userConfig: number
}
expectTypeOf<AppConfig>().toMatchTypeOf<ExpectedMergedAppConfig>()
})
})
describe('extends type declarations', () => {
it('correctly adds references to tsconfig', () => {
expectTypeOf<import('bing').BingInterface>().toEqualTypeOf<{ foo: 'bar' }>()
})
})
| test/fixtures/basic/types.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.9985015392303467,
0.17865332961082458,
0.0001647065073484555,
0.00017674086848273873,
0.37825798988342285
] |
{
"id": 10,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" request: Ref<ReqT> | ReqT | (() => ReqT),\n",
" opts?: Omit<UseFetchOptions<_ResT, Transform, PickKeys>, 'lazy'>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null | true>\n",
"export function useLazyFetch<\n",
" ResT = void,\n",
" ErrorT = FetchError,\n",
" ReqT extends NitroFetchRequest = NitroFetchRequest,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 116
} | {
"private": true,
"name": "fixture-bridge",
"scripts": {
"build": "nuxi build"
},
"dependencies": {
"nuxt": "workspace:*"
}
}
| test/fixtures/basic/package.json | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017686010687611997,
0.00017529184697195888,
0.000173723601619713,
0.00017529184697195888,
0.0000015682526282034814
] |
{
"id": 10,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" request: Ref<ReqT> | ReqT | (() => ReqT),\n",
" opts?: Omit<UseFetchOptions<_ResT, Transform, PickKeys>, 'lazy'>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null | true>\n",
"export function useLazyFetch<\n",
" ResT = void,\n",
" ErrorT = FetchError,\n",
" ReqT extends NitroFetchRequest = NitroFetchRequest,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 116
} | import { defineBuildConfig } from 'unbuild'
export default defineBuildConfig({
declaration: true,
entries: [
'src/index'
],
externals: [
'vitest',
'jest',
'playwright',
'playwright-core',
'listhen'
]
})
| packages/test-utils/build.config.ts | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017905476852320135,
0.0001775439886841923,
0.00017603319429326802,
0.0001775439886841923,
0.0000015107871149666607
] |
{
"id": 10,
"code_window": [
" PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>\n",
"> (\n",
" request: Ref<ReqT> | ReqT | (() => ReqT),\n",
" opts?: Omit<UseFetchOptions<_ResT, Transform, PickKeys>, 'lazy'>\n",
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null | true>\n",
"export function useLazyFetch<\n",
" ResT = void,\n",
" ErrorT = FetchError,\n",
" ReqT extends NitroFetchRequest = NitroFetchRequest,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null>\n"
],
"file_path": "packages/nuxt/src/app/composables/fetch.ts",
"type": "replace",
"edit_start_line_idx": 116
} | ---
navigation.icon: IconDirectory
title: server
head.title: Server
description: The server/ directory is used to register API and server handlers to your application.
---
# Server Directory
Nuxt automatically scans files inside the `~/server/api`, `~/server/routes`, and `~/server/middleware` directories to register API and server handlers with HMR support.
Each file should export a default function defined with `defineEventHandler()`.
The handler can directly return JSON data, a `Promise` or use `event.res.end()` to send response.
::ReadMore{link="https://nitro.unjs.io/guide/introduction/routing" title="Nitro Route Handling Docs"}
::
## Example
Create a new file in `server/api/hello.ts`:
```ts [server/api/hello.ts]
export default defineEventHandler((event) => {
return {
api: 'works'
}
})
```
You can now universally call this API using `await $fetch('/api/hello')`.
## Server Routes
Files inside the `~/server/api` are automatically prefixed with `/api` in their route.
For adding server routes without `/api` prefix, you can instead put them into `~/server/routes` directory.
**Example:**
```ts [server/routes/hello.ts]
export default defineEventHandler(() => 'Hello World!')
```
Given the example above, the `/hello` route will be accessible at <http://localhost:3000/hello>.
## Server Middleware
Nuxt will automatically read in any file in the `~/server/middleware` to create server middleware for your project.
Middleware handlers will run on every request before any other server route to add or check headers, log requests, or extend the event's request object.
::alert{type=warning}
Middleware handlers should not return anything (nor close or respond to the request) and only inspect or extend the request context or throw an error.
::
**Examples:**
```ts [server/middleware/log.ts]
export default defineEventHandler((event) => {
console.log('New request: ' + event.req.url)
})
```
```ts [server/middleware/auth.ts]
export default defineEventHandler((event) => {
event.context.auth = { user: 123 }
})
```
## Server Plugins
Nuxt will automatically read any files in the `~/server/plugins` directory and register them as Nitro plugins. This allows extending Nitro's runtime behavior and hooking into lifecycle events.
**Example:**
```ts [server/plugins/nitroPlugin.ts]
export default defineNitroPlugin((nitroApp) => {
console.log('Nitro plugin', nitroApp)
})
```
::ReadMore{link="https://nitro.unjs.io/guide/advanced/plugins" title="Nitro Plugins"}
::
## Server Utilities
Server routes are powered by [unjs/h3](https://github.com/unjs/h3) which comes with a handy set of helpers.
::ReadMore{link="https://www.jsdocs.io/package/h3#package-index-functions" title="Available H3 Request Helpers"}
::
You can add more helpers yourself inside the `~/server/utils` directory.
## Usage Examples
### Matching Route Parameters
Server routes can use dynamic parameters within brackets in the file name like `/api/hello/[name].ts` and be accessed via `event.context.params`.
**Example:**
```ts [server/api/hello/[name].ts]
export default defineEventHandler((event) => `Hello, ${event.context.params.name}!`)
```
You can now universally call this API using `await $fetch('/api/hello/nuxt')` and get `Hello, nuxt!`.
### Matching HTTP Method
Handle file names can be suffixed with `.get`, `.post`, `.put`, `.delete`, ... to match request's [HTTP Method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods).
```ts [server/api/test.get.ts]
export default defineEventHandler(() => 'Test get handler')
```
```ts [server/api/test.post.ts]
export default defineEventHandler(() => 'Test post handler')
```
Given the example above, fetching `/test` with:
- **GET** method: Returns `Test get handler`
- **POST** method: Returns `Test post handler`
- Any other method: Returns 405 error
### Catch-all Route
Catch-all routes are helpful for fallback route handling. For example, creating a file named `~/server/api/foo/[...].ts` will register a catch-all route for all requests that do not match any route handler, such as `/api/foo/bar/baz`.
**Examples:**
```ts [server/api/foo/[...].ts]
export default defineEventHandler(() => `Default foo handler`)
```
```ts [server/api/[...].ts]
export default defineEventHandler(() => `Default api handler`)
```
### Handling Requests with Body
```ts [server/api/submit.post.ts]
export default defineEventHandler(async (event) => {
const body = await readBody(event)
return { body }
})
```
You can now universally call this API using `$fetch('/api/submit', { method: 'post', body: { test: 123 } })`.
::alert{type=warning title=Attention}
We are using `submit.post.ts` in the filename only to match requests with `POST` method that can accept the request body. When using `readBody` within a GET request, `readBody` will throw a `405 Method Not Allowed` HTTP error.
::
### Handling Requests With Query Parameters
Sample query `/api/query?param1=a¶m2=b`
```ts [server/api/query.get.ts]
export default defineEventHandler((event) => {
const query = getQuery(event)
return { a: query.param1, b: query.param2 }
})
```
### Accessing Runtime Config
```ts [server/api/foo.ts]
export default defineEventHandler((event) => {
const config = useRuntimeConfig()
return { key: config.KEY }
})
```
### Accessing Request Cookies
```ts
export default defineEventHandler((event) => {
const cookies = parseCookies(event)
return { cookies }
})
```
## Advanced Usage Examples
### Nitro Configuration
You can use `nitro` key in `nuxt.config` to directly set [Nitro configuration](https://nitro.unjs.io/config).
::alert{type=warning}
This is an advanced option. Custom config can affect production deployments, as the configuration interface might change over time when Nitro is upgraded in semver-minor versions of Nuxt.
::
```ts [nuxt.config.ts]
export default defineNuxtConfig({
// https://nitro.unjs.io/config
nitro: {}
})
```
### Using a Nested Router
```ts [server/api/hello.ts]
import { createRouter } from 'h3'
const router = createRouter()
router.get('/', () => 'Hello World')
export default router
```
### Sending Streams (Experimental)
**Note:** This is an experimental feature and is only available within Node.js environments.
```ts [server/api/foo.get.ts]
import fs from 'node:fs'
import { sendStream } from 'h3'
export default defineEventHandler((event) => {
return sendStream(event, fs.createReadStream('/path/to/file'))
})
```
### Return a Legacy Handler or Middleware
```ts [server/api/legacy.ts]
export default (req, res) => {
res.end('Legacy handler')
}
```
::alert{type=warning}
Legacy support is possible using [unjs/h3](https://github.com/unjs/h3), but it is advised to avoid legacy handlers as much as you can.
::
```ts [server/middleware/legacy.ts]
export default (req, res, next) => {
console.log('Legacy middleware')
next()
}
```
::alert{type=warning}
Never combine `next()` callback with a legacy middleware that is `async` or returns a `Promise`!
::
### Server Storage
Nitro provides a cross-platform [storage layer](https://nitro.unjs.io/guide/introduction/storage). In order to configure additional storage mount points, you can use `nitro.storage`.
#### Example: Using Redis
```ts [nuxt.config.ts]
export default defineNuxtConfig({
nitro: {
storage: {
'redis': {
driver: 'redis',
/* redis connector options */
port: 6379, // Redis port
host: "127.0.0.1", // Redis host
username: "", // needs Redis >= 6
password: "",
db: 0 // Defaults to 0
}
}
}
})
```
Create a new file in `server/api/test.post.ts`:
```ts [server/api/test.post.ts]
export default defineEventHandler(async (event) => {
const body = await readBody(event)
await useStorage().setItem('redis:test', body)
return 'Data is set'
})
```
Create a new file in `server/api/test.get.ts`:
```ts [server/api/test.get.ts]
export default defineEventHandler(async (event) => {
const data = await useStorage().getItem('redis:test')
return data
})
```
Create a new file in `app.vue`:
```vue [app.vue]
<template>
<div>
<div>Post state: {{ resDataSuccess }}</div>
<div>Get Data: {{ resData.text }}</div>
</div>
</template>
<script setup lang="ts">
const { data: resDataSuccess } = await useFetch('/api/test', {
method: 'post',
body: { text: 'Nuxt is Awesome!' }
})
const { data: resData } = await useFetch('/api/test')
</script>
```
::ReadMore{link="/guide/directory-structure/server"}
| docs/content/2.guide/2.directory-structure/1.server.md | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00020326487720012665,
0.00017088602180592716,
0.00016100663924589753,
0.00017161419964395463,
0.000007296965122804977
] |
{
"id": 11,
"code_window": [
" expectTypeOf(useAsyncData('api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useAsyncData<TestResponse>('api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()\n",
" expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()\n",
"\n",
" expectTypeOf(useLazyAsyncData('lazy-api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()\n",
" expectTypeOf(useLazyAsyncData('lazy-api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()\n",
" expectTypeOf(useLazyAsyncData('lazy-api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | null>>()\n",
" expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 30
} | import { expectTypeOf } from 'expect-type'
import { describe, it } from 'vitest'
import type { Ref } from 'vue'
import type { AppConfig } from '@nuxt/schema'
import type { FetchError } from 'ohmyfetch'
import { NavigationFailure, RouteLocationNormalizedLoaded, RouteLocationRaw, useRouter as vueUseRouter } from 'vue-router'
import { defineNuxtConfig } from '~~/../../../packages/nuxt/config'
import type { NavigateToOptions } from '~~/../../../packages/nuxt/dist/app/composables/router'
// eslint-disable-next-line import/order
import { isVue3 } from '#app'
import { useRouter } from '#imports'
interface TestResponse { message: string }
describe('API routes', () => {
it('generates types for routes', () => {
expectTypeOf($fetch('/api/hello')).toEqualTypeOf<Promise<string>>()
expectTypeOf($fetch('/api/hey')).toEqualTypeOf<Promise<{ foo: string, baz: string }>>()
expectTypeOf($fetch('/api/other')).toEqualTypeOf<Promise<unknown>>()
expectTypeOf($fetch<TestResponse>('/test')).toEqualTypeOf<Promise<TestResponse>>()
})
it('works with useAsyncData', () => {
expectTypeOf(useAsyncData('api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useAsyncData('api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useAsyncData('api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useAsyncData('api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useAsyncData<TestResponse>('api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
expectTypeOf(useLazyAsyncData('lazy-api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyAsyncData<TestResponse>('lazy-api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
})
it('works with useFetch', () => {
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
})
})
describe('aliases', () => {
it('allows importing from path aliases', () => {
expectTypeOf(useRouter).toEqualTypeOf<typeof vueUseRouter>()
expectTypeOf(isVue3).toEqualTypeOf<boolean>()
})
})
describe('middleware', () => {
it('recognizes named middleware', () => {
definePageMeta({ middleware: 'inject-auth' })
// @ts-expect-error ignore global middleware
definePageMeta({ middleware: 'redirect' })
// @ts-expect-error Invalid middleware
definePageMeta({ middleware: 'invalid-middleware' })
})
it('handles adding middleware', () => {
addRouteMiddleware('example', (to, from) => {
expectTypeOf(to).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(from).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(navigateTo).toEqualTypeOf<(to: RouteLocationRaw, options?: NavigateToOptions) => RouteLocationRaw | Promise<void | NavigationFailure>>()
navigateTo('/')
abortNavigation()
abortNavigation('error string')
abortNavigation(new Error('my error'))
// @ts-expect-error Must return error or string
abortNavigation(true)
}, { global: true })
})
})
describe('layouts', () => {
it('recognizes named layouts', () => {
definePageMeta({ layout: 'custom' })
definePageMeta({ layout: 'pascal-case' })
// @ts-expect-error Invalid layout
definePageMeta({ layout: 'invalid-layout' })
})
})
describe('modules', () => {
it('augments schema automatically', () => {
defineNuxtConfig({ sampleModule: { enabled: false } })
// @ts-expect-error
defineNuxtConfig({ sampleModule: { other: false } })
// @ts-expect-error
defineNuxtConfig({ undeclaredKey: { other: false } })
})
})
describe('runtimeConfig', () => {
it('generated runtimeConfig types', () => {
const runtimeConfig = useRuntimeConfig()
expectTypeOf(runtimeConfig.testConfig).toEqualTypeOf<number>()
expectTypeOf(runtimeConfig.privateConfig).toEqualTypeOf<string>()
expectTypeOf(runtimeConfig.unknown).toEqualTypeOf<any>()
})
})
describe('head', () => {
it('correctly types nuxt.config options', () => {
// @ts-expect-error
defineNuxtConfig({ app: { head: { titleTemplate: () => 'test' } } })
defineNuxtConfig({
app: {
head: {
meta: [{ key: 'key', name: 'description', content: 'some description ' }],
titleTemplate: 'test %s'
}
}
})
})
it('types useHead', () => {
useHead({
base: { href: '/base' },
link: computed(() => []),
meta: [
{ key: 'key', name: 'description', content: 'some description ' },
() => ({ key: 'key', name: 'description', content: 'some description ' })
],
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - Site Title` : 'Site Title'
}
})
})
})
describe('composables', () => {
it('allows providing default refs', () => {
expectTypeOf(useState('test', () => ref('hello'))).toEqualTypeOf<Ref<string>>()
expectTypeOf(useState('test', () => 'hello')).toEqualTypeOf<Ref<string>>()
expectTypeOf(useCookie('test', { default: () => ref(500) })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useCookie('test', { default: () => 500 })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
})
it('infer request url string literal from server/api routes', () => {
// request can accept dynamic string type
const dynamicStringUrl: string = 'https://example.com/api'
expectTypeOf(useFetch(dynamicStringUrl).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
// request param should infer string literal type / show auto-complete hint base on server routes, ex: '/api/hello'
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
// request can accept string literal and Request object type
expectTypeOf(useFetch('https://example.com/api').data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
expectTypeOf(useFetch(new Request('test')).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
})
it('provides proper type support when using overloads', () => {
expectTypeOf(useState('test')).toEqualTypeOf(useState())
expectTypeOf(useState('test', () => ({ foo: Math.random() }))).toEqualTypeOf(useState(() => ({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
})
})
describe('app config', () => {
it('merges app config as expected', () => {
interface ExpectedMergedAppConfig {
fromLayer: boolean,
fromNuxtConfig: boolean,
nested: {
val: number
},
userConfig: number
}
expectTypeOf<AppConfig>().toMatchTypeOf<ExpectedMergedAppConfig>()
})
})
describe('extends type declarations', () => {
it('correctly adds references to tsconfig', () => {
expectTypeOf<import('bing').BingInterface>().toEqualTypeOf<{ foo: 'bar' }>()
})
})
| test/fixtures/basic/types.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.830406665802002,
0.0892188772559166,
0.00016871145635377616,
0.00018989712407346815,
0.20965851843357086
] |
{
"id": 11,
"code_window": [
" expectTypeOf(useAsyncData('api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useAsyncData<TestResponse>('api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()\n",
" expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()\n",
"\n",
" expectTypeOf(useLazyAsyncData('lazy-api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()\n",
" expectTypeOf(useLazyAsyncData('lazy-api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()\n",
" expectTypeOf(useLazyAsyncData('lazy-api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | null>>()\n",
" expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 30
} | ---
navigation: false
title: "Community"
redirect: /community/getting-help
---
| docs/content/5.community/index.md | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017035122436936945,
0.00017035122436936945,
0.00017035122436936945,
0.00017035122436936945,
0
] |
{
"id": 11,
"code_window": [
" expectTypeOf(useAsyncData('api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useAsyncData<TestResponse>('api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()\n",
" expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()\n",
"\n",
" expectTypeOf(useLazyAsyncData('lazy-api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()\n",
" expectTypeOf(useLazyAsyncData('lazy-api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()\n",
" expectTypeOf(useLazyAsyncData('lazy-api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | null>>()\n",
" expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 30
} | navigation.icon: heroicons-outline:cube
titleTemplate: '%s · Nuxt Components'
| docs/content/3.api/2.components/_dir.yml | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00016958932974375784,
0.00016958932974375784,
0.00016958932974375784,
0.00016958932974375784,
0
] |
{
"id": 11,
"code_window": [
" expectTypeOf(useAsyncData('api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useAsyncData<TestResponse>('api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()\n",
" expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()\n",
"\n",
" expectTypeOf(useLazyAsyncData('lazy-api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()\n",
" expectTypeOf(useLazyAsyncData('lazy-api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()\n",
" expectTypeOf(useLazyAsyncData('lazy-api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | null>>()\n",
" expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 30
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars
export default defineNuxtRouteMiddleware(() => {
setPageLayout('other')
})
| examples/routing/layouts/middleware/other.ts | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00016606664576102048,
0.00016606664576102048,
0.00016606664576102048,
0.00016606664576102048,
0
] |
{
"id": 12,
"code_window": [
" expectTypeOf(useLazyAsyncData('lazy-api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyAsyncData<TestResponse>('lazy-api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()\n",
" expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()\n",
" })\n",
"\n",
" it('works with useFetch', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | null>>()\n",
" expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 39
} | import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from 'vue'
import type { Ref, WatchSource } from 'vue'
import { NuxtApp, useNuxtApp } from '../nuxt'
export type _Transform<Input = any, Output = any> = (input: Input) => Output
export type PickFrom<T, K extends Array<string>> = T extends Array<any>
? T
: T extends Record<string, any>
? keyof T extends K[number]
? T // Exact same keys as the target, skip Pick
: Pick<T, K[number]>
: T
export type KeysOf<T> = Array<keyof T extends string ? keyof T : string>
export type KeyOfRes<Transform extends _Transform> = KeysOf<ReturnType<Transform>>
type MultiWatchSources = (WatchSource<unknown> | object)[]
export interface AsyncDataOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<_Transform> = KeyOfRes<Transform>
> {
server?: boolean
lazy?: boolean
default?: () => DataT | Ref<DataT> | null
transform?: Transform
pick?: PickKeys
watch?: MultiWatchSources
initialCache?: boolean
immediate?: boolean
}
export interface AsyncDataExecuteOptions {
_initial?: boolean
/**
* Force a refresh, even if there is already a pending request. Previous requests will
* not be cancelled, but their result will not affect the data/pending state - and any
* previously awaited promises will not resolve until this new request resolves.
*/
dedupe?: boolean
}
export interface _AsyncData<DataT, ErrorT> {
data: Ref<DataT | null>
pending: Ref<boolean>
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>
error: Ref<ErrorT | null>
}
export type AsyncData<Data, Error> = _AsyncData<Data, Error> & Promise<_AsyncData<Data, Error>>
const getDefault = () => null
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
// eslint-disable-next-line prefer-const
let [key, handler, options = {}] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// Validate arguments
if (typeof key !== 'string') {
throw new TypeError('[nuxt] [asyncData] key must be a string.')
}
if (typeof handler !== 'function') {
throw new TypeError('[nuxt] [asyncData] handler must be a function.')
}
// Apply defaults
options.server = options.server ?? true
options.default = options.default ?? getDefault
// TODO: remove support for `defer` in Nuxt 3 RC
if ((options as any).defer) {
console.warn('[useAsyncData] `defer` has been renamed to `lazy`. Support for `defer` will be removed in RC.')
}
options.lazy = options.lazy ?? (options as any).defer ?? false
options.initialCache = options.initialCache ?? true
options.immediate = options.immediate ?? true
// Setup nuxt instance payload
const nuxt = useNuxtApp()
const useInitialCache = () => (nuxt.isHydrating || options.initialCache) && nuxt.payload.data[key] !== undefined
// Create or use a shared asyncData entity
if (!nuxt._asyncData[key]) {
nuxt._asyncData[key] = {
data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),
pending: ref(!useInitialCache()),
error: ref(nuxt.payload._errors[key] ?? null)
}
}
// TODO: Else, Soemhow check for confliciting keys with different defaults or fetcher
const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>
asyncData.refresh = asyncData.execute = (opts = {}) => {
if (nuxt._asyncDataPromises[key]) {
if (opts.dedupe === false) {
// Avoid fetching same key more than once at a time
return nuxt._asyncDataPromises[key]
}
(nuxt._asyncDataPromises[key] as any).cancelled = true
}
// Avoid fetching same key that is already fetched
if (opts._initial && useInitialCache()) {
return nuxt.payload.data[key]
}
asyncData.pending.value = true
// TODO: Cancel previous promise
const promise = new Promise<DataT>(
(resolve, reject) => {
try {
resolve(handler(nuxt))
} catch (err) {
reject(err)
}
})
.then((result) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
if (options.transform) {
result = options.transform(result)
}
if (options.pick) {
result = pick(result as any, options.pick) as DataT
}
asyncData.data.value = result
asyncData.error.value = null
})
.catch((error: any) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
asyncData.error.value = error
asyncData.data.value = unref(options.default?.() ?? null)
})
.finally(() => {
if ((promise as any).cancelled) { return }
asyncData.pending.value = false
nuxt.payload.data[key] = asyncData.data.value
if (asyncData.error.value) {
nuxt.payload._errors[key] = true
}
delete nuxt._asyncDataPromises[key]
})
nuxt._asyncDataPromises[key] = promise
return nuxt._asyncDataPromises[key]
}
const initialFetch = () => asyncData.refresh({ _initial: true })
const fetchOnServer = options.server !== false && nuxt.payload.serverRendered
// Server side
if (process.server && fetchOnServer && options.immediate) {
const promise = initialFetch()
onServerPrefetch(() => promise)
}
// Client side
if (process.client) {
// Setup hook callbacks once per instance
const instance = getCurrentInstance()
if (instance && !instance._nuxtOnBeforeMountCbs) {
instance._nuxtOnBeforeMountCbs = []
const cbs = instance._nuxtOnBeforeMountCbs
if (instance) {
onBeforeMount(() => {
cbs.forEach((cb) => { cb() })
cbs.splice(0, cbs.length)
})
onUnmounted(() => cbs.splice(0, cbs.length))
}
}
if (fetchOnServer && nuxt.isHydrating && key in nuxt.payload.data) {
// 1. Hydration (server: true): no fetch
asyncData.pending.value = false
} else if (instance && ((nuxt.payload.serverRendered && nuxt.isHydrating) || options.lazy) && options.immediate) {
// 2. Initial load (server: false): fetch on mounted
// 3. Initial load or navigation (lazy: true): fetch on mounted
instance._nuxtOnBeforeMountCbs.push(initialFetch)
} else if (options.immediate) {
// 4. Navigation (lazy: false) - or plugin usage: await fetch
initialFetch()
}
if (options.watch) {
watch(options.watch, () => asyncData.refresh())
}
const off = nuxt.hook('app:data:refresh', (keys) => {
if (!keys || keys.includes(key)) {
return asyncData.refresh()
}
})
if (instance) {
onUnmounted(off)
}
}
// Allow directly awaiting on asyncData
const asyncDataPromise = Promise.resolve(nuxt._asyncDataPromises[key]).then(() => asyncData) as AsyncData<DataT, DataE>
Object.assign(asyncDataPromise, asyncData)
return asyncDataPromise as AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE>
}
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// @ts-ignore
return useAsyncData(key, handler, { ...options, lazy: true }, null)
}
export async function refreshNuxtData (keys?: string | string[]): Promise<void> {
if (process.server) {
return Promise.resolve()
}
const _keys = keys ? Array.isArray(keys) ? keys : [keys] : undefined
await useNuxtApp().hooks.callHookParallel('app:data:refresh', _keys)
}
export function clearNuxtData (keys?: string | string[] | ((key: string) => boolean)): void {
const nuxtApp = useNuxtApp()
const _allKeys = Object.keys(nuxtApp.payload.data)
const _keys: string[] = !keys
? _allKeys
: typeof keys === 'function'
? _allKeys.filter(keys)
: Array.isArray(keys) ? keys : [keys]
for (const key of _keys) {
if (key in nuxtApp.payload.data) {
nuxtApp.payload.data[key] = undefined
}
if (key in nuxtApp.payload._errors) {
nuxtApp.payload._errors[key] = undefined
}
if (nuxtApp._asyncData[key]) {
nuxtApp._asyncData[key]!.data.value = undefined
nuxtApp._asyncData[key]!.error.value = undefined
nuxtApp._asyncData[key]!.pending.value = false
}
if (key in nuxtApp._asyncDataPromises) {
nuxtApp._asyncDataPromises[key] = undefined
}
}
}
function pick (obj: Record<string, any>, keys: string[]) {
const newObj = {}
for (const key of keys) {
(newObj as any)[key] = obj[key]
}
return newObj
}
| packages/nuxt/src/app/composables/asyncData.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.003178051672875881,
0.0004626925801858306,
0.00016359193250536919,
0.0001684592425590381,
0.000653085473459214
] |
{
"id": 12,
"code_window": [
" expectTypeOf(useLazyAsyncData('lazy-api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyAsyncData<TestResponse>('lazy-api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()\n",
" expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()\n",
" })\n",
"\n",
" it('works with useFetch', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | null>>()\n",
" expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 39
} | <template>
<div>
keyed-child-parent
<NuxtPage />
</div>
</template>
| test/fixtures/basic/pages/keyed-child-parent.vue | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.0001745940971886739,
0.0001745940971886739,
0.0001745940971886739,
0.0001745940971886739,
0
] |
{
"id": 12,
"code_window": [
" expectTypeOf(useLazyAsyncData('lazy-api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyAsyncData<TestResponse>('lazy-api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()\n",
" expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()\n",
" })\n",
"\n",
" it('works with useFetch', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | null>>()\n",
" expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 39
} | import { getCurrentInstance, inject } from 'vue'
import type { Router, RouteLocationNormalizedLoaded, NavigationGuard, RouteLocationNormalized, RouteLocationRaw, NavigationFailure, RouteLocationPathRaw } from 'vue-router'
import { sendRedirect } from 'h3'
import { hasProtocol, joinURL, parseURL } from 'ufo'
import { useNuxtApp, useRuntimeConfig } from '../nuxt'
import { createError, NuxtError } from './error'
import { useState } from './state'
export const useRouter = () => {
return useNuxtApp()?.$router as Router
}
export const useRoute = (): RouteLocationNormalizedLoaded => {
if (getCurrentInstance()) {
return inject('_route', useNuxtApp()._route)
}
return useNuxtApp()._route
}
/** @deprecated Use `useRoute` instead. */
export const useActiveRoute = (): RouteLocationNormalizedLoaded => {
return useNuxtApp()._route
}
export interface RouteMiddleware {
(to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard>
}
export const defineNuxtRouteMiddleware = (middleware: RouteMiddleware) => middleware
export interface AddRouteMiddlewareOptions {
global?: boolean
}
interface AddRouteMiddleware {
(name: string, middleware: RouteMiddleware, options?: AddRouteMiddlewareOptions): void
(middleware: RouteMiddleware): void
}
export const addRouteMiddleware: AddRouteMiddleware = (name: string | RouteMiddleware, middleware?: RouteMiddleware, options: AddRouteMiddlewareOptions = {}) => {
const nuxtApp = useNuxtApp()
if (options.global || typeof name === 'function') {
nuxtApp._middleware.global.push(typeof name === 'function' ? name : middleware)
} else {
nuxtApp._middleware.named[name] = middleware
}
}
const isProcessingMiddleware = () => {
try {
if (useNuxtApp()._processingMiddleware) {
return true
}
} catch {
// Within an async middleware
return true
}
return false
}
export interface NavigateToOptions {
replace?: boolean
redirectCode?: number,
external?: boolean
}
export const navigateTo = (to: RouteLocationRaw | undefined | null, options?: NavigateToOptions): Promise<void | NavigationFailure> | RouteLocationRaw => {
if (!to) {
to = '/'
}
const toPath = typeof to === 'string' ? to : ((to as RouteLocationPathRaw).path || '/')
const isExternal = hasProtocol(toPath, true)
if (isExternal && !options?.external) {
throw new Error('Navigating to external URL is not allowed by default. Use `nagivateTo (url, { external: true })`.')
}
if (isExternal && parseURL(toPath).protocol === 'script:') {
throw new Error('Cannot navigate to an URL with script protocol.')
}
// Early redirect on client-side
if (process.client && !isExternal && isProcessingMiddleware()) {
return to
}
const router = useRouter()
if (process.server) {
const nuxtApp = useNuxtApp()
if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) {
const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || '/')
return nuxtApp.callHook('app:redirected').then(() => sendRedirect(nuxtApp.ssrContext!.event, redirectLocation, options?.redirectCode || 302))
}
}
// Client-side redirection using vue-router
if (isExternal) {
if (options?.replace) {
location.replace(toPath)
} else {
location.href = toPath
}
return Promise.resolve()
}
return options?.replace ? router.replace(to) : router.push(to)
}
/** This will abort navigation within a Nuxt route middleware handler. */
export const abortNavigation = (err?: string | Partial<NuxtError>) => {
if (process.dev && !isProcessingMiddleware()) {
throw new Error('abortNavigation() is only usable inside a route middleware handler.')
}
if (err) {
throw createError(err)
}
return false
}
export const setPageLayout = (layout: string) => {
if (process.server) {
if (process.dev && getCurrentInstance() && useState('_layout').value !== layout) {
console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout on the server within a component as this will cause hydration errors.')
}
useState('_layout').value = layout
}
const nuxtApp = useNuxtApp()
if (process.dev && nuxtApp.isHydrating && useState('_layout').value !== layout) {
console.warn('[warn] [nuxt] `setPageLayout` should not be called to change the layout during hydration as this will cause hydration errors.')
}
const inMiddleware = isProcessingMiddleware()
if (inMiddleware || process.server || nuxtApp.isHydrating) {
const unsubscribe = useRouter().beforeResolve((to) => {
to.meta.layout = layout
unsubscribe()
})
}
if (!inMiddleware) {
useRoute().meta.layout = layout
}
}
| packages/nuxt/src/app/composables/router.ts | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017710514657665044,
0.0001720985019346699,
0.00016524213424418122,
0.000172072381246835,
0.000003212682258890709
] |
{
"id": 12,
"code_window": [
" expectTypeOf(useLazyAsyncData('lazy-api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyAsyncData<TestResponse>('lazy-api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()\n",
" expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()\n",
" })\n",
"\n",
" it('works with useFetch', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | null>>()\n",
" expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 39
} | <script setup>
definePageMeta({
layout: 'override',
middleware: 'override'
})
</script>
<template>
<div>
<div>Extended page from bar</div>
<div>Middleware | override: {{ $route.meta.override }}</div>
<ExtendsOverride />
</div>
</template>
| test/fixtures/basic/extends/bar/pages/override.vue | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017214393301401287,
0.00017173716332763433,
0.0001713303936412558,
0.00017173716332763433,
4.067696863785386e-7
] |
{
"id": 13,
"code_window": [
" expectTypeOf(useFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()\n",
" expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()\n",
" expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()\n",
"\n",
" expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()\n",
" expectTypeOf(useLazyFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null>>()\n",
" expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 50
} | import { expectTypeOf } from 'expect-type'
import { describe, it } from 'vitest'
import type { Ref } from 'vue'
import type { AppConfig } from '@nuxt/schema'
import type { FetchError } from 'ohmyfetch'
import { NavigationFailure, RouteLocationNormalizedLoaded, RouteLocationRaw, useRouter as vueUseRouter } from 'vue-router'
import { defineNuxtConfig } from '~~/../../../packages/nuxt/config'
import type { NavigateToOptions } from '~~/../../../packages/nuxt/dist/app/composables/router'
// eslint-disable-next-line import/order
import { isVue3 } from '#app'
import { useRouter } from '#imports'
interface TestResponse { message: string }
describe('API routes', () => {
it('generates types for routes', () => {
expectTypeOf($fetch('/api/hello')).toEqualTypeOf<Promise<string>>()
expectTypeOf($fetch('/api/hey')).toEqualTypeOf<Promise<{ foo: string, baz: string }>>()
expectTypeOf($fetch('/api/other')).toEqualTypeOf<Promise<unknown>>()
expectTypeOf($fetch<TestResponse>('/test')).toEqualTypeOf<Promise<TestResponse>>()
})
it('works with useAsyncData', () => {
expectTypeOf(useAsyncData('api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useAsyncData('api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useAsyncData('api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useAsyncData('api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useAsyncData<TestResponse>('api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useAsyncData('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useAsyncData<any, string>('api-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
expectTypeOf(useLazyAsyncData('lazy-api-hello', () => $fetch('/api/hello')).data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey', () => $fetch('/api/hey')).data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-hey-with-pick', () => $fetch('/api/hey'), { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyAsyncData('lazy-api-other', () => $fetch('/api/other')).data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyAsyncData<TestResponse>('lazy-api-generics', () => $fetch('/test')).data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyAsyncData('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<Error | true | null>>()
expectTypeOf(useLazyAsyncData<any, string>('lazy-error-generics', () => $fetch('/error')).error).toEqualTypeOf<Ref<string | true | null>>()
})
it('works with useFetch', () => {
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()
expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()
expectTypeOf(useLazyFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()
expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()
expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()
})
})
describe('aliases', () => {
it('allows importing from path aliases', () => {
expectTypeOf(useRouter).toEqualTypeOf<typeof vueUseRouter>()
expectTypeOf(isVue3).toEqualTypeOf<boolean>()
})
})
describe('middleware', () => {
it('recognizes named middleware', () => {
definePageMeta({ middleware: 'inject-auth' })
// @ts-expect-error ignore global middleware
definePageMeta({ middleware: 'redirect' })
// @ts-expect-error Invalid middleware
definePageMeta({ middleware: 'invalid-middleware' })
})
it('handles adding middleware', () => {
addRouteMiddleware('example', (to, from) => {
expectTypeOf(to).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(from).toEqualTypeOf<RouteLocationNormalizedLoaded>()
expectTypeOf(navigateTo).toEqualTypeOf<(to: RouteLocationRaw, options?: NavigateToOptions) => RouteLocationRaw | Promise<void | NavigationFailure>>()
navigateTo('/')
abortNavigation()
abortNavigation('error string')
abortNavigation(new Error('my error'))
// @ts-expect-error Must return error or string
abortNavigation(true)
}, { global: true })
})
})
describe('layouts', () => {
it('recognizes named layouts', () => {
definePageMeta({ layout: 'custom' })
definePageMeta({ layout: 'pascal-case' })
// @ts-expect-error Invalid layout
definePageMeta({ layout: 'invalid-layout' })
})
})
describe('modules', () => {
it('augments schema automatically', () => {
defineNuxtConfig({ sampleModule: { enabled: false } })
// @ts-expect-error
defineNuxtConfig({ sampleModule: { other: false } })
// @ts-expect-error
defineNuxtConfig({ undeclaredKey: { other: false } })
})
})
describe('runtimeConfig', () => {
it('generated runtimeConfig types', () => {
const runtimeConfig = useRuntimeConfig()
expectTypeOf(runtimeConfig.testConfig).toEqualTypeOf<number>()
expectTypeOf(runtimeConfig.privateConfig).toEqualTypeOf<string>()
expectTypeOf(runtimeConfig.unknown).toEqualTypeOf<any>()
})
})
describe('head', () => {
it('correctly types nuxt.config options', () => {
// @ts-expect-error
defineNuxtConfig({ app: { head: { titleTemplate: () => 'test' } } })
defineNuxtConfig({
app: {
head: {
meta: [{ key: 'key', name: 'description', content: 'some description ' }],
titleTemplate: 'test %s'
}
}
})
})
it('types useHead', () => {
useHead({
base: { href: '/base' },
link: computed(() => []),
meta: [
{ key: 'key', name: 'description', content: 'some description ' },
() => ({ key: 'key', name: 'description', content: 'some description ' })
],
titleTemplate: (titleChunk) => {
return titleChunk ? `${titleChunk} - Site Title` : 'Site Title'
}
})
})
})
describe('composables', () => {
it('allows providing default refs', () => {
expectTypeOf(useState('test', () => ref('hello'))).toEqualTypeOf<Ref<string>>()
expectTypeOf(useState('test', () => 'hello')).toEqualTypeOf<Ref<string>>()
expectTypeOf(useCookie('test', { default: () => ref(500) })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useCookie('test', { default: () => 500 })).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useAsyncData('test', () => Promise.resolve(500), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
// @ts-expect-error
expectTypeOf(useAsyncData('test', () => Promise.resolve('500'), { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => ref(500) }).data).toEqualTypeOf<Ref<number>>()
expectTypeOf(useFetch('/test', { default: () => 500 }).data).toEqualTypeOf<Ref<number>>()
})
it('infer request url string literal from server/api routes', () => {
// request can accept dynamic string type
const dynamicStringUrl: string = 'https://example.com/api'
expectTypeOf(useFetch(dynamicStringUrl).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
// request param should infer string literal type / show auto-complete hint base on server routes, ex: '/api/hello'
expectTypeOf(useFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()
// request can accept string literal and Request object type
expectTypeOf(useFetch('https://example.com/api').data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
expectTypeOf(useFetch(new Request('test')).data).toEqualTypeOf<Ref<Pick<unknown, never>>>()
})
it('provides proper type support when using overloads', () => {
expectTypeOf(useState('test')).toEqualTypeOf(useState())
expectTypeOf(useState('test', () => ({ foo: Math.random() }))).toEqualTypeOf(useState(() => ({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() })))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() })))
expectTypeOf(useLazyAsyncData('test', () => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
.toEqualTypeOf(useLazyAsyncData(() => Promise.resolve({ foo: Math.random() }), { transform: data => data.foo }))
})
})
describe('app config', () => {
it('merges app config as expected', () => {
interface ExpectedMergedAppConfig {
fromLayer: boolean,
fromNuxtConfig: boolean,
nested: {
val: number
},
userConfig: number
}
expectTypeOf<AppConfig>().toMatchTypeOf<ExpectedMergedAppConfig>()
})
})
describe('extends type declarations', () => {
it('correctly adds references to tsconfig', () => {
expectTypeOf<import('bing').BingInterface>().toEqualTypeOf<{ foo: 'bar' }>()
})
})
| test/fixtures/basic/types.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.9736163020133972,
0.11181151866912842,
0.00016206588770728558,
0.00017860380467027426,
0.26849234104156494
] |
{
"id": 13,
"code_window": [
" expectTypeOf(useFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()\n",
" expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()\n",
" expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()\n",
"\n",
" expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()\n",
" expectTypeOf(useLazyFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null>>()\n",
" expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 50
} | <template>
<div class="p-4">
Custom layout defined with <code>definePageMeta</code>
<br>
<NuxtLink to="/">
Back to home
</NuxtLink>
</div>
</template>
<script>
definePageMeta({
layout: 'custom'
})
</script>
| examples/routing/layouts/pages/custom.vue | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017187249613925815,
0.00017043270054273307,
0.000168992904946208,
0.00017043270054273307,
0.000001439795596525073
] |
{
"id": 13,
"code_window": [
" expectTypeOf(useFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()\n",
" expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()\n",
" expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()\n",
"\n",
" expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()\n",
" expectTypeOf(useLazyFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null>>()\n",
" expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 50
} | import type { AppConfig } from '@nuxt/schema'
import { reactive } from 'vue'
import { useNuxtApp } from './nuxt'
// @ts-ignore
import __appConfig from '#build/app.config.mjs'
type DeepPartial<T> = T extends Function ? T : T extends Record<string, any> ? { [P in keyof T]?: DeepPartial<T[P]> } : T
// Workaround for vite HMR with virtual modules
export const _getAppConfig = () => __appConfig as AppConfig
function deepDelete (obj: any, newObj: any) {
for (const key in obj) {
const val = newObj[key]
if (!(key in newObj)) {
delete (obj as any)[key]
}
if (val !== null && typeof val === 'object') {
deepDelete(obj[key], newObj[key])
}
}
}
function deepAssign (obj: any, newObj: any) {
for (const key in newObj) {
const val = newObj[key]
if (val !== null && typeof val === 'object') {
deepAssign(obj[key], val)
} else {
obj[key] = val
}
}
}
export function useAppConfig (): AppConfig {
const nuxtApp = useNuxtApp()
if (!nuxtApp._appConfig) {
nuxtApp._appConfig = reactive(__appConfig) as AppConfig
}
return nuxtApp._appConfig
}
/**
* Deep assign the current appConfig with the new one.
*
* Will preserve existing properties.
*/
export function updateAppConfig (appConfig: DeepPartial<AppConfig>) {
const _appConfig = useAppConfig()
deepAssign(_appConfig, appConfig)
}
// HMR Support
if (process.dev) {
function applyHMR (newConfig: AppConfig) {
const appConfig = useAppConfig()
if (newConfig && appConfig) {
deepAssign(appConfig, newConfig)
deepDelete(appConfig, newConfig)
}
}
// Vite
if (import.meta.hot) {
import.meta.hot.accept((newModule) => {
const newConfig = newModule._getAppConfig()
applyHMR(newConfig)
})
}
// Webpack
if (import.meta.webpackHot) {
import.meta.webpackHot.accept('#build/app.config.mjs', () => {
applyHMR(__appConfig)
})
}
}
| packages/nuxt/src/app/config.ts | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.0001911396684590727,
0.00017286528600379825,
0.00016668472380843014,
0.00017091783229261637,
0.000007164708677009912
] |
{
"id": 13,
"code_window": [
" expectTypeOf(useFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()\n",
" expectTypeOf(useFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()\n",
" expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()\n",
"\n",
" expectTypeOf(useLazyFetch('/api/hello').data).toEqualTypeOf<Ref<string>>()\n",
" expectTypeOf(useLazyFetch('/api/hey').data).toEqualTypeOf<Ref<{ foo: string, baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useFetch('/error').error).toEqualTypeOf<Ref<FetchError | null>>()\n",
" expectTypeOf(useFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 50
} | ---
description: Nuxt provides utilities to give you control over prefetching and preloading components.
---
# `preloadComponents`
Nuxt provides composables and utilities to give you fine-grained control over prefetching and preloading components.
> Preloading components loads components that your page will need very soon, which you want to start loading early in rendering lifecycle. This ensures they are available earlier and are less likely to block the page's render, improving performance.
Use `preloadComponents` to manually preload individual components that have been registered globally in your Nuxt app. (By default Nuxt registers these as async components.) You must use the Pascal-cased version of the component name.
```js
await preloadComponents('MyGlobalComponent')
await preloadComponents(['MyGlobalComponent1', 'MyGlobalComponent2'])
```
::alert{icon=👉}
Currently, on server, `preloadComponents` will have no effect.
::
| docs/content/3.api/3.utils/preload-components.md | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017265106725972146,
0.0001686613104538992,
0.0001650238991715014,
0.00016830896493047476,
0.000003123729811704834
] |
{
"id": 14,
"code_window": [
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()\n",
" expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()\n",
" })\n",
"})\n",
"\n",
"describe('aliases', () => {\n",
" it('allows importing from path aliases', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null>>()\n",
" expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 60
} | import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from 'vue'
import type { Ref, WatchSource } from 'vue'
import { NuxtApp, useNuxtApp } from '../nuxt'
export type _Transform<Input = any, Output = any> = (input: Input) => Output
export type PickFrom<T, K extends Array<string>> = T extends Array<any>
? T
: T extends Record<string, any>
? keyof T extends K[number]
? T // Exact same keys as the target, skip Pick
: Pick<T, K[number]>
: T
export type KeysOf<T> = Array<keyof T extends string ? keyof T : string>
export type KeyOfRes<Transform extends _Transform> = KeysOf<ReturnType<Transform>>
type MultiWatchSources = (WatchSource<unknown> | object)[]
export interface AsyncDataOptions<
DataT,
Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<_Transform> = KeyOfRes<Transform>
> {
server?: boolean
lazy?: boolean
default?: () => DataT | Ref<DataT> | null
transform?: Transform
pick?: PickKeys
watch?: MultiWatchSources
initialCache?: boolean
immediate?: boolean
}
export interface AsyncDataExecuteOptions {
_initial?: boolean
/**
* Force a refresh, even if there is already a pending request. Previous requests will
* not be cancelled, but their result will not affect the data/pending state - and any
* previously awaited promises will not resolve until this new request resolves.
*/
dedupe?: boolean
}
export interface _AsyncData<DataT, ErrorT> {
data: Ref<DataT | null>
pending: Ref<boolean>
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>
error: Ref<ErrorT | null>
}
export type AsyncData<Data, Error> = _AsyncData<Data, Error> & Promise<_AsyncData<Data, Error>>
const getDefault = () => null
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: AsyncDataOptions<DataT, Transform, PickKeys>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
// eslint-disable-next-line prefer-const
let [key, handler, options = {}] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// Validate arguments
if (typeof key !== 'string') {
throw new TypeError('[nuxt] [asyncData] key must be a string.')
}
if (typeof handler !== 'function') {
throw new TypeError('[nuxt] [asyncData] handler must be a function.')
}
// Apply defaults
options.server = options.server ?? true
options.default = options.default ?? getDefault
// TODO: remove support for `defer` in Nuxt 3 RC
if ((options as any).defer) {
console.warn('[useAsyncData] `defer` has been renamed to `lazy`. Support for `defer` will be removed in RC.')
}
options.lazy = options.lazy ?? (options as any).defer ?? false
options.initialCache = options.initialCache ?? true
options.immediate = options.immediate ?? true
// Setup nuxt instance payload
const nuxt = useNuxtApp()
const useInitialCache = () => (nuxt.isHydrating || options.initialCache) && nuxt.payload.data[key] !== undefined
// Create or use a shared asyncData entity
if (!nuxt._asyncData[key]) {
nuxt._asyncData[key] = {
data: ref(useInitialCache() ? nuxt.payload.data[key] : options.default?.() ?? null),
pending: ref(!useInitialCache()),
error: ref(nuxt.payload._errors[key] ?? null)
}
}
// TODO: Else, Soemhow check for confliciting keys with different defaults or fetcher
const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>
asyncData.refresh = asyncData.execute = (opts = {}) => {
if (nuxt._asyncDataPromises[key]) {
if (opts.dedupe === false) {
// Avoid fetching same key more than once at a time
return nuxt._asyncDataPromises[key]
}
(nuxt._asyncDataPromises[key] as any).cancelled = true
}
// Avoid fetching same key that is already fetched
if (opts._initial && useInitialCache()) {
return nuxt.payload.data[key]
}
asyncData.pending.value = true
// TODO: Cancel previous promise
const promise = new Promise<DataT>(
(resolve, reject) => {
try {
resolve(handler(nuxt))
} catch (err) {
reject(err)
}
})
.then((result) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
if (options.transform) {
result = options.transform(result)
}
if (options.pick) {
result = pick(result as any, options.pick) as DataT
}
asyncData.data.value = result
asyncData.error.value = null
})
.catch((error: any) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
asyncData.error.value = error
asyncData.data.value = unref(options.default?.() ?? null)
})
.finally(() => {
if ((promise as any).cancelled) { return }
asyncData.pending.value = false
nuxt.payload.data[key] = asyncData.data.value
if (asyncData.error.value) {
nuxt.payload._errors[key] = true
}
delete nuxt._asyncDataPromises[key]
})
nuxt._asyncDataPromises[key] = promise
return nuxt._asyncDataPromises[key]
}
const initialFetch = () => asyncData.refresh({ _initial: true })
const fetchOnServer = options.server !== false && nuxt.payload.serverRendered
// Server side
if (process.server && fetchOnServer && options.immediate) {
const promise = initialFetch()
onServerPrefetch(() => promise)
}
// Client side
if (process.client) {
// Setup hook callbacks once per instance
const instance = getCurrentInstance()
if (instance && !instance._nuxtOnBeforeMountCbs) {
instance._nuxtOnBeforeMountCbs = []
const cbs = instance._nuxtOnBeforeMountCbs
if (instance) {
onBeforeMount(() => {
cbs.forEach((cb) => { cb() })
cbs.splice(0, cbs.length)
})
onUnmounted(() => cbs.splice(0, cbs.length))
}
}
if (fetchOnServer && nuxt.isHydrating && key in nuxt.payload.data) {
// 1. Hydration (server: true): no fetch
asyncData.pending.value = false
} else if (instance && ((nuxt.payload.serverRendered && nuxt.isHydrating) || options.lazy) && options.immediate) {
// 2. Initial load (server: false): fetch on mounted
// 3. Initial load or navigation (lazy: true): fetch on mounted
instance._nuxtOnBeforeMountCbs.push(initialFetch)
} else if (options.immediate) {
// 4. Navigation (lazy: false) - or plugin usage: await fetch
initialFetch()
}
if (options.watch) {
watch(options.watch, () => asyncData.refresh())
}
const off = nuxt.hook('app:data:refresh', (keys) => {
if (!keys || keys.includes(key)) {
return asyncData.refresh()
}
})
if (instance) {
onUnmounted(off)
}
}
// Allow directly awaiting on asyncData
const asyncDataPromise = Promise.resolve(nuxt._asyncDataPromises[key]).then(() => asyncData) as AsyncData<DataT, DataE>
Object.assign(asyncDataPromise, asyncData)
return asyncDataPromise as AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE>
}
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>
): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>
export function useLazyAsyncData<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>
> (...args: any[]): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true> {
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
const [key, handler, options] = args as [string, (ctx?: NuxtApp) => Promise<DataT>, AsyncDataOptions<DataT, Transform, PickKeys>]
// @ts-ignore
return useAsyncData(key, handler, { ...options, lazy: true }, null)
}
export async function refreshNuxtData (keys?: string | string[]): Promise<void> {
if (process.server) {
return Promise.resolve()
}
const _keys = keys ? Array.isArray(keys) ? keys : [keys] : undefined
await useNuxtApp().hooks.callHookParallel('app:data:refresh', _keys)
}
export function clearNuxtData (keys?: string | string[] | ((key: string) => boolean)): void {
const nuxtApp = useNuxtApp()
const _allKeys = Object.keys(nuxtApp.payload.data)
const _keys: string[] = !keys
? _allKeys
: typeof keys === 'function'
? _allKeys.filter(keys)
: Array.isArray(keys) ? keys : [keys]
for (const key of _keys) {
if (key in nuxtApp.payload.data) {
nuxtApp.payload.data[key] = undefined
}
if (key in nuxtApp.payload._errors) {
nuxtApp.payload._errors[key] = undefined
}
if (nuxtApp._asyncData[key]) {
nuxtApp._asyncData[key]!.data.value = undefined
nuxtApp._asyncData[key]!.error.value = undefined
nuxtApp._asyncData[key]!.pending.value = false
}
if (key in nuxtApp._asyncDataPromises) {
nuxtApp._asyncDataPromises[key] = undefined
}
}
}
function pick (obj: Record<string, any>, keys: string[]) {
const newObj = {}
for (const key of keys) {
(newObj as any)[key] = obj[key]
}
return newObj
}
| packages/nuxt/src/app/composables/asyncData.ts | 1 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00032231296063400805,
0.0001734026736812666,
0.00016038515605032444,
0.0001696556428214535,
0.000027477004550746642
] |
{
"id": 14,
"code_window": [
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()\n",
" expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()\n",
" })\n",
"})\n",
"\n",
"describe('aliases', () => {\n",
" it('allows importing from path aliases', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null>>()\n",
" expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 60
} | <script lang="tsx" setup>
// Component could be a simple function with JSX syntax
const Welcome = () => <span>Welcome </span>
// Or using defineComponent setup that returns render function with JSX syntax
const Nuxt3 = defineComponent(() => {
return () => <span>nuxt3</span>
})
// We can combine components with JSX syntax too
const InlineComponent = () => (
<div>
<Welcome />
<span>to </span>
<Nuxt3 />
</div>
)
</script>
<template>
<NuxtExampleLayout example="advanced/jsx">
<InlineComponent />
<!-- Defined in components/jsx-component.ts -->
<MyComponent message="This is an external JSX component" />
</NuxtExampleLayout>
</template>
| examples/advanced/jsx/app.vue | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017491052858531475,
0.00017265428323298693,
0.000170665152836591,
0.00017238719738088548,
0.0000017434274468541844
] |
{
"id": 14,
"code_window": [
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()\n",
" expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()\n",
" })\n",
"})\n",
"\n",
"describe('aliases', () => {\n",
" it('allows importing from path aliases', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null>>()\n",
" expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 60
} | {
"extends": "./.nuxt/tsconfig.json"
}
| examples/routing/nuxt-link/tsconfig.json | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017076283984351903,
0.00017076283984351903,
0.00017076283984351903,
0.00017076283984351903,
0
] |
{
"id": 14,
"code_window": [
" expectTypeOf(useLazyFetch('/api/hey', { pick: ['baz'] }).data).toEqualTypeOf<Ref<{ baz: string }>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch('/api/other').data).toEqualTypeOf<Ref<unknown>>()\n",
" expectTypeOf(useLazyFetch<TestResponse>('/test').data).toEqualTypeOf<Ref<TestResponse>>()\n",
"\n",
" expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null | true>>()\n",
" expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null | true>>()\n",
" })\n",
"})\n",
"\n",
"describe('aliases', () => {\n",
" it('allows importing from path aliases', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expectTypeOf(useLazyFetch('/error').error).toEqualTypeOf<Ref<FetchError | null>>()\n",
" expectTypeOf(useLazyFetch<any, string>('/error').error).toEqualTypeOf<Ref<string | null>>()\n"
],
"file_path": "test/fixtures/basic/types.ts",
"type": "replace",
"edit_start_line_idx": 60
} | <template>
<div>
parent/index
</div>
</template>
| test/fixtures/basic/pages/parent/index.vue | 0 | https://github.com/nuxt/nuxt/commit/bdacfa6ffe65d8887e4830fa0d4c8ef2f424698c | [
0.00017234974075108767,
0.00017234974075108767,
0.00017234974075108767,
0.00017234974075108767,
0
] |
{
"id": 0,
"code_window": [
" },\n",
" \"activationEvents\": [\n",
" \"onResolveRemoteAuthority:test\",\n",
" \"onCommand:vscode-testresolver.newWindow\",\n",
" \"onCommand:vscode-testresolver.newWindowWithError\",\n",
" \"onCommand:vscode-testresolver.showLog\",\n",
" \"onCommand:vscode-testresolver.openTunnel\",\n",
" \"onCommand:vscode-testresolver.startRemoteServer\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"onCommand:vscode-testresolver.currentWindow\",\n"
],
"file_path": "extensions/vscode-test-resolver/package.json",
"type": "add",
"edit_start_line_idx": 25
} | {
"name": "vscode-test-resolver",
"description": "Test resolver for VS Code",
"version": "0.0.1",
"publisher": "vscode",
"license": "MIT",
"enableProposedApi": true,
"enabledApiProposals": [
"resolvers"
],
"private": true,
"engines": {
"vscode": "^1.25.0"
},
"icon": "media/icon.png",
"extensionKind": [
"ui"
],
"scripts": {
"compile": "node ./node_modules/vscode/bin/compile -watch -p ./",
"vscode:prepublish": "node ../../node_modules/gulp/bin/gulp.js --gulpfile ../../build/gulpfile.extensions.js compile-extension:vscode-test-resolver"
},
"activationEvents": [
"onResolveRemoteAuthority:test",
"onCommand:vscode-testresolver.newWindow",
"onCommand:vscode-testresolver.newWindowWithError",
"onCommand:vscode-testresolver.showLog",
"onCommand:vscode-testresolver.openTunnel",
"onCommand:vscode-testresolver.startRemoteServer",
"onCommand:vscode-testresolver.toggleConnectionPause"
],
"main": "./out/extension",
"devDependencies": {
"@types/node": "14.x"
},
"capabilities": {
"untrustedWorkspaces": {
"supported": true
},
"virtualWorkspaces": true
},
"contributes": {
"resourceLabelFormatters": [
{
"scheme": "vscode-remote",
"authority": "test+*",
"formatting": {
"label": "${path}",
"separator": "/",
"tildify": true,
"workspaceSuffix": "TestResolver",
"workspaceTooltip": "Remote running on the same machine"
}
}
],
"commands": [
{
"title": "New TestResolver Window",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.newWindow"
},
{
"title": "Show TestResolver Log",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.showLog"
},
{
"title": "Kill Remote Server and Trigger Handled Error",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.killServerAndTriggerHandledError"
},
{
"title": "Open Tunnel...",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.openTunnel"
},
{
"title": "Open a Remote Port...",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.startRemoteServer"
},
{
"title": "Pause Connection (Test Reconnect)",
"category": "Remote-TestResolver",
"command": "vscode-testresolver.toggleConnectionPause"
}
],
"menus": {
"commandPalette": [
{
"command": "vscode-testresolver.openTunnel",
"when": "remoteName == test"
},
{
"command": "vscode-testresolver.startRemoteServer",
"when": "remoteName == test"
},
{
"command": "vscode-testresolver.toggleConnectionPause",
"when": "remoteName == test"
}
],
"statusBar/remoteIndicator": [
{
"command": "vscode-testresolver.newWindow",
"when": "!remoteName && !virtualWorkspace",
"group": "remote_90_test_1_local@2"
},
{
"command": "vscode-testresolver.showLog",
"when": "remoteName == test",
"group": "remote_90_test_1_open@3"
},
{
"command": "vscode-testresolver.newWindow",
"when": "remoteName == test",
"group": "remote_90_test_1_open@1"
},
{
"command": "vscode-testresolver.openTunnel",
"when": "remoteName == test",
"group": "remote_90_test_2_more@4"
},
{
"command": "vscode-testresolver.startRemoteServer",
"when": "remoteName == test",
"group": "remote_90_test_2_more@5"
},
{
"command": "vscode-testresolver.toggleConnectionPause",
"when": "remoteName == test",
"group": "remote_90_test_2_more@6"
}
]
},
"configuration": {
"properties": {
"testresolver.startupDelay": {
"description": "If set, the resolver will delay for the given amount of seconds. Use ths setting for testing a slow resolver",
"type": "number",
"default": 0
},
"testresolver.startupError": {
"description": "If set, the resolver will fail. Use ths setting for testing the failure of a resolver.",
"type": "boolean",
"default": false
},
"testresolver.supportPublicPorts": {
"description": "If set, the test resolver tunnel factory will support mock public ports. Forwarded ports will not actually be public. Requires reload.",
"type": "boolean",
"default": false
}
}
}
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/vscode.git"
}
}
| extensions/vscode-test-resolver/package.json | 1 | https://github.com/microsoft/vscode/commit/ad57fde11d9b5c159918199b54301d57e204a1a7 | [
0.9651408791542053,
0.05711713433265686,
0.00016251915076281875,
0.00021797399676870555,
0.22700604796409607
] |
{
"id": 0,
"code_window": [
" },\n",
" \"activationEvents\": [\n",
" \"onResolveRemoteAuthority:test\",\n",
" \"onCommand:vscode-testresolver.newWindow\",\n",
" \"onCommand:vscode-testresolver.newWindowWithError\",\n",
" \"onCommand:vscode-testresolver.showLog\",\n",
" \"onCommand:vscode-testresolver.openTunnel\",\n",
" \"onCommand:vscode-testresolver.startRemoteServer\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"onCommand:vscode-testresolver.currentWindow\",\n"
],
"file_path": "extensions/vscode-test-resolver/package.json",
"type": "add",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import { ScanCode, ScanCodeUtils } from 'vs/base/common/keyCodes';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IKeyboardEvent } from 'vs/platform/keybinding/common/keybinding';
import { DispatchConfig } from 'vs/platform/keyboardLayout/common/dispatchConfig';
import { IKeyboardMapper } from 'vs/platform/keyboardLayout/common/keyboardMapper';
export const IKeyboardLayoutService = createDecorator<IKeyboardLayoutService>('keyboardLayoutService');
export interface IWindowsKeyMapping {
vkey: string;
value: string;
withShift: string;
withAltGr: string;
withShiftAltGr: string;
}
export interface IWindowsKeyboardMapping {
[code: string]: IWindowsKeyMapping;
}
export interface ILinuxKeyMapping {
value: string;
withShift: string;
withAltGr: string;
withShiftAltGr: string;
}
export interface ILinuxKeyboardMapping {
[code: string]: ILinuxKeyMapping;
}
export interface IMacKeyMapping {
value: string;
valueIsDeadKey: boolean;
withShift: string;
withShiftIsDeadKey: boolean;
withAltGr: string;
withAltGrIsDeadKey: boolean;
withShiftAltGr: string;
withShiftAltGrIsDeadKey: boolean;
}
export interface IMacKeyboardMapping {
[code: string]: IMacKeyMapping;
}
export type IMacLinuxKeyMapping = IMacKeyMapping | ILinuxKeyMapping;
export type IMacLinuxKeyboardMapping = IMacKeyboardMapping | ILinuxKeyboardMapping;
export type IKeyboardMapping = IWindowsKeyboardMapping | ILinuxKeyboardMapping | IMacKeyboardMapping;
/* __GDPR__FRAGMENT__
"IKeyboardLayoutInfo" : {
"name" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"id": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"text": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
export interface IWindowsKeyboardLayoutInfo {
name: string;
id: string;
text: string;
}
/* __GDPR__FRAGMENT__
"IKeyboardLayoutInfo" : {
"model" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"layout": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"variant": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"options": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"rules": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
export interface ILinuxKeyboardLayoutInfo {
model: string;
group: number;
layout: string;
variant: string;
options: string;
rules: string;
}
/* __GDPR__FRAGMENT__
"IKeyboardLayoutInfo" : {
"id" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"lang": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"localizedName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
export interface IMacKeyboardLayoutInfo {
id: string;
lang: string;
localizedName?: string;
}
export type IKeyboardLayoutInfo = (IWindowsKeyboardLayoutInfo | ILinuxKeyboardLayoutInfo | IMacKeyboardLayoutInfo) & { isUserKeyboardLayout?: boolean; isUSStandard?: true };
export interface IKeyboardLayoutService {
readonly _serviceBrand: undefined;
readonly onDidChangeKeyboardLayout: Event<void>;
getRawKeyboardMapping(): IKeyboardMapping | null;
getCurrentKeyboardLayout(): IKeyboardLayoutInfo | null;
getAllKeyboardLayouts(): IKeyboardLayoutInfo[];
getKeyboardMapper(dispatchConfig: DispatchConfig): IKeyboardMapper;
validateCurrentKeyboardMapping(keyboardEvent: IKeyboardEvent): void;
}
export function areKeyboardLayoutsEqual(a: IKeyboardLayoutInfo | null, b: IKeyboardLayoutInfo | null): boolean {
if (!a || !b) {
return false;
}
if ((<IWindowsKeyboardLayoutInfo>a).name && (<IWindowsKeyboardLayoutInfo>b).name && (<IWindowsKeyboardLayoutInfo>a).name === (<IWindowsKeyboardLayoutInfo>b).name) {
return true;
}
if ((<IMacKeyboardLayoutInfo>a).id && (<IMacKeyboardLayoutInfo>b).id && (<IMacKeyboardLayoutInfo>a).id === (<IMacKeyboardLayoutInfo>b).id) {
return true;
}
if ((<ILinuxKeyboardLayoutInfo>a).model &&
(<ILinuxKeyboardLayoutInfo>b).model &&
(<ILinuxKeyboardLayoutInfo>a).model === (<ILinuxKeyboardLayoutInfo>b).model &&
(<ILinuxKeyboardLayoutInfo>a).layout === (<ILinuxKeyboardLayoutInfo>b).layout
) {
return true;
}
return false;
}
export function parseKeyboardLayoutDescription(layout: IKeyboardLayoutInfo | null): { label: string, description: string } {
if (!layout) {
return { label: '', description: '' };
}
if ((<IWindowsKeyboardLayoutInfo>layout).name) {
// windows
let windowsLayout = <IWindowsKeyboardLayoutInfo>layout;
return {
label: windowsLayout.text,
description: ''
};
}
if ((<IMacKeyboardLayoutInfo>layout).id) {
let macLayout = <IMacKeyboardLayoutInfo>layout;
if (macLayout.localizedName) {
return {
label: macLayout.localizedName,
description: ''
};
}
if (/^com\.apple\.keylayout\./.test(macLayout.id)) {
return {
label: macLayout.id.replace(/^com\.apple\.keylayout\./, '').replace(/-/, ' '),
description: ''
};
}
if (/^.*inputmethod\./.test(macLayout.id)) {
return {
label: macLayout.id.replace(/^.*inputmethod\./, '').replace(/[-\.]/, ' '),
description: `Input Method (${macLayout.lang})`
};
}
return {
label: macLayout.lang,
description: ''
};
}
let linuxLayout = <ILinuxKeyboardLayoutInfo>layout;
return {
label: linuxLayout.layout,
description: ''
};
}
export function getKeyboardLayoutId(layout: IKeyboardLayoutInfo): string {
if ((<IWindowsKeyboardLayoutInfo>layout).name) {
return (<IWindowsKeyboardLayoutInfo>layout).name;
}
if ((<IMacKeyboardLayoutInfo>layout).id) {
return (<IMacKeyboardLayoutInfo>layout).id;
}
return (<ILinuxKeyboardLayoutInfo>layout).layout;
}
function windowsKeyMappingEquals(a: IWindowsKeyMapping, b: IWindowsKeyMapping): boolean {
if (!a && !b) {
return true;
}
if (!a || !b) {
return false;
}
return (
a.vkey === b.vkey
&& a.value === b.value
&& a.withShift === b.withShift
&& a.withAltGr === b.withAltGr
&& a.withShiftAltGr === b.withShiftAltGr
);
}
export function windowsKeyboardMappingEquals(a: IWindowsKeyboardMapping | null, b: IWindowsKeyboardMapping | null): boolean {
if (!a && !b) {
return true;
}
if (!a || !b) {
return false;
}
for (let scanCode = 0; scanCode < ScanCode.MAX_VALUE; scanCode++) {
const strScanCode = ScanCodeUtils.toString(scanCode);
const aEntry = a[strScanCode];
const bEntry = b[strScanCode];
if (!windowsKeyMappingEquals(aEntry, bEntry)) {
return false;
}
}
return true;
}
function macLinuxKeyMappingEquals(a: IMacLinuxKeyMapping, b: IMacLinuxKeyMapping): boolean {
if (!a && !b) {
return true;
}
if (!a || !b) {
return false;
}
return (
a.value === b.value
&& a.withShift === b.withShift
&& a.withAltGr === b.withAltGr
&& a.withShiftAltGr === b.withShiftAltGr
);
}
export function macLinuxKeyboardMappingEquals(a: IMacLinuxKeyboardMapping | null, b: IMacLinuxKeyboardMapping | null): boolean {
if (!a && !b) {
return true;
}
if (!a || !b) {
return false;
}
for (let scanCode = 0; scanCode < ScanCode.MAX_VALUE; scanCode++) {
const strScanCode = ScanCodeUtils.toString(scanCode);
const aEntry = a[strScanCode];
const bEntry = b[strScanCode];
if (!macLinuxKeyMappingEquals(aEntry, bEntry)) {
return false;
}
}
return true;
}
| src/vs/platform/keyboardLayout/common/keyboardLayout.ts | 0 | https://github.com/microsoft/vscode/commit/ad57fde11d9b5c159918199b54301d57e204a1a7 | [
0.0002570899960119277,
0.00017284088244196028,
0.0001646024320507422,
0.00016959676577243954,
0.0000166948539117584
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.