DataTable replaces the 20-line Table scaffold entirely: columns, sorting, filtering, pagination, selection, bulk actions, comparison layout, sticky first column, custom HTML cells, and a remote source driven by a `request` output rather than a function prop (props travel as HTML attributes, so a function arrives as its own source text). Toaster replaces the hand-rolled status div: tone icons, actions, hover pause/resume and a progress bar. Overlays audit -- Modal and Drawer declared aria-modal="true" but nothing ever moved focus into the panel, so the @keydown handler on their root never ran and closeOnEscape did nothing. Focus, focus restore, a Tab trap and a body scroll lock now live in the reactive runtime, shared by both. ContextMenu placed pointer menus by subtracting a guessed 340x420 from the viewport, which pushed every menu that was not that size away from the pointer; it now positions at the pointer and lets the anchored clamp pull it back once it can be measured. The reactive runtime size budget moves 150k -> 175k to cover anchored overlays, dialog behaviour, the toaster and the DataTable client half. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
32298 lines
1.2 MiB
Plaintext
32298 lines
1.2 MiB
Plaintext
// WRN editor extension source hash: 174fee91d6ec09c86f71f1204aeb46a20e5a563cc8af1484051d68dde01c8e10
|
|
// WRN editor extension generator hash: 456d1d614e44e5fb1f19b784176c09cf2ade9b64ef73a17934c2698150b62728
|
|
"use strict";
|
|
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/utils/is.js
|
|
var require_is = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.boolean = boolean;
|
|
exports2.string = string;
|
|
exports2.number = number;
|
|
exports2.error = error;
|
|
exports2.func = func;
|
|
exports2.array = array;
|
|
exports2.stringArray = stringArray;
|
|
exports2.typedArray = typedArray;
|
|
exports2.thenable = thenable;
|
|
exports2.asPromise = asPromise;
|
|
function boolean(value) {
|
|
return value === true || value === false;
|
|
}
|
|
function string(value) {
|
|
return typeof value === "string" || value instanceof String;
|
|
}
|
|
function number(value) {
|
|
return typeof value === "number" || value instanceof Number;
|
|
}
|
|
function error(value) {
|
|
return value instanceof Error;
|
|
}
|
|
function func(value) {
|
|
return typeof value === "function";
|
|
}
|
|
function array(value) {
|
|
return Array.isArray(value);
|
|
}
|
|
function stringArray(value) {
|
|
return array(value) && value.every((elem) => string(elem));
|
|
}
|
|
function typedArray(value, check) {
|
|
return Array.isArray(value) && value.every(check);
|
|
}
|
|
function thenable(value) {
|
|
return value && func(value.then);
|
|
}
|
|
function asPromise(value) {
|
|
if (value instanceof Promise) {
|
|
return value;
|
|
} else if (thenable(value)) {
|
|
return new Promise((resolve, reject) => {
|
|
value.then((resolved) => resolve(resolved), (error2) => reject(error2));
|
|
});
|
|
} else {
|
|
return Promise.resolve(value);
|
|
}
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/is.js
|
|
var require_is2 = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.boolean = boolean;
|
|
exports2.string = string;
|
|
exports2.number = number;
|
|
exports2.error = error;
|
|
exports2.func = func;
|
|
exports2.array = array;
|
|
exports2.stringArray = stringArray;
|
|
function boolean(value) {
|
|
return value === true || value === false;
|
|
}
|
|
function string(value) {
|
|
return typeof value === "string" || value instanceof String;
|
|
}
|
|
function number(value) {
|
|
return typeof value === "number" || value instanceof Number;
|
|
}
|
|
function error(value) {
|
|
return value instanceof Error;
|
|
}
|
|
function func(value) {
|
|
return typeof value === "function";
|
|
}
|
|
function array(value) {
|
|
return Array.isArray(value);
|
|
}
|
|
function stringArray(value) {
|
|
return array(value) && value.every((elem) => string(elem));
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/messages.js
|
|
var require_messages = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.Message = exports2.NotificationType9 = exports2.NotificationType8 = exports2.NotificationType7 = exports2.NotificationType6 = exports2.NotificationType5 = exports2.NotificationType4 = exports2.NotificationType3 = exports2.NotificationType2 = exports2.NotificationType1 = exports2.NotificationType0 = exports2.NotificationType = exports2.RequestType9 = exports2.RequestType8 = exports2.RequestType7 = exports2.RequestType6 = exports2.RequestType5 = exports2.RequestType4 = exports2.RequestType3 = exports2.RequestType2 = exports2.RequestType1 = exports2.RequestType = exports2.RequestType0 = exports2.AbstractMessageSignature = exports2.ParameterStructures = exports2.ResponseError = exports2.ErrorCodes = undefined;
|
|
var is = __importStar(require_is2());
|
|
var ErrorCodes;
|
|
(function(ErrorCodes2) {
|
|
ErrorCodes2.ParseError = -32700;
|
|
ErrorCodes2.InvalidRequest = -32600;
|
|
ErrorCodes2.MethodNotFound = -32601;
|
|
ErrorCodes2.InvalidParams = -32602;
|
|
ErrorCodes2.InternalError = -32603;
|
|
ErrorCodes2.jsonrpcReservedErrorRangeStart = -32099;
|
|
ErrorCodes2.serverErrorStart = -32099;
|
|
ErrorCodes2.MessageWriteError = -32099;
|
|
ErrorCodes2.MessageReadError = -32098;
|
|
ErrorCodes2.PendingResponseRejected = -32097;
|
|
ErrorCodes2.ConnectionInactive = -32096;
|
|
ErrorCodes2.ServerNotInitialized = -32002;
|
|
ErrorCodes2.UnknownErrorCode = -32001;
|
|
ErrorCodes2.jsonrpcReservedErrorRangeEnd = -32000;
|
|
ErrorCodes2.serverErrorEnd = -32000;
|
|
})(ErrorCodes || (exports2.ErrorCodes = ErrorCodes = {}));
|
|
|
|
class ResponseError extends Error {
|
|
code;
|
|
data;
|
|
constructor(code, message, data) {
|
|
super(message);
|
|
this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
|
|
this.data = data;
|
|
Object.setPrototypeOf(this, ResponseError.prototype);
|
|
}
|
|
toJson() {
|
|
const result = {
|
|
code: this.code,
|
|
message: this.message
|
|
};
|
|
if (this.data !== undefined) {
|
|
result.data = this.data;
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
exports2.ResponseError = ResponseError;
|
|
|
|
class ParameterStructures {
|
|
kind;
|
|
static auto = new ParameterStructures("auto");
|
|
static byPosition = new ParameterStructures("byPosition");
|
|
static byName = new ParameterStructures("byName");
|
|
constructor(kind) {
|
|
this.kind = kind;
|
|
}
|
|
static is(value) {
|
|
return value === ParameterStructures.auto || value === ParameterStructures.byName || value === ParameterStructures.byPosition;
|
|
}
|
|
toString() {
|
|
return this.kind;
|
|
}
|
|
}
|
|
exports2.ParameterStructures = ParameterStructures;
|
|
|
|
class AbstractMessageSignature {
|
|
method;
|
|
numberOfParams;
|
|
constructor(method, numberOfParams) {
|
|
this.method = method;
|
|
this.numberOfParams = numberOfParams;
|
|
}
|
|
get parameterStructures() {
|
|
return ParameterStructures.auto;
|
|
}
|
|
}
|
|
exports2.AbstractMessageSignature = AbstractMessageSignature;
|
|
|
|
class RequestType0 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 0);
|
|
}
|
|
}
|
|
exports2.RequestType0 = RequestType0;
|
|
|
|
class RequestType extends AbstractMessageSignature {
|
|
_parameterStructures;
|
|
_;
|
|
constructor(method, _parameterStructures = ParameterStructures.auto) {
|
|
super(method, 1);
|
|
this._parameterStructures = _parameterStructures;
|
|
}
|
|
get parameterStructures() {
|
|
return this._parameterStructures;
|
|
}
|
|
}
|
|
exports2.RequestType = RequestType;
|
|
|
|
class RequestType1 extends AbstractMessageSignature {
|
|
_parameterStructures;
|
|
_;
|
|
constructor(method, _parameterStructures = ParameterStructures.auto) {
|
|
super(method, 1);
|
|
this._parameterStructures = _parameterStructures;
|
|
}
|
|
get parameterStructures() {
|
|
return this._parameterStructures;
|
|
}
|
|
}
|
|
exports2.RequestType1 = RequestType1;
|
|
|
|
class RequestType2 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 2);
|
|
}
|
|
}
|
|
exports2.RequestType2 = RequestType2;
|
|
|
|
class RequestType3 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 3);
|
|
}
|
|
}
|
|
exports2.RequestType3 = RequestType3;
|
|
|
|
class RequestType4 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 4);
|
|
}
|
|
}
|
|
exports2.RequestType4 = RequestType4;
|
|
|
|
class RequestType5 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 5);
|
|
}
|
|
}
|
|
exports2.RequestType5 = RequestType5;
|
|
|
|
class RequestType6 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 6);
|
|
}
|
|
}
|
|
exports2.RequestType6 = RequestType6;
|
|
|
|
class RequestType7 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 7);
|
|
}
|
|
}
|
|
exports2.RequestType7 = RequestType7;
|
|
|
|
class RequestType8 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 8);
|
|
}
|
|
}
|
|
exports2.RequestType8 = RequestType8;
|
|
|
|
class RequestType9 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 9);
|
|
}
|
|
}
|
|
exports2.RequestType9 = RequestType9;
|
|
|
|
class NotificationType extends AbstractMessageSignature {
|
|
_parameterStructures;
|
|
_;
|
|
constructor(method, _parameterStructures = ParameterStructures.auto) {
|
|
super(method, 1);
|
|
this._parameterStructures = _parameterStructures;
|
|
}
|
|
get parameterStructures() {
|
|
return this._parameterStructures;
|
|
}
|
|
}
|
|
exports2.NotificationType = NotificationType;
|
|
|
|
class NotificationType0 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 0);
|
|
}
|
|
}
|
|
exports2.NotificationType0 = NotificationType0;
|
|
|
|
class NotificationType1 extends AbstractMessageSignature {
|
|
_parameterStructures;
|
|
_;
|
|
constructor(method, _parameterStructures = ParameterStructures.auto) {
|
|
super(method, 1);
|
|
this._parameterStructures = _parameterStructures;
|
|
}
|
|
get parameterStructures() {
|
|
return this._parameterStructures;
|
|
}
|
|
}
|
|
exports2.NotificationType1 = NotificationType1;
|
|
|
|
class NotificationType2 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 2);
|
|
}
|
|
}
|
|
exports2.NotificationType2 = NotificationType2;
|
|
|
|
class NotificationType3 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 3);
|
|
}
|
|
}
|
|
exports2.NotificationType3 = NotificationType3;
|
|
|
|
class NotificationType4 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 4);
|
|
}
|
|
}
|
|
exports2.NotificationType4 = NotificationType4;
|
|
|
|
class NotificationType5 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 5);
|
|
}
|
|
}
|
|
exports2.NotificationType5 = NotificationType5;
|
|
|
|
class NotificationType6 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 6);
|
|
}
|
|
}
|
|
exports2.NotificationType6 = NotificationType6;
|
|
|
|
class NotificationType7 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 7);
|
|
}
|
|
}
|
|
exports2.NotificationType7 = NotificationType7;
|
|
|
|
class NotificationType8 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 8);
|
|
}
|
|
}
|
|
exports2.NotificationType8 = NotificationType8;
|
|
|
|
class NotificationType9 extends AbstractMessageSignature {
|
|
_;
|
|
constructor(method) {
|
|
super(method, 9);
|
|
}
|
|
}
|
|
exports2.NotificationType9 = NotificationType9;
|
|
var Message;
|
|
(function(Message2) {
|
|
function isRequest(message) {
|
|
const candidate = message;
|
|
return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
|
|
}
|
|
Message2.isRequest = isRequest;
|
|
function isNotification(message) {
|
|
const candidate = message;
|
|
return candidate && is.string(candidate.method) && message.id === undefined;
|
|
}
|
|
Message2.isNotification = isNotification;
|
|
function isResponse(message) {
|
|
const candidate = message;
|
|
return candidate && (candidate.result !== undefined || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
|
|
}
|
|
Message2.isResponse = isResponse;
|
|
})(Message || (exports2.Message = Message = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/linkedMap.js
|
|
var require_linkedMap = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.LRUCache = exports2.LinkedMap = exports2.Touch = undefined;
|
|
var Touch;
|
|
(function(Touch2) {
|
|
Touch2.None = 0;
|
|
Touch2.First = 1;
|
|
Touch2.AsOld = Touch2.First;
|
|
Touch2.Last = 2;
|
|
Touch2.AsNew = Touch2.Last;
|
|
})(Touch || (exports2.Touch = Touch = {}));
|
|
|
|
class LinkedMap {
|
|
[Symbol.toStringTag] = "LinkedMap";
|
|
_map;
|
|
_head;
|
|
_tail;
|
|
_size;
|
|
_state;
|
|
constructor() {
|
|
this._map = new Map;
|
|
this._head = undefined;
|
|
this._tail = undefined;
|
|
this._size = 0;
|
|
this._state = 0;
|
|
}
|
|
clear() {
|
|
this._map.clear();
|
|
this._head = undefined;
|
|
this._tail = undefined;
|
|
this._size = 0;
|
|
this._state++;
|
|
}
|
|
isEmpty() {
|
|
return !this._head && !this._tail;
|
|
}
|
|
get size() {
|
|
return this._size;
|
|
}
|
|
get first() {
|
|
return this._head?.value;
|
|
}
|
|
get last() {
|
|
return this._tail?.value;
|
|
}
|
|
before(key) {
|
|
const item = this._map.get(key);
|
|
return item ? item.previous?.value : undefined;
|
|
}
|
|
after(key) {
|
|
const item = this._map.get(key);
|
|
return item ? item.next?.value : undefined;
|
|
}
|
|
has(key) {
|
|
return this._map.has(key);
|
|
}
|
|
get(key, touch = Touch.None) {
|
|
const item = this._map.get(key);
|
|
if (!item) {
|
|
return;
|
|
}
|
|
if (touch !== Touch.None) {
|
|
this.touch(item, touch);
|
|
}
|
|
return item.value;
|
|
}
|
|
set(key, value, touch = Touch.None) {
|
|
let item = this._map.get(key);
|
|
if (item) {
|
|
item.value = value;
|
|
if (touch !== Touch.None) {
|
|
this.touch(item, touch);
|
|
}
|
|
} else {
|
|
item = { key, value, next: undefined, previous: undefined };
|
|
switch (touch) {
|
|
case Touch.None:
|
|
this.addItemLast(item);
|
|
break;
|
|
case Touch.First:
|
|
this.addItemFirst(item);
|
|
break;
|
|
case Touch.Last:
|
|
this.addItemLast(item);
|
|
break;
|
|
default:
|
|
this.addItemLast(item);
|
|
break;
|
|
}
|
|
this._map.set(key, item);
|
|
this._size++;
|
|
}
|
|
return this;
|
|
}
|
|
delete(key) {
|
|
return !!this.remove(key);
|
|
}
|
|
remove(key) {
|
|
const item = this._map.get(key);
|
|
if (!item) {
|
|
return;
|
|
}
|
|
this._map.delete(key);
|
|
this.removeItem(item);
|
|
this._size--;
|
|
return item.value;
|
|
}
|
|
shift() {
|
|
if (!this._head && !this._tail) {
|
|
return;
|
|
}
|
|
if (!this._head || !this._tail) {
|
|
throw new Error("Invalid list");
|
|
}
|
|
const item = this._head;
|
|
this._map.delete(item.key);
|
|
this.removeItem(item);
|
|
this._size--;
|
|
return item.value;
|
|
}
|
|
forEach(callbackfn, thisArg) {
|
|
const state = this._state;
|
|
let current = this._head;
|
|
while (current) {
|
|
if (thisArg) {
|
|
callbackfn.bind(thisArg)(current.value, current.key, this);
|
|
} else {
|
|
callbackfn(current.value, current.key, this);
|
|
}
|
|
if (this._state !== state) {
|
|
throw new Error(`LinkedMap got modified during iteration.`);
|
|
}
|
|
current = current.next;
|
|
}
|
|
}
|
|
keys() {
|
|
const state = this._state;
|
|
let current = this._head;
|
|
const iterator = {
|
|
[Symbol.iterator]: () => {
|
|
return iterator;
|
|
},
|
|
next: () => {
|
|
if (this._state !== state) {
|
|
throw new Error(`LinkedMap got modified during iteration.`);
|
|
}
|
|
if (current) {
|
|
const result = { value: current.key, done: false };
|
|
current = current.next;
|
|
return result;
|
|
} else {
|
|
return { value: undefined, done: true };
|
|
}
|
|
}
|
|
};
|
|
return iterator;
|
|
}
|
|
values() {
|
|
const state = this._state;
|
|
let current = this._head;
|
|
const iterator = {
|
|
[Symbol.iterator]: () => {
|
|
return iterator;
|
|
},
|
|
next: () => {
|
|
if (this._state !== state) {
|
|
throw new Error(`LinkedMap got modified during iteration.`);
|
|
}
|
|
if (current) {
|
|
const result = { value: current.value, done: false };
|
|
current = current.next;
|
|
return result;
|
|
} else {
|
|
return { value: undefined, done: true };
|
|
}
|
|
}
|
|
};
|
|
return iterator;
|
|
}
|
|
entries() {
|
|
const state = this._state;
|
|
let current = this._head;
|
|
const iterator = {
|
|
[Symbol.iterator]: () => {
|
|
return iterator;
|
|
},
|
|
next: () => {
|
|
if (this._state !== state) {
|
|
throw new Error(`LinkedMap got modified during iteration.`);
|
|
}
|
|
if (current) {
|
|
const result = { value: [current.key, current.value], done: false };
|
|
current = current.next;
|
|
return result;
|
|
} else {
|
|
return { value: undefined, done: true };
|
|
}
|
|
}
|
|
};
|
|
return iterator;
|
|
}
|
|
[Symbol.iterator]() {
|
|
return this.entries();
|
|
}
|
|
trimOld(newSize) {
|
|
if (newSize >= this.size) {
|
|
return;
|
|
}
|
|
if (newSize === 0) {
|
|
this.clear();
|
|
return;
|
|
}
|
|
let current = this._head;
|
|
let currentSize = this.size;
|
|
while (current && currentSize > newSize) {
|
|
this._map.delete(current.key);
|
|
current = current.next;
|
|
currentSize--;
|
|
}
|
|
this._head = current;
|
|
this._size = currentSize;
|
|
if (current) {
|
|
current.previous = undefined;
|
|
}
|
|
this._state++;
|
|
}
|
|
addItemFirst(item) {
|
|
if (!this._head && !this._tail) {
|
|
this._tail = item;
|
|
} else if (!this._head) {
|
|
throw new Error("Invalid list");
|
|
} else {
|
|
item.next = this._head;
|
|
this._head.previous = item;
|
|
}
|
|
this._head = item;
|
|
this._state++;
|
|
}
|
|
addItemLast(item) {
|
|
if (!this._head && !this._tail) {
|
|
this._head = item;
|
|
} else if (!this._tail) {
|
|
throw new Error("Invalid list");
|
|
} else {
|
|
item.previous = this._tail;
|
|
this._tail.next = item;
|
|
}
|
|
this._tail = item;
|
|
this._state++;
|
|
}
|
|
removeItem(item) {
|
|
if (item === this._head && item === this._tail) {
|
|
this._head = undefined;
|
|
this._tail = undefined;
|
|
} else if (item === this._head) {
|
|
if (!item.next) {
|
|
throw new Error("Invalid list");
|
|
}
|
|
item.next.previous = undefined;
|
|
this._head = item.next;
|
|
} else if (item === this._tail) {
|
|
if (!item.previous) {
|
|
throw new Error("Invalid list");
|
|
}
|
|
item.previous.next = undefined;
|
|
this._tail = item.previous;
|
|
} else {
|
|
const next = item.next;
|
|
const previous = item.previous;
|
|
if (!next || !previous) {
|
|
throw new Error("Invalid list");
|
|
}
|
|
next.previous = previous;
|
|
previous.next = next;
|
|
}
|
|
item.next = undefined;
|
|
item.previous = undefined;
|
|
this._state++;
|
|
}
|
|
touch(item, touch) {
|
|
if (!this._head || !this._tail) {
|
|
throw new Error("Invalid list");
|
|
}
|
|
if (touch !== Touch.First && touch !== Touch.Last) {
|
|
return;
|
|
}
|
|
if (touch === Touch.First) {
|
|
if (item === this._head) {
|
|
return;
|
|
}
|
|
const next = item.next;
|
|
const previous = item.previous;
|
|
if (item === this._tail) {
|
|
previous.next = undefined;
|
|
this._tail = previous;
|
|
} else {
|
|
next.previous = previous;
|
|
previous.next = next;
|
|
}
|
|
item.previous = undefined;
|
|
item.next = this._head;
|
|
this._head.previous = item;
|
|
this._head = item;
|
|
this._state++;
|
|
} else if (touch === Touch.Last) {
|
|
if (item === this._tail) {
|
|
return;
|
|
}
|
|
const next = item.next;
|
|
const previous = item.previous;
|
|
if (item === this._head) {
|
|
next.previous = undefined;
|
|
this._head = next;
|
|
} else {
|
|
next.previous = previous;
|
|
previous.next = next;
|
|
}
|
|
item.next = undefined;
|
|
item.previous = this._tail;
|
|
this._tail.next = item;
|
|
this._tail = item;
|
|
this._state++;
|
|
}
|
|
}
|
|
toJSON() {
|
|
const data = [];
|
|
this.forEach((value, key) => {
|
|
data.push([key, value]);
|
|
});
|
|
return data;
|
|
}
|
|
fromJSON(data) {
|
|
this.clear();
|
|
for (const [key, value] of data) {
|
|
this.set(key, value);
|
|
}
|
|
}
|
|
}
|
|
exports2.LinkedMap = LinkedMap;
|
|
|
|
class LRUCache extends LinkedMap {
|
|
_limit;
|
|
_ratio;
|
|
constructor(limit, ratio = 1) {
|
|
super();
|
|
this._limit = limit;
|
|
this._ratio = Math.min(Math.max(0, ratio), 1);
|
|
}
|
|
get limit() {
|
|
return this._limit;
|
|
}
|
|
set limit(limit) {
|
|
this._limit = limit;
|
|
this.checkTrim();
|
|
}
|
|
get ratio() {
|
|
return this._ratio;
|
|
}
|
|
set ratio(ratio) {
|
|
this._ratio = Math.min(Math.max(0, ratio), 1);
|
|
this.checkTrim();
|
|
}
|
|
get(key, touch = Touch.AsNew) {
|
|
return super.get(key, touch);
|
|
}
|
|
peek(key) {
|
|
return super.get(key, Touch.None);
|
|
}
|
|
set(key, value) {
|
|
super.set(key, value, Touch.Last);
|
|
this.checkTrim();
|
|
return this;
|
|
}
|
|
checkTrim() {
|
|
if (this.size > this._limit) {
|
|
this.trimOld(Math.round(this._limit * this._ratio));
|
|
}
|
|
}
|
|
}
|
|
exports2.LRUCache = LRUCache;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/disposable.js
|
|
var require_disposable = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.Disposable = undefined;
|
|
var Disposable;
|
|
(function(Disposable2) {
|
|
function create(func) {
|
|
return {
|
|
dispose: func
|
|
};
|
|
}
|
|
Disposable2.create = create;
|
|
})(Disposable || (exports2.Disposable = Disposable = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/ral.js
|
|
var require_ral = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
var _ral;
|
|
function RAL() {
|
|
if (_ral === undefined) {
|
|
throw new Error(`No runtime abstraction layer installed`);
|
|
}
|
|
return _ral;
|
|
}
|
|
(function(RAL2) {
|
|
function install(ral) {
|
|
if (ral === undefined) {
|
|
throw new Error(`No runtime abstraction layer provided`);
|
|
}
|
|
_ral = ral;
|
|
}
|
|
RAL2.install = install;
|
|
})(RAL || (RAL = {}));
|
|
exports2.default = RAL;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/events.js
|
|
var require_events = __commonJS((exports2) => {
|
|
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
|
|
return mod && mod.__esModule ? mod : { default: mod };
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.Emitter = exports2.Event = undefined;
|
|
var ral_1 = __importDefault(require_ral());
|
|
var Event;
|
|
(function(Event2) {
|
|
const _disposable = { dispose() {} };
|
|
Event2.None = function() {
|
|
return _disposable;
|
|
};
|
|
})(Event || (exports2.Event = Event = {}));
|
|
|
|
class CallbackList {
|
|
_callbacks;
|
|
_contexts;
|
|
add(callback, context = null, bucket) {
|
|
if (!this._callbacks) {
|
|
this._callbacks = [];
|
|
this._contexts = [];
|
|
}
|
|
this._callbacks.push(callback);
|
|
this._contexts.push(context);
|
|
if (Array.isArray(bucket)) {
|
|
bucket.push({ dispose: () => this.remove(callback, context) });
|
|
}
|
|
}
|
|
remove(callback, context = null) {
|
|
if (!this._callbacks) {
|
|
return;
|
|
}
|
|
let foundCallbackWithDifferentContext = false;
|
|
for (let i = 0, len = this._callbacks.length;i < len; i++) {
|
|
if (this._callbacks[i] === callback) {
|
|
if (this._contexts[i] === context) {
|
|
this._callbacks.splice(i, 1);
|
|
this._contexts.splice(i, 1);
|
|
return;
|
|
} else {
|
|
foundCallbackWithDifferentContext = true;
|
|
}
|
|
}
|
|
}
|
|
if (foundCallbackWithDifferentContext) {
|
|
throw new Error("When adding a listener with a context, you should remove it with the same context");
|
|
}
|
|
}
|
|
invoke(...args) {
|
|
if (!this._callbacks) {
|
|
return [];
|
|
}
|
|
const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
|
|
for (let i = 0, len = callbacks.length;i < len; i++) {
|
|
try {
|
|
ret.push(callbacks[i].apply(contexts[i], args));
|
|
} catch (e) {
|
|
(0, ral_1.default)().console.error(e);
|
|
}
|
|
}
|
|
return ret;
|
|
}
|
|
isEmpty() {
|
|
return !this._callbacks || this._callbacks.length === 0;
|
|
}
|
|
dispose() {
|
|
this._callbacks = undefined;
|
|
this._contexts = undefined;
|
|
}
|
|
}
|
|
|
|
class Emitter {
|
|
_options;
|
|
static _noop = function() {};
|
|
_event;
|
|
_callbacks;
|
|
constructor(_options) {
|
|
this._options = _options;
|
|
}
|
|
get event() {
|
|
if (!this._event) {
|
|
this._event = (listener, thisArgs, disposables) => {
|
|
if (!this._callbacks) {
|
|
this._callbacks = new CallbackList;
|
|
}
|
|
if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
|
|
this._options.onFirstListenerAdd(this);
|
|
}
|
|
this._callbacks.add(listener, thisArgs);
|
|
const result = {
|
|
dispose: () => {
|
|
if (!this._callbacks) {
|
|
return;
|
|
}
|
|
this._callbacks.remove(listener, thisArgs);
|
|
result.dispose = Emitter._noop;
|
|
if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
|
|
this._options.onLastListenerRemove(this);
|
|
}
|
|
}
|
|
};
|
|
if (Array.isArray(disposables)) {
|
|
disposables.push(result);
|
|
}
|
|
return result;
|
|
};
|
|
}
|
|
return this._event;
|
|
}
|
|
fire(event) {
|
|
if (this._callbacks) {
|
|
this._callbacks.invoke.call(this._callbacks, event);
|
|
}
|
|
}
|
|
dispose() {
|
|
if (this._callbacks) {
|
|
this._callbacks.dispose();
|
|
this._callbacks = undefined;
|
|
}
|
|
}
|
|
}
|
|
exports2.Emitter = Emitter;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/cancellation.js
|
|
var require_cancellation = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
|
|
return mod && mod.__esModule ? mod : { default: mod };
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.CancellationTokenSource = exports2.CancellationToken = undefined;
|
|
var ral_1 = __importDefault(require_ral());
|
|
var Is = __importStar(require_is2());
|
|
var events_1 = require_events();
|
|
var CancellationToken;
|
|
(function(CancellationToken2) {
|
|
CancellationToken2.None = Object.freeze({
|
|
isCancellationRequested: false,
|
|
onCancellationRequested: events_1.Event.None
|
|
});
|
|
CancellationToken2.Cancelled = Object.freeze({
|
|
isCancellationRequested: true,
|
|
onCancellationRequested: events_1.Event.None
|
|
});
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && (candidate === CancellationToken2.None || candidate === CancellationToken2.Cancelled || Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested);
|
|
}
|
|
CancellationToken2.is = is;
|
|
})(CancellationToken || (exports2.CancellationToken = CancellationToken = {}));
|
|
var shortcutEvent = Object.freeze(function(callback, context) {
|
|
const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);
|
|
return { dispose() {
|
|
handle.dispose();
|
|
} };
|
|
});
|
|
|
|
class MutableToken {
|
|
_isCancelled = false;
|
|
_emitter;
|
|
cancel() {
|
|
if (!this._isCancelled) {
|
|
this._isCancelled = true;
|
|
if (this._emitter) {
|
|
this._emitter.fire(undefined);
|
|
this.dispose();
|
|
}
|
|
}
|
|
}
|
|
get isCancellationRequested() {
|
|
return this._isCancelled;
|
|
}
|
|
get onCancellationRequested() {
|
|
if (this._isCancelled) {
|
|
return shortcutEvent;
|
|
}
|
|
if (!this._emitter) {
|
|
this._emitter = new events_1.Emitter;
|
|
}
|
|
return this._emitter.event;
|
|
}
|
|
dispose() {
|
|
if (this._emitter) {
|
|
this._emitter.dispose();
|
|
this._emitter = undefined;
|
|
}
|
|
}
|
|
}
|
|
|
|
class CancellationTokenSource {
|
|
_token;
|
|
get token() {
|
|
if (!this._token) {
|
|
this._token = new MutableToken;
|
|
}
|
|
return this._token;
|
|
}
|
|
cancel() {
|
|
if (!this._token) {
|
|
this._token = CancellationToken.Cancelled;
|
|
} else {
|
|
this._token.cancel();
|
|
}
|
|
}
|
|
dispose() {
|
|
if (!this._token) {
|
|
this._token = CancellationToken.None;
|
|
} else if (this._token instanceof MutableToken) {
|
|
this._token.dispose();
|
|
}
|
|
}
|
|
}
|
|
exports2.CancellationTokenSource = CancellationTokenSource;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js
|
|
var require_sharedArrayCancellation = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.SharedArrayReceiverStrategy = exports2.SharedArraySenderStrategy = undefined;
|
|
var cancellation_1 = require_cancellation();
|
|
var CancellationState;
|
|
(function(CancellationState2) {
|
|
CancellationState2.Continue = 0;
|
|
CancellationState2.Cancelled = 1;
|
|
})(CancellationState || (CancellationState = {}));
|
|
|
|
class SharedArraySenderStrategy {
|
|
buffers;
|
|
constructor() {
|
|
this.buffers = new Map;
|
|
}
|
|
enableCancellation(request) {
|
|
if (request.id === null) {
|
|
return;
|
|
}
|
|
const buffer = new SharedArrayBuffer(4);
|
|
const data = new Int32Array(buffer, 0, 1);
|
|
data[0] = CancellationState.Continue;
|
|
this.buffers.set(request.id, buffer);
|
|
request.$cancellationData = buffer;
|
|
}
|
|
async sendCancellation(_conn, id) {
|
|
const buffer = this.buffers.get(id);
|
|
if (buffer === undefined) {
|
|
return;
|
|
}
|
|
const data = new Int32Array(buffer, 0, 1);
|
|
Atomics.store(data, 0, CancellationState.Cancelled);
|
|
}
|
|
cleanup(id) {
|
|
this.buffers.delete(id);
|
|
}
|
|
dispose() {
|
|
this.buffers.clear();
|
|
}
|
|
}
|
|
exports2.SharedArraySenderStrategy = SharedArraySenderStrategy;
|
|
|
|
class SharedArrayBufferCancellationToken {
|
|
data;
|
|
constructor(buffer) {
|
|
this.data = new Int32Array(buffer, 0, 1);
|
|
}
|
|
get isCancellationRequested() {
|
|
return Atomics.load(this.data, 0) === CancellationState.Cancelled;
|
|
}
|
|
get onCancellationRequested() {
|
|
throw new Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`);
|
|
}
|
|
}
|
|
|
|
class SharedArrayBufferCancellationTokenSource {
|
|
token;
|
|
constructor(buffer) {
|
|
this.token = new SharedArrayBufferCancellationToken(buffer);
|
|
}
|
|
cancel() {}
|
|
dispose() {}
|
|
}
|
|
|
|
class SharedArrayReceiverStrategy {
|
|
kind = "request";
|
|
createCancellationTokenSource(request) {
|
|
const buffer = request.$cancellationData;
|
|
if (buffer === undefined) {
|
|
return new cancellation_1.CancellationTokenSource;
|
|
}
|
|
return new SharedArrayBufferCancellationTokenSource(buffer);
|
|
}
|
|
}
|
|
exports2.SharedArrayReceiverStrategy = SharedArrayReceiverStrategy;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/semaphore.js
|
|
var require_semaphore = __commonJS((exports2) => {
|
|
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
|
|
return mod && mod.__esModule ? mod : { default: mod };
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.Semaphore = undefined;
|
|
var ral_1 = __importDefault(require_ral());
|
|
|
|
class Semaphore {
|
|
_capacity;
|
|
_active;
|
|
_waiting;
|
|
constructor(capacity = 1) {
|
|
if (capacity <= 0) {
|
|
throw new Error("Capacity must be greater than 0");
|
|
}
|
|
this._capacity = capacity;
|
|
this._active = 0;
|
|
this._waiting = [];
|
|
}
|
|
lock(thunk) {
|
|
return new Promise((resolve, reject) => {
|
|
this._waiting.push({ thunk, resolve, reject });
|
|
this.runNext();
|
|
});
|
|
}
|
|
get active() {
|
|
return this._active;
|
|
}
|
|
runNext() {
|
|
if (this._waiting.length === 0 || this._active === this._capacity) {
|
|
return;
|
|
}
|
|
(0, ral_1.default)().timer.setImmediate(() => this.doRunNext());
|
|
}
|
|
doRunNext() {
|
|
if (this._waiting.length === 0 || this._active === this._capacity) {
|
|
return;
|
|
}
|
|
const next = this._waiting.shift();
|
|
this._active++;
|
|
if (this._active > this._capacity) {
|
|
throw new Error(`Too many thunks active`);
|
|
}
|
|
try {
|
|
const result = next.thunk();
|
|
if (result instanceof Promise) {
|
|
result.then((value) => {
|
|
this._active--;
|
|
next.resolve(value);
|
|
this.runNext();
|
|
}, (err) => {
|
|
this._active--;
|
|
next.reject(err);
|
|
this.runNext();
|
|
});
|
|
} else {
|
|
this._active--;
|
|
next.resolve(result);
|
|
this.runNext();
|
|
}
|
|
} catch (err) {
|
|
this._active--;
|
|
next.reject(err);
|
|
this.runNext();
|
|
}
|
|
}
|
|
}
|
|
exports2.Semaphore = Semaphore;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/messageReader.js
|
|
var require_messageReader = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
|
|
return mod && mod.__esModule ? mod : { default: mod };
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ReadableStreamMessageReader = exports2.AbstractMessageReader = exports2.MessageReader = undefined;
|
|
var ral_1 = __importDefault(require_ral());
|
|
var Is = __importStar(require_is2());
|
|
var events_1 = require_events();
|
|
var semaphore_1 = require_semaphore();
|
|
var MessageReader;
|
|
(function(MessageReader2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) && Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
|
|
}
|
|
MessageReader2.is = is;
|
|
})(MessageReader || (exports2.MessageReader = MessageReader = {}));
|
|
|
|
class AbstractMessageReader {
|
|
errorEmitter;
|
|
closeEmitter;
|
|
partialMessageEmitter;
|
|
constructor() {
|
|
this.errorEmitter = new events_1.Emitter;
|
|
this.closeEmitter = new events_1.Emitter;
|
|
this.partialMessageEmitter = new events_1.Emitter;
|
|
}
|
|
dispose() {
|
|
this.errorEmitter.dispose();
|
|
this.closeEmitter.dispose();
|
|
this.partialMessageEmitter.dispose();
|
|
}
|
|
get onError() {
|
|
return this.errorEmitter.event;
|
|
}
|
|
fireError(error) {
|
|
this.errorEmitter.fire(this.asError(error));
|
|
}
|
|
get onClose() {
|
|
return this.closeEmitter.event;
|
|
}
|
|
fireClose() {
|
|
this.closeEmitter.fire(undefined);
|
|
}
|
|
get onPartialMessage() {
|
|
return this.partialMessageEmitter.event;
|
|
}
|
|
firePartialMessage(info) {
|
|
this.partialMessageEmitter.fire(info);
|
|
}
|
|
asError(error) {
|
|
if (error instanceof Error) {
|
|
return error;
|
|
} else {
|
|
return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
|
|
}
|
|
}
|
|
}
|
|
exports2.AbstractMessageReader = AbstractMessageReader;
|
|
var ResolvedMessageReaderOptions;
|
|
(function(ResolvedMessageReaderOptions2) {
|
|
function fromOptions(options) {
|
|
let charset;
|
|
let result;
|
|
let contentDecoder;
|
|
const contentDecoders = new Map;
|
|
let contentTypeDecoder;
|
|
const contentTypeDecoders = new Map;
|
|
if (options === undefined || typeof options === "string") {
|
|
charset = options ?? "utf-8";
|
|
} else {
|
|
charset = options.charset ?? "utf-8";
|
|
if (options.contentDecoder !== undefined) {
|
|
contentDecoder = options.contentDecoder;
|
|
contentDecoders.set(contentDecoder.name, contentDecoder);
|
|
}
|
|
if (options.contentDecoders !== undefined) {
|
|
for (const decoder of options.contentDecoders) {
|
|
contentDecoders.set(decoder.name, decoder);
|
|
}
|
|
}
|
|
if (options.contentTypeDecoder !== undefined) {
|
|
contentTypeDecoder = options.contentTypeDecoder;
|
|
contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
|
|
}
|
|
if (options.contentTypeDecoders !== undefined) {
|
|
for (const decoder of options.contentTypeDecoders) {
|
|
contentTypeDecoders.set(decoder.name, decoder);
|
|
}
|
|
}
|
|
}
|
|
if (contentTypeDecoder === undefined) {
|
|
contentTypeDecoder = (0, ral_1.default)().applicationJson.decoder;
|
|
contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
|
|
}
|
|
return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders };
|
|
}
|
|
ResolvedMessageReaderOptions2.fromOptions = fromOptions;
|
|
})(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));
|
|
|
|
class ReadableStreamMessageReader extends AbstractMessageReader {
|
|
readable;
|
|
options;
|
|
callback;
|
|
nextMessageLength;
|
|
messageToken;
|
|
buffer;
|
|
partialMessageTimer;
|
|
_partialMessageTimeout;
|
|
readSemaphore;
|
|
constructor(readable, options) {
|
|
super();
|
|
this.readable = readable;
|
|
this.options = ResolvedMessageReaderOptions.fromOptions(options);
|
|
this.buffer = (0, ral_1.default)().messageBuffer.create(this.options.charset);
|
|
this._partialMessageTimeout = 1e4;
|
|
this.nextMessageLength = -1;
|
|
this.messageToken = 0;
|
|
this.readSemaphore = new semaphore_1.Semaphore(1);
|
|
}
|
|
set partialMessageTimeout(timeout) {
|
|
this._partialMessageTimeout = timeout;
|
|
}
|
|
get partialMessageTimeout() {
|
|
return this._partialMessageTimeout;
|
|
}
|
|
listen(callback) {
|
|
this.nextMessageLength = -1;
|
|
this.messageToken = 0;
|
|
this.partialMessageTimer = undefined;
|
|
this.callback = callback;
|
|
const result = this.readable.onData((data) => {
|
|
this.onData(data);
|
|
});
|
|
this.readable.onError((error) => this.fireError(error));
|
|
this.readable.onClose(() => this.fireClose());
|
|
return result;
|
|
}
|
|
onData(data) {
|
|
try {
|
|
this.buffer.append(data);
|
|
while (true) {
|
|
if (this.nextMessageLength === -1) {
|
|
const headers = this.buffer.tryReadHeaders(true);
|
|
if (!headers) {
|
|
return;
|
|
}
|
|
const contentLength = headers.get("content-length");
|
|
if (!contentLength) {
|
|
this.fireError(new Error(`Header must provide a Content-Length property.
|
|
${JSON.stringify(Object.fromEntries(headers))}`));
|
|
return;
|
|
}
|
|
const length = parseInt(contentLength);
|
|
if (isNaN(length)) {
|
|
this.fireError(new Error(`Content-Length value must be a number. Got ${contentLength}`));
|
|
return;
|
|
}
|
|
this.nextMessageLength = length;
|
|
}
|
|
const body = this.buffer.tryReadBody(this.nextMessageLength);
|
|
if (body === undefined) {
|
|
this.setPartialMessageTimer();
|
|
return;
|
|
}
|
|
this.clearPartialMessageTimer();
|
|
this.nextMessageLength = -1;
|
|
this.readSemaphore.lock(async () => {
|
|
const bytes = this.options.contentDecoder !== undefined ? await this.options.contentDecoder.decode(body) : body;
|
|
const message = await this.options.contentTypeDecoder.decode(bytes, this.options);
|
|
this.callback(message);
|
|
}).catch((error) => {
|
|
this.fireError(error);
|
|
});
|
|
}
|
|
} catch (error) {
|
|
this.fireError(error);
|
|
}
|
|
}
|
|
clearPartialMessageTimer() {
|
|
if (this.partialMessageTimer) {
|
|
this.partialMessageTimer.dispose();
|
|
this.partialMessageTimer = undefined;
|
|
}
|
|
}
|
|
setPartialMessageTimer() {
|
|
this.clearPartialMessageTimer();
|
|
if (this._partialMessageTimeout <= 0) {
|
|
return;
|
|
}
|
|
this.partialMessageTimer = (0, ral_1.default)().timer.setTimeout((token, timeout) => {
|
|
this.partialMessageTimer = undefined;
|
|
if (token === this.messageToken) {
|
|
this.firePartialMessage({ messageToken: token, waitingTime: timeout });
|
|
this.setPartialMessageTimer();
|
|
}
|
|
}, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
|
|
}
|
|
}
|
|
exports2.ReadableStreamMessageReader = ReadableStreamMessageReader;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/messageWriter.js
|
|
var require_messageWriter = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
|
|
return mod && mod.__esModule ? mod : { default: mod };
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.WriteableStreamMessageWriter = exports2.AbstractMessageWriter = exports2.MessageWriter = undefined;
|
|
var ral_1 = __importDefault(require_ral());
|
|
var Is = __importStar(require_is2());
|
|
var semaphore_1 = require_semaphore();
|
|
var events_1 = require_events();
|
|
var ContentLength = "Content-Length: ";
|
|
var CRLF = `\r
|
|
`;
|
|
var MessageWriter;
|
|
(function(MessageWriter2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) && Is.func(candidate.onError) && Is.func(candidate.write);
|
|
}
|
|
MessageWriter2.is = is;
|
|
})(MessageWriter || (exports2.MessageWriter = MessageWriter = {}));
|
|
|
|
class AbstractMessageWriter {
|
|
errorEmitter;
|
|
closeEmitter;
|
|
constructor() {
|
|
this.errorEmitter = new events_1.Emitter;
|
|
this.closeEmitter = new events_1.Emitter;
|
|
}
|
|
dispose() {
|
|
this.errorEmitter.dispose();
|
|
this.closeEmitter.dispose();
|
|
}
|
|
get onError() {
|
|
return this.errorEmitter.event;
|
|
}
|
|
fireError(error, message, count) {
|
|
this.errorEmitter.fire([this.asError(error), message, count]);
|
|
}
|
|
get onClose() {
|
|
return this.closeEmitter.event;
|
|
}
|
|
fireClose() {
|
|
this.closeEmitter.fire(undefined);
|
|
}
|
|
asError(error) {
|
|
if (error instanceof Error) {
|
|
return error;
|
|
} else {
|
|
return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
|
|
}
|
|
}
|
|
}
|
|
exports2.AbstractMessageWriter = AbstractMessageWriter;
|
|
var ResolvedMessageWriterOptions;
|
|
(function(ResolvedMessageWriterOptions2) {
|
|
function fromOptions(options) {
|
|
if (options === undefined || typeof options === "string") {
|
|
return { charset: options ?? "utf-8", contentTypeEncoder: (0, ral_1.default)().applicationJson.encoder };
|
|
} else {
|
|
return { charset: options.charset ?? "utf-8", contentEncoder: options.contentEncoder, contentTypeEncoder: options.contentTypeEncoder ?? (0, ral_1.default)().applicationJson.encoder };
|
|
}
|
|
}
|
|
ResolvedMessageWriterOptions2.fromOptions = fromOptions;
|
|
})(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));
|
|
|
|
class WriteableStreamMessageWriter extends AbstractMessageWriter {
|
|
writable;
|
|
options;
|
|
errorCount;
|
|
writeSemaphore;
|
|
constructor(writable, options) {
|
|
super();
|
|
this.writable = writable;
|
|
this.options = ResolvedMessageWriterOptions.fromOptions(options);
|
|
this.errorCount = 0;
|
|
this.writeSemaphore = new semaphore_1.Semaphore(1);
|
|
this.writable.onError((error) => this.fireError(error));
|
|
this.writable.onClose(() => this.fireClose());
|
|
}
|
|
async write(msg) {
|
|
return this.writeSemaphore.lock(async () => {
|
|
const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {
|
|
if (this.options.contentEncoder !== undefined) {
|
|
return this.options.contentEncoder.encode(buffer);
|
|
} else {
|
|
return buffer;
|
|
}
|
|
});
|
|
return payload.then((buffer) => {
|
|
const headers = [];
|
|
headers.push(ContentLength, buffer.byteLength.toString(), CRLF);
|
|
headers.push(CRLF);
|
|
return this.doWrite(msg, headers, buffer);
|
|
}, (error) => {
|
|
this.fireError(error);
|
|
throw error;
|
|
});
|
|
});
|
|
}
|
|
async doWrite(msg, headers, data) {
|
|
try {
|
|
await this.writable.write(headers.join(""), "ascii");
|
|
return this.writable.write(data);
|
|
} catch (error) {
|
|
this.handleError(error, msg);
|
|
return Promise.reject(error);
|
|
}
|
|
}
|
|
handleError(error, msg) {
|
|
this.errorCount++;
|
|
this.fireError(error, msg, this.errorCount);
|
|
}
|
|
end() {
|
|
this.writable.end();
|
|
}
|
|
}
|
|
exports2.WriteableStreamMessageWriter = WriteableStreamMessageWriter;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/messageBuffer.js
|
|
var require_messageBuffer = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.AbstractMessageBuffer = undefined;
|
|
var CR = 13;
|
|
var LF = 10;
|
|
var CRLF = `\r
|
|
`;
|
|
|
|
class AbstractMessageBuffer {
|
|
_encoding;
|
|
_chunks;
|
|
_totalLength;
|
|
constructor(encoding = "utf-8") {
|
|
this._encoding = encoding;
|
|
this._chunks = [];
|
|
this._totalLength = 0;
|
|
}
|
|
get encoding() {
|
|
return this._encoding;
|
|
}
|
|
append(chunk) {
|
|
const toAppend = typeof chunk === "string" ? this.fromString(chunk, this._encoding) : chunk;
|
|
this._chunks.push(toAppend);
|
|
this._totalLength += toAppend.byteLength;
|
|
}
|
|
tryReadHeaders(lowerCaseKeys = false) {
|
|
if (this._chunks.length === 0) {
|
|
return;
|
|
}
|
|
let state = 0;
|
|
let chunkIndex = 0;
|
|
let offset = 0;
|
|
let chunkBytesRead = 0;
|
|
row:
|
|
while (chunkIndex < this._chunks.length) {
|
|
const chunk = this._chunks[chunkIndex];
|
|
offset = 0;
|
|
while (offset < chunk.length) {
|
|
const value = chunk[offset];
|
|
switch (value) {
|
|
case CR:
|
|
switch (state) {
|
|
case 0:
|
|
state = 1;
|
|
break;
|
|
case 2:
|
|
state = 3;
|
|
break;
|
|
default:
|
|
state = 0;
|
|
}
|
|
break;
|
|
case LF:
|
|
switch (state) {
|
|
case 1:
|
|
state = 2;
|
|
break;
|
|
case 3:
|
|
state = 4;
|
|
offset++;
|
|
break row;
|
|
default:
|
|
state = 0;
|
|
}
|
|
break;
|
|
default:
|
|
state = 0;
|
|
}
|
|
offset++;
|
|
}
|
|
chunkBytesRead += chunk.byteLength;
|
|
chunkIndex++;
|
|
}
|
|
if (state !== 4) {
|
|
return;
|
|
}
|
|
const buffer = this._read(chunkBytesRead + offset);
|
|
const result = new Map;
|
|
const headers = this.toString(buffer, "ascii").split(CRLF);
|
|
if (headers.length < 2) {
|
|
return result;
|
|
}
|
|
for (let i = 0;i < headers.length - 2; i++) {
|
|
const header = headers[i];
|
|
const index = header.indexOf(":");
|
|
if (index === -1) {
|
|
throw new Error(`Message header must separate key and value using ':'
|
|
${header}`);
|
|
}
|
|
const key = header.substr(0, index);
|
|
const value = header.substr(index + 1).trim();
|
|
result.set(lowerCaseKeys ? key.toLowerCase() : key, value);
|
|
}
|
|
return result;
|
|
}
|
|
tryReadBody(length) {
|
|
if (this._totalLength < length) {
|
|
return;
|
|
}
|
|
return this._read(length);
|
|
}
|
|
get numberOfBytes() {
|
|
return this._totalLength;
|
|
}
|
|
_read(byteCount) {
|
|
if (byteCount === 0) {
|
|
return this.emptyBuffer();
|
|
}
|
|
if (byteCount > this._totalLength) {
|
|
throw new Error(`Cannot read so many bytes!`);
|
|
}
|
|
if (this._chunks[0].byteLength === byteCount) {
|
|
const chunk = this._chunks[0];
|
|
this._chunks.shift();
|
|
this._totalLength -= byteCount;
|
|
return this.asNative(chunk);
|
|
}
|
|
if (this._chunks[0].byteLength > byteCount) {
|
|
const chunk = this._chunks[0];
|
|
const result2 = this.asNative(chunk, byteCount);
|
|
this._chunks[0] = chunk.slice(byteCount);
|
|
this._totalLength -= byteCount;
|
|
return result2;
|
|
}
|
|
const result = this.allocNative(byteCount);
|
|
let resultOffset = 0;
|
|
const chunkIndex = 0;
|
|
while (byteCount > 0) {
|
|
const chunk = this._chunks[chunkIndex];
|
|
if (chunk.byteLength > byteCount) {
|
|
const chunkPart = chunk.slice(0, byteCount);
|
|
result.set(chunkPart, resultOffset);
|
|
resultOffset += byteCount;
|
|
this._chunks[chunkIndex] = chunk.slice(byteCount);
|
|
this._totalLength -= byteCount;
|
|
byteCount -= byteCount;
|
|
} else {
|
|
result.set(chunk, resultOffset);
|
|
resultOffset += chunk.byteLength;
|
|
this._chunks.shift();
|
|
this._totalLength -= chunk.byteLength;
|
|
byteCount -= chunk.byteLength;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
exports2.AbstractMessageBuffer = AbstractMessageBuffer;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/connection.js
|
|
var require_connection = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
|
|
return mod && mod.__esModule ? mod : { default: mod };
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ConnectionOptions = exports2.MessageStrategy = exports2.CancellationStrategy = exports2.CancellationSenderStrategy = exports2.CancellationReceiverStrategy = exports2.RequestCancellationReceiverStrategy = exports2.IdCancellationReceiverStrategy = exports2.ConnectionStrategy = exports2.ConnectionError = exports2.ConnectionErrors = exports2.LogTraceNotification = exports2.SetTraceNotification = exports2.TraceFormat = exports2.TraceValues = exports2.TraceValue = exports2.Trace = exports2.NullLogger = exports2.ProgressType = exports2.ProgressToken = undefined;
|
|
exports2.createMessageConnection = createMessageConnection;
|
|
var ral_1 = __importDefault(require_ral());
|
|
var Is = __importStar(require_is2());
|
|
var messages_1 = require_messages();
|
|
var linkedMap_1 = require_linkedMap();
|
|
var events_1 = require_events();
|
|
var cancellation_1 = require_cancellation();
|
|
var CancelNotification;
|
|
(function(CancelNotification2) {
|
|
CancelNotification2.type = new messages_1.NotificationType("$/cancelRequest");
|
|
})(CancelNotification || (CancelNotification = {}));
|
|
var ProgressToken;
|
|
(function(ProgressToken2) {
|
|
function is(value) {
|
|
return typeof value === "string" || typeof value === "number";
|
|
}
|
|
ProgressToken2.is = is;
|
|
})(ProgressToken || (exports2.ProgressToken = ProgressToken = {}));
|
|
var ProgressNotification;
|
|
(function(ProgressNotification2) {
|
|
ProgressNotification2.type = new messages_1.NotificationType("$/progress");
|
|
})(ProgressNotification || (ProgressNotification = {}));
|
|
|
|
class ProgressType {
|
|
__;
|
|
_pr;
|
|
constructor() {}
|
|
}
|
|
exports2.ProgressType = ProgressType;
|
|
var StarRequestHandler;
|
|
(function(StarRequestHandler2) {
|
|
function is(value) {
|
|
return Is.func(value);
|
|
}
|
|
StarRequestHandler2.is = is;
|
|
})(StarRequestHandler || (StarRequestHandler = {}));
|
|
exports2.NullLogger = Object.freeze({
|
|
error: () => {},
|
|
warn: () => {},
|
|
info: () => {},
|
|
log: () => {}
|
|
});
|
|
var Trace;
|
|
(function(Trace2) {
|
|
Trace2[Trace2["Off"] = 0] = "Off";
|
|
Trace2[Trace2["Messages"] = 1] = "Messages";
|
|
Trace2[Trace2["Compact"] = 2] = "Compact";
|
|
Trace2[Trace2["Verbose"] = 3] = "Verbose";
|
|
})(Trace || (exports2.Trace = Trace = {}));
|
|
var TraceValue;
|
|
(function(TraceValue2) {
|
|
TraceValue2.Off = "off";
|
|
TraceValue2.Messages = "messages";
|
|
TraceValue2.Compact = "compact";
|
|
TraceValue2.Verbose = "verbose";
|
|
})(TraceValue || (exports2.TraceValue = TraceValue = {}));
|
|
exports2.TraceValues = TraceValue;
|
|
(function(Trace2) {
|
|
function fromString(value) {
|
|
if (!Is.string(value)) {
|
|
return Trace2.Off;
|
|
}
|
|
value = value.toLowerCase();
|
|
switch (value) {
|
|
case "off":
|
|
return Trace2.Off;
|
|
case "messages":
|
|
return Trace2.Messages;
|
|
case "compact":
|
|
return Trace2.Compact;
|
|
case "verbose":
|
|
return Trace2.Verbose;
|
|
default:
|
|
return Trace2.Off;
|
|
}
|
|
}
|
|
Trace2.fromString = fromString;
|
|
function toString(value) {
|
|
switch (value) {
|
|
case Trace2.Off:
|
|
return "off";
|
|
case Trace2.Messages:
|
|
return "messages";
|
|
case Trace2.Compact:
|
|
return "compact";
|
|
case Trace2.Verbose:
|
|
return "verbose";
|
|
default:
|
|
return "off";
|
|
}
|
|
}
|
|
Trace2.toString = toString;
|
|
})(Trace || (exports2.Trace = Trace = {}));
|
|
var TraceFormat;
|
|
(function(TraceFormat2) {
|
|
TraceFormat2["Text"] = "text";
|
|
TraceFormat2["JSON"] = "json";
|
|
})(TraceFormat || (exports2.TraceFormat = TraceFormat = {}));
|
|
(function(TraceFormat2) {
|
|
function fromString(value) {
|
|
if (!Is.string(value)) {
|
|
return TraceFormat2.Text;
|
|
}
|
|
value = value.toLowerCase();
|
|
if (value === "json") {
|
|
return TraceFormat2.JSON;
|
|
} else {
|
|
return TraceFormat2.Text;
|
|
}
|
|
}
|
|
TraceFormat2.fromString = fromString;
|
|
})(TraceFormat || (exports2.TraceFormat = TraceFormat = {}));
|
|
var SetTraceNotification;
|
|
(function(SetTraceNotification2) {
|
|
SetTraceNotification2.type = new messages_1.NotificationType("$/setTrace");
|
|
})(SetTraceNotification || (exports2.SetTraceNotification = SetTraceNotification = {}));
|
|
var LogTraceNotification;
|
|
(function(LogTraceNotification2) {
|
|
LogTraceNotification2.type = new messages_1.NotificationType("$/logTrace");
|
|
})(LogTraceNotification || (exports2.LogTraceNotification = LogTraceNotification = {}));
|
|
var ConnectionErrors;
|
|
(function(ConnectionErrors2) {
|
|
ConnectionErrors2[ConnectionErrors2["Closed"] = 1] = "Closed";
|
|
ConnectionErrors2[ConnectionErrors2["Disposed"] = 2] = "Disposed";
|
|
ConnectionErrors2[ConnectionErrors2["AlreadyListening"] = 3] = "AlreadyListening";
|
|
})(ConnectionErrors || (exports2.ConnectionErrors = ConnectionErrors = {}));
|
|
|
|
class ConnectionError extends Error {
|
|
code;
|
|
constructor(code, message) {
|
|
super(message);
|
|
this.code = code;
|
|
Object.setPrototypeOf(this, ConnectionError.prototype);
|
|
}
|
|
}
|
|
exports2.ConnectionError = ConnectionError;
|
|
var ConnectionStrategy;
|
|
(function(ConnectionStrategy2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && Is.func(candidate.cancelUndispatched);
|
|
}
|
|
ConnectionStrategy2.is = is;
|
|
})(ConnectionStrategy || (exports2.ConnectionStrategy = ConnectionStrategy = {}));
|
|
var IdCancellationReceiverStrategy;
|
|
(function(IdCancellationReceiverStrategy2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && (candidate.kind === undefined || candidate.kind === "id") && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose));
|
|
}
|
|
IdCancellationReceiverStrategy2.is = is;
|
|
})(IdCancellationReceiverStrategy || (exports2.IdCancellationReceiverStrategy = IdCancellationReceiverStrategy = {}));
|
|
var RequestCancellationReceiverStrategy;
|
|
(function(RequestCancellationReceiverStrategy2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && candidate.kind === "request" && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose));
|
|
}
|
|
RequestCancellationReceiverStrategy2.is = is;
|
|
})(RequestCancellationReceiverStrategy || (exports2.RequestCancellationReceiverStrategy = RequestCancellationReceiverStrategy = {}));
|
|
var CancellationReceiverStrategy;
|
|
(function(CancellationReceiverStrategy2) {
|
|
CancellationReceiverStrategy2.Message = Object.freeze({
|
|
createCancellationTokenSource(_) {
|
|
return new cancellation_1.CancellationTokenSource;
|
|
}
|
|
});
|
|
function is(value) {
|
|
return IdCancellationReceiverStrategy.is(value) || RequestCancellationReceiverStrategy.is(value);
|
|
}
|
|
CancellationReceiverStrategy2.is = is;
|
|
})(CancellationReceiverStrategy || (exports2.CancellationReceiverStrategy = CancellationReceiverStrategy = {}));
|
|
var CancellationSenderStrategy;
|
|
(function(CancellationSenderStrategy2) {
|
|
CancellationSenderStrategy2.Message = Object.freeze({
|
|
sendCancellation(conn, id) {
|
|
return conn.sendNotification(CancelNotification.type, { id });
|
|
},
|
|
cleanup(_) {}
|
|
});
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup);
|
|
}
|
|
CancellationSenderStrategy2.is = is;
|
|
})(CancellationSenderStrategy || (exports2.CancellationSenderStrategy = CancellationSenderStrategy = {}));
|
|
var CancellationStrategy;
|
|
(function(CancellationStrategy2) {
|
|
CancellationStrategy2.Message = Object.freeze({
|
|
receiver: CancellationReceiverStrategy.Message,
|
|
sender: CancellationSenderStrategy.Message
|
|
});
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);
|
|
}
|
|
CancellationStrategy2.is = is;
|
|
})(CancellationStrategy || (exports2.CancellationStrategy = CancellationStrategy = {}));
|
|
var MessageStrategy;
|
|
(function(MessageStrategy2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && Is.func(candidate.handleMessage);
|
|
}
|
|
MessageStrategy2.is = is;
|
|
})(MessageStrategy || (exports2.MessageStrategy = MessageStrategy = {}));
|
|
var ConnectionOptions;
|
|
(function(ConnectionOptions2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy) || MessageStrategy.is(candidate.messageStrategy) || Is.number(candidate.maxParallelism));
|
|
}
|
|
ConnectionOptions2.is = is;
|
|
})(ConnectionOptions || (exports2.ConnectionOptions = ConnectionOptions = {}));
|
|
var ConnectionState;
|
|
(function(ConnectionState2) {
|
|
ConnectionState2[ConnectionState2["New"] = 1] = "New";
|
|
ConnectionState2[ConnectionState2["Listening"] = 2] = "Listening";
|
|
ConnectionState2[ConnectionState2["Closed"] = 3] = "Closed";
|
|
ConnectionState2[ConnectionState2["Disposed"] = 4] = "Disposed";
|
|
})(ConnectionState || (ConnectionState = {}));
|
|
function createMessageConnection(messageReader, messageWriter, _logger, options) {
|
|
const logger = _logger !== undefined ? _logger : exports2.NullLogger;
|
|
let sequenceNumber = 0;
|
|
let notificationSequenceNumber = 0;
|
|
let unknownResponseSequenceNumber = 0;
|
|
const version = "2.0";
|
|
const maxParallelism = options?.maxParallelism ?? -1;
|
|
let inFlight = 0;
|
|
let starRequestHandler = undefined;
|
|
const requestHandlers = new Map;
|
|
let starNotificationHandler = undefined;
|
|
const notificationHandlers = new Map;
|
|
const progressHandlers = new Map;
|
|
let timer;
|
|
let messageQueue = new linkedMap_1.LinkedMap;
|
|
let responsePromises = new Map;
|
|
let knownCanceledRequests = new Set;
|
|
let requestTokens = new Map;
|
|
let trace = Trace.Off;
|
|
let traceFormat = TraceFormat.Text;
|
|
let tracer;
|
|
let state = ConnectionState.New;
|
|
const errorEmitter = new events_1.Emitter;
|
|
const closeEmitter = new events_1.Emitter;
|
|
const unhandledNotificationEmitter = new events_1.Emitter;
|
|
const unhandledProgressEmitter = new events_1.Emitter;
|
|
const disposeEmitter = new events_1.Emitter;
|
|
const cancellationStrategy = options && options.cancellationStrategy ? options.cancellationStrategy : CancellationStrategy.Message;
|
|
function cancelUndispatched(_message) {
|
|
return;
|
|
}
|
|
function isListening() {
|
|
return state === ConnectionState.Listening;
|
|
}
|
|
function isClosed() {
|
|
return state === ConnectionState.Closed;
|
|
}
|
|
function isDisposed() {
|
|
return state === ConnectionState.Disposed;
|
|
}
|
|
function closeHandler() {
|
|
if (state === ConnectionState.New || state === ConnectionState.Listening) {
|
|
state = ConnectionState.Closed;
|
|
closeEmitter.fire(undefined);
|
|
}
|
|
}
|
|
function readErrorHandler(error) {
|
|
errorEmitter.fire([error, undefined, undefined]);
|
|
}
|
|
function writeErrorHandler(data) {
|
|
errorEmitter.fire(data);
|
|
}
|
|
messageReader.onClose(closeHandler);
|
|
messageReader.onError(readErrorHandler);
|
|
messageWriter.onClose(closeHandler);
|
|
messageWriter.onError(writeErrorHandler);
|
|
function createRequestQueueKey(id) {
|
|
if (id === null) {
|
|
throw new Error(`Can't send requests with id null since the response can't be correlated.`);
|
|
}
|
|
return "req-" + id.toString();
|
|
}
|
|
function createResponseQueueKey(id) {
|
|
if (id === null) {
|
|
return "res-unknown-" + (++unknownResponseSequenceNumber).toString();
|
|
} else {
|
|
return "res-" + id.toString();
|
|
}
|
|
}
|
|
function createNotificationQueueKey() {
|
|
return "not-" + (++notificationSequenceNumber).toString();
|
|
}
|
|
function addMessageToQueue(queue, message) {
|
|
if (messages_1.Message.isRequest(message)) {
|
|
queue.set(createRequestQueueKey(message.id), message);
|
|
} else if (messages_1.Message.isResponse(message)) {
|
|
if (maxParallelism === -1) {
|
|
queue.set(createResponseQueueKey(message.id), message);
|
|
} else {
|
|
handleResponse(message);
|
|
}
|
|
} else {
|
|
queue.set(createNotificationQueueKey(), message);
|
|
}
|
|
}
|
|
function triggerMessageQueue() {
|
|
if (timer || messageQueue.size === 0) {
|
|
return;
|
|
}
|
|
if (maxParallelism !== -1 && inFlight >= maxParallelism) {
|
|
return;
|
|
}
|
|
timer = (0, ral_1.default)().timer.setImmediate(async () => {
|
|
timer = undefined;
|
|
if (messageQueue.size === 0) {
|
|
return;
|
|
}
|
|
if (maxParallelism !== -1 && inFlight >= maxParallelism) {
|
|
return;
|
|
}
|
|
const message = messageQueue.shift();
|
|
let result;
|
|
try {
|
|
inFlight++;
|
|
const messageStrategy = options?.messageStrategy;
|
|
if (MessageStrategy.is(messageStrategy)) {
|
|
result = messageStrategy.handleMessage(message, handleMessage);
|
|
} else {
|
|
result = handleMessage(message);
|
|
}
|
|
} catch (error) {
|
|
logger.error(`Processing message queue failed: ${error.toString()}`);
|
|
} finally {
|
|
if (result instanceof Promise) {
|
|
result.then(() => {
|
|
inFlight--;
|
|
triggerMessageQueue();
|
|
}).catch((error) => {
|
|
logger.error(`Processing message queue failed: ${error.toString()}`);
|
|
});
|
|
} else {
|
|
inFlight--;
|
|
}
|
|
triggerMessageQueue();
|
|
}
|
|
});
|
|
}
|
|
async function handleMessage(message) {
|
|
if (messages_1.Message.isRequest(message)) {
|
|
return handleRequest(message);
|
|
} else if (messages_1.Message.isNotification(message)) {
|
|
return handleNotification(message);
|
|
} else if (messages_1.Message.isResponse(message)) {
|
|
return handleResponse(message);
|
|
} else {
|
|
return handleInvalidMessage(message);
|
|
}
|
|
}
|
|
const callback = (message) => {
|
|
try {
|
|
if (messages_1.Message.isNotification(message) && message.method === CancelNotification.type.method) {
|
|
const cancelId = message.params.id;
|
|
const key = createRequestQueueKey(cancelId);
|
|
const toCancel = messageQueue.get(key);
|
|
if (messages_1.Message.isRequest(toCancel)) {
|
|
const strategy = options?.connectionStrategy;
|
|
const response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
|
|
if (response && (response.error !== undefined || response.result !== undefined)) {
|
|
messageQueue.delete(key);
|
|
requestTokens.delete(cancelId);
|
|
response.id = toCancel.id;
|
|
traceSendingResponse(response, message.method, Date.now());
|
|
messageWriter.write(response).catch(() => logger.error(`Sending response for canceled message failed.`));
|
|
return;
|
|
}
|
|
}
|
|
const cancellationToken = requestTokens.get(cancelId);
|
|
if (cancellationToken !== undefined) {
|
|
cancellationToken.cancel();
|
|
traceReceivedNotification(message);
|
|
return;
|
|
} else {
|
|
knownCanceledRequests.add(cancelId);
|
|
}
|
|
}
|
|
addMessageToQueue(messageQueue, message);
|
|
} finally {
|
|
triggerMessageQueue();
|
|
}
|
|
};
|
|
async function handleRequest(requestMessage) {
|
|
if (isDisposed()) {
|
|
return Promise.resolve();
|
|
}
|
|
function reply(resultOrError, method, startTime2) {
|
|
const message = {
|
|
jsonrpc: version,
|
|
id: requestMessage.id
|
|
};
|
|
if (resultOrError instanceof messages_1.ResponseError) {
|
|
message.error = resultOrError.toJson();
|
|
} else {
|
|
message.result = resultOrError === undefined ? null : resultOrError;
|
|
}
|
|
traceSendingResponse(message, method, startTime2);
|
|
return messageWriter.write(message);
|
|
}
|
|
function replyError(error, method, startTime2) {
|
|
const message = {
|
|
jsonrpc: version,
|
|
id: requestMessage.id,
|
|
error: error.toJson()
|
|
};
|
|
traceSendingResponse(message, method, startTime2);
|
|
return messageWriter.write(message);
|
|
}
|
|
traceReceivedRequest(requestMessage);
|
|
const element = requestHandlers.get(requestMessage.method);
|
|
let type;
|
|
let requestHandler;
|
|
if (element) {
|
|
type = element.type;
|
|
requestHandler = element.handler;
|
|
}
|
|
const startTime = Date.now();
|
|
if (requestHandler || starRequestHandler) {
|
|
const tokenKey = requestMessage.id ?? String(Date.now());
|
|
const cancellationSource = IdCancellationReceiverStrategy.is(cancellationStrategy.receiver) ? cancellationStrategy.receiver.createCancellationTokenSource(tokenKey) : cancellationStrategy.receiver.createCancellationTokenSource(requestMessage);
|
|
if (requestMessage.id !== null && knownCanceledRequests.has(requestMessage.id)) {
|
|
cancellationSource.cancel();
|
|
}
|
|
if (requestMessage.id !== null) {
|
|
requestTokens.set(tokenKey, cancellationSource);
|
|
}
|
|
try {
|
|
let handlerResult;
|
|
if (requestHandler) {
|
|
if (requestMessage.params === undefined) {
|
|
if (type !== undefined && type.numberOfParams !== 0) {
|
|
return replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime);
|
|
}
|
|
handlerResult = requestHandler(cancellationSource.token);
|
|
} else if (Array.isArray(requestMessage.params)) {
|
|
if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byName) {
|
|
return replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime);
|
|
}
|
|
handlerResult = requestHandler(...requestMessage.params, cancellationSource.token);
|
|
} else {
|
|
if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
|
|
return replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime);
|
|
}
|
|
handlerResult = requestHandler(requestMessage.params, cancellationSource.token);
|
|
}
|
|
} else if (starRequestHandler) {
|
|
handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
|
|
}
|
|
const resultOrError = await handlerResult;
|
|
await reply(resultOrError, requestMessage.method, startTime);
|
|
} catch (error) {
|
|
if (error instanceof messages_1.ResponseError) {
|
|
await reply(error, requestMessage.method, startTime);
|
|
} else if (error && Is.string(error.message)) {
|
|
await replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
|
|
} else {
|
|
await replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
|
|
}
|
|
} finally {
|
|
requestTokens.delete(tokenKey);
|
|
}
|
|
} else {
|
|
await replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
|
|
}
|
|
}
|
|
function handleResponse(responseMessage) {
|
|
if (isDisposed()) {
|
|
return;
|
|
}
|
|
if (responseMessage.id === null) {
|
|
if (responseMessage.error) {
|
|
logger.error(`Received response message without id: Error is:
|
|
${JSON.stringify(responseMessage.error, undefined, 4)}`);
|
|
} else {
|
|
logger.error(`Received response message without id. No further error information provided.`);
|
|
}
|
|
} else {
|
|
const key = responseMessage.id;
|
|
const responsePromise = responsePromises.get(key);
|
|
traceReceivedResponse(responseMessage, responsePromise);
|
|
if (responsePromise !== undefined) {
|
|
responsePromises.delete(key);
|
|
try {
|
|
if (responseMessage.error) {
|
|
const error = responseMessage.error;
|
|
responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
|
|
} else if (responseMessage.result !== undefined) {
|
|
responsePromise.resolve(responseMessage.result);
|
|
} else {
|
|
throw new Error("Should never happen.");
|
|
}
|
|
} catch (error) {
|
|
if (error.message) {
|
|
logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
|
|
} else {
|
|
logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
async function handleNotification(message) {
|
|
if (isDisposed()) {
|
|
return;
|
|
}
|
|
let type = undefined;
|
|
let notificationHandler;
|
|
if (message.method === CancelNotification.type.method) {
|
|
const cancelId = message.params.id;
|
|
knownCanceledRequests.delete(cancelId);
|
|
traceReceivedNotification(message);
|
|
return;
|
|
} else {
|
|
const element = notificationHandlers.get(message.method);
|
|
if (element) {
|
|
notificationHandler = element.handler;
|
|
type = element.type;
|
|
}
|
|
}
|
|
if (notificationHandler || starNotificationHandler) {
|
|
try {
|
|
traceReceivedNotification(message);
|
|
if (notificationHandler) {
|
|
if (message.params === undefined) {
|
|
if (type !== undefined) {
|
|
if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) {
|
|
logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`);
|
|
}
|
|
}
|
|
await notificationHandler();
|
|
} else if (Array.isArray(message.params)) {
|
|
const params = message.params;
|
|
if (message.method === ProgressNotification.type.method && params.length === 2 && ProgressToken.is(params[0])) {
|
|
await notificationHandler({ token: params[0], value: params[1] });
|
|
} else {
|
|
if (type !== undefined) {
|
|
if (type.parameterStructures === messages_1.ParameterStructures.byName) {
|
|
logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`);
|
|
}
|
|
if (type.numberOfParams !== message.params.length) {
|
|
logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`);
|
|
}
|
|
}
|
|
await notificationHandler(...params);
|
|
}
|
|
} else {
|
|
if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
|
|
logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`);
|
|
}
|
|
await notificationHandler(message.params);
|
|
}
|
|
} else if (starNotificationHandler) {
|
|
await starNotificationHandler(message.method, message.params);
|
|
}
|
|
} catch (error) {
|
|
if (error.message) {
|
|
logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
|
|
} else {
|
|
logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
|
|
}
|
|
}
|
|
} else {
|
|
unhandledNotificationEmitter.fire(message);
|
|
}
|
|
}
|
|
function handleInvalidMessage(message) {
|
|
if (!message) {
|
|
logger.error("Received empty message.");
|
|
return;
|
|
}
|
|
logger.error(`Received message which is neither a response nor a notification message:
|
|
${JSON.stringify(message, null, 4)}`);
|
|
const responseMessage = message;
|
|
if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
|
|
const key = responseMessage.id;
|
|
const responseHandler = responsePromises.get(key);
|
|
if (responseHandler) {
|
|
responseHandler.reject(new Error("The received response has neither a result nor an error property."));
|
|
}
|
|
}
|
|
}
|
|
function stringifyTrace(params) {
|
|
if (params === undefined || params === null) {
|
|
return;
|
|
}
|
|
switch (trace) {
|
|
case Trace.Verbose:
|
|
return JSON.stringify(params, null, 4);
|
|
case Trace.Compact:
|
|
return JSON.stringify(params);
|
|
default:
|
|
return;
|
|
}
|
|
}
|
|
function traceSendingRequest(message) {
|
|
if (trace === Trace.Off || !tracer) {
|
|
return;
|
|
}
|
|
if (traceFormat === TraceFormat.Text) {
|
|
let data = undefined;
|
|
if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
|
|
data = `Params: ${stringifyTrace(message.params)}`;
|
|
}
|
|
tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
|
|
} else {
|
|
logLSPMessage("send-request", message);
|
|
}
|
|
}
|
|
function traceSendingNotification(message) {
|
|
if (trace === Trace.Off || !tracer) {
|
|
return;
|
|
}
|
|
if (traceFormat === TraceFormat.Text) {
|
|
let data = undefined;
|
|
if (trace === Trace.Verbose || trace === Trace.Compact) {
|
|
if (message.params) {
|
|
data = `Params: ${stringifyTrace(message.params)}`;
|
|
} else {
|
|
data = "No parameters provided.";
|
|
}
|
|
}
|
|
tracer.log(`Sending notification '${message.method}'.`, data);
|
|
} else {
|
|
logLSPMessage("send-notification", message);
|
|
}
|
|
}
|
|
function traceSendingResponse(message, method, startTime) {
|
|
if (trace === Trace.Off || !tracer) {
|
|
return;
|
|
}
|
|
if (traceFormat === TraceFormat.Text) {
|
|
let data = undefined;
|
|
if (trace === Trace.Verbose || trace === Trace.Compact) {
|
|
if (message.error && message.error.data) {
|
|
data = `Error data: ${stringifyTrace(message.error.data)}`;
|
|
} else {
|
|
if (message.result) {
|
|
data = `Result: ${stringifyTrace(message.result)}`;
|
|
} else if (message.error === undefined) {
|
|
data = "No result returned.";
|
|
}
|
|
}
|
|
}
|
|
tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
|
|
} else {
|
|
logLSPMessage("send-response", message);
|
|
}
|
|
}
|
|
function traceReceivedRequest(message) {
|
|
if (trace === Trace.Off || !tracer) {
|
|
return;
|
|
}
|
|
if (traceFormat === TraceFormat.Text) {
|
|
let data = undefined;
|
|
if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
|
|
data = `Params: ${stringifyTrace(message.params)}`;
|
|
}
|
|
tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
|
|
} else {
|
|
logLSPMessage("receive-request", message);
|
|
}
|
|
}
|
|
function traceReceivedNotification(message) {
|
|
if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
|
|
return;
|
|
}
|
|
if (traceFormat === TraceFormat.Text) {
|
|
let data = undefined;
|
|
if (trace === Trace.Verbose || trace === Trace.Compact) {
|
|
if (message.params) {
|
|
data = `Params: ${stringifyTrace(message.params)}`;
|
|
} else {
|
|
data = "No parameters provided.";
|
|
}
|
|
}
|
|
tracer.log(`Received notification '${message.method}'.`, data);
|
|
} else {
|
|
logLSPMessage("receive-notification", message);
|
|
}
|
|
}
|
|
function traceReceivedResponse(message, responsePromise) {
|
|
if (trace === Trace.Off || !tracer) {
|
|
return;
|
|
}
|
|
if (traceFormat === TraceFormat.Text) {
|
|
let data = undefined;
|
|
if (trace === Trace.Verbose || trace === Trace.Compact) {
|
|
if (message.error && message.error.data) {
|
|
data = `Error data: ${stringifyTrace(message.error.data)}`;
|
|
} else {
|
|
if (message.result) {
|
|
data = `Result: ${stringifyTrace(message.result)}`;
|
|
} else if (message.error === undefined) {
|
|
data = "No result returned.";
|
|
}
|
|
}
|
|
}
|
|
if (responsePromise) {
|
|
const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : "";
|
|
tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
|
|
} else {
|
|
tracer.log(`Received response ${message.id} without active response promise.`, data);
|
|
}
|
|
} else {
|
|
logLSPMessage("receive-response", message);
|
|
}
|
|
}
|
|
function logLSPMessage(type, message) {
|
|
if (!tracer || trace === Trace.Off) {
|
|
return;
|
|
}
|
|
const lspMessage = {
|
|
isLSPMessage: true,
|
|
type,
|
|
message,
|
|
timestamp: Date.now()
|
|
};
|
|
tracer.log(lspMessage);
|
|
}
|
|
function throwIfClosedOrDisposed() {
|
|
if (isClosed()) {
|
|
throw new ConnectionError(ConnectionErrors.Closed, "Connection is closed.");
|
|
}
|
|
if (isDisposed()) {
|
|
throw new ConnectionError(ConnectionErrors.Disposed, "Connection is disposed.");
|
|
}
|
|
}
|
|
function throwIfListening() {
|
|
if (isListening()) {
|
|
throw new ConnectionError(ConnectionErrors.AlreadyListening, "Connection is already listening");
|
|
}
|
|
}
|
|
function throwIfNotListening() {
|
|
if (!isListening()) {
|
|
throw new Error("Call listen() first.");
|
|
}
|
|
}
|
|
function undefinedToNull(param) {
|
|
if (param === undefined) {
|
|
return null;
|
|
} else {
|
|
return param;
|
|
}
|
|
}
|
|
function nullToUndefined(param) {
|
|
if (param === null) {
|
|
return;
|
|
} else {
|
|
return param;
|
|
}
|
|
}
|
|
function isNamedParam(param) {
|
|
return param !== undefined && param !== null && !Array.isArray(param) && typeof param === "object";
|
|
}
|
|
function computeSingleParam(parameterStructures, param) {
|
|
switch (parameterStructures) {
|
|
case messages_1.ParameterStructures.auto:
|
|
if (isNamedParam(param)) {
|
|
return nullToUndefined(param);
|
|
} else {
|
|
return [undefinedToNull(param)];
|
|
}
|
|
case messages_1.ParameterStructures.byName:
|
|
if (!isNamedParam(param)) {
|
|
throw new Error(`Received parameters by name but param is not an object literal.`);
|
|
}
|
|
return nullToUndefined(param);
|
|
case messages_1.ParameterStructures.byPosition:
|
|
return [undefinedToNull(param)];
|
|
default:
|
|
throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`);
|
|
}
|
|
}
|
|
function computeMessageParams(type, params) {
|
|
let result;
|
|
const numberOfParams = type.numberOfParams;
|
|
switch (numberOfParams) {
|
|
case 0:
|
|
result = undefined;
|
|
break;
|
|
case 1:
|
|
result = computeSingleParam(type.parameterStructures, params[0]);
|
|
break;
|
|
default:
|
|
result = [];
|
|
for (let i = 0;i < params.length && i < numberOfParams; i++) {
|
|
result.push(undefinedToNull(params[i]));
|
|
}
|
|
if (params.length < numberOfParams) {
|
|
for (let i = params.length;i < numberOfParams; i++) {
|
|
result.push(null);
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
return result;
|
|
}
|
|
const connection = {
|
|
sendNotification: (type, ...args) => {
|
|
throwIfClosedOrDisposed();
|
|
let method;
|
|
let messageParams;
|
|
if (Is.string(type)) {
|
|
method = type;
|
|
const first = args[0];
|
|
let paramStart = 0;
|
|
let parameterStructures = messages_1.ParameterStructures.auto;
|
|
if (messages_1.ParameterStructures.is(first)) {
|
|
paramStart = 1;
|
|
parameterStructures = first;
|
|
}
|
|
const paramEnd = args.length;
|
|
const numberOfParams = paramEnd - paramStart;
|
|
switch (numberOfParams) {
|
|
case 0:
|
|
messageParams = undefined;
|
|
break;
|
|
case 1:
|
|
messageParams = computeSingleParam(parameterStructures, args[paramStart]);
|
|
break;
|
|
default:
|
|
if (parameterStructures === messages_1.ParameterStructures.byName) {
|
|
throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`);
|
|
}
|
|
messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
|
|
break;
|
|
}
|
|
} else {
|
|
const params = args;
|
|
method = type.method;
|
|
messageParams = computeMessageParams(type, params);
|
|
}
|
|
const notificationMessage = {
|
|
jsonrpc: version,
|
|
method,
|
|
params: messageParams
|
|
};
|
|
traceSendingNotification(notificationMessage);
|
|
return messageWriter.write(notificationMessage).catch((error) => {
|
|
logger.error(`Sending notification failed.`);
|
|
throw error;
|
|
});
|
|
},
|
|
onNotification: (type, handler) => {
|
|
throwIfClosedOrDisposed();
|
|
let method;
|
|
if (Is.func(type)) {
|
|
starNotificationHandler = type;
|
|
} else if (handler) {
|
|
if (Is.string(type)) {
|
|
method = type;
|
|
notificationHandlers.set(type, { type: undefined, handler });
|
|
} else {
|
|
method = type.method;
|
|
notificationHandlers.set(type.method, { type, handler });
|
|
}
|
|
}
|
|
return {
|
|
dispose: () => {
|
|
if (method !== undefined) {
|
|
if (notificationHandlers.get(method)?.handler === handler) {
|
|
notificationHandlers.delete(method);
|
|
}
|
|
} else if (starNotificationHandler === type) {
|
|
starNotificationHandler = undefined;
|
|
}
|
|
}
|
|
};
|
|
},
|
|
onProgress: (_type, token, handler) => {
|
|
if (progressHandlers.has(token)) {
|
|
throw new Error(`Progress handler for token ${token} already registered`);
|
|
}
|
|
progressHandlers.set(token, handler);
|
|
return {
|
|
dispose: () => {
|
|
if (progressHandlers.get(token) === handler) {
|
|
progressHandlers.delete(token);
|
|
}
|
|
}
|
|
};
|
|
},
|
|
sendProgress: (_type, token, value) => {
|
|
return connection.sendNotification(ProgressNotification.type, { token, value });
|
|
},
|
|
onUnhandledProgress: unhandledProgressEmitter.event,
|
|
sendRequest: (type, ...args) => {
|
|
throwIfClosedOrDisposed();
|
|
throwIfNotListening();
|
|
function sendCancellation(connection2, id2) {
|
|
const p = cancellationStrategy.sender.sendCancellation(connection2, id2);
|
|
if (p === undefined) {
|
|
logger.log(`Received no promise from cancellation strategy when cancelling id ${id2}`);
|
|
} else {
|
|
p.catch(() => {
|
|
logger.log(`Sending cancellation messages for id ${id2} failed.`);
|
|
});
|
|
}
|
|
}
|
|
let method;
|
|
let messageParams;
|
|
let token = undefined;
|
|
if (Is.string(type)) {
|
|
method = type;
|
|
const first = args[0];
|
|
const last = args[args.length - 1];
|
|
let paramStart = 0;
|
|
let parameterStructures = messages_1.ParameterStructures.auto;
|
|
if (messages_1.ParameterStructures.is(first)) {
|
|
paramStart = 1;
|
|
parameterStructures = first;
|
|
}
|
|
let paramEnd = args.length;
|
|
if (cancellation_1.CancellationToken.is(last)) {
|
|
paramEnd = paramEnd - 1;
|
|
token = last;
|
|
}
|
|
const numberOfParams = paramEnd - paramStart;
|
|
switch (numberOfParams) {
|
|
case 0:
|
|
messageParams = undefined;
|
|
break;
|
|
case 1:
|
|
messageParams = computeSingleParam(parameterStructures, args[paramStart]);
|
|
break;
|
|
default:
|
|
if (parameterStructures === messages_1.ParameterStructures.byName) {
|
|
throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`);
|
|
}
|
|
messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
|
|
break;
|
|
}
|
|
} else {
|
|
const params = args;
|
|
method = type.method;
|
|
messageParams = computeMessageParams(type, params);
|
|
const numberOfParams = type.numberOfParams;
|
|
token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
|
|
}
|
|
const id = sequenceNumber++;
|
|
let disposable;
|
|
let tokenWasCancelled = false;
|
|
if (token !== undefined) {
|
|
if (token.isCancellationRequested) {
|
|
tokenWasCancelled = true;
|
|
} else {
|
|
disposable = token.onCancellationRequested(() => {
|
|
sendCancellation(connection, id);
|
|
});
|
|
}
|
|
}
|
|
const requestMessage = {
|
|
jsonrpc: version,
|
|
id,
|
|
method,
|
|
params: messageParams
|
|
};
|
|
traceSendingRequest(requestMessage);
|
|
if (typeof cancellationStrategy.sender.enableCancellation === "function") {
|
|
cancellationStrategy.sender.enableCancellation(requestMessage);
|
|
}
|
|
return new Promise(async (resolve, reject) => {
|
|
const resolveWithCleanup = (r) => {
|
|
resolve(r);
|
|
cancellationStrategy.sender.cleanup(id);
|
|
disposable?.dispose();
|
|
};
|
|
const rejectWithCleanup = (r) => {
|
|
reject(r);
|
|
cancellationStrategy.sender.cleanup(id);
|
|
disposable?.dispose();
|
|
};
|
|
const responsePromise = { method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup };
|
|
try {
|
|
responsePromises.set(id, responsePromise);
|
|
await messageWriter.write(requestMessage);
|
|
if (tokenWasCancelled) {
|
|
sendCancellation(connection, id);
|
|
}
|
|
} catch (error) {
|
|
responsePromises.delete(id);
|
|
responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : "Unknown reason"));
|
|
logger.error(`Sending request failed.`);
|
|
throw error;
|
|
}
|
|
});
|
|
},
|
|
onRequest: (type, handler) => {
|
|
throwIfClosedOrDisposed();
|
|
let method = null;
|
|
if (StarRequestHandler.is(type)) {
|
|
method = undefined;
|
|
starRequestHandler = type;
|
|
} else if (Is.string(type)) {
|
|
method = null;
|
|
if (handler !== undefined) {
|
|
method = type;
|
|
requestHandlers.set(type, { handler, type: undefined });
|
|
}
|
|
} else {
|
|
if (handler !== undefined) {
|
|
method = type.method;
|
|
requestHandlers.set(type.method, { type, handler });
|
|
}
|
|
}
|
|
return {
|
|
dispose: () => {
|
|
if (method === null) {
|
|
return;
|
|
}
|
|
if (method !== undefined) {
|
|
if (requestHandlers.get(method)?.handler === handler) {
|
|
requestHandlers.delete(method);
|
|
}
|
|
} else if (starRequestHandler === type) {
|
|
starRequestHandler = undefined;
|
|
}
|
|
}
|
|
};
|
|
},
|
|
hasPendingResponse: () => {
|
|
return responsePromises.size > 0;
|
|
},
|
|
trace: async (_value, _tracer, sendNotificationOrTraceOptions) => {
|
|
let _sendNotification = false;
|
|
let _traceFormat = TraceFormat.Text;
|
|
if (sendNotificationOrTraceOptions !== undefined) {
|
|
if (Is.boolean(sendNotificationOrTraceOptions)) {
|
|
_sendNotification = sendNotificationOrTraceOptions;
|
|
} else {
|
|
_sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
|
|
_traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
|
|
}
|
|
}
|
|
trace = _value;
|
|
traceFormat = _traceFormat;
|
|
if (trace === Trace.Off) {
|
|
tracer = undefined;
|
|
} else {
|
|
tracer = _tracer;
|
|
}
|
|
if (_sendNotification && !isClosed() && !isDisposed()) {
|
|
await connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
|
|
}
|
|
},
|
|
onError: errorEmitter.event,
|
|
onClose: closeEmitter.event,
|
|
onUnhandledNotification: unhandledNotificationEmitter.event,
|
|
onDispose: disposeEmitter.event,
|
|
end: () => {
|
|
messageWriter.end();
|
|
},
|
|
dispose: () => {
|
|
if (isDisposed()) {
|
|
return;
|
|
}
|
|
state = ConnectionState.Disposed;
|
|
disposeEmitter.fire(undefined);
|
|
const error = new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected, "Pending response rejected since connection got disposed");
|
|
for (const promise of responsePromises.values()) {
|
|
promise.reject(error);
|
|
}
|
|
responsePromises = new Map;
|
|
requestTokens = new Map;
|
|
knownCanceledRequests = new Set;
|
|
messageQueue = new linkedMap_1.LinkedMap;
|
|
if (Is.func(messageWriter.dispose)) {
|
|
messageWriter.dispose();
|
|
}
|
|
if (Is.func(messageReader.dispose)) {
|
|
messageReader.dispose();
|
|
}
|
|
},
|
|
listen: () => {
|
|
throwIfClosedOrDisposed();
|
|
throwIfListening();
|
|
state = ConnectionState.Listening;
|
|
messageReader.listen(callback);
|
|
},
|
|
inspect: () => {
|
|
(0, ral_1.default)().console.log("inspect");
|
|
}
|
|
};
|
|
connection.onNotification(LogTraceNotification.type, (params) => {
|
|
if (trace === Trace.Off || !tracer) {
|
|
return;
|
|
}
|
|
const verbose = trace === Trace.Verbose || trace === Trace.Compact;
|
|
tracer.log(params.message, verbose ? params.verbose : undefined);
|
|
});
|
|
connection.onNotification(ProgressNotification.type, async (params) => {
|
|
const handler = progressHandlers.get(params.token);
|
|
if (handler) {
|
|
await handler(params.value);
|
|
} else {
|
|
unhandledProgressEmitter.fire(params);
|
|
}
|
|
});
|
|
return connection;
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/common/api.js
|
|
var require_api = __commonJS((exports2) => {
|
|
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
|
|
return mod && mod.__esModule ? mod : { default: mod };
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ProgressType = exports2.ProgressToken = exports2.createMessageConnection = exports2.NullLogger = exports2.ConnectionOptions = exports2.ConnectionStrategy = exports2.AbstractMessageBuffer = exports2.WriteableStreamMessageWriter = exports2.AbstractMessageWriter = exports2.MessageWriter = exports2.ReadableStreamMessageReader = exports2.AbstractMessageReader = exports2.MessageReader = exports2.SharedArrayReceiverStrategy = exports2.SharedArraySenderStrategy = exports2.CancellationToken = exports2.CancellationTokenSource = exports2.Emitter = exports2.Event = exports2.Disposable = exports2.LRUCache = exports2.Touch = exports2.LinkedMap = exports2.ParameterStructures = exports2.NotificationType9 = exports2.NotificationType8 = exports2.NotificationType7 = exports2.NotificationType6 = exports2.NotificationType5 = exports2.NotificationType4 = exports2.NotificationType3 = exports2.NotificationType2 = exports2.NotificationType1 = exports2.NotificationType0 = exports2.NotificationType = exports2.ErrorCodes = exports2.ResponseError = exports2.RequestType9 = exports2.RequestType8 = exports2.RequestType7 = exports2.RequestType6 = exports2.RequestType5 = exports2.RequestType4 = exports2.RequestType3 = exports2.RequestType2 = exports2.RequestType1 = exports2.RequestType0 = exports2.RequestType = exports2.Message = exports2.RAL = undefined;
|
|
exports2.MessageStrategy = exports2.CancellationStrategy = exports2.CancellationSenderStrategy = exports2.RequestCancellationReceiverStrategy = exports2.IdCancellationReceiverStrategy = exports2.CancellationReceiverStrategy = exports2.ConnectionError = exports2.ConnectionErrors = exports2.LogTraceNotification = exports2.SetTraceNotification = exports2.TraceFormat = exports2.TraceValues = exports2.TraceValue = exports2.Trace = undefined;
|
|
var messages_1 = require_messages();
|
|
Object.defineProperty(exports2, "Message", { enumerable: true, get: function() {
|
|
return messages_1.Message;
|
|
} });
|
|
Object.defineProperty(exports2, "RequestType", { enumerable: true, get: function() {
|
|
return messages_1.RequestType;
|
|
} });
|
|
Object.defineProperty(exports2, "RequestType0", { enumerable: true, get: function() {
|
|
return messages_1.RequestType0;
|
|
} });
|
|
Object.defineProperty(exports2, "RequestType1", { enumerable: true, get: function() {
|
|
return messages_1.RequestType1;
|
|
} });
|
|
Object.defineProperty(exports2, "RequestType2", { enumerable: true, get: function() {
|
|
return messages_1.RequestType2;
|
|
} });
|
|
Object.defineProperty(exports2, "RequestType3", { enumerable: true, get: function() {
|
|
return messages_1.RequestType3;
|
|
} });
|
|
Object.defineProperty(exports2, "RequestType4", { enumerable: true, get: function() {
|
|
return messages_1.RequestType4;
|
|
} });
|
|
Object.defineProperty(exports2, "RequestType5", { enumerable: true, get: function() {
|
|
return messages_1.RequestType5;
|
|
} });
|
|
Object.defineProperty(exports2, "RequestType6", { enumerable: true, get: function() {
|
|
return messages_1.RequestType6;
|
|
} });
|
|
Object.defineProperty(exports2, "RequestType7", { enumerable: true, get: function() {
|
|
return messages_1.RequestType7;
|
|
} });
|
|
Object.defineProperty(exports2, "RequestType8", { enumerable: true, get: function() {
|
|
return messages_1.RequestType8;
|
|
} });
|
|
Object.defineProperty(exports2, "RequestType9", { enumerable: true, get: function() {
|
|
return messages_1.RequestType9;
|
|
} });
|
|
Object.defineProperty(exports2, "ResponseError", { enumerable: true, get: function() {
|
|
return messages_1.ResponseError;
|
|
} });
|
|
Object.defineProperty(exports2, "ErrorCodes", { enumerable: true, get: function() {
|
|
return messages_1.ErrorCodes;
|
|
} });
|
|
Object.defineProperty(exports2, "NotificationType", { enumerable: true, get: function() {
|
|
return messages_1.NotificationType;
|
|
} });
|
|
Object.defineProperty(exports2, "NotificationType0", { enumerable: true, get: function() {
|
|
return messages_1.NotificationType0;
|
|
} });
|
|
Object.defineProperty(exports2, "NotificationType1", { enumerable: true, get: function() {
|
|
return messages_1.NotificationType1;
|
|
} });
|
|
Object.defineProperty(exports2, "NotificationType2", { enumerable: true, get: function() {
|
|
return messages_1.NotificationType2;
|
|
} });
|
|
Object.defineProperty(exports2, "NotificationType3", { enumerable: true, get: function() {
|
|
return messages_1.NotificationType3;
|
|
} });
|
|
Object.defineProperty(exports2, "NotificationType4", { enumerable: true, get: function() {
|
|
return messages_1.NotificationType4;
|
|
} });
|
|
Object.defineProperty(exports2, "NotificationType5", { enumerable: true, get: function() {
|
|
return messages_1.NotificationType5;
|
|
} });
|
|
Object.defineProperty(exports2, "NotificationType6", { enumerable: true, get: function() {
|
|
return messages_1.NotificationType6;
|
|
} });
|
|
Object.defineProperty(exports2, "NotificationType7", { enumerable: true, get: function() {
|
|
return messages_1.NotificationType7;
|
|
} });
|
|
Object.defineProperty(exports2, "NotificationType8", { enumerable: true, get: function() {
|
|
return messages_1.NotificationType8;
|
|
} });
|
|
Object.defineProperty(exports2, "NotificationType9", { enumerable: true, get: function() {
|
|
return messages_1.NotificationType9;
|
|
} });
|
|
Object.defineProperty(exports2, "ParameterStructures", { enumerable: true, get: function() {
|
|
return messages_1.ParameterStructures;
|
|
} });
|
|
var linkedMap_1 = require_linkedMap();
|
|
Object.defineProperty(exports2, "LinkedMap", { enumerable: true, get: function() {
|
|
return linkedMap_1.LinkedMap;
|
|
} });
|
|
Object.defineProperty(exports2, "LRUCache", { enumerable: true, get: function() {
|
|
return linkedMap_1.LRUCache;
|
|
} });
|
|
Object.defineProperty(exports2, "Touch", { enumerable: true, get: function() {
|
|
return linkedMap_1.Touch;
|
|
} });
|
|
var disposable_1 = require_disposable();
|
|
Object.defineProperty(exports2, "Disposable", { enumerable: true, get: function() {
|
|
return disposable_1.Disposable;
|
|
} });
|
|
var events_1 = require_events();
|
|
Object.defineProperty(exports2, "Event", { enumerable: true, get: function() {
|
|
return events_1.Event;
|
|
} });
|
|
Object.defineProperty(exports2, "Emitter", { enumerable: true, get: function() {
|
|
return events_1.Emitter;
|
|
} });
|
|
var cancellation_1 = require_cancellation();
|
|
Object.defineProperty(exports2, "CancellationTokenSource", { enumerable: true, get: function() {
|
|
return cancellation_1.CancellationTokenSource;
|
|
} });
|
|
Object.defineProperty(exports2, "CancellationToken", { enumerable: true, get: function() {
|
|
return cancellation_1.CancellationToken;
|
|
} });
|
|
var sharedArrayCancellation_1 = require_sharedArrayCancellation();
|
|
Object.defineProperty(exports2, "SharedArraySenderStrategy", { enumerable: true, get: function() {
|
|
return sharedArrayCancellation_1.SharedArraySenderStrategy;
|
|
} });
|
|
Object.defineProperty(exports2, "SharedArrayReceiverStrategy", { enumerable: true, get: function() {
|
|
return sharedArrayCancellation_1.SharedArrayReceiverStrategy;
|
|
} });
|
|
var messageReader_1 = require_messageReader();
|
|
Object.defineProperty(exports2, "MessageReader", { enumerable: true, get: function() {
|
|
return messageReader_1.MessageReader;
|
|
} });
|
|
Object.defineProperty(exports2, "AbstractMessageReader", { enumerable: true, get: function() {
|
|
return messageReader_1.AbstractMessageReader;
|
|
} });
|
|
Object.defineProperty(exports2, "ReadableStreamMessageReader", { enumerable: true, get: function() {
|
|
return messageReader_1.ReadableStreamMessageReader;
|
|
} });
|
|
var messageWriter_1 = require_messageWriter();
|
|
Object.defineProperty(exports2, "MessageWriter", { enumerable: true, get: function() {
|
|
return messageWriter_1.MessageWriter;
|
|
} });
|
|
Object.defineProperty(exports2, "AbstractMessageWriter", { enumerable: true, get: function() {
|
|
return messageWriter_1.AbstractMessageWriter;
|
|
} });
|
|
Object.defineProperty(exports2, "WriteableStreamMessageWriter", { enumerable: true, get: function() {
|
|
return messageWriter_1.WriteableStreamMessageWriter;
|
|
} });
|
|
var messageBuffer_1 = require_messageBuffer();
|
|
Object.defineProperty(exports2, "AbstractMessageBuffer", { enumerable: true, get: function() {
|
|
return messageBuffer_1.AbstractMessageBuffer;
|
|
} });
|
|
var connection_1 = require_connection();
|
|
Object.defineProperty(exports2, "ConnectionStrategy", { enumerable: true, get: function() {
|
|
return connection_1.ConnectionStrategy;
|
|
} });
|
|
Object.defineProperty(exports2, "ConnectionOptions", { enumerable: true, get: function() {
|
|
return connection_1.ConnectionOptions;
|
|
} });
|
|
Object.defineProperty(exports2, "NullLogger", { enumerable: true, get: function() {
|
|
return connection_1.NullLogger;
|
|
} });
|
|
Object.defineProperty(exports2, "createMessageConnection", { enumerable: true, get: function() {
|
|
return connection_1.createMessageConnection;
|
|
} });
|
|
Object.defineProperty(exports2, "ProgressToken", { enumerable: true, get: function() {
|
|
return connection_1.ProgressToken;
|
|
} });
|
|
Object.defineProperty(exports2, "ProgressType", { enumerable: true, get: function() {
|
|
return connection_1.ProgressType;
|
|
} });
|
|
Object.defineProperty(exports2, "Trace", { enumerable: true, get: function() {
|
|
return connection_1.Trace;
|
|
} });
|
|
Object.defineProperty(exports2, "TraceValue", { enumerable: true, get: function() {
|
|
return connection_1.TraceValue;
|
|
} });
|
|
Object.defineProperty(exports2, "TraceFormat", { enumerable: true, get: function() {
|
|
return connection_1.TraceFormat;
|
|
} });
|
|
Object.defineProperty(exports2, "SetTraceNotification", { enumerable: true, get: function() {
|
|
return connection_1.SetTraceNotification;
|
|
} });
|
|
Object.defineProperty(exports2, "LogTraceNotification", { enumerable: true, get: function() {
|
|
return connection_1.LogTraceNotification;
|
|
} });
|
|
Object.defineProperty(exports2, "ConnectionErrors", { enumerable: true, get: function() {
|
|
return connection_1.ConnectionErrors;
|
|
} });
|
|
Object.defineProperty(exports2, "ConnectionError", { enumerable: true, get: function() {
|
|
return connection_1.ConnectionError;
|
|
} });
|
|
Object.defineProperty(exports2, "CancellationReceiverStrategy", { enumerable: true, get: function() {
|
|
return connection_1.CancellationReceiverStrategy;
|
|
} });
|
|
Object.defineProperty(exports2, "IdCancellationReceiverStrategy", { enumerable: true, get: function() {
|
|
return connection_1.IdCancellationReceiverStrategy;
|
|
} });
|
|
Object.defineProperty(exports2, "RequestCancellationReceiverStrategy", { enumerable: true, get: function() {
|
|
return connection_1.RequestCancellationReceiverStrategy;
|
|
} });
|
|
Object.defineProperty(exports2, "CancellationSenderStrategy", { enumerable: true, get: function() {
|
|
return connection_1.CancellationSenderStrategy;
|
|
} });
|
|
Object.defineProperty(exports2, "CancellationStrategy", { enumerable: true, get: function() {
|
|
return connection_1.CancellationStrategy;
|
|
} });
|
|
Object.defineProperty(exports2, "MessageStrategy", { enumerable: true, get: function() {
|
|
return connection_1.MessageStrategy;
|
|
} });
|
|
Object.defineProperty(exports2, "TraceValues", { enumerable: true, get: function() {
|
|
return connection_1.TraceValues;
|
|
} });
|
|
var ral_1 = __importDefault(require_ral());
|
|
exports2.RAL = ral_1.default;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-types/lib/umd/main.js
|
|
var require_main = __commonJS((exports2, module2) => {
|
|
(function(factory) {
|
|
if (typeof module2 === "object" && typeof module2.exports === "object") {
|
|
var v = factory(require, exports2);
|
|
if (v !== undefined)
|
|
module2.exports = v;
|
|
} else if (typeof define === "function" && define.amd) {
|
|
define(["require", "exports"], factory);
|
|
}
|
|
})(function(require2, exports3) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.TextDocument = exports3.EOL = exports3.WorkspaceFolder = exports3.InlineCompletionContext = exports3.SelectedCompletionInfo = exports3.InlineCompletionTriggerKind = exports3.InlineCompletionList = exports3.InlineCompletionItem = exports3.StringValue = exports3.InlayHint = exports3.InlayHintLabelPart = exports3.InlayHintKind = exports3.InlineValueContext = exports3.InlineValueEvaluatableExpression = exports3.InlineValueVariableLookup = exports3.InlineValueText = exports3.SemanticTokens = exports3.SemanticTokenModifiers = exports3.SemanticTokenTypes = exports3.SelectionRange = exports3.DocumentLink = exports3.FormattingOptions = exports3.CodeLens = exports3.CodeAction = exports3.CodeActionTag = exports3.CodeActionContext = exports3.CodeActionTriggerKind = exports3.CodeActionKind = exports3.DocumentSymbol = exports3.WorkspaceSymbol = exports3.SymbolInformation = exports3.SymbolTag = exports3.SymbolKind = exports3.DocumentHighlight = exports3.DocumentHighlightKind = exports3.SignatureInformation = exports3.ParameterInformation = exports3.Hover = exports3.MarkedString = exports3.CompletionList = exports3.CompletionItem = exports3.CompletionItemLabelDetails = exports3.ApplyKind = exports3.InsertTextMode = exports3.InsertReplaceEdit = exports3.CompletionItemTag = exports3.InsertTextFormat = exports3.CompletionItemKind = exports3.MarkupContent = exports3.MarkupKind = exports3.TextDocumentItem = exports3.LanguageKind = exports3.OptionalVersionedTextDocumentIdentifier = exports3.VersionedTextDocumentIdentifier = exports3.TextDocumentIdentifier = exports3.WorkspaceChange = exports3.SnippetTextEdit = exports3.WorkspaceEdit = exports3.DeleteFile = exports3.RenameFile = exports3.CreateFile = exports3.TextDocumentEdit = exports3.AnnotatedTextEdit = exports3.ChangeAnnotationIdentifier = exports3.ChangeAnnotation = exports3.TextEdit = exports3.Command = exports3.Diagnostic = exports3.CodeDescription = exports3.DiagnosticTag = exports3.DiagnosticSeverity = exports3.DiagnosticRelatedInformation = exports3.FoldingRange = exports3.FoldingRangeKind = exports3.ColorPresentation = exports3.ColorInformation = exports3.Color = exports3.LocationLink = exports3.Location = exports3.Range = exports3.Position = exports3.uinteger = exports3.integer = exports3.URI = exports3.DocumentUri = undefined;
|
|
var DocumentUri;
|
|
(function(DocumentUri2) {
|
|
function is(value) {
|
|
return typeof value === "string";
|
|
}
|
|
DocumentUri2.is = is;
|
|
})(DocumentUri || (exports3.DocumentUri = DocumentUri = {}));
|
|
var URI;
|
|
(function(URI2) {
|
|
function is(value) {
|
|
return typeof value === "string";
|
|
}
|
|
URI2.is = is;
|
|
})(URI || (exports3.URI = URI = {}));
|
|
var integer;
|
|
(function(integer2) {
|
|
integer2.MIN_VALUE = -2147483648;
|
|
integer2.MAX_VALUE = 2147483647;
|
|
function is(value) {
|
|
return typeof value === "number" && integer2.MIN_VALUE <= value && value <= integer2.MAX_VALUE;
|
|
}
|
|
integer2.is = is;
|
|
})(integer || (exports3.integer = integer = {}));
|
|
var uinteger;
|
|
(function(uinteger2) {
|
|
uinteger2.MIN_VALUE = 0;
|
|
uinteger2.MAX_VALUE = 2147483647;
|
|
function is(value) {
|
|
return typeof value === "number" && uinteger2.MIN_VALUE <= value && value <= uinteger2.MAX_VALUE;
|
|
}
|
|
uinteger2.is = is;
|
|
})(uinteger || (exports3.uinteger = uinteger = {}));
|
|
var Position;
|
|
(function(Position2) {
|
|
function create(line, character) {
|
|
if (line === Number.MAX_VALUE) {
|
|
line = uinteger.MAX_VALUE;
|
|
}
|
|
if (character === Number.MAX_VALUE) {
|
|
character = uinteger.MAX_VALUE;
|
|
}
|
|
return { line, character };
|
|
}
|
|
Position2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character);
|
|
}
|
|
Position2.is = is;
|
|
})(Position || (exports3.Position = Position = {}));
|
|
var Range;
|
|
(function(Range2) {
|
|
function create(one, two, three, four) {
|
|
if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) {
|
|
return { start: Position.create(one, two), end: Position.create(three, four) };
|
|
} else if (Position.is(one) && Position.is(two)) {
|
|
return { start: one, end: two };
|
|
} else {
|
|
throw new Error("Range#create called with invalid arguments[".concat(one, ", ").concat(two, ", ").concat(three, ", ").concat(four, "]"));
|
|
}
|
|
}
|
|
Range2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
|
|
}
|
|
Range2.is = is;
|
|
})(Range || (exports3.Range = Range = {}));
|
|
var Location;
|
|
(function(Location2) {
|
|
function create(uri, range) {
|
|
return { uri, range };
|
|
}
|
|
Location2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
|
|
}
|
|
Location2.is = is;
|
|
})(Location || (exports3.Location = Location = {}));
|
|
var LocationLink;
|
|
(function(LocationLink2) {
|
|
function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
|
|
return { targetUri, targetRange, targetSelectionRange, originSelectionRange };
|
|
}
|
|
LocationLink2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) && Range.is(candidate.targetSelectionRange) && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
|
|
}
|
|
LocationLink2.is = is;
|
|
})(LocationLink || (exports3.LocationLink = LocationLink = {}));
|
|
var Color;
|
|
(function(Color2) {
|
|
function create(red, green, blue, alpha) {
|
|
return {
|
|
red,
|
|
green,
|
|
blue,
|
|
alpha
|
|
};
|
|
}
|
|
Color2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Is.numberRange(candidate.red, 0, 1) && Is.numberRange(candidate.green, 0, 1) && Is.numberRange(candidate.blue, 0, 1) && Is.numberRange(candidate.alpha, 0, 1);
|
|
}
|
|
Color2.is = is;
|
|
})(Color || (exports3.Color = Color = {}));
|
|
var ColorInformation;
|
|
(function(ColorInformation2) {
|
|
function create(range, color) {
|
|
return {
|
|
range,
|
|
color
|
|
};
|
|
}
|
|
ColorInformation2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color);
|
|
}
|
|
ColorInformation2.is = is;
|
|
})(ColorInformation || (exports3.ColorInformation = ColorInformation = {}));
|
|
var ColorPresentation;
|
|
(function(ColorPresentation2) {
|
|
function create(label, textEdit, additionalTextEdits) {
|
|
return {
|
|
label,
|
|
textEdit,
|
|
additionalTextEdits
|
|
};
|
|
}
|
|
ColorPresentation2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
|
|
}
|
|
ColorPresentation2.is = is;
|
|
})(ColorPresentation || (exports3.ColorPresentation = ColorPresentation = {}));
|
|
var FoldingRangeKind;
|
|
(function(FoldingRangeKind2) {
|
|
FoldingRangeKind2.Comment = "comment";
|
|
FoldingRangeKind2.Imports = "imports";
|
|
FoldingRangeKind2.Region = "region";
|
|
})(FoldingRangeKind || (exports3.FoldingRangeKind = FoldingRangeKind = {}));
|
|
var FoldingRange;
|
|
(function(FoldingRange2) {
|
|
function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) {
|
|
var result = {
|
|
startLine,
|
|
endLine
|
|
};
|
|
if (Is.defined(startCharacter)) {
|
|
result.startCharacter = startCharacter;
|
|
}
|
|
if (Is.defined(endCharacter)) {
|
|
result.endCharacter = endCharacter;
|
|
}
|
|
if (Is.defined(kind)) {
|
|
result.kind = kind;
|
|
}
|
|
if (Is.defined(collapsedText)) {
|
|
result.collapsedText = collapsedText;
|
|
}
|
|
return result;
|
|
}
|
|
FoldingRange2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
|
|
}
|
|
FoldingRange2.is = is;
|
|
})(FoldingRange || (exports3.FoldingRange = FoldingRange = {}));
|
|
var DiagnosticRelatedInformation;
|
|
(function(DiagnosticRelatedInformation2) {
|
|
function create(location, message) {
|
|
return {
|
|
location,
|
|
message
|
|
};
|
|
}
|
|
DiagnosticRelatedInformation2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
|
|
}
|
|
DiagnosticRelatedInformation2.is = is;
|
|
})(DiagnosticRelatedInformation || (exports3.DiagnosticRelatedInformation = DiagnosticRelatedInformation = {}));
|
|
var DiagnosticSeverity;
|
|
(function(DiagnosticSeverity2) {
|
|
DiagnosticSeverity2.Error = 1;
|
|
DiagnosticSeverity2.Warning = 2;
|
|
DiagnosticSeverity2.Information = 3;
|
|
DiagnosticSeverity2.Hint = 4;
|
|
})(DiagnosticSeverity || (exports3.DiagnosticSeverity = DiagnosticSeverity = {}));
|
|
var DiagnosticTag;
|
|
(function(DiagnosticTag2) {
|
|
DiagnosticTag2.Unnecessary = 1;
|
|
DiagnosticTag2.Deprecated = 2;
|
|
})(DiagnosticTag || (exports3.DiagnosticTag = DiagnosticTag = {}));
|
|
var CodeDescription;
|
|
(function(CodeDescription2) {
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Is.string(candidate.href);
|
|
}
|
|
CodeDescription2.is = is;
|
|
})(CodeDescription || (exports3.CodeDescription = CodeDescription = {}));
|
|
var Diagnostic;
|
|
(function(Diagnostic2) {
|
|
function create(range, message, severity, code, source, relatedInformation) {
|
|
var result = { range, message };
|
|
if (Is.defined(severity)) {
|
|
result.severity = severity;
|
|
}
|
|
if (Is.defined(code)) {
|
|
result.code = code;
|
|
}
|
|
if (Is.defined(source)) {
|
|
result.source = source;
|
|
}
|
|
if (Is.defined(relatedInformation)) {
|
|
result.relatedInformation = relatedInformation;
|
|
}
|
|
return result;
|
|
}
|
|
Diagnostic2.create = create;
|
|
function is(value) {
|
|
var _a;
|
|
var candidate = value;
|
|
return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.message) || MarkupContent.is(candidate.message)) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.undefined(candidate.codeDescription) || Is.string((_a = candidate.codeDescription) === null || _a === undefined ? undefined : _a.href)) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
|
|
}
|
|
Diagnostic2.is = is;
|
|
function is3_17(value) {
|
|
return Is.string(value.message);
|
|
}
|
|
Diagnostic2.is3_17 = is3_17;
|
|
function getMessageString(diagnostic) {
|
|
if (Is.string(diagnostic.message)) {
|
|
return diagnostic.message;
|
|
} else if (MarkupContent.is(diagnostic.message)) {
|
|
return diagnostic.message.value;
|
|
} else {
|
|
throw new Error("Unknown message type ".concat(typeof diagnostic.message));
|
|
}
|
|
}
|
|
Diagnostic2.getMessageString = getMessageString;
|
|
})(Diagnostic || (exports3.Diagnostic = Diagnostic = {}));
|
|
var Command;
|
|
(function(Command2) {
|
|
function create(title, command) {
|
|
var args = [];
|
|
for (var _i = 2;_i < arguments.length; _i++) {
|
|
args[_i - 2] = arguments[_i];
|
|
}
|
|
var result = { title, command };
|
|
if (Is.defined(args) && args.length > 0) {
|
|
result.arguments = args;
|
|
}
|
|
return result;
|
|
}
|
|
Command2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.defined(candidate) && Is.string(candidate.title) && (candidate.tooltip === undefined || Is.string(candidate.tooltip)) && Is.string(candidate.command);
|
|
}
|
|
Command2.is = is;
|
|
})(Command || (exports3.Command = Command = {}));
|
|
var TextEdit;
|
|
(function(TextEdit2) {
|
|
function replace(range, newText) {
|
|
return { range, newText };
|
|
}
|
|
TextEdit2.replace = replace;
|
|
function insert(position, newText) {
|
|
return { range: { start: position, end: position }, newText };
|
|
}
|
|
TextEdit2.insert = insert;
|
|
function del(range) {
|
|
return { range, newText: "" };
|
|
}
|
|
TextEdit2.del = del;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range.is(candidate.range);
|
|
}
|
|
TextEdit2.is = is;
|
|
})(TextEdit || (exports3.TextEdit = TextEdit = {}));
|
|
var ChangeAnnotation;
|
|
(function(ChangeAnnotation2) {
|
|
function create(label, needsConfirmation, description) {
|
|
var result = { label };
|
|
if (needsConfirmation !== undefined) {
|
|
result.needsConfirmation = needsConfirmation;
|
|
}
|
|
if (description !== undefined) {
|
|
result.description = description;
|
|
}
|
|
return result;
|
|
}
|
|
ChangeAnnotation2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === undefined) && (Is.string(candidate.description) || candidate.description === undefined);
|
|
}
|
|
ChangeAnnotation2.is = is;
|
|
})(ChangeAnnotation || (exports3.ChangeAnnotation = ChangeAnnotation = {}));
|
|
var ChangeAnnotationIdentifier;
|
|
(function(ChangeAnnotationIdentifier2) {
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.string(candidate);
|
|
}
|
|
ChangeAnnotationIdentifier2.is = is;
|
|
})(ChangeAnnotationIdentifier || (exports3.ChangeAnnotationIdentifier = ChangeAnnotationIdentifier = {}));
|
|
var AnnotatedTextEdit;
|
|
(function(AnnotatedTextEdit2) {
|
|
function replace(range, newText, annotation) {
|
|
return { range, newText, annotationId: annotation };
|
|
}
|
|
AnnotatedTextEdit2.replace = replace;
|
|
function insert(position, newText, annotation) {
|
|
return { range: { start: position, end: position }, newText, annotationId: annotation };
|
|
}
|
|
AnnotatedTextEdit2.insert = insert;
|
|
function del(range, annotation) {
|
|
return { range, newText: "", annotationId: annotation };
|
|
}
|
|
AnnotatedTextEdit2.del = del;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId));
|
|
}
|
|
AnnotatedTextEdit2.is = is;
|
|
})(AnnotatedTextEdit || (exports3.AnnotatedTextEdit = AnnotatedTextEdit = {}));
|
|
var TextDocumentEdit;
|
|
(function(TextDocumentEdit2) {
|
|
function create(textDocument, edits) {
|
|
return { textDocument, edits };
|
|
}
|
|
TextDocumentEdit2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits);
|
|
}
|
|
TextDocumentEdit2.is = is;
|
|
})(TextDocumentEdit || (exports3.TextDocumentEdit = TextDocumentEdit = {}));
|
|
var CreateFile;
|
|
(function(CreateFile2) {
|
|
function create(uri, options, annotation) {
|
|
var result = {
|
|
kind: "create",
|
|
uri
|
|
};
|
|
if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {
|
|
result.options = options;
|
|
}
|
|
if (annotation !== undefined) {
|
|
result.annotationId = annotation;
|
|
}
|
|
return result;
|
|
}
|
|
CreateFile2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return candidate && candidate.kind === "create" && Is.string(candidate.uri) && (candidate.options === undefined || (candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));
|
|
}
|
|
CreateFile2.is = is;
|
|
})(CreateFile || (exports3.CreateFile = CreateFile = {}));
|
|
var RenameFile;
|
|
(function(RenameFile2) {
|
|
function create(oldUri, newUri, options, annotation) {
|
|
var result = {
|
|
kind: "rename",
|
|
oldUri,
|
|
newUri
|
|
};
|
|
if (options !== undefined && (options.overwrite !== undefined || options.ignoreIfExists !== undefined)) {
|
|
result.options = options;
|
|
}
|
|
if (annotation !== undefined) {
|
|
result.annotationId = annotation;
|
|
}
|
|
return result;
|
|
}
|
|
RenameFile2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return candidate && candidate.kind === "rename" && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === undefined || (candidate.options.overwrite === undefined || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === undefined || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));
|
|
}
|
|
RenameFile2.is = is;
|
|
})(RenameFile || (exports3.RenameFile = RenameFile = {}));
|
|
var DeleteFile;
|
|
(function(DeleteFile2) {
|
|
function create(uri, options, annotation) {
|
|
var result = {
|
|
kind: "delete",
|
|
uri
|
|
};
|
|
if (options !== undefined && (options.recursive !== undefined || options.ignoreIfNotExists !== undefined)) {
|
|
result.options = options;
|
|
}
|
|
if (annotation !== undefined) {
|
|
result.annotationId = annotation;
|
|
}
|
|
return result;
|
|
}
|
|
DeleteFile2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return candidate && candidate.kind === "delete" && Is.string(candidate.uri) && (candidate.options === undefined || (candidate.options.recursive === undefined || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === undefined || Is.boolean(candidate.options.ignoreIfNotExists))) && (candidate.annotationId === undefined || ChangeAnnotationIdentifier.is(candidate.annotationId));
|
|
}
|
|
DeleteFile2.is = is;
|
|
})(DeleteFile || (exports3.DeleteFile = DeleteFile = {}));
|
|
var WorkspaceEdit;
|
|
(function(WorkspaceEdit2) {
|
|
function is(value) {
|
|
var candidate = value;
|
|
return candidate && (candidate.changes !== undefined || candidate.documentChanges !== undefined) && (candidate.documentChanges === undefined || candidate.documentChanges.every(function(change) {
|
|
if (Is.string(change.kind)) {
|
|
return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
|
|
} else {
|
|
return TextDocumentEdit.is(change);
|
|
}
|
|
}));
|
|
}
|
|
WorkspaceEdit2.is = is;
|
|
})(WorkspaceEdit || (exports3.WorkspaceEdit = WorkspaceEdit = {}));
|
|
var TextEditChangeImpl = function() {
|
|
function TextEditChangeImpl2(edits, changeAnnotations) {
|
|
this.edits = edits;
|
|
this.changeAnnotations = changeAnnotations;
|
|
}
|
|
TextEditChangeImpl2.prototype.insert = function(position, newText, annotation) {
|
|
var edit;
|
|
var id;
|
|
if (annotation === undefined) {
|
|
edit = TextEdit.insert(position, newText);
|
|
} else if (ChangeAnnotationIdentifier.is(annotation)) {
|
|
id = annotation;
|
|
edit = AnnotatedTextEdit.insert(position, newText, annotation);
|
|
} else {
|
|
this.assertChangeAnnotations(this.changeAnnotations);
|
|
id = this.changeAnnotations.manage(annotation);
|
|
edit = AnnotatedTextEdit.insert(position, newText, id);
|
|
}
|
|
this.edits.push(edit);
|
|
if (id !== undefined) {
|
|
return id;
|
|
}
|
|
};
|
|
TextEditChangeImpl2.prototype.replace = function(range, newText, annotation) {
|
|
var edit;
|
|
var id;
|
|
if (annotation === undefined) {
|
|
edit = TextEdit.replace(range, newText);
|
|
} else if (ChangeAnnotationIdentifier.is(annotation)) {
|
|
id = annotation;
|
|
edit = AnnotatedTextEdit.replace(range, newText, annotation);
|
|
} else {
|
|
this.assertChangeAnnotations(this.changeAnnotations);
|
|
id = this.changeAnnotations.manage(annotation);
|
|
edit = AnnotatedTextEdit.replace(range, newText, id);
|
|
}
|
|
this.edits.push(edit);
|
|
if (id !== undefined) {
|
|
return id;
|
|
}
|
|
};
|
|
TextEditChangeImpl2.prototype.delete = function(range, annotation) {
|
|
var edit;
|
|
var id;
|
|
if (annotation === undefined) {
|
|
edit = TextEdit.del(range);
|
|
} else if (ChangeAnnotationIdentifier.is(annotation)) {
|
|
id = annotation;
|
|
edit = AnnotatedTextEdit.del(range, annotation);
|
|
} else {
|
|
this.assertChangeAnnotations(this.changeAnnotations);
|
|
id = this.changeAnnotations.manage(annotation);
|
|
edit = AnnotatedTextEdit.del(range, id);
|
|
}
|
|
this.edits.push(edit);
|
|
if (id !== undefined) {
|
|
return id;
|
|
}
|
|
};
|
|
TextEditChangeImpl2.prototype.add = function(edit) {
|
|
this.edits.push(edit);
|
|
};
|
|
TextEditChangeImpl2.prototype.all = function() {
|
|
return this.edits;
|
|
};
|
|
TextEditChangeImpl2.prototype.clear = function() {
|
|
this.edits.splice(0, this.edits.length);
|
|
};
|
|
TextEditChangeImpl2.prototype.assertChangeAnnotations = function(value) {
|
|
if (value === undefined) {
|
|
throw new Error("Text edit change is not configured to manage change annotations.");
|
|
}
|
|
};
|
|
return TextEditChangeImpl2;
|
|
}();
|
|
var SnippetTextEdit;
|
|
(function(SnippetTextEdit2) {
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Range.is(candidate.range) && StringValue.isSnippet(candidate.snippet) && (candidate.annotationId === undefined || (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId)));
|
|
}
|
|
SnippetTextEdit2.is = is;
|
|
})(SnippetTextEdit || (exports3.SnippetTextEdit = SnippetTextEdit = {}));
|
|
var ChangeAnnotations = function() {
|
|
function ChangeAnnotations2(annotations) {
|
|
this._annotations = annotations === undefined ? Object.create(null) : annotations;
|
|
this._counter = 0;
|
|
this._size = 0;
|
|
}
|
|
ChangeAnnotations2.prototype.all = function() {
|
|
return this._annotations;
|
|
};
|
|
Object.defineProperty(ChangeAnnotations2.prototype, "size", {
|
|
get: function() {
|
|
return this._size;
|
|
},
|
|
enumerable: false,
|
|
configurable: true
|
|
});
|
|
ChangeAnnotations2.prototype.manage = function(idOrAnnotation, annotation) {
|
|
var id;
|
|
if (ChangeAnnotationIdentifier.is(idOrAnnotation)) {
|
|
id = idOrAnnotation;
|
|
} else {
|
|
id = this.nextId();
|
|
annotation = idOrAnnotation;
|
|
}
|
|
if (this._annotations[id] !== undefined) {
|
|
throw new Error("Id ".concat(id, " is already in use."));
|
|
}
|
|
if (annotation === undefined) {
|
|
throw new Error("No annotation provided for id ".concat(id));
|
|
}
|
|
this._annotations[id] = annotation;
|
|
this._size++;
|
|
return id;
|
|
};
|
|
ChangeAnnotations2.prototype.nextId = function() {
|
|
this._counter++;
|
|
return this._counter.toString();
|
|
};
|
|
return ChangeAnnotations2;
|
|
}();
|
|
var WorkspaceChange = function() {
|
|
function WorkspaceChange2(workspaceEdit) {
|
|
var _this = this;
|
|
this._textEditChanges = Object.create(null);
|
|
if (workspaceEdit !== undefined) {
|
|
this._workspaceEdit = workspaceEdit;
|
|
if (workspaceEdit.documentChanges) {
|
|
this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations);
|
|
workspaceEdit.changeAnnotations = this._changeAnnotations.all();
|
|
workspaceEdit.documentChanges.forEach(function(change) {
|
|
if (TextDocumentEdit.is(change)) {
|
|
var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations);
|
|
_this._textEditChanges[change.textDocument.uri] = textEditChange;
|
|
}
|
|
});
|
|
} else if (workspaceEdit.changes) {
|
|
Object.keys(workspaceEdit.changes).forEach(function(key) {
|
|
var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
|
|
_this._textEditChanges[key] = textEditChange;
|
|
});
|
|
}
|
|
} else {
|
|
this._workspaceEdit = {};
|
|
}
|
|
}
|
|
Object.defineProperty(WorkspaceChange2.prototype, "edit", {
|
|
get: function() {
|
|
this.initDocumentChanges();
|
|
if (this._changeAnnotations !== undefined) {
|
|
if (this._changeAnnotations.size === 0) {
|
|
this._workspaceEdit.changeAnnotations = undefined;
|
|
} else {
|
|
this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
|
|
}
|
|
}
|
|
return this._workspaceEdit;
|
|
},
|
|
enumerable: false,
|
|
configurable: true
|
|
});
|
|
WorkspaceChange2.prototype.getTextEditChange = function(key) {
|
|
if (OptionalVersionedTextDocumentIdentifier.is(key)) {
|
|
this.initDocumentChanges();
|
|
if (this._workspaceEdit.documentChanges === undefined) {
|
|
throw new Error("Workspace edit is not configured for document changes.");
|
|
}
|
|
var textDocument = { uri: key.uri, version: key.version };
|
|
var result = this._textEditChanges[textDocument.uri];
|
|
if (!result) {
|
|
var edits = [];
|
|
var textDocumentEdit = {
|
|
textDocument,
|
|
edits
|
|
};
|
|
this._workspaceEdit.documentChanges.push(textDocumentEdit);
|
|
result = new TextEditChangeImpl(edits, this._changeAnnotations);
|
|
this._textEditChanges[textDocument.uri] = result;
|
|
}
|
|
return result;
|
|
} else {
|
|
this.initChanges();
|
|
if (this._workspaceEdit.changes === undefined) {
|
|
throw new Error("Workspace edit is not configured for normal text edit changes.");
|
|
}
|
|
var result = this._textEditChanges[key];
|
|
if (!result) {
|
|
var edits = [];
|
|
this._workspaceEdit.changes[key] = edits;
|
|
result = new TextEditChangeImpl(edits);
|
|
this._textEditChanges[key] = result;
|
|
}
|
|
return result;
|
|
}
|
|
};
|
|
WorkspaceChange2.prototype.initDocumentChanges = function() {
|
|
if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {
|
|
this._changeAnnotations = new ChangeAnnotations;
|
|
this._workspaceEdit.documentChanges = [];
|
|
this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
|
|
}
|
|
};
|
|
WorkspaceChange2.prototype.initChanges = function() {
|
|
if (this._workspaceEdit.documentChanges === undefined && this._workspaceEdit.changes === undefined) {
|
|
this._workspaceEdit.changes = Object.create(null);
|
|
}
|
|
};
|
|
WorkspaceChange2.prototype.createFile = function(uri, optionsOrAnnotation, options) {
|
|
this.initDocumentChanges();
|
|
if (this._workspaceEdit.documentChanges === undefined) {
|
|
throw new Error("Workspace edit is not configured for document changes.");
|
|
}
|
|
var annotation;
|
|
if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
|
|
annotation = optionsOrAnnotation;
|
|
} else {
|
|
options = optionsOrAnnotation;
|
|
}
|
|
var operation;
|
|
var id;
|
|
if (annotation === undefined) {
|
|
operation = CreateFile.create(uri, options);
|
|
} else {
|
|
id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
|
|
operation = CreateFile.create(uri, options, id);
|
|
}
|
|
this._workspaceEdit.documentChanges.push(operation);
|
|
if (id !== undefined) {
|
|
return id;
|
|
}
|
|
};
|
|
WorkspaceChange2.prototype.renameFile = function(oldUri, newUri, optionsOrAnnotation, options) {
|
|
this.initDocumentChanges();
|
|
if (this._workspaceEdit.documentChanges === undefined) {
|
|
throw new Error("Workspace edit is not configured for document changes.");
|
|
}
|
|
var annotation;
|
|
if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
|
|
annotation = optionsOrAnnotation;
|
|
} else {
|
|
options = optionsOrAnnotation;
|
|
}
|
|
var operation;
|
|
var id;
|
|
if (annotation === undefined) {
|
|
operation = RenameFile.create(oldUri, newUri, options);
|
|
} else {
|
|
id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
|
|
operation = RenameFile.create(oldUri, newUri, options, id);
|
|
}
|
|
this._workspaceEdit.documentChanges.push(operation);
|
|
if (id !== undefined) {
|
|
return id;
|
|
}
|
|
};
|
|
WorkspaceChange2.prototype.deleteFile = function(uri, optionsOrAnnotation, options) {
|
|
this.initDocumentChanges();
|
|
if (this._workspaceEdit.documentChanges === undefined) {
|
|
throw new Error("Workspace edit is not configured for document changes.");
|
|
}
|
|
var annotation;
|
|
if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
|
|
annotation = optionsOrAnnotation;
|
|
} else {
|
|
options = optionsOrAnnotation;
|
|
}
|
|
var operation;
|
|
var id;
|
|
if (annotation === undefined) {
|
|
operation = DeleteFile.create(uri, options);
|
|
} else {
|
|
id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
|
|
operation = DeleteFile.create(uri, options, id);
|
|
}
|
|
this._workspaceEdit.documentChanges.push(operation);
|
|
if (id !== undefined) {
|
|
return id;
|
|
}
|
|
};
|
|
return WorkspaceChange2;
|
|
}();
|
|
exports3.WorkspaceChange = WorkspaceChange;
|
|
var TextDocumentIdentifier;
|
|
(function(TextDocumentIdentifier2) {
|
|
function create(uri) {
|
|
return { uri };
|
|
}
|
|
TextDocumentIdentifier2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.defined(candidate) && Is.string(candidate.uri);
|
|
}
|
|
TextDocumentIdentifier2.is = is;
|
|
})(TextDocumentIdentifier || (exports3.TextDocumentIdentifier = TextDocumentIdentifier = {}));
|
|
var VersionedTextDocumentIdentifier;
|
|
(function(VersionedTextDocumentIdentifier2) {
|
|
function create(uri, version) {
|
|
return { uri, version };
|
|
}
|
|
VersionedTextDocumentIdentifier2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version);
|
|
}
|
|
VersionedTextDocumentIdentifier2.is = is;
|
|
})(VersionedTextDocumentIdentifier || (exports3.VersionedTextDocumentIdentifier = VersionedTextDocumentIdentifier = {}));
|
|
var OptionalVersionedTextDocumentIdentifier;
|
|
(function(OptionalVersionedTextDocumentIdentifier2) {
|
|
function create(uri, version) {
|
|
return { uri, version };
|
|
}
|
|
OptionalVersionedTextDocumentIdentifier2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version));
|
|
}
|
|
OptionalVersionedTextDocumentIdentifier2.is = is;
|
|
})(OptionalVersionedTextDocumentIdentifier || (exports3.OptionalVersionedTextDocumentIdentifier = OptionalVersionedTextDocumentIdentifier = {}));
|
|
var LanguageKind;
|
|
(function(LanguageKind2) {
|
|
LanguageKind2.ABAP = "abap";
|
|
LanguageKind2.WindowsBat = "bat";
|
|
LanguageKind2.BibTeX = "bibtex";
|
|
LanguageKind2.Clojure = "clojure";
|
|
LanguageKind2.Coffeescript = "coffeescript";
|
|
LanguageKind2.C = "c";
|
|
LanguageKind2.CPP = "cpp";
|
|
LanguageKind2.CSharp = "csharp";
|
|
LanguageKind2.CSS = "css";
|
|
LanguageKind2.D = "d";
|
|
LanguageKind2.Delphi = "pascal";
|
|
LanguageKind2.Diff = "diff";
|
|
LanguageKind2.Dart = "dart";
|
|
LanguageKind2.Dockerfile = "dockerfile";
|
|
LanguageKind2.Elixir = "elixir";
|
|
LanguageKind2.Erlang = "erlang";
|
|
LanguageKind2.FSharp = "fsharp";
|
|
LanguageKind2.GitCommit = "git-commit";
|
|
LanguageKind2.GitRebase = "git-rebase";
|
|
LanguageKind2.Go = "go";
|
|
LanguageKind2.Groovy = "groovy";
|
|
LanguageKind2.Handlebars = "handlebars";
|
|
LanguageKind2.Haskell = "haskell";
|
|
LanguageKind2.HTML = "html";
|
|
LanguageKind2.Ini = "ini";
|
|
LanguageKind2.Java = "java";
|
|
LanguageKind2.JavaScript = "javascript";
|
|
LanguageKind2.JavaScriptReact = "javascriptreact";
|
|
LanguageKind2.JSON = "json";
|
|
LanguageKind2.LaTeX = "latex";
|
|
LanguageKind2.Less = "less";
|
|
LanguageKind2.Lua = "lua";
|
|
LanguageKind2.Makefile = "makefile";
|
|
LanguageKind2.Markdown = "markdown";
|
|
LanguageKind2.ObjectiveC = "objective-c";
|
|
LanguageKind2.ObjectiveCPP = "objective-cpp";
|
|
LanguageKind2.Pascal = "pascal";
|
|
LanguageKind2.Perl = "perl";
|
|
LanguageKind2.Perl6 = "perl6";
|
|
LanguageKind2.PHP = "php";
|
|
LanguageKind2.Plaintext = "plaintext";
|
|
LanguageKind2.Powershell = "powershell";
|
|
LanguageKind2.Pug = "jade";
|
|
LanguageKind2.Python = "python";
|
|
LanguageKind2.R = "r";
|
|
LanguageKind2.Razor = "razor";
|
|
LanguageKind2.Ruby = "ruby";
|
|
LanguageKind2.Rust = "rust";
|
|
LanguageKind2.SCSS = "scss";
|
|
LanguageKind2.SASS = "sass";
|
|
LanguageKind2.Scala = "scala";
|
|
LanguageKind2.ShaderLab = "shaderlab";
|
|
LanguageKind2.ShellScript = "shellscript";
|
|
LanguageKind2.SQL = "sql";
|
|
LanguageKind2.Swift = "swift";
|
|
LanguageKind2.TypeScript = "typescript";
|
|
LanguageKind2.TypeScriptReact = "typescriptreact";
|
|
LanguageKind2.TeX = "tex";
|
|
LanguageKind2.VisualBasic = "vb";
|
|
LanguageKind2.XML = "xml";
|
|
LanguageKind2.XSL = "xsl";
|
|
LanguageKind2.YAML = "yaml";
|
|
})(LanguageKind || (exports3.LanguageKind = LanguageKind = {}));
|
|
var TextDocumentItem;
|
|
(function(TextDocumentItem2) {
|
|
function create(uri, languageId, version, text) {
|
|
return { uri, languageId, version, text };
|
|
}
|
|
TextDocumentItem2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text);
|
|
}
|
|
TextDocumentItem2.is = is;
|
|
})(TextDocumentItem || (exports3.TextDocumentItem = TextDocumentItem = {}));
|
|
var MarkupKind;
|
|
(function(MarkupKind2) {
|
|
MarkupKind2.PlainText = "plaintext";
|
|
MarkupKind2.Markdown = "markdown";
|
|
function is(value) {
|
|
var candidate = value;
|
|
return candidate === MarkupKind2.PlainText || candidate === MarkupKind2.Markdown;
|
|
}
|
|
MarkupKind2.is = is;
|
|
})(MarkupKind || (exports3.MarkupKind = MarkupKind = {}));
|
|
var MarkupContent;
|
|
(function(MarkupContent2) {
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
|
|
}
|
|
MarkupContent2.is = is;
|
|
})(MarkupContent || (exports3.MarkupContent = MarkupContent = {}));
|
|
var CompletionItemKind;
|
|
(function(CompletionItemKind2) {
|
|
CompletionItemKind2.Text = 1;
|
|
CompletionItemKind2.Method = 2;
|
|
CompletionItemKind2.Function = 3;
|
|
CompletionItemKind2.Constructor = 4;
|
|
CompletionItemKind2.Field = 5;
|
|
CompletionItemKind2.Variable = 6;
|
|
CompletionItemKind2.Class = 7;
|
|
CompletionItemKind2.Interface = 8;
|
|
CompletionItemKind2.Module = 9;
|
|
CompletionItemKind2.Property = 10;
|
|
CompletionItemKind2.Unit = 11;
|
|
CompletionItemKind2.Value = 12;
|
|
CompletionItemKind2.Enum = 13;
|
|
CompletionItemKind2.Keyword = 14;
|
|
CompletionItemKind2.Snippet = 15;
|
|
CompletionItemKind2.Color = 16;
|
|
CompletionItemKind2.File = 17;
|
|
CompletionItemKind2.Reference = 18;
|
|
CompletionItemKind2.Folder = 19;
|
|
CompletionItemKind2.EnumMember = 20;
|
|
CompletionItemKind2.Constant = 21;
|
|
CompletionItemKind2.Struct = 22;
|
|
CompletionItemKind2.Event = 23;
|
|
CompletionItemKind2.Operator = 24;
|
|
CompletionItemKind2.TypeParameter = 25;
|
|
})(CompletionItemKind || (exports3.CompletionItemKind = CompletionItemKind = {}));
|
|
var InsertTextFormat;
|
|
(function(InsertTextFormat2) {
|
|
InsertTextFormat2.PlainText = 1;
|
|
InsertTextFormat2.Snippet = 2;
|
|
})(InsertTextFormat || (exports3.InsertTextFormat = InsertTextFormat = {}));
|
|
var CompletionItemTag;
|
|
(function(CompletionItemTag2) {
|
|
CompletionItemTag2.Deprecated = 1;
|
|
})(CompletionItemTag || (exports3.CompletionItemTag = CompletionItemTag = {}));
|
|
var InsertReplaceEdit;
|
|
(function(InsertReplaceEdit2) {
|
|
function create(newText, insert, replace) {
|
|
return { newText, insert, replace };
|
|
}
|
|
InsertReplaceEdit2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace);
|
|
}
|
|
InsertReplaceEdit2.is = is;
|
|
})(InsertReplaceEdit || (exports3.InsertReplaceEdit = InsertReplaceEdit = {}));
|
|
var InsertTextMode;
|
|
(function(InsertTextMode2) {
|
|
InsertTextMode2.asIs = 1;
|
|
InsertTextMode2.adjustIndentation = 2;
|
|
})(InsertTextMode || (exports3.InsertTextMode = InsertTextMode = {}));
|
|
var ApplyKind;
|
|
(function(ApplyKind2) {
|
|
ApplyKind2.Replace = 1;
|
|
ApplyKind2.Merge = 2;
|
|
})(ApplyKind || (exports3.ApplyKind = ApplyKind = {}));
|
|
var CompletionItemLabelDetails;
|
|
(function(CompletionItemLabelDetails2) {
|
|
function is(value) {
|
|
var candidate = value;
|
|
return candidate && (Is.string(candidate.detail) || candidate.detail === undefined) && (Is.string(candidate.description) || candidate.description === undefined);
|
|
}
|
|
CompletionItemLabelDetails2.is = is;
|
|
})(CompletionItemLabelDetails || (exports3.CompletionItemLabelDetails = CompletionItemLabelDetails = {}));
|
|
var CompletionItem;
|
|
(function(CompletionItem2) {
|
|
function create(label) {
|
|
return { label };
|
|
}
|
|
CompletionItem2.create = create;
|
|
})(CompletionItem || (exports3.CompletionItem = CompletionItem = {}));
|
|
var CompletionList;
|
|
(function(CompletionList2) {
|
|
function create(items, isIncomplete) {
|
|
return { items: items ? items : [], isIncomplete: !!isIncomplete };
|
|
}
|
|
CompletionList2.create = create;
|
|
})(CompletionList || (exports3.CompletionList = CompletionList = {}));
|
|
var MarkedString;
|
|
(function(MarkedString2) {
|
|
function fromPlainText(plainText) {
|
|
return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&");
|
|
}
|
|
MarkedString2.fromPlainText = fromPlainText;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.string(candidate) || Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value);
|
|
}
|
|
MarkedString2.is = is;
|
|
})(MarkedString || (exports3.MarkedString = MarkedString = {}));
|
|
var Hover;
|
|
(function(Hover2) {
|
|
function is(value) {
|
|
var candidate = value;
|
|
return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === undefined || Range.is(value.range));
|
|
}
|
|
Hover2.is = is;
|
|
})(Hover || (exports3.Hover = Hover = {}));
|
|
var ParameterInformation;
|
|
(function(ParameterInformation2) {
|
|
function create(label, documentation) {
|
|
return documentation ? { label, documentation } : { label };
|
|
}
|
|
ParameterInformation2.create = create;
|
|
})(ParameterInformation || (exports3.ParameterInformation = ParameterInformation = {}));
|
|
var SignatureInformation;
|
|
(function(SignatureInformation2) {
|
|
function create(label, documentation) {
|
|
var parameters = [];
|
|
for (var _i = 2;_i < arguments.length; _i++) {
|
|
parameters[_i - 2] = arguments[_i];
|
|
}
|
|
var result = { label };
|
|
if (Is.defined(documentation)) {
|
|
result.documentation = documentation;
|
|
}
|
|
if (Is.defined(parameters)) {
|
|
result.parameters = parameters;
|
|
} else {
|
|
result.parameters = [];
|
|
}
|
|
return result;
|
|
}
|
|
SignatureInformation2.create = create;
|
|
})(SignatureInformation || (exports3.SignatureInformation = SignatureInformation = {}));
|
|
var DocumentHighlightKind;
|
|
(function(DocumentHighlightKind2) {
|
|
DocumentHighlightKind2.Text = 1;
|
|
DocumentHighlightKind2.Read = 2;
|
|
DocumentHighlightKind2.Write = 3;
|
|
})(DocumentHighlightKind || (exports3.DocumentHighlightKind = DocumentHighlightKind = {}));
|
|
var DocumentHighlight;
|
|
(function(DocumentHighlight2) {
|
|
function create(range, kind) {
|
|
var result = { range };
|
|
if (Is.number(kind)) {
|
|
result.kind = kind;
|
|
}
|
|
return result;
|
|
}
|
|
DocumentHighlight2.create = create;
|
|
})(DocumentHighlight || (exports3.DocumentHighlight = DocumentHighlight = {}));
|
|
var SymbolKind;
|
|
(function(SymbolKind2) {
|
|
SymbolKind2.File = 1;
|
|
SymbolKind2.Module = 2;
|
|
SymbolKind2.Namespace = 3;
|
|
SymbolKind2.Package = 4;
|
|
SymbolKind2.Class = 5;
|
|
SymbolKind2.Method = 6;
|
|
SymbolKind2.Property = 7;
|
|
SymbolKind2.Field = 8;
|
|
SymbolKind2.Constructor = 9;
|
|
SymbolKind2.Enum = 10;
|
|
SymbolKind2.Interface = 11;
|
|
SymbolKind2.Function = 12;
|
|
SymbolKind2.Variable = 13;
|
|
SymbolKind2.Constant = 14;
|
|
SymbolKind2.String = 15;
|
|
SymbolKind2.Number = 16;
|
|
SymbolKind2.Boolean = 17;
|
|
SymbolKind2.Array = 18;
|
|
SymbolKind2.Object = 19;
|
|
SymbolKind2.Key = 20;
|
|
SymbolKind2.Null = 21;
|
|
SymbolKind2.EnumMember = 22;
|
|
SymbolKind2.Struct = 23;
|
|
SymbolKind2.Event = 24;
|
|
SymbolKind2.Operator = 25;
|
|
SymbolKind2.TypeParameter = 26;
|
|
})(SymbolKind || (exports3.SymbolKind = SymbolKind = {}));
|
|
var SymbolTag;
|
|
(function(SymbolTag2) {
|
|
SymbolTag2.Deprecated = 1;
|
|
})(SymbolTag || (exports3.SymbolTag = SymbolTag = {}));
|
|
var SymbolInformation;
|
|
(function(SymbolInformation2) {
|
|
function create(name, kind, range, uri, containerName) {
|
|
var result = {
|
|
name,
|
|
kind,
|
|
location: { uri, range }
|
|
};
|
|
if (containerName) {
|
|
result.containerName = containerName;
|
|
}
|
|
return result;
|
|
}
|
|
SymbolInformation2.create = create;
|
|
})(SymbolInformation || (exports3.SymbolInformation = SymbolInformation = {}));
|
|
var WorkspaceSymbol;
|
|
(function(WorkspaceSymbol2) {
|
|
function create(name, kind, uri, range) {
|
|
return range !== undefined ? { name, kind, location: { uri, range } } : { name, kind, location: { uri } };
|
|
}
|
|
WorkspaceSymbol2.create = create;
|
|
})(WorkspaceSymbol || (exports3.WorkspaceSymbol = WorkspaceSymbol = {}));
|
|
var DocumentSymbol;
|
|
(function(DocumentSymbol2) {
|
|
function create(name, detail, kind, range, selectionRange, children) {
|
|
var result = {
|
|
name,
|
|
detail,
|
|
kind,
|
|
range,
|
|
selectionRange
|
|
};
|
|
if (children !== undefined) {
|
|
result.children = children;
|
|
}
|
|
return result;
|
|
}
|
|
DocumentSymbol2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range.is(candidate.range) && Range.is(candidate.selectionRange) && (candidate.detail === undefined || Is.string(candidate.detail)) && (candidate.deprecated === undefined || Is.boolean(candidate.deprecated)) && (candidate.children === undefined || Array.isArray(candidate.children)) && (candidate.tags === undefined || Array.isArray(candidate.tags));
|
|
}
|
|
DocumentSymbol2.is = is;
|
|
})(DocumentSymbol || (exports3.DocumentSymbol = DocumentSymbol = {}));
|
|
var CodeActionKind;
|
|
(function(CodeActionKind2) {
|
|
CodeActionKind2.Empty = "";
|
|
CodeActionKind2.QuickFix = "quickfix";
|
|
CodeActionKind2.Refactor = "refactor";
|
|
CodeActionKind2.RefactorExtract = "refactor.extract";
|
|
CodeActionKind2.RefactorInline = "refactor.inline";
|
|
CodeActionKind2.RefactorMove = "refactor.move";
|
|
CodeActionKind2.RefactorRewrite = "refactor.rewrite";
|
|
CodeActionKind2.Source = "source";
|
|
CodeActionKind2.SourceOrganizeImports = "source.organizeImports";
|
|
CodeActionKind2.SourceFixAll = "source.fixAll";
|
|
CodeActionKind2.Notebook = "notebook";
|
|
})(CodeActionKind || (exports3.CodeActionKind = CodeActionKind = {}));
|
|
var CodeActionTriggerKind;
|
|
(function(CodeActionTriggerKind2) {
|
|
CodeActionTriggerKind2.Invoked = 1;
|
|
CodeActionTriggerKind2.Automatic = 2;
|
|
})(CodeActionTriggerKind || (exports3.CodeActionTriggerKind = CodeActionTriggerKind = {}));
|
|
var CodeActionContext;
|
|
(function(CodeActionContext2) {
|
|
function create(diagnostics, only, triggerKind) {
|
|
var result = { diagnostics };
|
|
if (only !== undefined && only !== null) {
|
|
result.only = only;
|
|
}
|
|
if (triggerKind !== undefined && triggerKind !== null) {
|
|
result.triggerKind = triggerKind;
|
|
}
|
|
return result;
|
|
}
|
|
CodeActionContext2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === undefined || Is.typedArray(candidate.only, Is.string)) && (candidate.triggerKind === undefined || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic);
|
|
}
|
|
CodeActionContext2.is = is;
|
|
})(CodeActionContext || (exports3.CodeActionContext = CodeActionContext = {}));
|
|
var CodeActionTag;
|
|
(function(CodeActionTag2) {
|
|
CodeActionTag2.LLMGenerated = 1;
|
|
function is(value) {
|
|
return Is.defined(value) && value === CodeActionTag2.LLMGenerated;
|
|
}
|
|
CodeActionTag2.is = is;
|
|
})(CodeActionTag || (exports3.CodeActionTag = CodeActionTag = {}));
|
|
var CodeAction;
|
|
(function(CodeAction2) {
|
|
function create(title, kindOrCommandOrEdit, kind) {
|
|
var result = { title };
|
|
var checkKind = true;
|
|
if (typeof kindOrCommandOrEdit === "string") {
|
|
checkKind = false;
|
|
result.kind = kindOrCommandOrEdit;
|
|
} else if (Command.is(kindOrCommandOrEdit)) {
|
|
result.command = kindOrCommandOrEdit;
|
|
} else {
|
|
result.edit = kindOrCommandOrEdit;
|
|
}
|
|
if (checkKind && kind !== undefined) {
|
|
result.kind = kind;
|
|
}
|
|
return result;
|
|
}
|
|
CodeAction2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return candidate && Is.string(candidate.title) && (candidate.diagnostics === undefined || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === undefined || Is.string(candidate.kind)) && (candidate.edit !== undefined || candidate.command !== undefined) && (candidate.command === undefined || Command.is(candidate.command)) && (candidate.isPreferred === undefined || Is.boolean(candidate.isPreferred)) && (candidate.edit === undefined || WorkspaceEdit.is(candidate.edit)) && (candidate.tags === undefined || Is.typedArray(candidate.tags, CodeActionTag.is));
|
|
}
|
|
CodeAction2.is = is;
|
|
})(CodeAction || (exports3.CodeAction = CodeAction = {}));
|
|
var CodeLens;
|
|
(function(CodeLens2) {
|
|
function create(range, data) {
|
|
var result = { range };
|
|
if (Is.defined(data)) {
|
|
result.data = data;
|
|
}
|
|
return result;
|
|
}
|
|
CodeLens2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
|
|
}
|
|
CodeLens2.is = is;
|
|
})(CodeLens || (exports3.CodeLens = CodeLens = {}));
|
|
var FormattingOptions;
|
|
(function(FormattingOptions2) {
|
|
function create(tabSize, insertSpaces) {
|
|
return { tabSize, insertSpaces };
|
|
}
|
|
FormattingOptions2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
|
|
}
|
|
FormattingOptions2.is = is;
|
|
})(FormattingOptions || (exports3.FormattingOptions = FormattingOptions = {}));
|
|
var DocumentLink;
|
|
(function(DocumentLink2) {
|
|
function create(range, target, data) {
|
|
return { range, target, data };
|
|
}
|
|
DocumentLink2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
|
|
}
|
|
DocumentLink2.is = is;
|
|
})(DocumentLink || (exports3.DocumentLink = DocumentLink = {}));
|
|
var SelectionRange;
|
|
(function(SelectionRange2) {
|
|
function create(range, parent) {
|
|
return { range, parent };
|
|
}
|
|
SelectionRange2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange2.is(candidate.parent));
|
|
}
|
|
SelectionRange2.is = is;
|
|
})(SelectionRange || (exports3.SelectionRange = SelectionRange = {}));
|
|
var SemanticTokenTypes;
|
|
(function(SemanticTokenTypes2) {
|
|
SemanticTokenTypes2["namespace"] = "namespace";
|
|
SemanticTokenTypes2["type"] = "type";
|
|
SemanticTokenTypes2["class"] = "class";
|
|
SemanticTokenTypes2["enum"] = "enum";
|
|
SemanticTokenTypes2["interface"] = "interface";
|
|
SemanticTokenTypes2["struct"] = "struct";
|
|
SemanticTokenTypes2["typeParameter"] = "typeParameter";
|
|
SemanticTokenTypes2["parameter"] = "parameter";
|
|
SemanticTokenTypes2["variable"] = "variable";
|
|
SemanticTokenTypes2["property"] = "property";
|
|
SemanticTokenTypes2["enumMember"] = "enumMember";
|
|
SemanticTokenTypes2["event"] = "event";
|
|
SemanticTokenTypes2["function"] = "function";
|
|
SemanticTokenTypes2["method"] = "method";
|
|
SemanticTokenTypes2["macro"] = "macro";
|
|
SemanticTokenTypes2["keyword"] = "keyword";
|
|
SemanticTokenTypes2["modifier"] = "modifier";
|
|
SemanticTokenTypes2["comment"] = "comment";
|
|
SemanticTokenTypes2["string"] = "string";
|
|
SemanticTokenTypes2["number"] = "number";
|
|
SemanticTokenTypes2["regexp"] = "regexp";
|
|
SemanticTokenTypes2["operator"] = "operator";
|
|
SemanticTokenTypes2["decorator"] = "decorator";
|
|
SemanticTokenTypes2["label"] = "label";
|
|
})(SemanticTokenTypes || (exports3.SemanticTokenTypes = SemanticTokenTypes = {}));
|
|
var SemanticTokenModifiers;
|
|
(function(SemanticTokenModifiers2) {
|
|
SemanticTokenModifiers2["declaration"] = "declaration";
|
|
SemanticTokenModifiers2["definition"] = "definition";
|
|
SemanticTokenModifiers2["readonly"] = "readonly";
|
|
SemanticTokenModifiers2["static"] = "static";
|
|
SemanticTokenModifiers2["deprecated"] = "deprecated";
|
|
SemanticTokenModifiers2["abstract"] = "abstract";
|
|
SemanticTokenModifiers2["async"] = "async";
|
|
SemanticTokenModifiers2["modification"] = "modification";
|
|
SemanticTokenModifiers2["documentation"] = "documentation";
|
|
SemanticTokenModifiers2["defaultLibrary"] = "defaultLibrary";
|
|
})(SemanticTokenModifiers || (exports3.SemanticTokenModifiers = SemanticTokenModifiers = {}));
|
|
var SemanticTokens;
|
|
(function(SemanticTokens2) {
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && (candidate.resultId === undefined || typeof candidate.resultId === "string") && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === "number");
|
|
}
|
|
SemanticTokens2.is = is;
|
|
})(SemanticTokens || (exports3.SemanticTokens = SemanticTokens = {}));
|
|
var InlineValueText;
|
|
(function(InlineValueText2) {
|
|
function create(range, text) {
|
|
return { range, text };
|
|
}
|
|
InlineValueText2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.string(candidate.text);
|
|
}
|
|
InlineValueText2.is = is;
|
|
})(InlineValueText || (exports3.InlineValueText = InlineValueText = {}));
|
|
var InlineValueVariableLookup;
|
|
(function(InlineValueVariableLookup2) {
|
|
function create(range, variableName, caseSensitiveLookup) {
|
|
return { range, variableName, caseSensitiveLookup };
|
|
}
|
|
InlineValueVariableLookup2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return candidate !== undefined && candidate !== null && Range.is(candidate.range) && Is.boolean(candidate.caseSensitiveLookup) && (Is.string(candidate.variableName) || candidate.variableName === undefined);
|
|
}
|
|
InlineValueVariableLookup2.is = is;
|
|
})(InlineValueVariableLookup || (exports3.InlineValueVariableLookup = InlineValueVariableLookup = {}));
|
|
var InlineValueEvaluatableExpression;
|
|
(function(InlineValueEvaluatableExpression2) {
|
|
function create(range, expression) {
|
|
return { range, expression };
|
|
}
|
|
InlineValueEvaluatableExpression2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return candidate !== undefined && candidate !== null && Range.is(candidate.range) && (Is.string(candidate.expression) || candidate.expression === undefined);
|
|
}
|
|
InlineValueEvaluatableExpression2.is = is;
|
|
})(InlineValueEvaluatableExpression || (exports3.InlineValueEvaluatableExpression = InlineValueEvaluatableExpression = {}));
|
|
var InlineValueContext;
|
|
(function(InlineValueContext2) {
|
|
function create(frameId, stoppedLocation) {
|
|
return { frameId, stoppedLocation };
|
|
}
|
|
InlineValueContext2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.defined(candidate) && Range.is(value.stoppedLocation);
|
|
}
|
|
InlineValueContext2.is = is;
|
|
})(InlineValueContext || (exports3.InlineValueContext = InlineValueContext = {}));
|
|
var InlayHintKind;
|
|
(function(InlayHintKind2) {
|
|
InlayHintKind2.Type = 1;
|
|
InlayHintKind2.Parameter = 2;
|
|
function is(value) {
|
|
return value === 1 || value === 2;
|
|
}
|
|
InlayHintKind2.is = is;
|
|
})(InlayHintKind || (exports3.InlayHintKind = InlayHintKind = {}));
|
|
var InlayHintLabelPart;
|
|
(function(InlayHintLabelPart2) {
|
|
function create(value) {
|
|
return { value };
|
|
}
|
|
InlayHintLabelPart2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.location === undefined || Location.is(candidate.location)) && (candidate.command === undefined || Command.is(candidate.command));
|
|
}
|
|
InlayHintLabelPart2.is = is;
|
|
})(InlayHintLabelPart || (exports3.InlayHintLabelPart = InlayHintLabelPart = {}));
|
|
var InlayHint;
|
|
(function(InlayHint2) {
|
|
function create(position, label, kind) {
|
|
var result = { position, label };
|
|
if (kind !== undefined) {
|
|
result.kind = kind;
|
|
}
|
|
return result;
|
|
}
|
|
InlayHint2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && Position.is(candidate.position) && (Is.string(candidate.label) || Is.typedArray(candidate.label, InlayHintLabelPart.is)) && (candidate.kind === undefined || InlayHintKind.is(candidate.kind)) && candidate.textEdits === undefined || Is.typedArray(candidate.textEdits, TextEdit.is) && (candidate.tooltip === undefined || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.paddingLeft === undefined || Is.boolean(candidate.paddingLeft)) && (candidate.paddingRight === undefined || Is.boolean(candidate.paddingRight));
|
|
}
|
|
InlayHint2.is = is;
|
|
})(InlayHint || (exports3.InlayHint = InlayHint = {}));
|
|
var StringValue;
|
|
(function(StringValue2) {
|
|
function createSnippet(value) {
|
|
return { kind: "snippet", value };
|
|
}
|
|
StringValue2.createSnippet = createSnippet;
|
|
function isSnippet(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && candidate.kind === "snippet" && Is.string(candidate.value);
|
|
}
|
|
StringValue2.isSnippet = isSnippet;
|
|
})(StringValue || (exports3.StringValue = StringValue = {}));
|
|
var InlineCompletionItem;
|
|
(function(InlineCompletionItem2) {
|
|
function create(insertText, filterText, range, command) {
|
|
return { insertText, filterText, range, command };
|
|
}
|
|
InlineCompletionItem2.create = create;
|
|
})(InlineCompletionItem || (exports3.InlineCompletionItem = InlineCompletionItem = {}));
|
|
var InlineCompletionList;
|
|
(function(InlineCompletionList2) {
|
|
function create(items) {
|
|
return { items };
|
|
}
|
|
InlineCompletionList2.create = create;
|
|
})(InlineCompletionList || (exports3.InlineCompletionList = InlineCompletionList = {}));
|
|
var InlineCompletionTriggerKind;
|
|
(function(InlineCompletionTriggerKind2) {
|
|
InlineCompletionTriggerKind2.Invoked = 1;
|
|
InlineCompletionTriggerKind2.Automatic = 2;
|
|
})(InlineCompletionTriggerKind || (exports3.InlineCompletionTriggerKind = InlineCompletionTriggerKind = {}));
|
|
var SelectedCompletionInfo;
|
|
(function(SelectedCompletionInfo2) {
|
|
function create(range, text) {
|
|
return { range, text };
|
|
}
|
|
SelectedCompletionInfo2.create = create;
|
|
})(SelectedCompletionInfo || (exports3.SelectedCompletionInfo = SelectedCompletionInfo = {}));
|
|
var InlineCompletionContext;
|
|
(function(InlineCompletionContext2) {
|
|
function create(triggerKind, selectedCompletionInfo) {
|
|
return { triggerKind, selectedCompletionInfo };
|
|
}
|
|
InlineCompletionContext2.create = create;
|
|
})(InlineCompletionContext || (exports3.InlineCompletionContext = InlineCompletionContext = {}));
|
|
var WorkspaceFolder;
|
|
(function(WorkspaceFolder2) {
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name);
|
|
}
|
|
WorkspaceFolder2.is = is;
|
|
})(WorkspaceFolder || (exports3.WorkspaceFolder = WorkspaceFolder = {}));
|
|
exports3.EOL = [`
|
|
`, `\r
|
|
`, "\r"];
|
|
var TextDocument;
|
|
(function(TextDocument2) {
|
|
function create(uri, languageId, version, content) {
|
|
return new FullTextDocument(uri, languageId, version, content);
|
|
}
|
|
TextDocument2.create = create;
|
|
function is(value) {
|
|
var candidate = value;
|
|
return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
|
|
}
|
|
TextDocument2.is = is;
|
|
function applyEdits(document, edits) {
|
|
var text = document.getText();
|
|
var sortedEdits = mergeSort(edits, function(a, b) {
|
|
var diff = a.range.start.line - b.range.start.line;
|
|
if (diff === 0) {
|
|
return a.range.start.character - b.range.start.character;
|
|
}
|
|
return diff;
|
|
});
|
|
var lastModifiedOffset = text.length;
|
|
for (var i = sortedEdits.length - 1;i >= 0; i--) {
|
|
var e = sortedEdits[i];
|
|
var startOffset = document.offsetAt(e.range.start);
|
|
var endOffset = document.offsetAt(e.range.end);
|
|
if (endOffset <= lastModifiedOffset) {
|
|
text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
|
|
} else {
|
|
throw new Error("Overlapping edit");
|
|
}
|
|
lastModifiedOffset = startOffset;
|
|
}
|
|
return text;
|
|
}
|
|
TextDocument2.applyEdits = applyEdits;
|
|
function mergeSort(data, compare) {
|
|
if (data.length <= 1) {
|
|
return data;
|
|
}
|
|
var p = data.length / 2 | 0;
|
|
var left = data.slice(0, p);
|
|
var right = data.slice(p);
|
|
mergeSort(left, compare);
|
|
mergeSort(right, compare);
|
|
var leftIdx = 0;
|
|
var rightIdx = 0;
|
|
var i = 0;
|
|
while (leftIdx < left.length && rightIdx < right.length) {
|
|
var ret = compare(left[leftIdx], right[rightIdx]);
|
|
if (ret <= 0) {
|
|
data[i++] = left[leftIdx++];
|
|
} else {
|
|
data[i++] = right[rightIdx++];
|
|
}
|
|
}
|
|
while (leftIdx < left.length) {
|
|
data[i++] = left[leftIdx++];
|
|
}
|
|
while (rightIdx < right.length) {
|
|
data[i++] = right[rightIdx++];
|
|
}
|
|
return data;
|
|
}
|
|
})(TextDocument || (exports3.TextDocument = TextDocument = {}));
|
|
var FullTextDocument = function() {
|
|
function FullTextDocument2(uri, languageId, version, content) {
|
|
this._uri = uri;
|
|
this._languageId = languageId;
|
|
this._version = version;
|
|
this._content = content;
|
|
this._lineOffsets = undefined;
|
|
}
|
|
Object.defineProperty(FullTextDocument2.prototype, "uri", {
|
|
get: function() {
|
|
return this._uri;
|
|
},
|
|
enumerable: false,
|
|
configurable: true
|
|
});
|
|
Object.defineProperty(FullTextDocument2.prototype, "languageId", {
|
|
get: function() {
|
|
return this._languageId;
|
|
},
|
|
enumerable: false,
|
|
configurable: true
|
|
});
|
|
Object.defineProperty(FullTextDocument2.prototype, "version", {
|
|
get: function() {
|
|
return this._version;
|
|
},
|
|
enumerable: false,
|
|
configurable: true
|
|
});
|
|
FullTextDocument2.prototype.getText = function(range) {
|
|
if (range) {
|
|
var start = this.offsetAt(range.start);
|
|
var end = this.offsetAt(range.end);
|
|
return this._content.substring(start, end);
|
|
}
|
|
return this._content;
|
|
};
|
|
FullTextDocument2.prototype.update = function(event, version) {
|
|
this._content = event.text;
|
|
this._version = version;
|
|
this._lineOffsets = undefined;
|
|
};
|
|
FullTextDocument2.prototype.getLineOffsets = function() {
|
|
if (this._lineOffsets === undefined) {
|
|
var lineOffsets = [];
|
|
var text = this._content;
|
|
var isLineStart = true;
|
|
for (var i = 0;i < text.length; i++) {
|
|
if (isLineStart) {
|
|
lineOffsets.push(i);
|
|
isLineStart = false;
|
|
}
|
|
var ch = text.charAt(i);
|
|
isLineStart = ch === "\r" || ch === `
|
|
`;
|
|
if (ch === "\r" && i + 1 < text.length && text.charAt(i + 1) === `
|
|
`) {
|
|
i++;
|
|
}
|
|
}
|
|
if (isLineStart && text.length > 0) {
|
|
lineOffsets.push(text.length);
|
|
}
|
|
this._lineOffsets = lineOffsets;
|
|
}
|
|
return this._lineOffsets;
|
|
};
|
|
FullTextDocument2.prototype.positionAt = function(offset) {
|
|
offset = Math.max(Math.min(offset, this._content.length), 0);
|
|
var lineOffsets = this.getLineOffsets();
|
|
var low = 0, high = lineOffsets.length;
|
|
if (high === 0) {
|
|
return Position.create(0, offset);
|
|
}
|
|
while (low < high) {
|
|
var mid = Math.floor((low + high) / 2);
|
|
if (lineOffsets[mid] > offset) {
|
|
high = mid;
|
|
} else {
|
|
low = mid + 1;
|
|
}
|
|
}
|
|
var line = low - 1;
|
|
return Position.create(line, offset - lineOffsets[line]);
|
|
};
|
|
FullTextDocument2.prototype.offsetAt = function(position) {
|
|
var lineOffsets = this.getLineOffsets();
|
|
if (position.line >= lineOffsets.length) {
|
|
return this._content.length;
|
|
} else if (position.line < 0) {
|
|
return 0;
|
|
}
|
|
var lineOffset = lineOffsets[position.line];
|
|
var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length;
|
|
return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
|
|
};
|
|
Object.defineProperty(FullTextDocument2.prototype, "lineCount", {
|
|
get: function() {
|
|
return this.getLineOffsets().length;
|
|
},
|
|
enumerable: false,
|
|
configurable: true
|
|
});
|
|
return FullTextDocument2;
|
|
}();
|
|
var Is;
|
|
(function(Is2) {
|
|
var toString = Object.prototype.toString;
|
|
function defined(value) {
|
|
return typeof value !== "undefined";
|
|
}
|
|
Is2.defined = defined;
|
|
function undefined2(value) {
|
|
return typeof value === "undefined";
|
|
}
|
|
Is2.undefined = undefined2;
|
|
function boolean(value) {
|
|
return value === true || value === false;
|
|
}
|
|
Is2.boolean = boolean;
|
|
function string(value) {
|
|
return toString.call(value) === "[object String]";
|
|
}
|
|
Is2.string = string;
|
|
function number(value) {
|
|
return toString.call(value) === "[object Number]";
|
|
}
|
|
Is2.number = number;
|
|
function numberRange(value, min, max) {
|
|
return toString.call(value) === "[object Number]" && min <= value && value <= max;
|
|
}
|
|
Is2.numberRange = numberRange;
|
|
function integer2(value) {
|
|
return toString.call(value) === "[object Number]" && -2147483648 <= value && value <= 2147483647;
|
|
}
|
|
Is2.integer = integer2;
|
|
function uinteger2(value) {
|
|
return toString.call(value) === "[object Number]" && 0 <= value && value <= 2147483647;
|
|
}
|
|
Is2.uinteger = uinteger2;
|
|
function func(value) {
|
|
return toString.call(value) === "[object Function]";
|
|
}
|
|
Is2.func = func;
|
|
function objectLiteral(value) {
|
|
return value !== null && typeof value === "object";
|
|
}
|
|
Is2.objectLiteral = objectLiteral;
|
|
function typedArray(value, check) {
|
|
return Array.isArray(value) && value.every(check);
|
|
}
|
|
Is2.typedArray = typedArray;
|
|
})(Is || (Is = {}));
|
|
});
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/messages.js
|
|
var require_messages2 = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.CM = exports2.ProtocolNotificationType = exports2.ProtocolNotificationType0 = exports2.ProtocolRequestType = exports2.ProtocolRequestType0 = exports2.RegistrationType = exports2.MessageDirection = undefined;
|
|
var vscode_jsonrpc_1 = require_api();
|
|
var MessageDirection;
|
|
(function(MessageDirection2) {
|
|
MessageDirection2["clientToServer"] = "clientToServer";
|
|
MessageDirection2["serverToClient"] = "serverToClient";
|
|
MessageDirection2["both"] = "both";
|
|
})(MessageDirection || (exports2.MessageDirection = MessageDirection = {}));
|
|
|
|
class RegistrationType {
|
|
____;
|
|
method;
|
|
constructor(method) {
|
|
this.method = method;
|
|
}
|
|
}
|
|
exports2.RegistrationType = RegistrationType;
|
|
|
|
class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
|
|
__;
|
|
___;
|
|
____;
|
|
_pr;
|
|
constructor(method) {
|
|
super(method);
|
|
}
|
|
}
|
|
exports2.ProtocolRequestType0 = ProtocolRequestType0;
|
|
|
|
class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
|
|
__;
|
|
___;
|
|
____;
|
|
_pr;
|
|
constructor(method) {
|
|
super(method, vscode_jsonrpc_1.ParameterStructures.byName);
|
|
}
|
|
}
|
|
exports2.ProtocolRequestType = ProtocolRequestType;
|
|
|
|
class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
|
|
___;
|
|
____;
|
|
constructor(method) {
|
|
super(method);
|
|
}
|
|
}
|
|
exports2.ProtocolNotificationType0 = ProtocolNotificationType0;
|
|
|
|
class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
|
|
___;
|
|
____;
|
|
constructor(method) {
|
|
super(method, vscode_jsonrpc_1.ParameterStructures.byName);
|
|
}
|
|
}
|
|
exports2.ProtocolNotificationType = ProtocolNotificationType;
|
|
var CM;
|
|
(function(CM2) {
|
|
function create(client, server) {
|
|
return { client, server };
|
|
}
|
|
CM2.create = create;
|
|
})(CM || (exports2.CM = CM = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/utils/is.js
|
|
var require_is3 = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.boolean = boolean;
|
|
exports2.string = string;
|
|
exports2.number = number;
|
|
exports2.error = error;
|
|
exports2.func = func;
|
|
exports2.array = array;
|
|
exports2.stringArray = stringArray;
|
|
exports2.typedArray = typedArray;
|
|
exports2.objectLiteral = objectLiteral;
|
|
function boolean(value) {
|
|
return value === true || value === false;
|
|
}
|
|
function string(value) {
|
|
return typeof value === "string" || value instanceof String;
|
|
}
|
|
function number(value) {
|
|
return typeof value === "number" || value instanceof Number;
|
|
}
|
|
function error(value) {
|
|
return value instanceof Error;
|
|
}
|
|
function func(value) {
|
|
return typeof value === "function";
|
|
}
|
|
function array(value) {
|
|
return Array.isArray(value);
|
|
}
|
|
function stringArray(value) {
|
|
return array(value) && value.every((elem) => string(elem));
|
|
}
|
|
function typedArray(value, check) {
|
|
return Array.isArray(value) && value.every(check);
|
|
}
|
|
function objectLiteral(value) {
|
|
return value !== null && typeof value === "object";
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.implementation.js
|
|
var require_protocol_implementation = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ImplementationRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var ImplementationRequest;
|
|
(function(ImplementationRequest2) {
|
|
ImplementationRequest2.method = "textDocument/implementation";
|
|
ImplementationRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
ImplementationRequest2.type = new messages_1.ProtocolRequestType(ImplementationRequest2.method);
|
|
ImplementationRequest2.capabilities = messages_1.CM.create("textDocument.implementation", "implementationProvider");
|
|
})(ImplementationRequest || (exports2.ImplementationRequest = ImplementationRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.typeDefinition.js
|
|
var require_protocol_typeDefinition = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.TypeDefinitionRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var TypeDefinitionRequest;
|
|
(function(TypeDefinitionRequest2) {
|
|
TypeDefinitionRequest2.method = "textDocument/typeDefinition";
|
|
TypeDefinitionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
TypeDefinitionRequest2.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest2.method);
|
|
TypeDefinitionRequest2.capabilities = messages_1.CM.create("textDocument.typeDefinition", "typeDefinitionProvider");
|
|
})(TypeDefinitionRequest || (exports2.TypeDefinitionRequest = TypeDefinitionRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.workspaceFolder.js
|
|
var require_protocol_workspaceFolder = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DidChangeWorkspaceFoldersNotification = exports2.WorkspaceFoldersRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var WorkspaceFoldersRequest;
|
|
(function(WorkspaceFoldersRequest2) {
|
|
WorkspaceFoldersRequest2.method = "workspace/workspaceFolders";
|
|
WorkspaceFoldersRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
WorkspaceFoldersRequest2.type = new messages_1.ProtocolRequestType0(WorkspaceFoldersRequest2.method);
|
|
WorkspaceFoldersRequest2.capabilities = messages_1.CM.create("workspace.workspaceFolders", "workspace.workspaceFolders");
|
|
})(WorkspaceFoldersRequest || (exports2.WorkspaceFoldersRequest = WorkspaceFoldersRequest = {}));
|
|
var DidChangeWorkspaceFoldersNotification;
|
|
(function(DidChangeWorkspaceFoldersNotification2) {
|
|
DidChangeWorkspaceFoldersNotification2.method = "workspace/didChangeWorkspaceFolders";
|
|
DidChangeWorkspaceFoldersNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidChangeWorkspaceFoldersNotification2.type = new messages_1.ProtocolNotificationType(DidChangeWorkspaceFoldersNotification2.method);
|
|
DidChangeWorkspaceFoldersNotification2.capabilities = messages_1.CM.create(undefined, "workspace.workspaceFolders.changeNotifications");
|
|
})(DidChangeWorkspaceFoldersNotification || (exports2.DidChangeWorkspaceFoldersNotification = DidChangeWorkspaceFoldersNotification = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.configuration.js
|
|
var require_protocol_configuration = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ConfigurationRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var ConfigurationRequest;
|
|
(function(ConfigurationRequest2) {
|
|
ConfigurationRequest2.method = "workspace/configuration";
|
|
ConfigurationRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
ConfigurationRequest2.type = new messages_1.ProtocolRequestType(ConfigurationRequest2.method);
|
|
ConfigurationRequest2.capabilities = messages_1.CM.create("workspace.configuration", undefined);
|
|
})(ConfigurationRequest || (exports2.ConfigurationRequest = ConfigurationRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.colorProvider.js
|
|
var require_protocol_colorProvider = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ColorPresentationRequest = exports2.DocumentColorRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var DocumentColorRequest;
|
|
(function(DocumentColorRequest2) {
|
|
DocumentColorRequest2.method = "textDocument/documentColor";
|
|
DocumentColorRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DocumentColorRequest2.type = new messages_1.ProtocolRequestType(DocumentColorRequest2.method);
|
|
DocumentColorRequest2.capabilities = messages_1.CM.create("textDocument.colorProvider", "colorProvider");
|
|
})(DocumentColorRequest || (exports2.DocumentColorRequest = DocumentColorRequest = {}));
|
|
var ColorPresentationRequest;
|
|
(function(ColorPresentationRequest2) {
|
|
ColorPresentationRequest2.method = "textDocument/colorPresentation";
|
|
ColorPresentationRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
ColorPresentationRequest2.type = new messages_1.ProtocolRequestType(ColorPresentationRequest2.method);
|
|
ColorPresentationRequest2.capabilities = messages_1.CM.create("textDocument.colorProvider", "colorProvider");
|
|
})(ColorPresentationRequest || (exports2.ColorPresentationRequest = ColorPresentationRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.foldingRange.js
|
|
var require_protocol_foldingRange = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.FoldingRangeRefreshRequest = exports2.FoldingRangeRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var FoldingRangeRequest;
|
|
(function(FoldingRangeRequest2) {
|
|
FoldingRangeRequest2.method = "textDocument/foldingRange";
|
|
FoldingRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
FoldingRangeRequest2.type = new messages_1.ProtocolRequestType(FoldingRangeRequest2.method);
|
|
FoldingRangeRequest2.capabilities = messages_1.CM.create("textDocument.foldingRange", "foldingRangeProvider");
|
|
})(FoldingRangeRequest || (exports2.FoldingRangeRequest = FoldingRangeRequest = {}));
|
|
var FoldingRangeRefreshRequest;
|
|
(function(FoldingRangeRefreshRequest2) {
|
|
FoldingRangeRefreshRequest2.method = `workspace/foldingRange/refresh`;
|
|
FoldingRangeRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
FoldingRangeRefreshRequest2.type = new messages_1.ProtocolRequestType0(FoldingRangeRefreshRequest2.method);
|
|
FoldingRangeRefreshRequest2.capabilities = messages_1.CM.create("workspace.foldingRange.refreshSupport", undefined);
|
|
})(FoldingRangeRefreshRequest || (exports2.FoldingRangeRefreshRequest = FoldingRangeRefreshRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.declaration.js
|
|
var require_protocol_declaration = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DeclarationRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var DeclarationRequest;
|
|
(function(DeclarationRequest2) {
|
|
DeclarationRequest2.method = "textDocument/declaration";
|
|
DeclarationRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DeclarationRequest2.type = new messages_1.ProtocolRequestType(DeclarationRequest2.method);
|
|
DeclarationRequest2.capabilities = messages_1.CM.create("textDocument.declaration", "declarationProvider");
|
|
})(DeclarationRequest || (exports2.DeclarationRequest = DeclarationRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.selectionRange.js
|
|
var require_protocol_selectionRange = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.SelectionRangeRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var SelectionRangeRequest;
|
|
(function(SelectionRangeRequest2) {
|
|
SelectionRangeRequest2.method = "textDocument/selectionRange";
|
|
SelectionRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
SelectionRangeRequest2.type = new messages_1.ProtocolRequestType(SelectionRangeRequest2.method);
|
|
SelectionRangeRequest2.capabilities = messages_1.CM.create("textDocument.selectionRange", "selectionRangeProvider");
|
|
})(SelectionRangeRequest || (exports2.SelectionRangeRequest = SelectionRangeRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.progress.js
|
|
var require_protocol_progress = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCreateRequest = exports2.WorkDoneProgress = undefined;
|
|
var vscode_jsonrpc_1 = require_api();
|
|
var messages_1 = require_messages2();
|
|
var WorkDoneProgress;
|
|
(function(WorkDoneProgress2) {
|
|
WorkDoneProgress2.type = new vscode_jsonrpc_1.ProgressType;
|
|
function is(value) {
|
|
return value === WorkDoneProgress2.type;
|
|
}
|
|
WorkDoneProgress2.is = is;
|
|
})(WorkDoneProgress || (exports2.WorkDoneProgress = WorkDoneProgress = {}));
|
|
var WorkDoneProgressCreateRequest;
|
|
(function(WorkDoneProgressCreateRequest2) {
|
|
WorkDoneProgressCreateRequest2.method = "window/workDoneProgress/create";
|
|
WorkDoneProgressCreateRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
WorkDoneProgressCreateRequest2.type = new messages_1.ProtocolRequestType(WorkDoneProgressCreateRequest2.method);
|
|
WorkDoneProgressCreateRequest2.capabilities = messages_1.CM.create("window.workDoneProgress", undefined);
|
|
})(WorkDoneProgressCreateRequest || (exports2.WorkDoneProgressCreateRequest = WorkDoneProgressCreateRequest = {}));
|
|
var WorkDoneProgressCancelNotification;
|
|
(function(WorkDoneProgressCancelNotification2) {
|
|
WorkDoneProgressCancelNotification2.method = "window/workDoneProgress/cancel";
|
|
WorkDoneProgressCancelNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
WorkDoneProgressCancelNotification2.type = new messages_1.ProtocolNotificationType(WorkDoneProgressCancelNotification2.method);
|
|
})(WorkDoneProgressCancelNotification || (exports2.WorkDoneProgressCancelNotification = WorkDoneProgressCancelNotification = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.callHierarchy.js
|
|
var require_protocol_callHierarchy = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyIncomingCallsRequest = exports2.CallHierarchyPrepareRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var CallHierarchyPrepareRequest;
|
|
(function(CallHierarchyPrepareRequest2) {
|
|
CallHierarchyPrepareRequest2.method = "textDocument/prepareCallHierarchy";
|
|
CallHierarchyPrepareRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
CallHierarchyPrepareRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest2.method);
|
|
CallHierarchyPrepareRequest2.capabilities = messages_1.CM.create("textDocument.callHierarchy", "callHierarchyProvider");
|
|
})(CallHierarchyPrepareRequest || (exports2.CallHierarchyPrepareRequest = CallHierarchyPrepareRequest = {}));
|
|
var CallHierarchyIncomingCallsRequest;
|
|
(function(CallHierarchyIncomingCallsRequest2) {
|
|
CallHierarchyIncomingCallsRequest2.method = "callHierarchy/incomingCalls";
|
|
CallHierarchyIncomingCallsRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
CallHierarchyIncomingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest2.method);
|
|
CallHierarchyIncomingCallsRequest2.capabilities = messages_1.CM.create("textDocument.callHierarchy", "callHierarchyProvider");
|
|
})(CallHierarchyIncomingCallsRequest || (exports2.CallHierarchyIncomingCallsRequest = CallHierarchyIncomingCallsRequest = {}));
|
|
var CallHierarchyOutgoingCallsRequest;
|
|
(function(CallHierarchyOutgoingCallsRequest2) {
|
|
CallHierarchyOutgoingCallsRequest2.method = "callHierarchy/outgoingCalls";
|
|
CallHierarchyOutgoingCallsRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
CallHierarchyOutgoingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest2.method);
|
|
CallHierarchyOutgoingCallsRequest2.capabilities = messages_1.CM.create("textDocument.callHierarchy", "callHierarchyProvider");
|
|
})(CallHierarchyOutgoingCallsRequest || (exports2.CallHierarchyOutgoingCallsRequest = CallHierarchyOutgoingCallsRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.semanticTokens.js
|
|
var require_protocol_semanticTokens = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.SemanticTokensRefreshRequest = exports2.SemanticTokensRangeRequest = exports2.SemanticTokensDeltaRequest = exports2.SemanticTokensRequest = exports2.SemanticTokensRegistrationType = exports2.TokenFormat = undefined;
|
|
var messages_1 = require_messages2();
|
|
var TokenFormat;
|
|
(function(TokenFormat2) {
|
|
TokenFormat2.Relative = "relative";
|
|
})(TokenFormat || (exports2.TokenFormat = TokenFormat = {}));
|
|
var SemanticTokensRegistrationType;
|
|
(function(SemanticTokensRegistrationType2) {
|
|
SemanticTokensRegistrationType2.method = "textDocument/semanticTokens";
|
|
SemanticTokensRegistrationType2.type = new messages_1.RegistrationType(SemanticTokensRegistrationType2.method);
|
|
})(SemanticTokensRegistrationType || (exports2.SemanticTokensRegistrationType = SemanticTokensRegistrationType = {}));
|
|
var SemanticTokensRequest;
|
|
(function(SemanticTokensRequest2) {
|
|
SemanticTokensRequest2.method = "textDocument/semanticTokens/full";
|
|
SemanticTokensRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
SemanticTokensRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRequest2.method);
|
|
SemanticTokensRequest2.registrationMethod = SemanticTokensRegistrationType.method;
|
|
SemanticTokensRequest2.capabilities = messages_1.CM.create("textDocument.semanticTokens", "semanticTokensProvider");
|
|
})(SemanticTokensRequest || (exports2.SemanticTokensRequest = SemanticTokensRequest = {}));
|
|
var SemanticTokensDeltaRequest;
|
|
(function(SemanticTokensDeltaRequest2) {
|
|
SemanticTokensDeltaRequest2.method = "textDocument/semanticTokens/full/delta";
|
|
SemanticTokensDeltaRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
SemanticTokensDeltaRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensDeltaRequest2.method);
|
|
SemanticTokensDeltaRequest2.registrationMethod = SemanticTokensRegistrationType.method;
|
|
SemanticTokensDeltaRequest2.capabilities = messages_1.CM.create("textDocument.semanticTokens.requests.full.delta", "semanticTokensProvider.full.delta");
|
|
})(SemanticTokensDeltaRequest || (exports2.SemanticTokensDeltaRequest = SemanticTokensDeltaRequest = {}));
|
|
var SemanticTokensRangeRequest;
|
|
(function(SemanticTokensRangeRequest2) {
|
|
SemanticTokensRangeRequest2.method = "textDocument/semanticTokens/range";
|
|
SemanticTokensRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
SemanticTokensRangeRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest2.method);
|
|
SemanticTokensRangeRequest2.registrationMethod = SemanticTokensRegistrationType.method;
|
|
SemanticTokensRangeRequest2.capabilities = messages_1.CM.create("textDocument.semanticTokens.requests.range", "semanticTokensProvider.range");
|
|
})(SemanticTokensRangeRequest || (exports2.SemanticTokensRangeRequest = SemanticTokensRangeRequest = {}));
|
|
var SemanticTokensRefreshRequest;
|
|
(function(SemanticTokensRefreshRequest2) {
|
|
SemanticTokensRefreshRequest2.method = `workspace/semanticTokens/refresh`;
|
|
SemanticTokensRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
SemanticTokensRefreshRequest2.type = new messages_1.ProtocolRequestType0(SemanticTokensRefreshRequest2.method);
|
|
SemanticTokensRefreshRequest2.capabilities = messages_1.CM.create("workspace.semanticTokens.refreshSupport", undefined);
|
|
})(SemanticTokensRefreshRequest || (exports2.SemanticTokensRefreshRequest = SemanticTokensRefreshRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.showDocument.js
|
|
var require_protocol_showDocument = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ShowDocumentRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var ShowDocumentRequest;
|
|
(function(ShowDocumentRequest2) {
|
|
ShowDocumentRequest2.method = "window/showDocument";
|
|
ShowDocumentRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
ShowDocumentRequest2.type = new messages_1.ProtocolRequestType(ShowDocumentRequest2.method);
|
|
ShowDocumentRequest2.capabilities = messages_1.CM.create("window.showDocument.support", undefined);
|
|
})(ShowDocumentRequest || (exports2.ShowDocumentRequest = ShowDocumentRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.linkedEditingRange.js
|
|
var require_protocol_linkedEditingRange = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.LinkedEditingRangeRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var LinkedEditingRangeRequest;
|
|
(function(LinkedEditingRangeRequest2) {
|
|
LinkedEditingRangeRequest2.method = "textDocument/linkedEditingRange";
|
|
LinkedEditingRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
LinkedEditingRangeRequest2.type = new messages_1.ProtocolRequestType(LinkedEditingRangeRequest2.method);
|
|
LinkedEditingRangeRequest2.capabilities = messages_1.CM.create("textDocument.linkedEditingRange", "linkedEditingRangeProvider");
|
|
})(LinkedEditingRangeRequest || (exports2.LinkedEditingRangeRequest = LinkedEditingRangeRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.fileOperations.js
|
|
var require_protocol_fileOperations = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.WillDeleteFilesRequest = exports2.DidDeleteFilesNotification = exports2.DidRenameFilesNotification = exports2.WillRenameFilesRequest = exports2.DidCreateFilesNotification = exports2.WillCreateFilesRequest = exports2.FileOperationPatternKind = undefined;
|
|
var messages_1 = require_messages2();
|
|
var FileOperationPatternKind;
|
|
(function(FileOperationPatternKind2) {
|
|
FileOperationPatternKind2.file = "file";
|
|
FileOperationPatternKind2.folder = "folder";
|
|
})(FileOperationPatternKind || (exports2.FileOperationPatternKind = FileOperationPatternKind = {}));
|
|
var WillCreateFilesRequest;
|
|
(function(WillCreateFilesRequest2) {
|
|
WillCreateFilesRequest2.method = "workspace/willCreateFiles";
|
|
WillCreateFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
WillCreateFilesRequest2.type = new messages_1.ProtocolRequestType(WillCreateFilesRequest2.method);
|
|
WillCreateFilesRequest2.capabilities = messages_1.CM.create("workspace.fileOperations.willCreate", "workspace.fileOperations.willCreate");
|
|
})(WillCreateFilesRequest || (exports2.WillCreateFilesRequest = WillCreateFilesRequest = {}));
|
|
var DidCreateFilesNotification;
|
|
(function(DidCreateFilesNotification2) {
|
|
DidCreateFilesNotification2.method = "workspace/didCreateFiles";
|
|
DidCreateFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidCreateFilesNotification2.type = new messages_1.ProtocolNotificationType(DidCreateFilesNotification2.method);
|
|
DidCreateFilesNotification2.capabilities = messages_1.CM.create("workspace.fileOperations.didCreate", "workspace.fileOperations.didCreate");
|
|
})(DidCreateFilesNotification || (exports2.DidCreateFilesNotification = DidCreateFilesNotification = {}));
|
|
var WillRenameFilesRequest;
|
|
(function(WillRenameFilesRequest2) {
|
|
WillRenameFilesRequest2.method = "workspace/willRenameFiles";
|
|
WillRenameFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
WillRenameFilesRequest2.type = new messages_1.ProtocolRequestType(WillRenameFilesRequest2.method);
|
|
WillRenameFilesRequest2.capabilities = messages_1.CM.create("workspace.fileOperations.willRename", "workspace.fileOperations.willRename");
|
|
})(WillRenameFilesRequest || (exports2.WillRenameFilesRequest = WillRenameFilesRequest = {}));
|
|
var DidRenameFilesNotification;
|
|
(function(DidRenameFilesNotification2) {
|
|
DidRenameFilesNotification2.method = "workspace/didRenameFiles";
|
|
DidRenameFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidRenameFilesNotification2.type = new messages_1.ProtocolNotificationType(DidRenameFilesNotification2.method);
|
|
DidRenameFilesNotification2.capabilities = messages_1.CM.create("workspace.fileOperations.didRename", "workspace.fileOperations.didRename");
|
|
})(DidRenameFilesNotification || (exports2.DidRenameFilesNotification = DidRenameFilesNotification = {}));
|
|
var DidDeleteFilesNotification;
|
|
(function(DidDeleteFilesNotification2) {
|
|
DidDeleteFilesNotification2.method = "workspace/didDeleteFiles";
|
|
DidDeleteFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidDeleteFilesNotification2.type = new messages_1.ProtocolNotificationType(DidDeleteFilesNotification2.method);
|
|
DidDeleteFilesNotification2.capabilities = messages_1.CM.create("workspace.fileOperations.didDelete", "workspace.fileOperations.didDelete");
|
|
})(DidDeleteFilesNotification || (exports2.DidDeleteFilesNotification = DidDeleteFilesNotification = {}));
|
|
var WillDeleteFilesRequest;
|
|
(function(WillDeleteFilesRequest2) {
|
|
WillDeleteFilesRequest2.method = "workspace/willDeleteFiles";
|
|
WillDeleteFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
WillDeleteFilesRequest2.type = new messages_1.ProtocolRequestType(WillDeleteFilesRequest2.method);
|
|
WillDeleteFilesRequest2.capabilities = messages_1.CM.create("workspace.fileOperations.willDelete", "workspace.fileOperations.willDelete");
|
|
})(WillDeleteFilesRequest || (exports2.WillDeleteFilesRequest = WillDeleteFilesRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.moniker.js
|
|
var require_protocol_moniker = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.MonikerRequest = exports2.MonikerKind = exports2.UniquenessLevel = undefined;
|
|
var messages_1 = require_messages2();
|
|
var UniquenessLevel;
|
|
(function(UniquenessLevel2) {
|
|
UniquenessLevel2.document = "document";
|
|
UniquenessLevel2.project = "project";
|
|
UniquenessLevel2.group = "group";
|
|
UniquenessLevel2.scheme = "scheme";
|
|
UniquenessLevel2.global = "global";
|
|
})(UniquenessLevel || (exports2.UniquenessLevel = UniquenessLevel = {}));
|
|
var MonikerKind;
|
|
(function(MonikerKind2) {
|
|
MonikerKind2.$import = "import";
|
|
MonikerKind2.$export = "export";
|
|
MonikerKind2.local = "local";
|
|
})(MonikerKind || (exports2.MonikerKind = MonikerKind = {}));
|
|
var MonikerRequest;
|
|
(function(MonikerRequest2) {
|
|
MonikerRequest2.method = "textDocument/moniker";
|
|
MonikerRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
MonikerRequest2.type = new messages_1.ProtocolRequestType(MonikerRequest2.method);
|
|
MonikerRequest2.capabilities = messages_1.CM.create("textDocument.moniker", "monikerProvider");
|
|
})(MonikerRequest || (exports2.MonikerRequest = MonikerRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.typeHierarchy.js
|
|
var require_protocol_typeHierarchy = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.TypeHierarchySubtypesRequest = exports2.TypeHierarchySupertypesRequest = exports2.TypeHierarchyPrepareRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var TypeHierarchyPrepareRequest;
|
|
(function(TypeHierarchyPrepareRequest2) {
|
|
TypeHierarchyPrepareRequest2.method = "textDocument/prepareTypeHierarchy";
|
|
TypeHierarchyPrepareRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
TypeHierarchyPrepareRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchyPrepareRequest2.method);
|
|
TypeHierarchyPrepareRequest2.capabilities = messages_1.CM.create("textDocument.typeHierarchy", "typeHierarchyProvider");
|
|
})(TypeHierarchyPrepareRequest || (exports2.TypeHierarchyPrepareRequest = TypeHierarchyPrepareRequest = {}));
|
|
var TypeHierarchySupertypesRequest;
|
|
(function(TypeHierarchySupertypesRequest2) {
|
|
TypeHierarchySupertypesRequest2.method = "typeHierarchy/supertypes";
|
|
TypeHierarchySupertypesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
TypeHierarchySupertypesRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchySupertypesRequest2.method);
|
|
})(TypeHierarchySupertypesRequest || (exports2.TypeHierarchySupertypesRequest = TypeHierarchySupertypesRequest = {}));
|
|
var TypeHierarchySubtypesRequest;
|
|
(function(TypeHierarchySubtypesRequest2) {
|
|
TypeHierarchySubtypesRequest2.method = "typeHierarchy/subtypes";
|
|
TypeHierarchySubtypesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
TypeHierarchySubtypesRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchySubtypesRequest2.method);
|
|
})(TypeHierarchySubtypesRequest || (exports2.TypeHierarchySubtypesRequest = TypeHierarchySubtypesRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineValue.js
|
|
var require_protocol_inlineValue = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.InlineValueRefreshRequest = exports2.InlineValueRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var InlineValueRequest;
|
|
(function(InlineValueRequest2) {
|
|
InlineValueRequest2.method = "textDocument/inlineValue";
|
|
InlineValueRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
InlineValueRequest2.type = new messages_1.ProtocolRequestType(InlineValueRequest2.method);
|
|
InlineValueRequest2.capabilities = messages_1.CM.create("textDocument.inlineValue", "inlineValueProvider");
|
|
})(InlineValueRequest || (exports2.InlineValueRequest = InlineValueRequest = {}));
|
|
var InlineValueRefreshRequest;
|
|
(function(InlineValueRefreshRequest2) {
|
|
InlineValueRefreshRequest2.method = `workspace/inlineValue/refresh`;
|
|
InlineValueRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
InlineValueRefreshRequest2.type = new messages_1.ProtocolRequestType0(InlineValueRefreshRequest2.method);
|
|
InlineValueRefreshRequest2.capabilities = messages_1.CM.create("workspace.inlineValue.refreshSupport", undefined);
|
|
})(InlineValueRefreshRequest || (exports2.InlineValueRefreshRequest = InlineValueRefreshRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlayHint.js
|
|
var require_protocol_inlayHint = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.InlayHintRefreshRequest = exports2.InlayHintResolveRequest = exports2.InlayHintRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var InlayHintRequest;
|
|
(function(InlayHintRequest2) {
|
|
InlayHintRequest2.method = "textDocument/inlayHint";
|
|
InlayHintRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
InlayHintRequest2.type = new messages_1.ProtocolRequestType(InlayHintRequest2.method);
|
|
InlayHintRequest2.capabilities = messages_1.CM.create("textDocument.inlayHint", "inlayHintProvider");
|
|
})(InlayHintRequest || (exports2.InlayHintRequest = InlayHintRequest = {}));
|
|
var InlayHintResolveRequest;
|
|
(function(InlayHintResolveRequest2) {
|
|
InlayHintResolveRequest2.method = "inlayHint/resolve";
|
|
InlayHintResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
InlayHintResolveRequest2.type = new messages_1.ProtocolRequestType(InlayHintResolveRequest2.method);
|
|
InlayHintResolveRequest2.capabilities = messages_1.CM.create("textDocument.inlayHint.resolveSupport", "inlayHintProvider.resolveProvider");
|
|
})(InlayHintResolveRequest || (exports2.InlayHintResolveRequest = InlayHintResolveRequest = {}));
|
|
var InlayHintRefreshRequest;
|
|
(function(InlayHintRefreshRequest2) {
|
|
InlayHintRefreshRequest2.method = `workspace/inlayHint/refresh`;
|
|
InlayHintRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
InlayHintRefreshRequest2.type = new messages_1.ProtocolRequestType0(InlayHintRefreshRequest2.method);
|
|
InlayHintRefreshRequest2.capabilities = messages_1.CM.create("workspace.inlayHint.refreshSupport", undefined);
|
|
})(InlayHintRefreshRequest || (exports2.InlayHintRefreshRequest = InlayHintRefreshRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.diagnostic.js
|
|
var require_protocol_diagnostic = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DiagnosticRefreshRequest = exports2.WorkspaceDiagnosticRequest = exports2.DocumentDiagnosticRequest = exports2.DocumentDiagnosticReportKind = exports2.DiagnosticServerCancellationData = undefined;
|
|
var vscode_jsonrpc_1 = require_api();
|
|
var Is = __importStar(require_is3());
|
|
var messages_1 = require_messages2();
|
|
var DiagnosticServerCancellationData;
|
|
(function(DiagnosticServerCancellationData2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && Is.boolean(candidate.retriggerRequest);
|
|
}
|
|
DiagnosticServerCancellationData2.is = is;
|
|
})(DiagnosticServerCancellationData || (exports2.DiagnosticServerCancellationData = DiagnosticServerCancellationData = {}));
|
|
var DocumentDiagnosticReportKind;
|
|
(function(DocumentDiagnosticReportKind2) {
|
|
DocumentDiagnosticReportKind2.Full = "full";
|
|
DocumentDiagnosticReportKind2.Unchanged = "unchanged";
|
|
})(DocumentDiagnosticReportKind || (exports2.DocumentDiagnosticReportKind = DocumentDiagnosticReportKind = {}));
|
|
var DocumentDiagnosticRequest;
|
|
(function(DocumentDiagnosticRequest2) {
|
|
DocumentDiagnosticRequest2.method = "textDocument/diagnostic";
|
|
DocumentDiagnosticRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DocumentDiagnosticRequest2.type = new messages_1.ProtocolRequestType(DocumentDiagnosticRequest2.method);
|
|
DocumentDiagnosticRequest2.partialResult = new vscode_jsonrpc_1.ProgressType;
|
|
DocumentDiagnosticRequest2.capabilities = messages_1.CM.create("textDocument.diagnostic", "diagnosticProvider");
|
|
})(DocumentDiagnosticRequest || (exports2.DocumentDiagnosticRequest = DocumentDiagnosticRequest = {}));
|
|
var WorkspaceDiagnosticRequest;
|
|
(function(WorkspaceDiagnosticRequest2) {
|
|
WorkspaceDiagnosticRequest2.method = "workspace/diagnostic";
|
|
WorkspaceDiagnosticRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
WorkspaceDiagnosticRequest2.type = new messages_1.ProtocolRequestType(WorkspaceDiagnosticRequest2.method);
|
|
WorkspaceDiagnosticRequest2.partialResult = new vscode_jsonrpc_1.ProgressType;
|
|
WorkspaceDiagnosticRequest2.capabilities = messages_1.CM.create("workspace.diagnostics", "diagnosticProvider.workspaceDiagnostics");
|
|
})(WorkspaceDiagnosticRequest || (exports2.WorkspaceDiagnosticRequest = WorkspaceDiagnosticRequest = {}));
|
|
var DiagnosticRefreshRequest;
|
|
(function(DiagnosticRefreshRequest2) {
|
|
DiagnosticRefreshRequest2.method = `workspace/diagnostic/refresh`;
|
|
DiagnosticRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
DiagnosticRefreshRequest2.type = new messages_1.ProtocolRequestType0(DiagnosticRefreshRequest2.method);
|
|
DiagnosticRefreshRequest2.capabilities = messages_1.CM.create("workspace.diagnostics.refreshSupport", undefined);
|
|
})(DiagnosticRefreshRequest || (exports2.DiagnosticRefreshRequest = DiagnosticRefreshRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.notebook.js
|
|
var require_protocol_notebook = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DidCloseNotebookDocumentNotification = exports2.DidSaveNotebookDocumentNotification = exports2.DidChangeNotebookDocumentNotification = exports2.NotebookCellArrayChange = exports2.DidOpenNotebookDocumentNotification = exports2.NotebookDocumentSyncRegistrationType = exports2.NotebookDocument = exports2.NotebookCell = exports2.ExecutionSummary = exports2.NotebookCellKind = undefined;
|
|
var vscode_languageserver_types_1 = require_main();
|
|
var Is = __importStar(require_is3());
|
|
var messages_1 = require_messages2();
|
|
var NotebookCellKind;
|
|
(function(NotebookCellKind2) {
|
|
NotebookCellKind2.Markup = 1;
|
|
NotebookCellKind2.Code = 2;
|
|
function is(value) {
|
|
return value === 1 || value === 2;
|
|
}
|
|
NotebookCellKind2.is = is;
|
|
})(NotebookCellKind || (exports2.NotebookCellKind = NotebookCellKind = {}));
|
|
var ExecutionSummary;
|
|
(function(ExecutionSummary2) {
|
|
function create(executionOrder, success) {
|
|
const result = { executionOrder };
|
|
if (success === true || success === false) {
|
|
result.success = success;
|
|
}
|
|
return result;
|
|
}
|
|
ExecutionSummary2.create = create;
|
|
function is(value) {
|
|
const candidate = value;
|
|
return Is.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.executionOrder) && (candidate.success === undefined || Is.boolean(candidate.success));
|
|
}
|
|
ExecutionSummary2.is = is;
|
|
function equals(one, other) {
|
|
if (one === other) {
|
|
return true;
|
|
}
|
|
if (one === null || one === undefined || other === null || other === undefined) {
|
|
return false;
|
|
}
|
|
return one.executionOrder === other.executionOrder && one.success === other.success;
|
|
}
|
|
ExecutionSummary2.equals = equals;
|
|
})(ExecutionSummary || (exports2.ExecutionSummary = ExecutionSummary = {}));
|
|
var NotebookCell;
|
|
(function(NotebookCell2) {
|
|
function create(kind, document) {
|
|
return { kind, document };
|
|
}
|
|
NotebookCell2.create = create;
|
|
function is(value) {
|
|
const candidate = value;
|
|
return Is.objectLiteral(candidate) && NotebookCellKind.is(candidate.kind) && vscode_languageserver_types_1.DocumentUri.is(candidate.document) && (candidate.metadata === undefined || Is.objectLiteral(candidate.metadata));
|
|
}
|
|
NotebookCell2.is = is;
|
|
function diff(one, two) {
|
|
const result = new Set;
|
|
if (one.document !== two.document) {
|
|
result.add("document");
|
|
}
|
|
if (one.kind !== two.kind) {
|
|
result.add("kind");
|
|
}
|
|
if (one.executionSummary !== two.executionSummary) {
|
|
result.add("executionSummary");
|
|
}
|
|
if ((one.metadata !== undefined || two.metadata !== undefined) && !equalsMetadata(one.metadata, two.metadata)) {
|
|
result.add("metadata");
|
|
}
|
|
if ((one.executionSummary !== undefined || two.executionSummary !== undefined) && !ExecutionSummary.equals(one.executionSummary, two.executionSummary)) {
|
|
result.add("executionSummary");
|
|
}
|
|
return result;
|
|
}
|
|
NotebookCell2.diff = diff;
|
|
function equalsMetadata(one, other) {
|
|
if (one === other) {
|
|
return true;
|
|
}
|
|
if (one === null || one === undefined || other === null || other === undefined) {
|
|
return false;
|
|
}
|
|
if (typeof one !== typeof other) {
|
|
return false;
|
|
}
|
|
if (typeof one !== "object") {
|
|
return false;
|
|
}
|
|
const oneArray = Array.isArray(one);
|
|
const otherArray = Array.isArray(other);
|
|
if (oneArray !== otherArray) {
|
|
return false;
|
|
}
|
|
if (oneArray && otherArray) {
|
|
if (one.length !== other.length) {
|
|
return false;
|
|
}
|
|
for (let i = 0;i < one.length; i++) {
|
|
if (!equalsMetadata(one[i], other[i])) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
if (Is.objectLiteral(one) && Is.objectLiteral(other)) {
|
|
const oneKeys = Object.keys(one);
|
|
const otherKeys = Object.keys(other);
|
|
if (oneKeys.length !== otherKeys.length) {
|
|
return false;
|
|
}
|
|
oneKeys.sort();
|
|
otherKeys.sort();
|
|
if (!equalsMetadata(oneKeys, otherKeys)) {
|
|
return false;
|
|
}
|
|
for (let i = 0;i < oneKeys.length; i++) {
|
|
const prop = oneKeys[i];
|
|
if (!equalsMetadata(one[prop], other[prop])) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
})(NotebookCell || (exports2.NotebookCell = NotebookCell = {}));
|
|
var NotebookDocument;
|
|
(function(NotebookDocument2) {
|
|
function create(uri, notebookType, version, cells) {
|
|
return { uri, notebookType, version, cells };
|
|
}
|
|
NotebookDocument2.create = create;
|
|
function is(value) {
|
|
const candidate = value;
|
|
return Is.objectLiteral(candidate) && Is.string(candidate.uri) && vscode_languageserver_types_1.integer.is(candidate.version) && Is.typedArray(candidate.cells, NotebookCell.is);
|
|
}
|
|
NotebookDocument2.is = is;
|
|
})(NotebookDocument || (exports2.NotebookDocument = NotebookDocument = {}));
|
|
var NotebookDocumentSyncRegistrationType;
|
|
(function(NotebookDocumentSyncRegistrationType2) {
|
|
NotebookDocumentSyncRegistrationType2.method = "notebookDocument/sync";
|
|
NotebookDocumentSyncRegistrationType2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
NotebookDocumentSyncRegistrationType2.type = new messages_1.RegistrationType(NotebookDocumentSyncRegistrationType2.method);
|
|
})(NotebookDocumentSyncRegistrationType || (exports2.NotebookDocumentSyncRegistrationType = NotebookDocumentSyncRegistrationType = {}));
|
|
var DidOpenNotebookDocumentNotification;
|
|
(function(DidOpenNotebookDocumentNotification2) {
|
|
DidOpenNotebookDocumentNotification2.method = "notebookDocument/didOpen";
|
|
DidOpenNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidOpenNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidOpenNotebookDocumentNotification2.method);
|
|
DidOpenNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
|
|
})(DidOpenNotebookDocumentNotification || (exports2.DidOpenNotebookDocumentNotification = DidOpenNotebookDocumentNotification = {}));
|
|
var NotebookCellArrayChange;
|
|
(function(NotebookCellArrayChange2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return Is.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.start) && vscode_languageserver_types_1.uinteger.is(candidate.deleteCount) && (candidate.cells === undefined || Is.typedArray(candidate.cells, NotebookCell.is));
|
|
}
|
|
NotebookCellArrayChange2.is = is;
|
|
function create(start, deleteCount, cells) {
|
|
const result = { start, deleteCount };
|
|
if (cells !== undefined) {
|
|
result.cells = cells;
|
|
}
|
|
return result;
|
|
}
|
|
NotebookCellArrayChange2.create = create;
|
|
})(NotebookCellArrayChange || (exports2.NotebookCellArrayChange = NotebookCellArrayChange = {}));
|
|
var DidChangeNotebookDocumentNotification;
|
|
(function(DidChangeNotebookDocumentNotification2) {
|
|
DidChangeNotebookDocumentNotification2.method = "notebookDocument/didChange";
|
|
DidChangeNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidChangeNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidChangeNotebookDocumentNotification2.method);
|
|
DidChangeNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
|
|
})(DidChangeNotebookDocumentNotification || (exports2.DidChangeNotebookDocumentNotification = DidChangeNotebookDocumentNotification = {}));
|
|
var DidSaveNotebookDocumentNotification;
|
|
(function(DidSaveNotebookDocumentNotification2) {
|
|
DidSaveNotebookDocumentNotification2.method = "notebookDocument/didSave";
|
|
DidSaveNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidSaveNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidSaveNotebookDocumentNotification2.method);
|
|
DidSaveNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
|
|
})(DidSaveNotebookDocumentNotification || (exports2.DidSaveNotebookDocumentNotification = DidSaveNotebookDocumentNotification = {}));
|
|
var DidCloseNotebookDocumentNotification;
|
|
(function(DidCloseNotebookDocumentNotification2) {
|
|
DidCloseNotebookDocumentNotification2.method = "notebookDocument/didClose";
|
|
DidCloseNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidCloseNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidCloseNotebookDocumentNotification2.method);
|
|
DidCloseNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
|
|
})(DidCloseNotebookDocumentNotification || (exports2.DidCloseNotebookDocumentNotification = DidCloseNotebookDocumentNotification = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineCompletion.js
|
|
var require_protocol_inlineCompletion = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.InlineCompletionRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var InlineCompletionRequest;
|
|
(function(InlineCompletionRequest2) {
|
|
InlineCompletionRequest2.method = "textDocument/inlineCompletion";
|
|
InlineCompletionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
InlineCompletionRequest2.type = new messages_1.ProtocolRequestType(InlineCompletionRequest2.method);
|
|
InlineCompletionRequest2.capabilities = messages_1.CM.create("textDocument.inlineCompletion", "inlineCompletionProvider");
|
|
})(InlineCompletionRequest || (exports2.InlineCompletionRequest = InlineCompletionRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.textDocumentContent.js
|
|
var require_protocol_textDocumentContent = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.TextDocumentContentRefreshRequest = exports2.TextDocumentContentRequest = undefined;
|
|
var messages_1 = require_messages2();
|
|
var TextDocumentContentRequest;
|
|
(function(TextDocumentContentRequest2) {
|
|
TextDocumentContentRequest2.method = "workspace/textDocumentContent";
|
|
TextDocumentContentRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
TextDocumentContentRequest2.type = new messages_1.ProtocolRequestType(TextDocumentContentRequest2.method);
|
|
TextDocumentContentRequest2.capabilities = messages_1.CM.create("workspace.textDocumentContent", "workspace.textDocumentContent");
|
|
})(TextDocumentContentRequest || (exports2.TextDocumentContentRequest = TextDocumentContentRequest = {}));
|
|
var TextDocumentContentRefreshRequest;
|
|
(function(TextDocumentContentRefreshRequest2) {
|
|
TextDocumentContentRefreshRequest2.method = `workspace/textDocumentContent/refresh`;
|
|
TextDocumentContentRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
TextDocumentContentRefreshRequest2.type = new messages_1.ProtocolRequestType(TextDocumentContentRefreshRequest2.method);
|
|
})(TextDocumentContentRefreshRequest || (exports2.TextDocumentContentRefreshRequest = TextDocumentContentRefreshRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/protocol.js
|
|
var require_protocol = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.CodeActionRequest = exports2.DocumentSymbolRequest = exports2.DocumentHighlightRequest = exports2.ReferencesRequest = exports2.DefinitionRequest = exports2.SignatureHelpRequest = exports2.SignatureHelpTriggerKind = exports2.HoverRequest = exports2.CompletionResolveRequest = exports2.CompletionRequest = exports2.CompletionTriggerKind = exports2.PublishDiagnosticsNotification = exports2.WatchKind = exports2.GlobPattern = exports2.RelativePattern = exports2.FileChangeType = exports2.DidChangeWatchedFilesNotification = exports2.WillSaveTextDocumentWaitUntilRequest = exports2.WillSaveTextDocumentNotification = exports2.TextDocumentSaveReason = exports2.DidSaveTextDocumentNotification = exports2.DidCloseTextDocumentNotification = exports2.DidChangeTextDocumentNotification = exports2.TextDocumentContentChangeEvent = exports2.DidOpenTextDocumentNotification = exports2.TextDocumentSyncKind = exports2.TelemetryEventNotification = exports2.LogMessageNotification = exports2.ShowMessageRequest = exports2.ShowMessageNotification = exports2.MessageType = exports2.DidChangeConfigurationNotification = exports2.ExitNotification = exports2.ShutdownRequest = exports2.InitializedNotification = exports2.InitializeErrorCodes = exports2.InitializeRequest = exports2.WorkDoneProgressOptions = exports2.TextDocumentRegistrationOptions = exports2.StaticRegistrationOptions = exports2.PositionEncodingKind = exports2.RegularExpressionEngineKind = exports2.FailureHandlingKind = exports2.ResourceOperationKind = exports2.UnregistrationRequest = exports2.RegistrationRequest = exports2.DocumentSelector = exports2.NotebookCellTextDocumentFilter = exports2.NotebookDocumentFilter = exports2.TextDocumentFilter = undefined;
|
|
exports2.UniquenessLevel = exports2.WillDeleteFilesRequest = exports2.DidDeleteFilesNotification = exports2.WillRenameFilesRequest = exports2.DidRenameFilesNotification = exports2.WillCreateFilesRequest = exports2.DidCreateFilesNotification = exports2.FileOperationPatternKind = exports2.LinkedEditingRangeRequest = exports2.ShowDocumentRequest = exports2.SemanticTokensRegistrationType = exports2.SemanticTokensRefreshRequest = exports2.SemanticTokensRangeRequest = exports2.SemanticTokensDeltaRequest = exports2.SemanticTokensRequest = exports2.TokenFormat = exports2.CallHierarchyPrepareRequest = exports2.CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyIncomingCallsRequest = exports2.WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCreateRequest = exports2.WorkDoneProgress = exports2.SelectionRangeRequest = exports2.DeclarationRequest = exports2.FoldingRangeRefreshRequest = exports2.FoldingRangeRequest = exports2.ColorPresentationRequest = exports2.DocumentColorRequest = exports2.ConfigurationRequest = exports2.DidChangeWorkspaceFoldersNotification = exports2.WorkspaceFoldersRequest = exports2.TypeDefinitionRequest = exports2.ImplementationRequest = exports2.ApplyWorkspaceEditRequest = exports2.ExecuteCommandRequest = exports2.PrepareRenameRequest = exports2.RenameRequest = exports2.PrepareSupportDefaultBehavior = exports2.DocumentOnTypeFormattingRequest = exports2.DocumentRangesFormattingRequest = exports2.DocumentRangeFormattingRequest = exports2.DocumentFormattingRequest = exports2.DocumentLinkResolveRequest = exports2.DocumentLinkRequest = exports2.CodeLensRefreshRequest = exports2.CodeLensResolveRequest = exports2.CodeLensRequest = exports2.WorkspaceSymbolResolveRequest = exports2.WorkspaceSymbolRequest = exports2.CodeActionResolveRequest = undefined;
|
|
exports2.TextDocumentContentRefreshRequest = exports2.TextDocumentContentRequest = exports2.InlineCompletionRequest = exports2.DidCloseNotebookDocumentNotification = exports2.DidSaveNotebookDocumentNotification = exports2.DidChangeNotebookDocumentNotification = exports2.NotebookCellArrayChange = exports2.DidOpenNotebookDocumentNotification = exports2.NotebookDocumentSyncRegistrationType = exports2.NotebookDocument = exports2.NotebookCell = exports2.ExecutionSummary = exports2.NotebookCellKind = exports2.DiagnosticRefreshRequest = exports2.WorkspaceDiagnosticRequest = exports2.DocumentDiagnosticRequest = exports2.DocumentDiagnosticReportKind = exports2.DiagnosticServerCancellationData = exports2.InlayHintRefreshRequest = exports2.InlayHintResolveRequest = exports2.InlayHintRequest = exports2.InlineValueRefreshRequest = exports2.InlineValueRequest = exports2.TypeHierarchySupertypesRequest = exports2.TypeHierarchySubtypesRequest = exports2.TypeHierarchyPrepareRequest = exports2.MonikerRequest = exports2.MonikerKind = undefined;
|
|
var messages_1 = require_messages2();
|
|
var vscode_languageserver_types_1 = require_main();
|
|
var Is = __importStar(require_is3());
|
|
var protocol_implementation_1 = require_protocol_implementation();
|
|
Object.defineProperty(exports2, "ImplementationRequest", { enumerable: true, get: function() {
|
|
return protocol_implementation_1.ImplementationRequest;
|
|
} });
|
|
var protocol_typeDefinition_1 = require_protocol_typeDefinition();
|
|
Object.defineProperty(exports2, "TypeDefinitionRequest", { enumerable: true, get: function() {
|
|
return protocol_typeDefinition_1.TypeDefinitionRequest;
|
|
} });
|
|
var protocol_workspaceFolder_1 = require_protocol_workspaceFolder();
|
|
Object.defineProperty(exports2, "WorkspaceFoldersRequest", { enumerable: true, get: function() {
|
|
return protocol_workspaceFolder_1.WorkspaceFoldersRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "DidChangeWorkspaceFoldersNotification", { enumerable: true, get: function() {
|
|
return protocol_workspaceFolder_1.DidChangeWorkspaceFoldersNotification;
|
|
} });
|
|
var protocol_configuration_1 = require_protocol_configuration();
|
|
Object.defineProperty(exports2, "ConfigurationRequest", { enumerable: true, get: function() {
|
|
return protocol_configuration_1.ConfigurationRequest;
|
|
} });
|
|
var protocol_colorProvider_1 = require_protocol_colorProvider();
|
|
Object.defineProperty(exports2, "DocumentColorRequest", { enumerable: true, get: function() {
|
|
return protocol_colorProvider_1.DocumentColorRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "ColorPresentationRequest", { enumerable: true, get: function() {
|
|
return protocol_colorProvider_1.ColorPresentationRequest;
|
|
} });
|
|
var protocol_foldingRange_1 = require_protocol_foldingRange();
|
|
Object.defineProperty(exports2, "FoldingRangeRequest", { enumerable: true, get: function() {
|
|
return protocol_foldingRange_1.FoldingRangeRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "FoldingRangeRefreshRequest", { enumerable: true, get: function() {
|
|
return protocol_foldingRange_1.FoldingRangeRefreshRequest;
|
|
} });
|
|
var protocol_declaration_1 = require_protocol_declaration();
|
|
Object.defineProperty(exports2, "DeclarationRequest", { enumerable: true, get: function() {
|
|
return protocol_declaration_1.DeclarationRequest;
|
|
} });
|
|
var protocol_selectionRange_1 = require_protocol_selectionRange();
|
|
Object.defineProperty(exports2, "SelectionRangeRequest", { enumerable: true, get: function() {
|
|
return protocol_selectionRange_1.SelectionRangeRequest;
|
|
} });
|
|
var protocol_progress_1 = require_protocol_progress();
|
|
Object.defineProperty(exports2, "WorkDoneProgress", { enumerable: true, get: function() {
|
|
return protocol_progress_1.WorkDoneProgress;
|
|
} });
|
|
Object.defineProperty(exports2, "WorkDoneProgressCreateRequest", { enumerable: true, get: function() {
|
|
return protocol_progress_1.WorkDoneProgressCreateRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "WorkDoneProgressCancelNotification", { enumerable: true, get: function() {
|
|
return protocol_progress_1.WorkDoneProgressCancelNotification;
|
|
} });
|
|
var protocol_callHierarchy_1 = require_protocol_callHierarchy();
|
|
Object.defineProperty(exports2, "CallHierarchyIncomingCallsRequest", { enumerable: true, get: function() {
|
|
return protocol_callHierarchy_1.CallHierarchyIncomingCallsRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "CallHierarchyOutgoingCallsRequest", { enumerable: true, get: function() {
|
|
return protocol_callHierarchy_1.CallHierarchyOutgoingCallsRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "CallHierarchyPrepareRequest", { enumerable: true, get: function() {
|
|
return protocol_callHierarchy_1.CallHierarchyPrepareRequest;
|
|
} });
|
|
var protocol_semanticTokens_1 = require_protocol_semanticTokens();
|
|
Object.defineProperty(exports2, "TokenFormat", { enumerable: true, get: function() {
|
|
return protocol_semanticTokens_1.TokenFormat;
|
|
} });
|
|
Object.defineProperty(exports2, "SemanticTokensRequest", { enumerable: true, get: function() {
|
|
return protocol_semanticTokens_1.SemanticTokensRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "SemanticTokensDeltaRequest", { enumerable: true, get: function() {
|
|
return protocol_semanticTokens_1.SemanticTokensDeltaRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "SemanticTokensRangeRequest", { enumerable: true, get: function() {
|
|
return protocol_semanticTokens_1.SemanticTokensRangeRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "SemanticTokensRefreshRequest", { enumerable: true, get: function() {
|
|
return protocol_semanticTokens_1.SemanticTokensRefreshRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "SemanticTokensRegistrationType", { enumerable: true, get: function() {
|
|
return protocol_semanticTokens_1.SemanticTokensRegistrationType;
|
|
} });
|
|
var protocol_showDocument_1 = require_protocol_showDocument();
|
|
Object.defineProperty(exports2, "ShowDocumentRequest", { enumerable: true, get: function() {
|
|
return protocol_showDocument_1.ShowDocumentRequest;
|
|
} });
|
|
var protocol_linkedEditingRange_1 = require_protocol_linkedEditingRange();
|
|
Object.defineProperty(exports2, "LinkedEditingRangeRequest", { enumerable: true, get: function() {
|
|
return protocol_linkedEditingRange_1.LinkedEditingRangeRequest;
|
|
} });
|
|
var protocol_fileOperations_1 = require_protocol_fileOperations();
|
|
Object.defineProperty(exports2, "FileOperationPatternKind", { enumerable: true, get: function() {
|
|
return protocol_fileOperations_1.FileOperationPatternKind;
|
|
} });
|
|
Object.defineProperty(exports2, "DidCreateFilesNotification", { enumerable: true, get: function() {
|
|
return protocol_fileOperations_1.DidCreateFilesNotification;
|
|
} });
|
|
Object.defineProperty(exports2, "WillCreateFilesRequest", { enumerable: true, get: function() {
|
|
return protocol_fileOperations_1.WillCreateFilesRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "DidRenameFilesNotification", { enumerable: true, get: function() {
|
|
return protocol_fileOperations_1.DidRenameFilesNotification;
|
|
} });
|
|
Object.defineProperty(exports2, "WillRenameFilesRequest", { enumerable: true, get: function() {
|
|
return protocol_fileOperations_1.WillRenameFilesRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "DidDeleteFilesNotification", { enumerable: true, get: function() {
|
|
return protocol_fileOperations_1.DidDeleteFilesNotification;
|
|
} });
|
|
Object.defineProperty(exports2, "WillDeleteFilesRequest", { enumerable: true, get: function() {
|
|
return protocol_fileOperations_1.WillDeleteFilesRequest;
|
|
} });
|
|
var protocol_moniker_1 = require_protocol_moniker();
|
|
Object.defineProperty(exports2, "UniquenessLevel", { enumerable: true, get: function() {
|
|
return protocol_moniker_1.UniquenessLevel;
|
|
} });
|
|
Object.defineProperty(exports2, "MonikerKind", { enumerable: true, get: function() {
|
|
return protocol_moniker_1.MonikerKind;
|
|
} });
|
|
Object.defineProperty(exports2, "MonikerRequest", { enumerable: true, get: function() {
|
|
return protocol_moniker_1.MonikerRequest;
|
|
} });
|
|
var protocol_typeHierarchy_1 = require_protocol_typeHierarchy();
|
|
Object.defineProperty(exports2, "TypeHierarchyPrepareRequest", { enumerable: true, get: function() {
|
|
return protocol_typeHierarchy_1.TypeHierarchyPrepareRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "TypeHierarchySubtypesRequest", { enumerable: true, get: function() {
|
|
return protocol_typeHierarchy_1.TypeHierarchySubtypesRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "TypeHierarchySupertypesRequest", { enumerable: true, get: function() {
|
|
return protocol_typeHierarchy_1.TypeHierarchySupertypesRequest;
|
|
} });
|
|
var protocol_inlineValue_1 = require_protocol_inlineValue();
|
|
Object.defineProperty(exports2, "InlineValueRequest", { enumerable: true, get: function() {
|
|
return protocol_inlineValue_1.InlineValueRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "InlineValueRefreshRequest", { enumerable: true, get: function() {
|
|
return protocol_inlineValue_1.InlineValueRefreshRequest;
|
|
} });
|
|
var protocol_inlayHint_1 = require_protocol_inlayHint();
|
|
Object.defineProperty(exports2, "InlayHintRequest", { enumerable: true, get: function() {
|
|
return protocol_inlayHint_1.InlayHintRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "InlayHintResolveRequest", { enumerable: true, get: function() {
|
|
return protocol_inlayHint_1.InlayHintResolveRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "InlayHintRefreshRequest", { enumerable: true, get: function() {
|
|
return protocol_inlayHint_1.InlayHintRefreshRequest;
|
|
} });
|
|
var protocol_diagnostic_1 = require_protocol_diagnostic();
|
|
Object.defineProperty(exports2, "DiagnosticServerCancellationData", { enumerable: true, get: function() {
|
|
return protocol_diagnostic_1.DiagnosticServerCancellationData;
|
|
} });
|
|
Object.defineProperty(exports2, "DocumentDiagnosticReportKind", { enumerable: true, get: function() {
|
|
return protocol_diagnostic_1.DocumentDiagnosticReportKind;
|
|
} });
|
|
Object.defineProperty(exports2, "DocumentDiagnosticRequest", { enumerable: true, get: function() {
|
|
return protocol_diagnostic_1.DocumentDiagnosticRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "WorkspaceDiagnosticRequest", { enumerable: true, get: function() {
|
|
return protocol_diagnostic_1.WorkspaceDiagnosticRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "DiagnosticRefreshRequest", { enumerable: true, get: function() {
|
|
return protocol_diagnostic_1.DiagnosticRefreshRequest;
|
|
} });
|
|
var protocol_notebook_1 = require_protocol_notebook();
|
|
Object.defineProperty(exports2, "NotebookCellKind", { enumerable: true, get: function() {
|
|
return protocol_notebook_1.NotebookCellKind;
|
|
} });
|
|
Object.defineProperty(exports2, "ExecutionSummary", { enumerable: true, get: function() {
|
|
return protocol_notebook_1.ExecutionSummary;
|
|
} });
|
|
Object.defineProperty(exports2, "NotebookCell", { enumerable: true, get: function() {
|
|
return protocol_notebook_1.NotebookCell;
|
|
} });
|
|
Object.defineProperty(exports2, "NotebookDocument", { enumerable: true, get: function() {
|
|
return protocol_notebook_1.NotebookDocument;
|
|
} });
|
|
Object.defineProperty(exports2, "NotebookDocumentSyncRegistrationType", { enumerable: true, get: function() {
|
|
return protocol_notebook_1.NotebookDocumentSyncRegistrationType;
|
|
} });
|
|
Object.defineProperty(exports2, "DidOpenNotebookDocumentNotification", { enumerable: true, get: function() {
|
|
return protocol_notebook_1.DidOpenNotebookDocumentNotification;
|
|
} });
|
|
Object.defineProperty(exports2, "NotebookCellArrayChange", { enumerable: true, get: function() {
|
|
return protocol_notebook_1.NotebookCellArrayChange;
|
|
} });
|
|
Object.defineProperty(exports2, "DidChangeNotebookDocumentNotification", { enumerable: true, get: function() {
|
|
return protocol_notebook_1.DidChangeNotebookDocumentNotification;
|
|
} });
|
|
Object.defineProperty(exports2, "DidSaveNotebookDocumentNotification", { enumerable: true, get: function() {
|
|
return protocol_notebook_1.DidSaveNotebookDocumentNotification;
|
|
} });
|
|
Object.defineProperty(exports2, "DidCloseNotebookDocumentNotification", { enumerable: true, get: function() {
|
|
return protocol_notebook_1.DidCloseNotebookDocumentNotification;
|
|
} });
|
|
var protocol_inlineCompletion_1 = require_protocol_inlineCompletion();
|
|
Object.defineProperty(exports2, "InlineCompletionRequest", { enumerable: true, get: function() {
|
|
return protocol_inlineCompletion_1.InlineCompletionRequest;
|
|
} });
|
|
var protocol_textDocumentContent_1 = require_protocol_textDocumentContent();
|
|
Object.defineProperty(exports2, "TextDocumentContentRequest", { enumerable: true, get: function() {
|
|
return protocol_textDocumentContent_1.TextDocumentContentRequest;
|
|
} });
|
|
Object.defineProperty(exports2, "TextDocumentContentRefreshRequest", { enumerable: true, get: function() {
|
|
return protocol_textDocumentContent_1.TextDocumentContentRefreshRequest;
|
|
} });
|
|
var TextDocumentFilter;
|
|
(function(TextDocumentFilter2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return Is.string(candidate) || (Is.string(candidate.language) || Is.string(candidate.scheme) || GlobPattern.is(candidate.pattern));
|
|
}
|
|
TextDocumentFilter2.is = is;
|
|
})(TextDocumentFilter || (exports2.TextDocumentFilter = TextDocumentFilter = {}));
|
|
var NotebookDocumentFilter;
|
|
(function(NotebookDocumentFilter2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return Is.objectLiteral(candidate) && (Is.string(candidate.notebookType) || Is.string(candidate.scheme) || Is.string(candidate.pattern));
|
|
}
|
|
NotebookDocumentFilter2.is = is;
|
|
})(NotebookDocumentFilter || (exports2.NotebookDocumentFilter = NotebookDocumentFilter = {}));
|
|
var NotebookCellTextDocumentFilter;
|
|
(function(NotebookCellTextDocumentFilter2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return Is.objectLiteral(candidate) && (Is.string(candidate.notebook) || NotebookDocumentFilter.is(candidate.notebook)) && (candidate.language === undefined || Is.string(candidate.language));
|
|
}
|
|
NotebookCellTextDocumentFilter2.is = is;
|
|
})(NotebookCellTextDocumentFilter || (exports2.NotebookCellTextDocumentFilter = NotebookCellTextDocumentFilter = {}));
|
|
var DocumentSelector;
|
|
(function(DocumentSelector2) {
|
|
function is(value) {
|
|
if (!Array.isArray(value)) {
|
|
return false;
|
|
}
|
|
for (const elem of value) {
|
|
if (!Is.string(elem) && !TextDocumentFilter.is(elem) && !NotebookCellTextDocumentFilter.is(elem)) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
DocumentSelector2.is = is;
|
|
})(DocumentSelector || (exports2.DocumentSelector = DocumentSelector = {}));
|
|
var RegistrationRequest;
|
|
(function(RegistrationRequest2) {
|
|
RegistrationRequest2.method = "client/registerCapability";
|
|
RegistrationRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
RegistrationRequest2.type = new messages_1.ProtocolRequestType(RegistrationRequest2.method);
|
|
})(RegistrationRequest || (exports2.RegistrationRequest = RegistrationRequest = {}));
|
|
var UnregistrationRequest;
|
|
(function(UnregistrationRequest2) {
|
|
UnregistrationRequest2.method = "client/unregisterCapability";
|
|
UnregistrationRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
UnregistrationRequest2.type = new messages_1.ProtocolRequestType(UnregistrationRequest2.method);
|
|
})(UnregistrationRequest || (exports2.UnregistrationRequest = UnregistrationRequest = {}));
|
|
var ResourceOperationKind;
|
|
(function(ResourceOperationKind2) {
|
|
ResourceOperationKind2.Create = "create";
|
|
ResourceOperationKind2.Rename = "rename";
|
|
ResourceOperationKind2.Delete = "delete";
|
|
})(ResourceOperationKind || (exports2.ResourceOperationKind = ResourceOperationKind = {}));
|
|
var FailureHandlingKind;
|
|
(function(FailureHandlingKind2) {
|
|
FailureHandlingKind2.Abort = "abort";
|
|
FailureHandlingKind2.Transactional = "transactional";
|
|
FailureHandlingKind2.TextOnlyTransactional = "textOnlyTransactional";
|
|
FailureHandlingKind2.Undo = "undo";
|
|
})(FailureHandlingKind || (exports2.FailureHandlingKind = FailureHandlingKind = {}));
|
|
var RegularExpressionEngineKind;
|
|
(function(RegularExpressionEngineKind2) {
|
|
RegularExpressionEngineKind2.ES2020 = "ES2020";
|
|
})(RegularExpressionEngineKind || (exports2.RegularExpressionEngineKind = RegularExpressionEngineKind = {}));
|
|
var PositionEncodingKind;
|
|
(function(PositionEncodingKind2) {
|
|
PositionEncodingKind2.UTF8 = "utf-8";
|
|
PositionEncodingKind2.UTF16 = "utf-16";
|
|
PositionEncodingKind2.UTF32 = "utf-32";
|
|
})(PositionEncodingKind || (exports2.PositionEncodingKind = PositionEncodingKind = {}));
|
|
var StaticRegistrationOptions;
|
|
(function(StaticRegistrationOptions2) {
|
|
function hasId(value) {
|
|
const candidate = value;
|
|
return candidate && Is.string(candidate.id) && candidate.id.length > 0;
|
|
}
|
|
StaticRegistrationOptions2.hasId = hasId;
|
|
})(StaticRegistrationOptions || (exports2.StaticRegistrationOptions = StaticRegistrationOptions = {}));
|
|
var TextDocumentRegistrationOptions;
|
|
(function(TextDocumentRegistrationOptions2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
|
|
}
|
|
TextDocumentRegistrationOptions2.is = is;
|
|
})(TextDocumentRegistrationOptions || (exports2.TextDocumentRegistrationOptions = TextDocumentRegistrationOptions = {}));
|
|
var WorkDoneProgressOptions;
|
|
(function(WorkDoneProgressOptions2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));
|
|
}
|
|
WorkDoneProgressOptions2.is = is;
|
|
function hasWorkDoneProgress(value) {
|
|
const candidate = value;
|
|
return candidate && Is.boolean(candidate.workDoneProgress);
|
|
}
|
|
WorkDoneProgressOptions2.hasWorkDoneProgress = hasWorkDoneProgress;
|
|
})(WorkDoneProgressOptions || (exports2.WorkDoneProgressOptions = WorkDoneProgressOptions = {}));
|
|
var InitializeRequest;
|
|
(function(InitializeRequest2) {
|
|
InitializeRequest2.method = "initialize";
|
|
InitializeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
InitializeRequest2.type = new messages_1.ProtocolRequestType(InitializeRequest2.method);
|
|
})(InitializeRequest || (exports2.InitializeRequest = InitializeRequest = {}));
|
|
var InitializeErrorCodes;
|
|
(function(InitializeErrorCodes2) {
|
|
InitializeErrorCodes2.unknownProtocolVersion = 1;
|
|
})(InitializeErrorCodes || (exports2.InitializeErrorCodes = InitializeErrorCodes = {}));
|
|
var InitializedNotification;
|
|
(function(InitializedNotification2) {
|
|
InitializedNotification2.method = "initialized";
|
|
InitializedNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
InitializedNotification2.type = new messages_1.ProtocolNotificationType(InitializedNotification2.method);
|
|
})(InitializedNotification || (exports2.InitializedNotification = InitializedNotification = {}));
|
|
var ShutdownRequest;
|
|
(function(ShutdownRequest2) {
|
|
ShutdownRequest2.method = "shutdown";
|
|
ShutdownRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
ShutdownRequest2.type = new messages_1.ProtocolRequestType0(ShutdownRequest2.method);
|
|
})(ShutdownRequest || (exports2.ShutdownRequest = ShutdownRequest = {}));
|
|
var ExitNotification;
|
|
(function(ExitNotification2) {
|
|
ExitNotification2.method = "exit";
|
|
ExitNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
ExitNotification2.type = new messages_1.ProtocolNotificationType0(ExitNotification2.method);
|
|
})(ExitNotification || (exports2.ExitNotification = ExitNotification = {}));
|
|
var DidChangeConfigurationNotification;
|
|
(function(DidChangeConfigurationNotification2) {
|
|
DidChangeConfigurationNotification2.method = "workspace/didChangeConfiguration";
|
|
DidChangeConfigurationNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidChangeConfigurationNotification2.type = new messages_1.ProtocolNotificationType(DidChangeConfigurationNotification2.method);
|
|
DidChangeConfigurationNotification2.capabilities = messages_1.CM.create("workspace.didChangeConfiguration", undefined);
|
|
})(DidChangeConfigurationNotification || (exports2.DidChangeConfigurationNotification = DidChangeConfigurationNotification = {}));
|
|
var MessageType;
|
|
(function(MessageType2) {
|
|
MessageType2.Error = 1;
|
|
MessageType2.Warning = 2;
|
|
MessageType2.Info = 3;
|
|
MessageType2.Log = 4;
|
|
MessageType2.Debug = 5;
|
|
})(MessageType || (exports2.MessageType = MessageType = {}));
|
|
var ShowMessageNotification;
|
|
(function(ShowMessageNotification2) {
|
|
ShowMessageNotification2.method = "window/showMessage";
|
|
ShowMessageNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
ShowMessageNotification2.type = new messages_1.ProtocolNotificationType(ShowMessageNotification2.method);
|
|
ShowMessageNotification2.capabilities = messages_1.CM.create("window.showMessage", undefined);
|
|
})(ShowMessageNotification || (exports2.ShowMessageNotification = ShowMessageNotification = {}));
|
|
var ShowMessageRequest;
|
|
(function(ShowMessageRequest2) {
|
|
ShowMessageRequest2.method = "window/showMessageRequest";
|
|
ShowMessageRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
ShowMessageRequest2.type = new messages_1.ProtocolRequestType(ShowMessageRequest2.method);
|
|
ShowMessageRequest2.capabilities = messages_1.CM.create("window.showMessage", undefined);
|
|
})(ShowMessageRequest || (exports2.ShowMessageRequest = ShowMessageRequest = {}));
|
|
var LogMessageNotification;
|
|
(function(LogMessageNotification2) {
|
|
LogMessageNotification2.method = "window/logMessage";
|
|
LogMessageNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
LogMessageNotification2.type = new messages_1.ProtocolNotificationType(LogMessageNotification2.method);
|
|
})(LogMessageNotification || (exports2.LogMessageNotification = LogMessageNotification = {}));
|
|
var TelemetryEventNotification;
|
|
(function(TelemetryEventNotification2) {
|
|
TelemetryEventNotification2.method = "telemetry/event";
|
|
TelemetryEventNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
TelemetryEventNotification2.type = new messages_1.ProtocolNotificationType(TelemetryEventNotification2.method);
|
|
})(TelemetryEventNotification || (exports2.TelemetryEventNotification = TelemetryEventNotification = {}));
|
|
var TextDocumentSyncKind;
|
|
(function(TextDocumentSyncKind2) {
|
|
TextDocumentSyncKind2.None = 0;
|
|
TextDocumentSyncKind2.Full = 1;
|
|
TextDocumentSyncKind2.Incremental = 2;
|
|
})(TextDocumentSyncKind || (exports2.TextDocumentSyncKind = TextDocumentSyncKind = {}));
|
|
var DidOpenTextDocumentNotification;
|
|
(function(DidOpenTextDocumentNotification2) {
|
|
DidOpenTextDocumentNotification2.method = "textDocument/didOpen";
|
|
DidOpenTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidOpenTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification2.method);
|
|
DidOpenTextDocumentNotification2.capabilities = messages_1.CM.create("textDocument.synchronization", "textDocumentSync.openClose");
|
|
})(DidOpenTextDocumentNotification || (exports2.DidOpenTextDocumentNotification = DidOpenTextDocumentNotification = {}));
|
|
var TextDocumentContentChangeEvent;
|
|
(function(TextDocumentContentChangeEvent2) {
|
|
function isIncremental(event) {
|
|
const candidate = event;
|
|
return candidate !== undefined && candidate !== null && typeof candidate.text === "string" && candidate.range !== undefined && (candidate.rangeLength === undefined || typeof candidate.rangeLength === "number");
|
|
}
|
|
TextDocumentContentChangeEvent2.isIncremental = isIncremental;
|
|
function isFull(event) {
|
|
const candidate = event;
|
|
return candidate !== undefined && candidate !== null && typeof candidate.text === "string" && candidate.range === undefined && candidate.rangeLength === undefined;
|
|
}
|
|
TextDocumentContentChangeEvent2.isFull = isFull;
|
|
})(TextDocumentContentChangeEvent || (exports2.TextDocumentContentChangeEvent = TextDocumentContentChangeEvent = {}));
|
|
var DidChangeTextDocumentNotification;
|
|
(function(DidChangeTextDocumentNotification2) {
|
|
DidChangeTextDocumentNotification2.method = "textDocument/didChange";
|
|
DidChangeTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidChangeTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification2.method);
|
|
DidChangeTextDocumentNotification2.capabilities = messages_1.CM.create("textDocument.synchronization", "textDocumentSync");
|
|
})(DidChangeTextDocumentNotification || (exports2.DidChangeTextDocumentNotification = DidChangeTextDocumentNotification = {}));
|
|
var DidCloseTextDocumentNotification;
|
|
(function(DidCloseTextDocumentNotification2) {
|
|
DidCloseTextDocumentNotification2.method = "textDocument/didClose";
|
|
DidCloseTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidCloseTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification2.method);
|
|
DidCloseTextDocumentNotification2.capabilities = messages_1.CM.create("textDocument.synchronization", "textDocumentSync.openClose");
|
|
})(DidCloseTextDocumentNotification || (exports2.DidCloseTextDocumentNotification = DidCloseTextDocumentNotification = {}));
|
|
var DidSaveTextDocumentNotification;
|
|
(function(DidSaveTextDocumentNotification2) {
|
|
DidSaveTextDocumentNotification2.method = "textDocument/didSave";
|
|
DidSaveTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification2.method);
|
|
DidSaveTextDocumentNotification2.capabilities = messages_1.CM.create("textDocument.synchronization.didSave", "textDocumentSync.save");
|
|
})(DidSaveTextDocumentNotification || (exports2.DidSaveTextDocumentNotification = DidSaveTextDocumentNotification = {}));
|
|
var TextDocumentSaveReason;
|
|
(function(TextDocumentSaveReason2) {
|
|
TextDocumentSaveReason2.Manual = 1;
|
|
TextDocumentSaveReason2.AfterDelay = 2;
|
|
TextDocumentSaveReason2.FocusOut = 3;
|
|
})(TextDocumentSaveReason || (exports2.TextDocumentSaveReason = TextDocumentSaveReason = {}));
|
|
var WillSaveTextDocumentNotification;
|
|
(function(WillSaveTextDocumentNotification2) {
|
|
WillSaveTextDocumentNotification2.method = "textDocument/willSave";
|
|
WillSaveTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
WillSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification2.method);
|
|
WillSaveTextDocumentNotification2.capabilities = messages_1.CM.create("textDocument.synchronization.willSave", "textDocumentSync.willSave");
|
|
})(WillSaveTextDocumentNotification || (exports2.WillSaveTextDocumentNotification = WillSaveTextDocumentNotification = {}));
|
|
var WillSaveTextDocumentWaitUntilRequest;
|
|
(function(WillSaveTextDocumentWaitUntilRequest2) {
|
|
WillSaveTextDocumentWaitUntilRequest2.method = "textDocument/willSaveWaitUntil";
|
|
WillSaveTextDocumentWaitUntilRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
WillSaveTextDocumentWaitUntilRequest2.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest2.method);
|
|
WillSaveTextDocumentWaitUntilRequest2.capabilities = messages_1.CM.create("textDocument.synchronization.willSaveWaitUntil", "textDocumentSync.willSaveWaitUntil");
|
|
})(WillSaveTextDocumentWaitUntilRequest || (exports2.WillSaveTextDocumentWaitUntilRequest = WillSaveTextDocumentWaitUntilRequest = {}));
|
|
var DidChangeWatchedFilesNotification;
|
|
(function(DidChangeWatchedFilesNotification2) {
|
|
DidChangeWatchedFilesNotification2.method = "workspace/didChangeWatchedFiles";
|
|
DidChangeWatchedFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DidChangeWatchedFilesNotification2.type = new messages_1.ProtocolNotificationType(DidChangeWatchedFilesNotification2.method);
|
|
DidChangeWatchedFilesNotification2.capabilities = messages_1.CM.create("workspace.didChangeWatchedFiles", undefined);
|
|
})(DidChangeWatchedFilesNotification || (exports2.DidChangeWatchedFilesNotification = DidChangeWatchedFilesNotification = {}));
|
|
var FileChangeType;
|
|
(function(FileChangeType2) {
|
|
FileChangeType2.Created = 1;
|
|
FileChangeType2.Changed = 2;
|
|
FileChangeType2.Deleted = 3;
|
|
})(FileChangeType || (exports2.FileChangeType = FileChangeType = {}));
|
|
var RelativePattern;
|
|
(function(RelativePattern2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return Is.objectLiteral(candidate) && (vscode_languageserver_types_1.URI.is(candidate.baseUri) || vscode_languageserver_types_1.WorkspaceFolder.is(candidate.baseUri)) && Is.string(candidate.pattern);
|
|
}
|
|
RelativePattern2.is = is;
|
|
})(RelativePattern || (exports2.RelativePattern = RelativePattern = {}));
|
|
var GlobPattern;
|
|
(function(GlobPattern2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return Is.string(candidate) || RelativePattern.is(candidate);
|
|
}
|
|
GlobPattern2.is = is;
|
|
})(GlobPattern || (exports2.GlobPattern = GlobPattern = {}));
|
|
var WatchKind;
|
|
(function(WatchKind2) {
|
|
WatchKind2.Create = 1;
|
|
WatchKind2.Change = 2;
|
|
WatchKind2.Delete = 4;
|
|
})(WatchKind || (exports2.WatchKind = WatchKind = {}));
|
|
var PublishDiagnosticsNotification;
|
|
(function(PublishDiagnosticsNotification2) {
|
|
PublishDiagnosticsNotification2.method = "textDocument/publishDiagnostics";
|
|
PublishDiagnosticsNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
PublishDiagnosticsNotification2.type = new messages_1.ProtocolNotificationType(PublishDiagnosticsNotification2.method);
|
|
PublishDiagnosticsNotification2.capabilities = messages_1.CM.create("textDocument.publishDiagnostics", undefined);
|
|
})(PublishDiagnosticsNotification || (exports2.PublishDiagnosticsNotification = PublishDiagnosticsNotification = {}));
|
|
var CompletionTriggerKind;
|
|
(function(CompletionTriggerKind2) {
|
|
CompletionTriggerKind2.Invoked = 1;
|
|
CompletionTriggerKind2.TriggerCharacter = 2;
|
|
CompletionTriggerKind2.TriggerForIncompleteCompletions = 3;
|
|
})(CompletionTriggerKind || (exports2.CompletionTriggerKind = CompletionTriggerKind = {}));
|
|
var CompletionRequest;
|
|
(function(CompletionRequest2) {
|
|
CompletionRequest2.method = "textDocument/completion";
|
|
CompletionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
CompletionRequest2.type = new messages_1.ProtocolRequestType(CompletionRequest2.method);
|
|
CompletionRequest2.capabilities = messages_1.CM.create("textDocument.completion", "completionProvider");
|
|
})(CompletionRequest || (exports2.CompletionRequest = CompletionRequest = {}));
|
|
var CompletionResolveRequest;
|
|
(function(CompletionResolveRequest2) {
|
|
CompletionResolveRequest2.method = "completionItem/resolve";
|
|
CompletionResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
CompletionResolveRequest2.type = new messages_1.ProtocolRequestType(CompletionResolveRequest2.method);
|
|
CompletionResolveRequest2.capabilities = messages_1.CM.create("textDocument.completion.completionItem.resolveSupport", "completionProvider.resolveProvider");
|
|
})(CompletionResolveRequest || (exports2.CompletionResolveRequest = CompletionResolveRequest = {}));
|
|
var HoverRequest;
|
|
(function(HoverRequest2) {
|
|
HoverRequest2.method = "textDocument/hover";
|
|
HoverRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
HoverRequest2.type = new messages_1.ProtocolRequestType(HoverRequest2.method);
|
|
HoverRequest2.capabilities = messages_1.CM.create("textDocument.hover", "hoverProvider");
|
|
})(HoverRequest || (exports2.HoverRequest = HoverRequest = {}));
|
|
var SignatureHelpTriggerKind;
|
|
(function(SignatureHelpTriggerKind2) {
|
|
SignatureHelpTriggerKind2.Invoked = 1;
|
|
SignatureHelpTriggerKind2.TriggerCharacter = 2;
|
|
SignatureHelpTriggerKind2.ContentChange = 3;
|
|
})(SignatureHelpTriggerKind || (exports2.SignatureHelpTriggerKind = SignatureHelpTriggerKind = {}));
|
|
var SignatureHelpRequest;
|
|
(function(SignatureHelpRequest2) {
|
|
SignatureHelpRequest2.method = "textDocument/signatureHelp";
|
|
SignatureHelpRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
SignatureHelpRequest2.type = new messages_1.ProtocolRequestType(SignatureHelpRequest2.method);
|
|
SignatureHelpRequest2.capabilities = messages_1.CM.create("textDocument.signatureHelp", "signatureHelpProvider");
|
|
})(SignatureHelpRequest || (exports2.SignatureHelpRequest = SignatureHelpRequest = {}));
|
|
var DefinitionRequest;
|
|
(function(DefinitionRequest2) {
|
|
DefinitionRequest2.method = "textDocument/definition";
|
|
DefinitionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DefinitionRequest2.type = new messages_1.ProtocolRequestType(DefinitionRequest2.method);
|
|
DefinitionRequest2.capabilities = messages_1.CM.create("textDocument.definition", "definitionProvider");
|
|
})(DefinitionRequest || (exports2.DefinitionRequest = DefinitionRequest = {}));
|
|
var ReferencesRequest;
|
|
(function(ReferencesRequest2) {
|
|
ReferencesRequest2.method = "textDocument/references";
|
|
ReferencesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
ReferencesRequest2.type = new messages_1.ProtocolRequestType(ReferencesRequest2.method);
|
|
ReferencesRequest2.capabilities = messages_1.CM.create("textDocument.references", "referencesProvider");
|
|
})(ReferencesRequest || (exports2.ReferencesRequest = ReferencesRequest = {}));
|
|
var DocumentHighlightRequest;
|
|
(function(DocumentHighlightRequest2) {
|
|
DocumentHighlightRequest2.method = "textDocument/documentHighlight";
|
|
DocumentHighlightRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DocumentHighlightRequest2.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest2.method);
|
|
DocumentHighlightRequest2.capabilities = messages_1.CM.create("textDocument.documentHighlight", "documentHighlightProvider");
|
|
})(DocumentHighlightRequest || (exports2.DocumentHighlightRequest = DocumentHighlightRequest = {}));
|
|
var DocumentSymbolRequest;
|
|
(function(DocumentSymbolRequest2) {
|
|
DocumentSymbolRequest2.method = "textDocument/documentSymbol";
|
|
DocumentSymbolRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DocumentSymbolRequest2.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest2.method);
|
|
DocumentSymbolRequest2.capabilities = messages_1.CM.create("textDocument.documentSymbol", "documentSymbolProvider");
|
|
})(DocumentSymbolRequest || (exports2.DocumentSymbolRequest = DocumentSymbolRequest = {}));
|
|
var CodeActionRequest;
|
|
(function(CodeActionRequest2) {
|
|
CodeActionRequest2.method = "textDocument/codeAction";
|
|
CodeActionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
CodeActionRequest2.type = new messages_1.ProtocolRequestType(CodeActionRequest2.method);
|
|
CodeActionRequest2.capabilities = messages_1.CM.create("textDocument.codeAction", "codeActionProvider");
|
|
})(CodeActionRequest || (exports2.CodeActionRequest = CodeActionRequest = {}));
|
|
var CodeActionResolveRequest;
|
|
(function(CodeActionResolveRequest2) {
|
|
CodeActionResolveRequest2.method = "codeAction/resolve";
|
|
CodeActionResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
CodeActionResolveRequest2.type = new messages_1.ProtocolRequestType(CodeActionResolveRequest2.method);
|
|
CodeActionResolveRequest2.capabilities = messages_1.CM.create("textDocument.codeAction.resolveSupport", "codeActionProvider.resolveProvider");
|
|
})(CodeActionResolveRequest || (exports2.CodeActionResolveRequest = CodeActionResolveRequest = {}));
|
|
var WorkspaceSymbolRequest;
|
|
(function(WorkspaceSymbolRequest2) {
|
|
WorkspaceSymbolRequest2.method = "workspace/symbol";
|
|
WorkspaceSymbolRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
WorkspaceSymbolRequest2.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest2.method);
|
|
WorkspaceSymbolRequest2.capabilities = messages_1.CM.create("workspace.symbol", "workspaceSymbolProvider");
|
|
})(WorkspaceSymbolRequest || (exports2.WorkspaceSymbolRequest = WorkspaceSymbolRequest = {}));
|
|
var WorkspaceSymbolResolveRequest;
|
|
(function(WorkspaceSymbolResolveRequest2) {
|
|
WorkspaceSymbolResolveRequest2.method = "workspaceSymbol/resolve";
|
|
WorkspaceSymbolResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
WorkspaceSymbolResolveRequest2.type = new messages_1.ProtocolRequestType(WorkspaceSymbolResolveRequest2.method);
|
|
WorkspaceSymbolResolveRequest2.capabilities = messages_1.CM.create("workspace.symbol.resolveSupport", "workspaceSymbolProvider.resolveProvider");
|
|
})(WorkspaceSymbolResolveRequest || (exports2.WorkspaceSymbolResolveRequest = WorkspaceSymbolResolveRequest = {}));
|
|
var CodeLensRequest;
|
|
(function(CodeLensRequest2) {
|
|
CodeLensRequest2.method = "textDocument/codeLens";
|
|
CodeLensRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
CodeLensRequest2.type = new messages_1.ProtocolRequestType(CodeLensRequest2.method);
|
|
CodeLensRequest2.capabilities = messages_1.CM.create("textDocument.codeLens", "codeLensProvider");
|
|
})(CodeLensRequest || (exports2.CodeLensRequest = CodeLensRequest = {}));
|
|
var CodeLensResolveRequest;
|
|
(function(CodeLensResolveRequest2) {
|
|
CodeLensResolveRequest2.method = "codeLens/resolve";
|
|
CodeLensResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
CodeLensResolveRequest2.type = new messages_1.ProtocolRequestType(CodeLensResolveRequest2.method);
|
|
CodeLensResolveRequest2.capabilities = messages_1.CM.create("textDocument.codeLens.resolveSupport", "codeLensProvider.resolveProvider");
|
|
})(CodeLensResolveRequest || (exports2.CodeLensResolveRequest = CodeLensResolveRequest = {}));
|
|
var CodeLensRefreshRequest;
|
|
(function(CodeLensRefreshRequest2) {
|
|
CodeLensRefreshRequest2.method = `workspace/codeLens/refresh`;
|
|
CodeLensRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
CodeLensRefreshRequest2.type = new messages_1.ProtocolRequestType0(CodeLensRefreshRequest2.method);
|
|
CodeLensRefreshRequest2.capabilities = messages_1.CM.create("workspace.codeLens", undefined);
|
|
})(CodeLensRefreshRequest || (exports2.CodeLensRefreshRequest = CodeLensRefreshRequest = {}));
|
|
var DocumentLinkRequest;
|
|
(function(DocumentLinkRequest2) {
|
|
DocumentLinkRequest2.method = "textDocument/documentLink";
|
|
DocumentLinkRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DocumentLinkRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkRequest2.method);
|
|
DocumentLinkRequest2.capabilities = messages_1.CM.create("textDocument.documentLink", "documentLinkProvider");
|
|
})(DocumentLinkRequest || (exports2.DocumentLinkRequest = DocumentLinkRequest = {}));
|
|
var DocumentLinkResolveRequest;
|
|
(function(DocumentLinkResolveRequest2) {
|
|
DocumentLinkResolveRequest2.method = "documentLink/resolve";
|
|
DocumentLinkResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DocumentLinkResolveRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkResolveRequest2.method);
|
|
DocumentLinkResolveRequest2.capabilities = messages_1.CM.create("textDocument.documentLink", "documentLinkProvider.resolveProvider");
|
|
})(DocumentLinkResolveRequest || (exports2.DocumentLinkResolveRequest = DocumentLinkResolveRequest = {}));
|
|
var DocumentFormattingRequest;
|
|
(function(DocumentFormattingRequest2) {
|
|
DocumentFormattingRequest2.method = "textDocument/formatting";
|
|
DocumentFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DocumentFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest2.method);
|
|
DocumentFormattingRequest2.capabilities = messages_1.CM.create("textDocument.formatting", "documentFormattingProvider");
|
|
})(DocumentFormattingRequest || (exports2.DocumentFormattingRequest = DocumentFormattingRequest = {}));
|
|
var DocumentRangeFormattingRequest;
|
|
(function(DocumentRangeFormattingRequest2) {
|
|
DocumentRangeFormattingRequest2.method = "textDocument/rangeFormatting";
|
|
DocumentRangeFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DocumentRangeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest2.method);
|
|
DocumentRangeFormattingRequest2.capabilities = messages_1.CM.create("textDocument.rangeFormatting", "documentRangeFormattingProvider");
|
|
})(DocumentRangeFormattingRequest || (exports2.DocumentRangeFormattingRequest = DocumentRangeFormattingRequest = {}));
|
|
var DocumentRangesFormattingRequest;
|
|
(function(DocumentRangesFormattingRequest2) {
|
|
DocumentRangesFormattingRequest2.method = "textDocument/rangesFormatting";
|
|
DocumentRangesFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DocumentRangesFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentRangesFormattingRequest2.method);
|
|
DocumentRangesFormattingRequest2.capabilities = messages_1.CM.create("textDocument.rangeFormatting.rangesSupport", "documentRangeFormattingProvider.rangesSupport");
|
|
})(DocumentRangesFormattingRequest || (exports2.DocumentRangesFormattingRequest = DocumentRangesFormattingRequest = {}));
|
|
var DocumentOnTypeFormattingRequest;
|
|
(function(DocumentOnTypeFormattingRequest2) {
|
|
DocumentOnTypeFormattingRequest2.method = "textDocument/onTypeFormatting";
|
|
DocumentOnTypeFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
DocumentOnTypeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest2.method);
|
|
DocumentOnTypeFormattingRequest2.capabilities = messages_1.CM.create("textDocument.onTypeFormatting", "documentOnTypeFormattingProvider");
|
|
})(DocumentOnTypeFormattingRequest || (exports2.DocumentOnTypeFormattingRequest = DocumentOnTypeFormattingRequest = {}));
|
|
var PrepareSupportDefaultBehavior;
|
|
(function(PrepareSupportDefaultBehavior2) {
|
|
PrepareSupportDefaultBehavior2.Identifier = 1;
|
|
})(PrepareSupportDefaultBehavior || (exports2.PrepareSupportDefaultBehavior = PrepareSupportDefaultBehavior = {}));
|
|
var RenameRequest;
|
|
(function(RenameRequest2) {
|
|
RenameRequest2.method = "textDocument/rename";
|
|
RenameRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
RenameRequest2.type = new messages_1.ProtocolRequestType(RenameRequest2.method);
|
|
RenameRequest2.capabilities = messages_1.CM.create("textDocument.rename", "renameProvider");
|
|
})(RenameRequest || (exports2.RenameRequest = RenameRequest = {}));
|
|
var PrepareRenameRequest;
|
|
(function(PrepareRenameRequest2) {
|
|
PrepareRenameRequest2.method = "textDocument/prepareRename";
|
|
PrepareRenameRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
PrepareRenameRequest2.type = new messages_1.ProtocolRequestType(PrepareRenameRequest2.method);
|
|
PrepareRenameRequest2.capabilities = messages_1.CM.create("textDocument.rename.prepareSupport", "renameProvider.prepareProvider");
|
|
})(PrepareRenameRequest || (exports2.PrepareRenameRequest = PrepareRenameRequest = {}));
|
|
var ExecuteCommandRequest;
|
|
(function(ExecuteCommandRequest2) {
|
|
ExecuteCommandRequest2.method = "workspace/executeCommand";
|
|
ExecuteCommandRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
|
|
ExecuteCommandRequest2.type = new messages_1.ProtocolRequestType(ExecuteCommandRequest2.method);
|
|
ExecuteCommandRequest2.capabilities = messages_1.CM.create("workspace.executeCommand", "executeCommandProvider");
|
|
})(ExecuteCommandRequest || (exports2.ExecuteCommandRequest = ExecuteCommandRequest = {}));
|
|
var ApplyWorkspaceEditRequest;
|
|
(function(ApplyWorkspaceEditRequest2) {
|
|
ApplyWorkspaceEditRequest2.method = "workspace/applyEdit";
|
|
ApplyWorkspaceEditRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
|
|
ApplyWorkspaceEditRequest2.type = new messages_1.ProtocolRequestType("workspace/applyEdit");
|
|
ApplyWorkspaceEditRequest2.capabilities = messages_1.CM.create("workspace.applyEdit", undefined);
|
|
})(ApplyWorkspaceEditRequest || (exports2.ApplyWorkspaceEditRequest = ApplyWorkspaceEditRequest = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/connection.js
|
|
var require_connection2 = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.createProtocolConnection = createProtocolConnection;
|
|
var vscode_jsonrpc_1 = require_api();
|
|
function createProtocolConnection(input, output, logger, options) {
|
|
if (vscode_jsonrpc_1.ConnectionStrategy.is(options)) {
|
|
options = { connectionStrategy: options };
|
|
}
|
|
return (0, vscode_jsonrpc_1.createMessageConnection)(input, output, logger, options);
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/common/api.js
|
|
var require_api2 = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
|
|
for (var p in m)
|
|
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p))
|
|
__createBinding(exports3, m, p);
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.LSPErrorCodes = exports2.createProtocolConnection = undefined;
|
|
__exportStar(require_api(), exports2);
|
|
__exportStar(require_main(), exports2);
|
|
__exportStar(require_messages2(), exports2);
|
|
__exportStar(require_protocol(), exports2);
|
|
var connection_1 = require_connection2();
|
|
Object.defineProperty(exports2, "createProtocolConnection", { enumerable: true, get: function() {
|
|
return connection_1.createProtocolConnection;
|
|
} });
|
|
var LSPErrorCodes;
|
|
(function(LSPErrorCodes2) {
|
|
LSPErrorCodes2.lspReservedErrorRangeStart = -32899;
|
|
LSPErrorCodes2.RequestFailed = -32803;
|
|
LSPErrorCodes2.ServerCancelled = -32802;
|
|
LSPErrorCodes2.ContentModified = -32801;
|
|
LSPErrorCodes2.RequestCancelled = -32800;
|
|
LSPErrorCodes2.lspReservedErrorRangeEnd = -32800;
|
|
})(LSPErrorCodes || (exports2.LSPErrorCodes = LSPErrorCodes = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/utils/async.js
|
|
var require_async = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.Semaphore = exports2.Delayer = undefined;
|
|
exports2.setTestMode = setTestMode;
|
|
exports2.clearTestMode = clearTestMode;
|
|
exports2.map = map;
|
|
exports2.mapAsync = mapAsync;
|
|
exports2.forEach = forEach;
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
|
|
class Delayer {
|
|
defaultDelay;
|
|
timeout;
|
|
completionPromise;
|
|
onSuccess;
|
|
task;
|
|
constructor(defaultDelay) {
|
|
this.defaultDelay = defaultDelay;
|
|
this.timeout = undefined;
|
|
this.completionPromise = undefined;
|
|
this.onSuccess = undefined;
|
|
this.task = undefined;
|
|
}
|
|
trigger(task, delay = this.defaultDelay) {
|
|
this.task = task;
|
|
if (delay >= 0) {
|
|
this.cancelTimeout();
|
|
}
|
|
if (!this.completionPromise) {
|
|
this.completionPromise = new Promise((resolve) => {
|
|
this.onSuccess = resolve;
|
|
}).then(() => {
|
|
this.completionPromise = undefined;
|
|
this.onSuccess = undefined;
|
|
const result = this.task();
|
|
this.task = undefined;
|
|
return result;
|
|
});
|
|
}
|
|
if (delay >= 0 || this.timeout === undefined) {
|
|
this.timeout = (0, vscode_languageserver_protocol_1.RAL)().timer.setTimeout(() => {
|
|
this.timeout = undefined;
|
|
this.onSuccess(undefined);
|
|
}, delay >= 0 ? delay : this.defaultDelay);
|
|
}
|
|
return this.completionPromise;
|
|
}
|
|
forceDelivery() {
|
|
if (!this.completionPromise) {
|
|
return;
|
|
}
|
|
this.cancelTimeout();
|
|
const result = this.task();
|
|
this.completionPromise = undefined;
|
|
this.onSuccess = undefined;
|
|
this.task = undefined;
|
|
return result;
|
|
}
|
|
isTriggered() {
|
|
return this.timeout !== undefined;
|
|
}
|
|
cancel() {
|
|
this.cancelTimeout();
|
|
this.completionPromise = undefined;
|
|
}
|
|
cancelTimeout() {
|
|
if (this.timeout !== undefined) {
|
|
this.timeout.dispose();
|
|
this.timeout = undefined;
|
|
}
|
|
}
|
|
}
|
|
exports2.Delayer = Delayer;
|
|
|
|
class Semaphore {
|
|
_capacity;
|
|
_active;
|
|
_waiting;
|
|
constructor(capacity = 1) {
|
|
if (capacity <= 0) {
|
|
throw new Error("Capacity must be greater than 0");
|
|
}
|
|
this._capacity = capacity;
|
|
this._active = 0;
|
|
this._waiting = [];
|
|
}
|
|
lock(thunk) {
|
|
return new Promise((resolve, reject) => {
|
|
this._waiting.push({ thunk, resolve, reject });
|
|
this.runNext();
|
|
});
|
|
}
|
|
get active() {
|
|
return this._active;
|
|
}
|
|
runNext() {
|
|
if (this._waiting.length === 0 || this._active === this._capacity) {
|
|
return;
|
|
}
|
|
(0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => this.doRunNext());
|
|
}
|
|
doRunNext() {
|
|
if (this._waiting.length === 0 || this._active === this._capacity) {
|
|
return;
|
|
}
|
|
const next = this._waiting.shift();
|
|
this._active++;
|
|
if (this._active > this._capacity) {
|
|
throw new Error(`To many thunks active`);
|
|
}
|
|
try {
|
|
const result = next.thunk();
|
|
if (result instanceof Promise) {
|
|
result.then((value) => {
|
|
this._active--;
|
|
next.resolve(value);
|
|
this.runNext();
|
|
}, (err) => {
|
|
this._active--;
|
|
next.reject(err);
|
|
this.runNext();
|
|
});
|
|
} else {
|
|
this._active--;
|
|
next.resolve(result);
|
|
this.runNext();
|
|
}
|
|
} catch (err) {
|
|
this._active--;
|
|
next.reject(err);
|
|
this.runNext();
|
|
}
|
|
}
|
|
}
|
|
exports2.Semaphore = Semaphore;
|
|
var $test = false;
|
|
function setTestMode() {
|
|
$test = true;
|
|
}
|
|
function clearTestMode() {
|
|
$test = false;
|
|
}
|
|
var defaultYieldTimeout = 15;
|
|
|
|
class Timer {
|
|
yieldAfter;
|
|
startTime;
|
|
counter;
|
|
total;
|
|
counterInterval;
|
|
constructor(yieldAfter = defaultYieldTimeout) {
|
|
this.yieldAfter = $test === true ? Math.max(yieldAfter, 2) : Math.max(yieldAfter, defaultYieldTimeout);
|
|
this.startTime = Date.now();
|
|
this.counter = 0;
|
|
this.total = 0;
|
|
this.counterInterval = 1;
|
|
}
|
|
start() {
|
|
this.counter = 0;
|
|
this.total = 0;
|
|
this.counterInterval = 1;
|
|
this.startTime = Date.now();
|
|
}
|
|
shouldYield() {
|
|
if (++this.counter >= this.counterInterval) {
|
|
const timeTaken = Date.now() - this.startTime;
|
|
const timeLeft = Math.max(0, this.yieldAfter - timeTaken);
|
|
this.total += this.counter;
|
|
this.counter = 0;
|
|
if (timeTaken >= this.yieldAfter || timeLeft <= 1) {
|
|
this.counterInterval = 1;
|
|
this.total = 0;
|
|
return true;
|
|
} else {
|
|
switch (timeTaken) {
|
|
case 0:
|
|
case 1:
|
|
this.counterInterval = this.total * 2;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
async function map(items, func, token, options) {
|
|
if (items.length === 0) {
|
|
return [];
|
|
}
|
|
const result = new Array(items.length);
|
|
const timer = new Timer(options?.yieldAfter);
|
|
function convertBatch(start) {
|
|
timer.start();
|
|
for (let i = start;i < items.length; i++) {
|
|
result[i] = func(items[i]);
|
|
if (timer.shouldYield()) {
|
|
options?.yieldCallback && options.yieldCallback();
|
|
return i + 1;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
let index = convertBatch(0);
|
|
while (index !== -1) {
|
|
if (token !== undefined && token.isCancellationRequested) {
|
|
break;
|
|
}
|
|
index = await new Promise((resolve) => {
|
|
(0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => {
|
|
if (token !== undefined && token.isCancellationRequested) {
|
|
resolve(-1);
|
|
} else {
|
|
resolve(convertBatch(index));
|
|
}
|
|
});
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
async function mapAsync(items, func, token, options) {
|
|
if (items.length === 0) {
|
|
return [];
|
|
}
|
|
const result = new Array(items.length);
|
|
const timer = new Timer(options?.yieldAfter);
|
|
async function convertBatch(start) {
|
|
timer.start();
|
|
for (let i = start;i < items.length; i++) {
|
|
result[i] = await func(items[i], token);
|
|
if (timer.shouldYield()) {
|
|
options?.yieldCallback && options.yieldCallback();
|
|
return i + 1;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
let index = await convertBatch(0);
|
|
while (index !== -1) {
|
|
if (token !== undefined && token.isCancellationRequested) {
|
|
break;
|
|
}
|
|
index = await new Promise((resolve) => {
|
|
(0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => {
|
|
if (token !== undefined && token.isCancellationRequested) {
|
|
resolve(-1);
|
|
} else {
|
|
resolve(convertBatch(index));
|
|
}
|
|
});
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
async function forEach(items, func, token, options) {
|
|
if (items.length === 0) {
|
|
return;
|
|
}
|
|
const timer = new Timer(options?.yieldAfter);
|
|
function runBatch(start) {
|
|
timer.start();
|
|
for (let i = start;i < items.length; i++) {
|
|
func(items[i]);
|
|
if (timer.shouldYield()) {
|
|
options?.yieldCallback && options.yieldCallback();
|
|
return i + 1;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
let index = runBatch(0);
|
|
while (index !== -1) {
|
|
if (token !== undefined && token.isCancellationRequested) {
|
|
break;
|
|
}
|
|
index = await new Promise((resolve) => {
|
|
(0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => {
|
|
if (token !== undefined && token.isCancellationRequested) {
|
|
resolve(-1);
|
|
} else {
|
|
resolve(runBatch(index));
|
|
}
|
|
});
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/protocolCompletionItem.js
|
|
var require_protocolCompletionItem = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
var code = __importStar(require("vscode"));
|
|
|
|
class ProtocolCompletionItem extends code.CompletionItem {
|
|
data;
|
|
fromEdit;
|
|
documentationFormat;
|
|
originalItemKind;
|
|
deprecated;
|
|
insertTextMode;
|
|
constructor(label) {
|
|
super(label);
|
|
}
|
|
}
|
|
exports2.default = ProtocolCompletionItem;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/protocolCodeLens.js
|
|
var require_protocolCodeLens = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
var code = __importStar(require("vscode"));
|
|
|
|
class ProtocolCodeLens extends code.CodeLens {
|
|
data;
|
|
constructor(range) {
|
|
super(range);
|
|
}
|
|
}
|
|
exports2.default = ProtocolCodeLens;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/protocolDocumentLink.js
|
|
var require_protocolDocumentLink = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
var code = __importStar(require("vscode"));
|
|
|
|
class ProtocolDocumentLink extends code.DocumentLink {
|
|
data;
|
|
constructor(range, target) {
|
|
super(range, target);
|
|
}
|
|
}
|
|
exports2.default = ProtocolDocumentLink;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/protocolCodeAction.js
|
|
var require_protocolCodeAction = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
var vscode = __importStar(require("vscode"));
|
|
|
|
class ProtocolCodeAction extends vscode.CodeAction {
|
|
data;
|
|
constructor(title, data) {
|
|
super(title);
|
|
this.data = data;
|
|
}
|
|
}
|
|
exports2.default = ProtocolCodeAction;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/protocolDiagnostic.js
|
|
var require_protocolDiagnostic = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ProtocolDiagnostic = exports2.DiagnosticCode = undefined;
|
|
var vscode = __importStar(require("vscode"));
|
|
var Is = __importStar(require_is());
|
|
var DiagnosticCode;
|
|
(function(DiagnosticCode2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate !== undefined && candidate !== null && (Is.number(candidate.value) || Is.string(candidate.value)) && Is.string(candidate.target);
|
|
}
|
|
DiagnosticCode2.is = is;
|
|
})(DiagnosticCode || (exports2.DiagnosticCode = DiagnosticCode = {}));
|
|
|
|
class ProtocolDiagnostic extends vscode.Diagnostic {
|
|
data;
|
|
hasDiagnosticCode;
|
|
constructor(range, message, severity, data) {
|
|
super(range, message, severity);
|
|
this.data = data;
|
|
this.hasDiagnosticCode = false;
|
|
}
|
|
}
|
|
exports2.ProtocolDiagnostic = ProtocolDiagnostic;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/protocolCallHierarchyItem.js
|
|
var require_protocolCallHierarchyItem = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
var code = __importStar(require("vscode"));
|
|
|
|
class ProtocolCallHierarchyItem extends code.CallHierarchyItem {
|
|
data;
|
|
constructor(kind, name, detail, uri, range, selectionRange, data) {
|
|
super(kind, name, detail, uri, range, selectionRange);
|
|
if (data !== undefined) {
|
|
this.data = data;
|
|
}
|
|
}
|
|
}
|
|
exports2.default = ProtocolCallHierarchyItem;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/protocolTypeHierarchyItem.js
|
|
var require_protocolTypeHierarchyItem = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
var code = __importStar(require("vscode"));
|
|
|
|
class ProtocolTypeHierarchyItem extends code.TypeHierarchyItem {
|
|
data;
|
|
constructor(kind, name, detail, uri, range, selectionRange, data) {
|
|
super(kind, name, detail, uri, range, selectionRange);
|
|
if (data !== undefined) {
|
|
this.data = data;
|
|
}
|
|
}
|
|
}
|
|
exports2.default = ProtocolTypeHierarchyItem;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/protocolWorkspaceSymbol.js
|
|
var require_protocolWorkspaceSymbol = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
var code = __importStar(require("vscode"));
|
|
|
|
class WorkspaceSymbol extends code.SymbolInformation {
|
|
data;
|
|
hasRange;
|
|
constructor(name, kind, containerName, locationOrUri, data) {
|
|
const hasRange = !(locationOrUri instanceof code.Uri);
|
|
super(name, kind, containerName, hasRange ? locationOrUri : new code.Location(locationOrUri, new code.Range(0, 0, 0, 0)));
|
|
this.hasRange = hasRange;
|
|
if (data !== undefined) {
|
|
this.data = data;
|
|
}
|
|
}
|
|
}
|
|
exports2.default = WorkspaceSymbol;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/protocolInlayHint.js
|
|
var require_protocolInlayHint = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
var code = __importStar(require("vscode"));
|
|
|
|
class ProtocolInlayHint extends code.InlayHint {
|
|
data;
|
|
constructor(position, label, kind) {
|
|
super(position, label, kind);
|
|
}
|
|
}
|
|
exports2.default = ProtocolInlayHint;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/codeConverter.js
|
|
var require_codeConverter = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
|
|
return mod && mod.__esModule ? mod : { default: mod };
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.createConverter = createConverter;
|
|
var code = __importStar(require("vscode"));
|
|
var proto = __importStar(require_api2());
|
|
var Is = __importStar(require_is());
|
|
var async = __importStar(require_async());
|
|
var protocolCompletionItem_1 = __importDefault(require_protocolCompletionItem());
|
|
var protocolCodeLens_1 = __importDefault(require_protocolCodeLens());
|
|
var protocolDocumentLink_1 = __importDefault(require_protocolDocumentLink());
|
|
var protocolCodeAction_1 = __importDefault(require_protocolCodeAction());
|
|
var protocolDiagnostic_1 = require_protocolDiagnostic();
|
|
var protocolCallHierarchyItem_1 = __importDefault(require_protocolCallHierarchyItem());
|
|
var protocolTypeHierarchyItem_1 = __importDefault(require_protocolTypeHierarchyItem());
|
|
var protocolWorkspaceSymbol_1 = __importDefault(require_protocolWorkspaceSymbol());
|
|
var protocolInlayHint_1 = __importDefault(require_protocolInlayHint());
|
|
var InsertReplaceRange;
|
|
(function(InsertReplaceRange2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && !!candidate.inserting && !!candidate.replacing;
|
|
}
|
|
InsertReplaceRange2.is = is;
|
|
})(InsertReplaceRange || (InsertReplaceRange = {}));
|
|
function createConverter(uriConverter) {
|
|
const nullConverter = (value) => value.toString();
|
|
const _uriConverter = uriConverter || nullConverter;
|
|
function asUri(value) {
|
|
return _uriConverter(value);
|
|
}
|
|
function asTextDocumentIdentifier(textDocument) {
|
|
return {
|
|
uri: _uriConverter(textDocument.uri)
|
|
};
|
|
}
|
|
function asTextDocumentItem(textDocument) {
|
|
return {
|
|
uri: _uriConverter(textDocument.uri),
|
|
languageId: textDocument.languageId,
|
|
version: textDocument.version,
|
|
text: textDocument.getText()
|
|
};
|
|
}
|
|
function asVersionedTextDocumentIdentifier(textDocument) {
|
|
return {
|
|
uri: _uriConverter(textDocument.uri),
|
|
version: textDocument.version
|
|
};
|
|
}
|
|
function asOpenTextDocumentParams(textDocument) {
|
|
return {
|
|
textDocument: asTextDocumentItem(textDocument)
|
|
};
|
|
}
|
|
function isTextDocumentChangeEvent(value) {
|
|
const candidate = value;
|
|
return !!candidate.document && !!candidate.contentChanges;
|
|
}
|
|
function isTextDocument(value) {
|
|
const candidate = value;
|
|
return !!candidate.uri && !!candidate.version;
|
|
}
|
|
function asChangeTextDocumentParams(arg0, arg1, arg2) {
|
|
if (isTextDocument(arg0)) {
|
|
const result = {
|
|
textDocument: {
|
|
uri: _uriConverter(arg0.uri),
|
|
version: arg0.version
|
|
},
|
|
contentChanges: [{ text: arg0.getText() }]
|
|
};
|
|
return result;
|
|
} else if (isTextDocumentChangeEvent(arg0)) {
|
|
const uri = arg1;
|
|
const version = arg2;
|
|
const result = {
|
|
textDocument: {
|
|
uri: _uriConverter(uri),
|
|
version
|
|
},
|
|
contentChanges: arg0.contentChanges.map((change) => {
|
|
const range = change.range;
|
|
return {
|
|
range: {
|
|
start: { line: range.start.line, character: range.start.character },
|
|
end: { line: range.end.line, character: range.end.character }
|
|
},
|
|
rangeLength: change.rangeLength,
|
|
text: change.text
|
|
};
|
|
})
|
|
};
|
|
return result;
|
|
} else {
|
|
throw Error("Unsupported text document change parameter");
|
|
}
|
|
}
|
|
function asCloseTextDocumentParams(textDocument) {
|
|
return {
|
|
textDocument: asTextDocumentIdentifier(textDocument)
|
|
};
|
|
}
|
|
function asSaveTextDocumentParams(textDocument, includeContent = false) {
|
|
const result = {
|
|
textDocument: asTextDocumentIdentifier(textDocument)
|
|
};
|
|
if (includeContent) {
|
|
result.text = textDocument.getText();
|
|
}
|
|
return result;
|
|
}
|
|
function asTextDocumentSaveReason(reason) {
|
|
switch (reason) {
|
|
case code.TextDocumentSaveReason.Manual:
|
|
return proto.TextDocumentSaveReason.Manual;
|
|
case code.TextDocumentSaveReason.AfterDelay:
|
|
return proto.TextDocumentSaveReason.AfterDelay;
|
|
case code.TextDocumentSaveReason.FocusOut:
|
|
return proto.TextDocumentSaveReason.FocusOut;
|
|
}
|
|
return proto.TextDocumentSaveReason.Manual;
|
|
}
|
|
function asWillSaveTextDocumentParams(event) {
|
|
return {
|
|
textDocument: asTextDocumentIdentifier(event.document),
|
|
reason: asTextDocumentSaveReason(event.reason)
|
|
};
|
|
}
|
|
function asDidCreateFilesParams(event) {
|
|
return {
|
|
files: event.files.map((fileUri) => ({
|
|
uri: _uriConverter(fileUri)
|
|
}))
|
|
};
|
|
}
|
|
function asDidRenameFilesParams(event) {
|
|
return {
|
|
files: event.files.map((file) => ({
|
|
oldUri: _uriConverter(file.oldUri),
|
|
newUri: _uriConverter(file.newUri)
|
|
}))
|
|
};
|
|
}
|
|
function asDidDeleteFilesParams(event) {
|
|
return {
|
|
files: event.files.map((fileUri) => ({
|
|
uri: _uriConverter(fileUri)
|
|
}))
|
|
};
|
|
}
|
|
function asWillCreateFilesParams(event) {
|
|
return {
|
|
files: event.files.map((fileUri) => ({
|
|
uri: _uriConverter(fileUri)
|
|
}))
|
|
};
|
|
}
|
|
function asWillRenameFilesParams(event) {
|
|
return {
|
|
files: event.files.map((file) => ({
|
|
oldUri: _uriConverter(file.oldUri),
|
|
newUri: _uriConverter(file.newUri)
|
|
}))
|
|
};
|
|
}
|
|
function asWillDeleteFilesParams(event) {
|
|
return {
|
|
files: event.files.map((fileUri) => ({
|
|
uri: _uriConverter(fileUri)
|
|
}))
|
|
};
|
|
}
|
|
function asTextDocumentPositionParams(textDocument, position) {
|
|
return {
|
|
textDocument: asTextDocumentIdentifier(textDocument),
|
|
position: asWorkerPosition(position)
|
|
};
|
|
}
|
|
function asCompletionTriggerKind(triggerKind) {
|
|
switch (triggerKind) {
|
|
case code.CompletionTriggerKind.TriggerCharacter:
|
|
return proto.CompletionTriggerKind.TriggerCharacter;
|
|
case code.CompletionTriggerKind.TriggerForIncompleteCompletions:
|
|
return proto.CompletionTriggerKind.TriggerForIncompleteCompletions;
|
|
default:
|
|
return proto.CompletionTriggerKind.Invoked;
|
|
}
|
|
}
|
|
function asCompletionParams(textDocument, position, context) {
|
|
return {
|
|
textDocument: asTextDocumentIdentifier(textDocument),
|
|
position: asWorkerPosition(position),
|
|
context: {
|
|
triggerKind: asCompletionTriggerKind(context.triggerKind),
|
|
triggerCharacter: context.triggerCharacter
|
|
}
|
|
};
|
|
}
|
|
function asSignatureHelpTriggerKind(triggerKind) {
|
|
switch (triggerKind) {
|
|
case code.SignatureHelpTriggerKind.Invoke:
|
|
return proto.SignatureHelpTriggerKind.Invoked;
|
|
case code.SignatureHelpTriggerKind.TriggerCharacter:
|
|
return proto.SignatureHelpTriggerKind.TriggerCharacter;
|
|
case code.SignatureHelpTriggerKind.ContentChange:
|
|
return proto.SignatureHelpTriggerKind.ContentChange;
|
|
}
|
|
}
|
|
function asParameterInformation(value) {
|
|
return {
|
|
label: value.label
|
|
};
|
|
}
|
|
function asParameterInformations(values) {
|
|
return values.map(asParameterInformation);
|
|
}
|
|
function asSignatureInformation(value) {
|
|
return {
|
|
label: value.label,
|
|
parameters: asParameterInformations(value.parameters)
|
|
};
|
|
}
|
|
function asSignatureInformations(values) {
|
|
return values.map(asSignatureInformation);
|
|
}
|
|
function asSignatureHelp(value) {
|
|
if (value === undefined) {
|
|
return value;
|
|
}
|
|
return {
|
|
signatures: asSignatureInformations(value.signatures),
|
|
activeSignature: value.activeSignature,
|
|
activeParameter: value.activeParameter
|
|
};
|
|
}
|
|
function asSignatureHelpParams(textDocument, position, context) {
|
|
return {
|
|
textDocument: asTextDocumentIdentifier(textDocument),
|
|
position: asWorkerPosition(position),
|
|
context: {
|
|
isRetrigger: context.isRetrigger,
|
|
triggerCharacter: context.triggerCharacter,
|
|
triggerKind: asSignatureHelpTriggerKind(context.triggerKind),
|
|
activeSignatureHelp: asSignatureHelp(context.activeSignatureHelp)
|
|
}
|
|
};
|
|
}
|
|
function asWorkerPosition(position) {
|
|
return { line: position.line, character: position.character };
|
|
}
|
|
function asPosition(value) {
|
|
if (value === undefined || value === null) {
|
|
return value;
|
|
}
|
|
return { line: value.line > proto.uinteger.MAX_VALUE ? proto.uinteger.MAX_VALUE : value.line, character: value.character > proto.uinteger.MAX_VALUE ? proto.uinteger.MAX_VALUE : value.character };
|
|
}
|
|
function asPositions(values, token) {
|
|
return async.map(values, asPosition, token);
|
|
}
|
|
function asPositionsSync(values) {
|
|
return values.map(asPosition);
|
|
}
|
|
function asRange(value) {
|
|
if (value === undefined || value === null) {
|
|
return value;
|
|
}
|
|
return { start: asPosition(value.start), end: asPosition(value.end) };
|
|
}
|
|
function asRanges(values) {
|
|
return values.map(asRange);
|
|
}
|
|
function asLocation(value) {
|
|
if (value === undefined || value === null) {
|
|
return value;
|
|
}
|
|
return proto.Location.create(asUri(value.uri), asRange(value.range));
|
|
}
|
|
function asDiagnosticSeverity(value) {
|
|
switch (value) {
|
|
case code.DiagnosticSeverity.Error:
|
|
return proto.DiagnosticSeverity.Error;
|
|
case code.DiagnosticSeverity.Warning:
|
|
return proto.DiagnosticSeverity.Warning;
|
|
case code.DiagnosticSeverity.Information:
|
|
return proto.DiagnosticSeverity.Information;
|
|
case code.DiagnosticSeverity.Hint:
|
|
return proto.DiagnosticSeverity.Hint;
|
|
}
|
|
}
|
|
function asDiagnosticTags(tags) {
|
|
if (!tags) {
|
|
return;
|
|
}
|
|
const result = [];
|
|
for (const tag of tags) {
|
|
const converted = asDiagnosticTag(tag);
|
|
if (converted !== undefined) {
|
|
result.push(converted);
|
|
}
|
|
}
|
|
return result.length > 0 ? result : undefined;
|
|
}
|
|
function asDiagnosticTag(tag) {
|
|
switch (tag) {
|
|
case code.DiagnosticTag.Unnecessary:
|
|
return proto.DiagnosticTag.Unnecessary;
|
|
case code.DiagnosticTag.Deprecated:
|
|
return proto.DiagnosticTag.Deprecated;
|
|
default:
|
|
return;
|
|
}
|
|
}
|
|
function asRelatedInformation(item) {
|
|
return {
|
|
message: item.message,
|
|
location: asLocation(item.location)
|
|
};
|
|
}
|
|
function asRelatedInformations(items) {
|
|
return items.map(asRelatedInformation);
|
|
}
|
|
function asDiagnosticCode(value) {
|
|
if (value === undefined || value === null) {
|
|
return;
|
|
}
|
|
if (Is.number(value) || Is.string(value)) {
|
|
return value;
|
|
}
|
|
return { value: value.value, target: asUri(value.target) };
|
|
}
|
|
function asDiagnostic(item) {
|
|
const result = proto.Diagnostic.create(asRange(item.range), item.message);
|
|
const protocolDiagnostic = item instanceof protocolDiagnostic_1.ProtocolDiagnostic ? item : undefined;
|
|
if (protocolDiagnostic !== undefined && protocolDiagnostic.data !== undefined) {
|
|
result.data = protocolDiagnostic.data;
|
|
}
|
|
const code2 = asDiagnosticCode(item.code);
|
|
if (protocolDiagnostic_1.DiagnosticCode.is(code2)) {
|
|
if (protocolDiagnostic !== undefined && protocolDiagnostic.hasDiagnosticCode) {
|
|
result.code = code2;
|
|
} else {
|
|
result.code = code2.value;
|
|
result.codeDescription = { href: code2.target };
|
|
}
|
|
} else {
|
|
result.code = code2;
|
|
}
|
|
if (Is.number(item.severity)) {
|
|
result.severity = asDiagnosticSeverity(item.severity);
|
|
}
|
|
if (Array.isArray(item.tags)) {
|
|
result.tags = asDiagnosticTags(item.tags);
|
|
}
|
|
if (item.relatedInformation) {
|
|
result.relatedInformation = asRelatedInformations(item.relatedInformation);
|
|
}
|
|
if (item.source) {
|
|
result.source = item.source;
|
|
}
|
|
return result;
|
|
}
|
|
function asDiagnostics(items, token) {
|
|
if (items === undefined || items === null) {
|
|
return items;
|
|
}
|
|
return async.map(items, asDiagnostic, token);
|
|
}
|
|
function asDiagnosticsSync(items) {
|
|
if (items === undefined || items === null) {
|
|
return items;
|
|
}
|
|
return items.map(asDiagnostic);
|
|
}
|
|
function asDocumentation(format, documentation) {
|
|
switch (format) {
|
|
case "$string":
|
|
return documentation;
|
|
case proto.MarkupKind.PlainText:
|
|
return { kind: format, value: documentation };
|
|
case proto.MarkupKind.Markdown:
|
|
return { kind: format, value: documentation.value };
|
|
default:
|
|
return `Unsupported Markup content received. Kind is: ${format}`;
|
|
}
|
|
}
|
|
function asCompletionItemTag(tag) {
|
|
switch (tag) {
|
|
case code.CompletionItemTag.Deprecated:
|
|
return proto.CompletionItemTag.Deprecated;
|
|
}
|
|
return;
|
|
}
|
|
function asCompletionItemTags(tags) {
|
|
if (tags === undefined) {
|
|
return tags;
|
|
}
|
|
const result = [];
|
|
for (const tag of tags) {
|
|
const converted = asCompletionItemTag(tag);
|
|
if (converted !== undefined) {
|
|
result.push(converted);
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
function asCompletionItemKind(value, original) {
|
|
if (original !== undefined) {
|
|
return original;
|
|
}
|
|
return value + 1;
|
|
}
|
|
function asCompletionItem(item, labelDetailsSupport = false) {
|
|
let label;
|
|
let labelDetails;
|
|
if (Is.string(item.label)) {
|
|
label = item.label;
|
|
} else {
|
|
label = item.label.label;
|
|
if (labelDetailsSupport && (item.label.detail !== undefined || item.label.description !== undefined)) {
|
|
labelDetails = { detail: item.label.detail, description: item.label.description };
|
|
}
|
|
}
|
|
const result = { label };
|
|
if (labelDetails !== undefined) {
|
|
result.labelDetails = labelDetails;
|
|
}
|
|
const protocolItem = item instanceof protocolCompletionItem_1.default ? item : undefined;
|
|
if (item.detail) {
|
|
result.detail = item.detail;
|
|
}
|
|
if (item.documentation) {
|
|
if (!protocolItem || protocolItem.documentationFormat === "$string") {
|
|
result.documentation = item.documentation;
|
|
} else {
|
|
result.documentation = asDocumentation(protocolItem.documentationFormat, item.documentation);
|
|
}
|
|
}
|
|
if (item.filterText) {
|
|
result.filterText = item.filterText;
|
|
}
|
|
fillPrimaryInsertText(result, item);
|
|
if (Is.number(item.kind)) {
|
|
result.kind = asCompletionItemKind(item.kind, protocolItem && protocolItem.originalItemKind);
|
|
}
|
|
if (item.sortText) {
|
|
result.sortText = item.sortText;
|
|
}
|
|
if (item.additionalTextEdits) {
|
|
result.additionalTextEdits = asTextEdits(item.additionalTextEdits);
|
|
}
|
|
if (item.commitCharacters) {
|
|
result.commitCharacters = item.commitCharacters.slice();
|
|
}
|
|
if (item.command) {
|
|
result.command = asCommand(item.command);
|
|
}
|
|
if (item.preselect === true || item.preselect === false) {
|
|
result.preselect = item.preselect;
|
|
}
|
|
const tags = asCompletionItemTags(item.tags);
|
|
if (protocolItem) {
|
|
if (protocolItem.data !== undefined) {
|
|
result.data = protocolItem.data;
|
|
}
|
|
if (protocolItem.deprecated === true || protocolItem.deprecated === false) {
|
|
if (protocolItem.deprecated === true && tags !== undefined && tags.length > 0) {
|
|
const index = tags.indexOf(code.CompletionItemTag.Deprecated);
|
|
if (index !== -1) {
|
|
tags.splice(index, 1);
|
|
}
|
|
}
|
|
result.deprecated = protocolItem.deprecated;
|
|
}
|
|
if (protocolItem.insertTextMode !== undefined) {
|
|
result.insertTextMode = protocolItem.insertTextMode;
|
|
}
|
|
}
|
|
if (tags !== undefined && tags.length > 0) {
|
|
result.tags = tags;
|
|
}
|
|
if (result.insertTextMode === undefined && item.keepWhitespace === true) {
|
|
result.insertTextMode = proto.InsertTextMode.adjustIndentation;
|
|
}
|
|
return result;
|
|
}
|
|
function fillPrimaryInsertText(target, source) {
|
|
let format = proto.InsertTextFormat.PlainText;
|
|
let text = undefined;
|
|
let range = undefined;
|
|
if (source.textEdit) {
|
|
text = source.textEdit.newText;
|
|
range = source.textEdit.range;
|
|
} else if (source.insertText instanceof code.SnippetString) {
|
|
format = proto.InsertTextFormat.Snippet;
|
|
text = source.insertText.value;
|
|
} else {
|
|
text = source.insertText;
|
|
}
|
|
if (source.range) {
|
|
range = source.range;
|
|
}
|
|
target.insertTextFormat = format;
|
|
if (source.fromEdit && text !== undefined && range !== undefined) {
|
|
target.textEdit = asCompletionTextEdit(text, range);
|
|
} else {
|
|
target.insertText = text;
|
|
}
|
|
}
|
|
function asCompletionTextEdit(newText, range) {
|
|
if (InsertReplaceRange.is(range)) {
|
|
return proto.InsertReplaceEdit.create(newText, asRange(range.inserting), asRange(range.replacing));
|
|
} else {
|
|
return { newText, range: asRange(range) };
|
|
}
|
|
}
|
|
function asTextEdit(edit) {
|
|
return { range: asRange(edit.range), newText: edit.newText };
|
|
}
|
|
function asTextEdits(edits) {
|
|
if (edits === undefined || edits === null) {
|
|
return edits;
|
|
}
|
|
return edits.map(asTextEdit);
|
|
}
|
|
function asSymbolKind(item) {
|
|
if (item <= code.SymbolKind.TypeParameter) {
|
|
return item + 1;
|
|
}
|
|
return proto.SymbolKind.Property;
|
|
}
|
|
function asSymbolTag(item) {
|
|
return item;
|
|
}
|
|
function asSymbolTags(items) {
|
|
return items.map(asSymbolTag);
|
|
}
|
|
function asReferenceParams(textDocument, position, options) {
|
|
return {
|
|
textDocument: asTextDocumentIdentifier(textDocument),
|
|
position: asWorkerPosition(position),
|
|
context: { includeDeclaration: options.includeDeclaration }
|
|
};
|
|
}
|
|
async function asCodeAction(item, token) {
|
|
const result = proto.CodeAction.create(item.title);
|
|
if (item instanceof protocolCodeAction_1.default && item.data !== undefined) {
|
|
result.data = item.data;
|
|
}
|
|
if (item.kind !== undefined) {
|
|
result.kind = asCodeActionKind(item.kind);
|
|
}
|
|
if (item.diagnostics !== undefined) {
|
|
result.diagnostics = await asDiagnostics(item.diagnostics, token);
|
|
}
|
|
if (item.edit !== undefined) {
|
|
throw new Error(`VS Code code actions can only be converted to a protocol code action without an edit.`);
|
|
}
|
|
if (item.command !== undefined) {
|
|
result.command = asCommand(item.command);
|
|
}
|
|
if (item.isPreferred !== undefined) {
|
|
result.isPreferred = item.isPreferred;
|
|
}
|
|
if (item.disabled !== undefined) {
|
|
result.disabled = { reason: item.disabled.reason };
|
|
}
|
|
if (item.isAI) {
|
|
result.tags ??= [];
|
|
result.tags.push(proto.CodeActionTag.LLMGenerated);
|
|
}
|
|
return result;
|
|
}
|
|
function asCodeActionSync(item) {
|
|
const result = proto.CodeAction.create(item.title);
|
|
if (item instanceof protocolCodeAction_1.default && item.data !== undefined) {
|
|
result.data = item.data;
|
|
}
|
|
if (item.kind !== undefined) {
|
|
result.kind = asCodeActionKind(item.kind);
|
|
}
|
|
if (item.diagnostics !== undefined) {
|
|
result.diagnostics = asDiagnosticsSync(item.diagnostics);
|
|
}
|
|
if (item.edit !== undefined) {
|
|
throw new Error(`VS Code code actions can only be converted to a protocol code action without an edit.`);
|
|
}
|
|
if (item.command !== undefined) {
|
|
result.command = asCommand(item.command);
|
|
}
|
|
if (item.isPreferred !== undefined) {
|
|
result.isPreferred = item.isPreferred;
|
|
}
|
|
if (item.disabled !== undefined) {
|
|
result.disabled = { reason: item.disabled.reason };
|
|
}
|
|
if (item.isAI) {
|
|
result.tags ??= [];
|
|
result.tags.push(proto.CodeActionTag.LLMGenerated);
|
|
}
|
|
return result;
|
|
}
|
|
async function asCodeActionContext(context, token) {
|
|
if (context === undefined || context === null) {
|
|
return context;
|
|
}
|
|
let only;
|
|
if (context.only && Is.string(context.only.value)) {
|
|
only = [context.only.value];
|
|
}
|
|
return proto.CodeActionContext.create(await asDiagnostics(context.diagnostics, token), only, asCodeActionTriggerKind(context.triggerKind));
|
|
}
|
|
function asCodeActionContextSync(context) {
|
|
if (context === undefined || context === null) {
|
|
return context;
|
|
}
|
|
let only;
|
|
if (context.only && Is.string(context.only.value)) {
|
|
only = [context.only.value];
|
|
}
|
|
return proto.CodeActionContext.create(asDiagnosticsSync(context.diagnostics), only, asCodeActionTriggerKind(context.triggerKind));
|
|
}
|
|
function asCodeActionTriggerKind(kind) {
|
|
switch (kind) {
|
|
case code.CodeActionTriggerKind.Invoke:
|
|
return proto.CodeActionTriggerKind.Invoked;
|
|
case code.CodeActionTriggerKind.Automatic:
|
|
return proto.CodeActionTriggerKind.Automatic;
|
|
default:
|
|
return;
|
|
}
|
|
}
|
|
function asCodeActionKind(item) {
|
|
if (item === undefined || item === null) {
|
|
return;
|
|
}
|
|
return item.value;
|
|
}
|
|
function asInlineValueContext(context) {
|
|
return proto.InlineValueContext.create(context.frameId, asRange(context.stoppedLocation));
|
|
}
|
|
function asInlineCompletionParams(document, position, context) {
|
|
return {
|
|
textDocument: asTextDocumentIdentifier(document),
|
|
position: asPosition(position),
|
|
context: asInlineCompletionContext(context)
|
|
};
|
|
}
|
|
function asInlineCompletionContext(context) {
|
|
return {
|
|
triggerKind: asInlineCompletionTriggerKind(context.triggerKind),
|
|
selectedCompletionInfo: asSelectedCompletionInfo(context.selectedCompletionInfo)
|
|
};
|
|
}
|
|
function asInlineCompletionTriggerKind(kind) {
|
|
switch (kind) {
|
|
case code.InlineCompletionTriggerKind.Invoke:
|
|
return proto.InlineCompletionTriggerKind.Invoked;
|
|
case code.InlineCompletionTriggerKind.Automatic:
|
|
return proto.InlineCompletionTriggerKind.Automatic;
|
|
}
|
|
}
|
|
function asSelectedCompletionInfo(info) {
|
|
if (info === undefined || info === null) {
|
|
return;
|
|
}
|
|
return { range: asRange(info.range), text: info.text };
|
|
}
|
|
function asCommand(item) {
|
|
const result = proto.Command.create(item.title, item.command);
|
|
if (item.tooltip) {
|
|
result.tooltip = item.tooltip;
|
|
}
|
|
if (item.arguments) {
|
|
result.arguments = item.arguments;
|
|
}
|
|
return result;
|
|
}
|
|
function asCodeLens(item) {
|
|
const result = proto.CodeLens.create(asRange(item.range));
|
|
if (item.command) {
|
|
result.command = asCommand(item.command);
|
|
}
|
|
if (item instanceof protocolCodeLens_1.default) {
|
|
if (item.data) {
|
|
result.data = item.data;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
function asFormattingOptions(options, fileOptions) {
|
|
const result = { tabSize: options.tabSize, insertSpaces: options.insertSpaces };
|
|
if (fileOptions.trimTrailingWhitespace) {
|
|
result.trimTrailingWhitespace = true;
|
|
}
|
|
if (fileOptions.trimFinalNewlines) {
|
|
result.trimFinalNewlines = true;
|
|
}
|
|
if (fileOptions.insertFinalNewline) {
|
|
result.insertFinalNewline = true;
|
|
}
|
|
return result;
|
|
}
|
|
function asDocumentSymbolParams(textDocument) {
|
|
return {
|
|
textDocument: asTextDocumentIdentifier(textDocument)
|
|
};
|
|
}
|
|
function asCodeLensParams(textDocument) {
|
|
return {
|
|
textDocument: asTextDocumentIdentifier(textDocument)
|
|
};
|
|
}
|
|
function asDocumentLink(item) {
|
|
const result = proto.DocumentLink.create(asRange(item.range));
|
|
if (item.target) {
|
|
result.target = asUri(item.target);
|
|
}
|
|
if (item.tooltip !== undefined) {
|
|
result.tooltip = item.tooltip;
|
|
}
|
|
const protocolItem = item instanceof protocolDocumentLink_1.default ? item : undefined;
|
|
if (protocolItem && protocolItem.data) {
|
|
result.data = protocolItem.data;
|
|
}
|
|
return result;
|
|
}
|
|
function asDocumentLinkParams(textDocument) {
|
|
return {
|
|
textDocument: asTextDocumentIdentifier(textDocument)
|
|
};
|
|
}
|
|
function asCallHierarchyItem(value) {
|
|
const result = {
|
|
name: value.name,
|
|
kind: asSymbolKind(value.kind),
|
|
uri: asUri(value.uri),
|
|
range: asRange(value.range),
|
|
selectionRange: asRange(value.selectionRange)
|
|
};
|
|
if (value.detail !== undefined && value.detail.length > 0) {
|
|
result.detail = value.detail;
|
|
}
|
|
if (value.tags !== undefined) {
|
|
result.tags = asSymbolTags(value.tags);
|
|
}
|
|
if (value instanceof protocolCallHierarchyItem_1.default && value.data !== undefined) {
|
|
result.data = value.data;
|
|
}
|
|
return result;
|
|
}
|
|
function asTypeHierarchyItem(value) {
|
|
const result = {
|
|
name: value.name,
|
|
kind: asSymbolKind(value.kind),
|
|
uri: asUri(value.uri),
|
|
range: asRange(value.range),
|
|
selectionRange: asRange(value.selectionRange)
|
|
};
|
|
if (value.detail !== undefined && value.detail.length > 0) {
|
|
result.detail = value.detail;
|
|
}
|
|
if (value.tags !== undefined) {
|
|
result.tags = asSymbolTags(value.tags);
|
|
}
|
|
if (value instanceof protocolTypeHierarchyItem_1.default && value.data !== undefined) {
|
|
result.data = value.data;
|
|
}
|
|
return result;
|
|
}
|
|
function asWorkspaceSymbol(item) {
|
|
const result = item instanceof protocolWorkspaceSymbol_1.default ? { name: item.name, kind: asSymbolKind(item.kind), location: item.hasRange ? asLocation(item.location) : { uri: _uriConverter(item.location.uri) }, data: item.data } : { name: item.name, kind: asSymbolKind(item.kind), location: asLocation(item.location) };
|
|
if (item.tags !== undefined) {
|
|
result.tags = asSymbolTags(item.tags);
|
|
}
|
|
if (item.containerName !== "") {
|
|
result.containerName = item.containerName;
|
|
}
|
|
return result;
|
|
}
|
|
function asInlayHint(item) {
|
|
const label = typeof item.label === "string" ? item.label : item.label.map(asInlayHintLabelPart);
|
|
const result = proto.InlayHint.create(asPosition(item.position), label);
|
|
if (item.kind !== undefined) {
|
|
result.kind = item.kind;
|
|
}
|
|
if (item.textEdits !== undefined) {
|
|
result.textEdits = asTextEdits(item.textEdits);
|
|
}
|
|
if (item.tooltip !== undefined) {
|
|
result.tooltip = asTooltip(item.tooltip);
|
|
}
|
|
if (item.paddingLeft !== undefined) {
|
|
result.paddingLeft = item.paddingLeft;
|
|
}
|
|
if (item.paddingRight !== undefined) {
|
|
result.paddingRight = item.paddingRight;
|
|
}
|
|
if (item instanceof protocolInlayHint_1.default && item.data !== undefined) {
|
|
result.data = item.data;
|
|
}
|
|
return result;
|
|
}
|
|
function asInlayHintLabelPart(item) {
|
|
const result = proto.InlayHintLabelPart.create(item.value);
|
|
if (item.location !== undefined) {
|
|
result.location = asLocation(item.location);
|
|
}
|
|
if (item.command !== undefined) {
|
|
result.command = asCommand(item.command);
|
|
}
|
|
if (item.tooltip !== undefined) {
|
|
result.tooltip = asTooltip(item.tooltip);
|
|
}
|
|
return result;
|
|
}
|
|
function asTooltip(value) {
|
|
if (typeof value === "string") {
|
|
return value;
|
|
}
|
|
const result = {
|
|
kind: proto.MarkupKind.Markdown,
|
|
value: value.value
|
|
};
|
|
return result;
|
|
}
|
|
return {
|
|
asUri,
|
|
asTextDocumentIdentifier,
|
|
asTextDocumentItem,
|
|
asVersionedTextDocumentIdentifier,
|
|
asOpenTextDocumentParams,
|
|
asChangeTextDocumentParams,
|
|
asCloseTextDocumentParams,
|
|
asSaveTextDocumentParams,
|
|
asWillSaveTextDocumentParams,
|
|
asDidCreateFilesParams,
|
|
asDidRenameFilesParams,
|
|
asDidDeleteFilesParams,
|
|
asWillCreateFilesParams,
|
|
asWillRenameFilesParams,
|
|
asWillDeleteFilesParams,
|
|
asTextDocumentPositionParams,
|
|
asCompletionParams,
|
|
asSignatureHelpParams,
|
|
asWorkerPosition,
|
|
asRange,
|
|
asRanges,
|
|
asPosition,
|
|
asPositions,
|
|
asPositionsSync,
|
|
asLocation,
|
|
asDiagnosticSeverity,
|
|
asDiagnosticTag,
|
|
asDiagnostic,
|
|
asDiagnostics,
|
|
asDiagnosticsSync,
|
|
asCompletionItem,
|
|
asTextEdit,
|
|
asSymbolKind,
|
|
asSymbolTag,
|
|
asSymbolTags,
|
|
asReferenceParams,
|
|
asCodeAction,
|
|
asCodeActionSync,
|
|
asCodeActionContext,
|
|
asCodeActionContextSync,
|
|
asInlineValueContext,
|
|
asCommand,
|
|
asCodeLens,
|
|
asFormattingOptions,
|
|
asDocumentSymbolParams,
|
|
asCodeLensParams,
|
|
asDocumentLink,
|
|
asDocumentLinkParams,
|
|
asCallHierarchyItem,
|
|
asTypeHierarchyItem,
|
|
asInlayHint,
|
|
asWorkspaceSymbol,
|
|
asInlineCompletionParams,
|
|
asInlineCompletionContext
|
|
};
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/protocolConverter.js
|
|
var require_protocolConverter = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
|
|
return mod && mod.__esModule ? mod : { default: mod };
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.createConverter = createConverter;
|
|
var code = __importStar(require("vscode"));
|
|
var ls = __importStar(require_api2());
|
|
var Is = __importStar(require_is());
|
|
var async = __importStar(require_async());
|
|
var protocolCompletionItem_1 = __importDefault(require_protocolCompletionItem());
|
|
var protocolCodeLens_1 = __importDefault(require_protocolCodeLens());
|
|
var protocolDocumentLink_1 = __importDefault(require_protocolDocumentLink());
|
|
var protocolCodeAction_1 = __importDefault(require_protocolCodeAction());
|
|
var protocolDiagnostic_1 = require_protocolDiagnostic();
|
|
var protocolCallHierarchyItem_1 = __importDefault(require_protocolCallHierarchyItem());
|
|
var protocolTypeHierarchyItem_1 = __importDefault(require_protocolTypeHierarchyItem());
|
|
var protocolWorkspaceSymbol_1 = __importDefault(require_protocolWorkspaceSymbol());
|
|
var protocolInlayHint_1 = __importDefault(require_protocolInlayHint());
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var CodeBlock;
|
|
(function(CodeBlock2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && Is.string(candidate.language) && Is.string(candidate.value);
|
|
}
|
|
CodeBlock2.is = is;
|
|
})(CodeBlock || (CodeBlock = {}));
|
|
function createConverter(uriConverter, trustMarkdown, supportHtml, supportThemeIcons) {
|
|
const nullConverter = (value) => code.Uri.parse(value);
|
|
const _uriConverter = uriConverter || nullConverter;
|
|
function asUri(value) {
|
|
return _uriConverter(value);
|
|
}
|
|
function asDocumentSelector(selector) {
|
|
const result = [];
|
|
for (const filter of selector) {
|
|
if (typeof filter === "string") {
|
|
result.push(filter);
|
|
} else if (vscode_languageserver_protocol_1.NotebookCellTextDocumentFilter.is(filter)) {
|
|
if (typeof filter.notebook === "string") {
|
|
result.push({ notebookType: filter.notebook, language: filter.language });
|
|
} else {
|
|
const notebookType = filter.notebook.notebookType ?? "*";
|
|
result.push({ notebookType, scheme: filter.notebook.scheme, pattern: asGlobPattern(filter.notebook.pattern), language: filter.language });
|
|
}
|
|
} else if (vscode_languageserver_protocol_1.TextDocumentFilter.is(filter)) {
|
|
result.push({ language: filter.language, scheme: filter.scheme, pattern: asGlobPattern(filter.pattern) });
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
async function asDiagnostics(diagnostics, token) {
|
|
return async.map(diagnostics, asDiagnostic, token);
|
|
}
|
|
function asDiagnosticsSync(diagnostics) {
|
|
const result = new Array(diagnostics.length);
|
|
for (let i = 0;i < diagnostics.length; i++) {
|
|
result[i] = asDiagnostic(diagnostics[i]);
|
|
}
|
|
return result;
|
|
}
|
|
function asDiagnostic(diagnostic) {
|
|
const message = typeof diagnostic.message === "string" ? diagnostic.message : diagnostic.message.kind === "plaintext" ? diagnostic.message.value : "Received a markup diagnostic message but the client does not support it.";
|
|
const result = new protocolDiagnostic_1.ProtocolDiagnostic(asRange(diagnostic.range), message, asDiagnosticSeverity(diagnostic.severity), diagnostic.data);
|
|
if (diagnostic.code !== undefined) {
|
|
if (typeof diagnostic.code === "string" || typeof diagnostic.code === "number") {
|
|
if (ls.CodeDescription.is(diagnostic.codeDescription)) {
|
|
result.code = {
|
|
value: diagnostic.code,
|
|
target: asUri(diagnostic.codeDescription.href)
|
|
};
|
|
} else {
|
|
result.code = diagnostic.code;
|
|
}
|
|
} else if (protocolDiagnostic_1.DiagnosticCode.is(diagnostic.code)) {
|
|
result.hasDiagnosticCode = true;
|
|
const diagnosticCode = diagnostic.code;
|
|
result.code = {
|
|
value: diagnosticCode.value,
|
|
target: asUri(diagnosticCode.target)
|
|
};
|
|
}
|
|
}
|
|
if (diagnostic.source) {
|
|
result.source = diagnostic.source;
|
|
}
|
|
if (diagnostic.relatedInformation) {
|
|
result.relatedInformation = asRelatedInformation(diagnostic.relatedInformation);
|
|
}
|
|
if (Array.isArray(diagnostic.tags)) {
|
|
result.tags = asDiagnosticTags(diagnostic.tags);
|
|
}
|
|
return result;
|
|
}
|
|
function asRelatedInformation(relatedInformation) {
|
|
const result = new Array(relatedInformation.length);
|
|
for (let i = 0;i < relatedInformation.length; i++) {
|
|
const info = relatedInformation[i];
|
|
result[i] = new code.DiagnosticRelatedInformation(asLocation(info.location), info.message);
|
|
}
|
|
return result;
|
|
}
|
|
function asDiagnosticTags(tags) {
|
|
if (!tags) {
|
|
return;
|
|
}
|
|
const result = [];
|
|
for (const tag of tags) {
|
|
const converted = asDiagnosticTag(tag);
|
|
if (converted !== undefined) {
|
|
result.push(converted);
|
|
}
|
|
}
|
|
return result.length > 0 ? result : undefined;
|
|
}
|
|
function asDiagnosticTag(tag) {
|
|
switch (tag) {
|
|
case ls.DiagnosticTag.Unnecessary:
|
|
return code.DiagnosticTag.Unnecessary;
|
|
case ls.DiagnosticTag.Deprecated:
|
|
return code.DiagnosticTag.Deprecated;
|
|
default:
|
|
return;
|
|
}
|
|
}
|
|
function asPosition(value) {
|
|
return value ? new code.Position(value.line, value.character) : undefined;
|
|
}
|
|
function asRange(value) {
|
|
return value ? new code.Range(value.start.line, value.start.character, value.end.line, value.end.character) : undefined;
|
|
}
|
|
async function asRanges(items, token) {
|
|
return async.map(items, (range) => {
|
|
return new code.Range(range.start.line, range.start.character, range.end.line, range.end.character);
|
|
}, token);
|
|
}
|
|
function asDiagnosticSeverity(value) {
|
|
if (value === undefined || value === null) {
|
|
return code.DiagnosticSeverity.Error;
|
|
}
|
|
switch (value) {
|
|
case ls.DiagnosticSeverity.Error:
|
|
return code.DiagnosticSeverity.Error;
|
|
case ls.DiagnosticSeverity.Warning:
|
|
return code.DiagnosticSeverity.Warning;
|
|
case ls.DiagnosticSeverity.Information:
|
|
return code.DiagnosticSeverity.Information;
|
|
case ls.DiagnosticSeverity.Hint:
|
|
return code.DiagnosticSeverity.Hint;
|
|
}
|
|
return code.DiagnosticSeverity.Error;
|
|
}
|
|
function asHoverContent(value) {
|
|
if (Is.string(value)) {
|
|
return asMarkdownString(value);
|
|
} else if (CodeBlock.is(value)) {
|
|
const result = asMarkdownString();
|
|
return result.appendCodeblock(value.value, value.language);
|
|
} else if (Array.isArray(value)) {
|
|
const result = [];
|
|
for (const element of value) {
|
|
const item = asMarkdownString();
|
|
if (CodeBlock.is(element)) {
|
|
item.appendCodeblock(element.value, element.language);
|
|
} else {
|
|
item.appendMarkdown(element);
|
|
}
|
|
result.push(item);
|
|
}
|
|
return result;
|
|
} else {
|
|
return asMarkdownString(value);
|
|
}
|
|
}
|
|
function asDocumentation(value) {
|
|
if (Is.string(value)) {
|
|
return value;
|
|
} else {
|
|
switch (value.kind) {
|
|
case ls.MarkupKind.Markdown:
|
|
return asMarkdownString(value.value);
|
|
case ls.MarkupKind.PlainText:
|
|
return value.value;
|
|
default:
|
|
return `Unsupported Markup content received. Kind is: ${value.kind}`;
|
|
}
|
|
}
|
|
}
|
|
function asMarkdownString(value) {
|
|
let result;
|
|
if (value === undefined || typeof value === "string") {
|
|
result = new code.MarkdownString(value);
|
|
} else {
|
|
switch (value.kind) {
|
|
case ls.MarkupKind.Markdown:
|
|
result = new code.MarkdownString(value.value);
|
|
break;
|
|
case ls.MarkupKind.PlainText:
|
|
result = new code.MarkdownString;
|
|
result.appendText(value.value);
|
|
break;
|
|
default:
|
|
result = new code.MarkdownString;
|
|
result.appendText(`Unsupported Markup content received. Kind is: ${value.kind}`);
|
|
break;
|
|
}
|
|
}
|
|
result.isTrusted = trustMarkdown;
|
|
result.supportHtml = supportHtml;
|
|
result.supportThemeIcons = supportThemeIcons;
|
|
return result;
|
|
}
|
|
function asHover(hover) {
|
|
if (!hover) {
|
|
return;
|
|
}
|
|
return new code.Hover(asHoverContent(hover.contents), asRange(hover.range));
|
|
}
|
|
async function asCompletionResult(value, allCommitCharacters, token) {
|
|
if (!value) {
|
|
return;
|
|
}
|
|
if (Array.isArray(value)) {
|
|
return async.map(value, (item) => asCompletionItem(item, allCommitCharacters), token);
|
|
}
|
|
const list = value;
|
|
const { defaultRange, commitCharacters } = getCompletionItemDefaults(list, allCommitCharacters);
|
|
const converted = await async.map(list.items, (item) => {
|
|
return asCompletionItem(item, commitCharacters, list.applyKind?.commitCharacters, defaultRange, list.itemDefaults?.insertTextMode, list.itemDefaults?.insertTextFormat, list.itemDefaults?.data, list.applyKind?.data);
|
|
}, token);
|
|
return new code.CompletionList(converted, list.isIncomplete);
|
|
}
|
|
function getCompletionItemDefaults(list, allCommitCharacters) {
|
|
const rangeDefaults = list.itemDefaults?.editRange;
|
|
const commitCharacters = list.itemDefaults?.commitCharacters ?? allCommitCharacters;
|
|
return ls.Range.is(rangeDefaults) ? { defaultRange: asRange(rangeDefaults), commitCharacters } : rangeDefaults !== undefined ? { defaultRange: { inserting: asRange(rangeDefaults.insert), replacing: asRange(rangeDefaults.replace) }, commitCharacters } : { defaultRange: undefined, commitCharacters };
|
|
}
|
|
function asCompletionItemKind(value) {
|
|
if (ls.CompletionItemKind.Text <= value && value <= ls.CompletionItemKind.TypeParameter) {
|
|
return [value - 1, undefined];
|
|
}
|
|
return [code.CompletionItemKind.Text, value];
|
|
}
|
|
function asCompletionItemTag(tag) {
|
|
switch (tag) {
|
|
case ls.CompletionItemTag.Deprecated:
|
|
return code.CompletionItemTag.Deprecated;
|
|
}
|
|
return;
|
|
}
|
|
function asCompletionItemTags(tags) {
|
|
if (tags === undefined || tags === null) {
|
|
return [];
|
|
}
|
|
const result = [];
|
|
for (const tag of tags) {
|
|
const converted = asCompletionItemTag(tag);
|
|
if (converted !== undefined) {
|
|
result.push(converted);
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
function asCompletionItem(item, defaultCommitCharacters, commitCharactersApplyKind, defaultRange, defaultInsertTextMode, defaultInsertTextFormat, defaultData, dataApplyKind) {
|
|
const tags = asCompletionItemTags(item.tags);
|
|
const label = asCompletionItemLabel(item);
|
|
const result = new protocolCompletionItem_1.default(label);
|
|
if (item.detail) {
|
|
result.detail = item.detail;
|
|
}
|
|
if (item.documentation) {
|
|
result.documentation = asDocumentation(item.documentation);
|
|
result.documentationFormat = Is.string(item.documentation) ? "$string" : item.documentation.kind;
|
|
}
|
|
if (item.filterText) {
|
|
result.filterText = item.filterText;
|
|
}
|
|
const insertText = asCompletionInsertText(item, defaultRange, defaultInsertTextFormat);
|
|
if (insertText) {
|
|
result.insertText = insertText.text;
|
|
result.range = insertText.range;
|
|
result.fromEdit = insertText.fromEdit;
|
|
}
|
|
if (Is.number(item.kind)) {
|
|
const [itemKind, original] = asCompletionItemKind(item.kind);
|
|
result.kind = itemKind;
|
|
if (original) {
|
|
result.originalItemKind = original;
|
|
}
|
|
}
|
|
if (item.sortText) {
|
|
result.sortText = item.sortText;
|
|
}
|
|
if (item.additionalTextEdits) {
|
|
result.additionalTextEdits = asTextEditsSync(item.additionalTextEdits);
|
|
}
|
|
const commitCharacters = applyCommitCharacters(item, defaultCommitCharacters, commitCharactersApplyKind);
|
|
if (commitCharacters) {
|
|
result.commitCharacters = commitCharacters.slice();
|
|
}
|
|
if (item.command) {
|
|
result.command = asCommand(item.command);
|
|
}
|
|
if (item.deprecated === true || item.deprecated === false) {
|
|
result.deprecated = item.deprecated;
|
|
if (item.deprecated === true) {
|
|
tags.push(code.CompletionItemTag.Deprecated);
|
|
}
|
|
}
|
|
if (item.preselect === true || item.preselect === false) {
|
|
result.preselect = item.preselect;
|
|
}
|
|
const data = applyData(item, defaultData, dataApplyKind);
|
|
if (data !== undefined) {
|
|
result.data = data;
|
|
}
|
|
if (tags.length > 0) {
|
|
result.tags = tags;
|
|
}
|
|
const insertTextMode = item.insertTextMode ?? defaultInsertTextMode;
|
|
if (insertTextMode !== undefined) {
|
|
result.insertTextMode = insertTextMode;
|
|
if (insertTextMode === ls.InsertTextMode.asIs) {
|
|
result.keepWhitespace = true;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
function applyCommitCharacters(item, defaultCommitCharacters, applyKind) {
|
|
if (applyKind === ls.ApplyKind.Merge) {
|
|
if (!defaultCommitCharacters && !item.commitCharacters) {
|
|
return;
|
|
}
|
|
const set = new Set;
|
|
if (defaultCommitCharacters) {
|
|
for (const char of defaultCommitCharacters) {
|
|
set.add(char);
|
|
}
|
|
}
|
|
if (Is.stringArray(item.commitCharacters)) {
|
|
for (const char of item.commitCharacters) {
|
|
set.add(char);
|
|
}
|
|
}
|
|
return Array.from(set);
|
|
}
|
|
return item.commitCharacters !== undefined ? Is.stringArray(item.commitCharacters) ? item.commitCharacters : undefined : defaultCommitCharacters;
|
|
}
|
|
function applyData(item, defaultData, applyKind) {
|
|
if (applyKind === ls.ApplyKind.Merge) {
|
|
const data = {
|
|
...defaultData
|
|
};
|
|
if (item.data) {
|
|
Object.entries(item.data).forEach(([key, value]) => {
|
|
if (value !== undefined && value !== null) {
|
|
data[key] = value;
|
|
}
|
|
});
|
|
}
|
|
return data;
|
|
}
|
|
return item.data ?? defaultData;
|
|
}
|
|
function asCompletionItemLabel(item) {
|
|
if (ls.CompletionItemLabelDetails.is(item.labelDetails)) {
|
|
return {
|
|
label: item.label,
|
|
detail: item.labelDetails.detail,
|
|
description: item.labelDetails.description
|
|
};
|
|
} else {
|
|
return item.label;
|
|
}
|
|
}
|
|
function asCompletionInsertText(item, defaultRange, defaultInsertTextFormat) {
|
|
const insertTextFormat = item.insertTextFormat ?? defaultInsertTextFormat;
|
|
if (item.textEdit !== undefined || defaultRange !== undefined) {
|
|
const [range, newText] = item.textEdit !== undefined ? getCompletionRangeAndText(item.textEdit) : [defaultRange, item.textEditText ?? item.label];
|
|
if (insertTextFormat === ls.InsertTextFormat.Snippet) {
|
|
return { text: new code.SnippetString(newText), range, fromEdit: true };
|
|
} else {
|
|
return { text: newText, range, fromEdit: true };
|
|
}
|
|
} else if (item.insertText) {
|
|
if (insertTextFormat === ls.InsertTextFormat.Snippet) {
|
|
return { text: new code.SnippetString(item.insertText), fromEdit: false };
|
|
} else {
|
|
return { text: item.insertText, fromEdit: false };
|
|
}
|
|
} else {
|
|
return;
|
|
}
|
|
}
|
|
function getCompletionRangeAndText(value) {
|
|
if (ls.InsertReplaceEdit.is(value)) {
|
|
return [{ inserting: asRange(value.insert), replacing: asRange(value.replace) }, value.newText];
|
|
} else {
|
|
return [asRange(value.range), value.newText];
|
|
}
|
|
}
|
|
function asTextEdit(edit) {
|
|
if (!edit) {
|
|
return;
|
|
}
|
|
return new code.TextEdit(asRange(edit.range), edit.newText);
|
|
}
|
|
async function asTextEdits(items, token) {
|
|
if (!items) {
|
|
return;
|
|
}
|
|
return async.map(items, asTextEdit, token);
|
|
}
|
|
function asTextEditsSync(items) {
|
|
if (!items) {
|
|
return;
|
|
}
|
|
const result = new Array(items.length);
|
|
for (let i = 0;i < items.length; i++) {
|
|
result[i] = asTextEdit(items[i]);
|
|
}
|
|
return result;
|
|
}
|
|
async function asSignatureHelp(item, token) {
|
|
if (!item) {
|
|
return;
|
|
}
|
|
const result = new code.SignatureHelp;
|
|
if (Is.number(item.activeSignature)) {
|
|
result.activeSignature = item.activeSignature;
|
|
} else {
|
|
result.activeSignature = 0;
|
|
}
|
|
if (Is.number(item.activeParameter)) {
|
|
result.activeParameter = item.activeParameter;
|
|
} else if (item.activeParameter === null) {
|
|
result.activeParameter = -1;
|
|
} else {
|
|
result.activeParameter = 0;
|
|
}
|
|
if (item.signatures) {
|
|
result.signatures = await asSignatureInformations(item.signatures, token);
|
|
}
|
|
return result;
|
|
}
|
|
async function asSignatureInformations(items, token) {
|
|
return async.mapAsync(items, asSignatureInformation, token);
|
|
}
|
|
async function asSignatureInformation(item, token) {
|
|
const result = new code.SignatureInformation(item.label);
|
|
if (item.documentation !== undefined) {
|
|
result.documentation = asDocumentation(item.documentation);
|
|
}
|
|
if (item.parameters !== undefined) {
|
|
result.parameters = await asParameterInformations(item.parameters, token);
|
|
}
|
|
if (item.activeParameter !== undefined) {
|
|
result.activeParameter = item.activeParameter ?? -1;
|
|
}
|
|
{
|
|
return result;
|
|
}
|
|
}
|
|
function asParameterInformations(items, token) {
|
|
return async.map(items, asParameterInformation, token);
|
|
}
|
|
function asParameterInformation(item) {
|
|
const result = new code.ParameterInformation(item.label);
|
|
if (item.documentation) {
|
|
result.documentation = asDocumentation(item.documentation);
|
|
}
|
|
return result;
|
|
}
|
|
function asLocation(item) {
|
|
return item ? new code.Location(_uriConverter(item.uri), asRange(item.range)) : undefined;
|
|
}
|
|
async function asDeclarationResult(item, token) {
|
|
if (!item) {
|
|
return;
|
|
}
|
|
return asLocationResult(item, token);
|
|
}
|
|
async function asDefinitionResult(item, token) {
|
|
if (!item) {
|
|
return;
|
|
}
|
|
return asLocationResult(item, token);
|
|
}
|
|
function asLocationLink(item) {
|
|
if (!item) {
|
|
return;
|
|
}
|
|
const result = {
|
|
targetUri: _uriConverter(item.targetUri),
|
|
targetRange: asRange(item.targetRange),
|
|
originSelectionRange: asRange(item.originSelectionRange),
|
|
targetSelectionRange: asRange(item.targetSelectionRange)
|
|
};
|
|
if (!result.targetSelectionRange) {
|
|
throw new Error(`targetSelectionRange must not be undefined or null`);
|
|
}
|
|
return result;
|
|
}
|
|
async function asLocationResult(item, token) {
|
|
if (!item) {
|
|
return;
|
|
}
|
|
if (Is.array(item)) {
|
|
if (item.length === 0) {
|
|
return [];
|
|
} else if (ls.LocationLink.is(item[0])) {
|
|
const links = item;
|
|
return async.map(links, asLocationLink, token);
|
|
} else {
|
|
const locations = item;
|
|
return async.map(locations, asLocation, token);
|
|
}
|
|
} else if (ls.LocationLink.is(item)) {
|
|
return [asLocationLink(item)];
|
|
} else {
|
|
return asLocation(item);
|
|
}
|
|
}
|
|
async function asReferences(values, token) {
|
|
if (!values) {
|
|
return;
|
|
}
|
|
return async.map(values, asLocation, token);
|
|
}
|
|
async function asDocumentHighlights(values, token) {
|
|
if (!values) {
|
|
return;
|
|
}
|
|
return async.map(values, asDocumentHighlight, token);
|
|
}
|
|
function asDocumentHighlight(item) {
|
|
const result = new code.DocumentHighlight(asRange(item.range));
|
|
if (Is.number(item.kind)) {
|
|
result.kind = asDocumentHighlightKind(item.kind);
|
|
}
|
|
return result;
|
|
}
|
|
function asDocumentHighlightKind(item) {
|
|
switch (item) {
|
|
case ls.DocumentHighlightKind.Text:
|
|
return code.DocumentHighlightKind.Text;
|
|
case ls.DocumentHighlightKind.Read:
|
|
return code.DocumentHighlightKind.Read;
|
|
case ls.DocumentHighlightKind.Write:
|
|
return code.DocumentHighlightKind.Write;
|
|
}
|
|
return code.DocumentHighlightKind.Text;
|
|
}
|
|
async function asSymbolInformations(values, token) {
|
|
if (!values) {
|
|
return;
|
|
}
|
|
return async.map(values, asSymbolInformation, token);
|
|
}
|
|
function asSymbolKind(item) {
|
|
if (item <= ls.SymbolKind.TypeParameter) {
|
|
return item - 1;
|
|
}
|
|
return code.SymbolKind.Property;
|
|
}
|
|
function asSymbolTag(value) {
|
|
switch (value) {
|
|
case ls.SymbolTag.Deprecated:
|
|
return code.SymbolTag.Deprecated;
|
|
default:
|
|
return;
|
|
}
|
|
}
|
|
function asSymbolTags(items) {
|
|
if (items === undefined || items === null) {
|
|
return;
|
|
}
|
|
const result = [];
|
|
for (const item of items) {
|
|
const converted = asSymbolTag(item);
|
|
if (converted !== undefined) {
|
|
result.push(converted);
|
|
}
|
|
}
|
|
return result.length === 0 ? undefined : result;
|
|
}
|
|
function asSymbolInformation(item) {
|
|
const data = item.data;
|
|
const location = item.location;
|
|
const result = location.range === undefined || data !== undefined ? new protocolWorkspaceSymbol_1.default(item.name, asSymbolKind(item.kind), item.containerName ?? "", location.range === undefined ? _uriConverter(location.uri) : new code.Location(_uriConverter(item.location.uri), asRange(location.range)), data) : new code.SymbolInformation(item.name, asSymbolKind(item.kind), item.containerName ?? "", new code.Location(_uriConverter(item.location.uri), asRange(location.range)));
|
|
fillTags(result, item);
|
|
return result;
|
|
}
|
|
async function asDocumentSymbols(values, token) {
|
|
if (values === undefined || values === null) {
|
|
return;
|
|
}
|
|
return async.map(values, asDocumentSymbol, token);
|
|
}
|
|
function asDocumentSymbol(value) {
|
|
const result = new code.DocumentSymbol(value.name, value.detail || "", asSymbolKind(value.kind), asRange(value.range), asRange(value.selectionRange));
|
|
fillTags(result, value);
|
|
if (value.children !== undefined && value.children.length > 0) {
|
|
const children = [];
|
|
for (const child of value.children) {
|
|
children.push(asDocumentSymbol(child));
|
|
}
|
|
result.children = children;
|
|
}
|
|
return result;
|
|
}
|
|
function fillTags(result, value) {
|
|
result.tags = asSymbolTags(value.tags);
|
|
if (value.deprecated) {
|
|
if (!result.tags) {
|
|
result.tags = [code.SymbolTag.Deprecated];
|
|
} else {
|
|
if (!result.tags.includes(code.SymbolTag.Deprecated)) {
|
|
result.tags = result.tags.concat(code.SymbolTag.Deprecated);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
function asCommand(item) {
|
|
const result = { title: item.title, command: item.command };
|
|
if (item.tooltip) {
|
|
result.tooltip = item.tooltip;
|
|
}
|
|
if (item.arguments) {
|
|
result.arguments = item.arguments;
|
|
}
|
|
return result;
|
|
}
|
|
async function asCommands(items, token) {
|
|
if (!items) {
|
|
return;
|
|
}
|
|
return async.map(items, asCommand, token);
|
|
}
|
|
const kindMapping = new Map;
|
|
kindMapping.set(ls.CodeActionKind.Empty, code.CodeActionKind.Empty);
|
|
kindMapping.set(ls.CodeActionKind.QuickFix, code.CodeActionKind.QuickFix);
|
|
kindMapping.set(ls.CodeActionKind.Refactor, code.CodeActionKind.Refactor);
|
|
kindMapping.set(ls.CodeActionKind.RefactorExtract, code.CodeActionKind.RefactorExtract);
|
|
kindMapping.set(ls.CodeActionKind.RefactorInline, code.CodeActionKind.RefactorInline);
|
|
kindMapping.set(ls.CodeActionKind.RefactorRewrite, code.CodeActionKind.RefactorRewrite);
|
|
kindMapping.set(ls.CodeActionKind.Source, code.CodeActionKind.Source);
|
|
kindMapping.set(ls.CodeActionKind.SourceOrganizeImports, code.CodeActionKind.SourceOrganizeImports);
|
|
function asCodeActionKind(item) {
|
|
if (item === undefined || item === null) {
|
|
return;
|
|
}
|
|
let result = kindMapping.get(item);
|
|
if (result) {
|
|
return result;
|
|
}
|
|
const parts = item.split(".");
|
|
result = code.CodeActionKind.Empty;
|
|
for (const part of parts) {
|
|
result = result.append(part);
|
|
}
|
|
return result;
|
|
}
|
|
function asCodeActionKinds(items) {
|
|
if (items === undefined || items === null) {
|
|
return;
|
|
}
|
|
return items.map((kind) => asCodeActionKind(kind));
|
|
}
|
|
function asCodeActionDocumentations(items) {
|
|
if (items === undefined || items === null) {
|
|
return;
|
|
}
|
|
return items.map((doc) => ({ kind: asCodeActionKind(doc.kind), command: asCommand(doc.command) }));
|
|
}
|
|
async function asCodeAction(item, token) {
|
|
if (item === undefined || item === null) {
|
|
return;
|
|
}
|
|
const result = new protocolCodeAction_1.default(item.title, item.data);
|
|
if (item.kind !== undefined) {
|
|
result.kind = asCodeActionKind(item.kind);
|
|
}
|
|
if (item.diagnostics !== undefined) {
|
|
result.diagnostics = asDiagnosticsSync(item.diagnostics);
|
|
}
|
|
if (item.edit !== undefined) {
|
|
result.edit = await asWorkspaceEdit(item.edit, token);
|
|
}
|
|
if (item.command !== undefined) {
|
|
result.command = asCommand(item.command);
|
|
}
|
|
if (item.isPreferred !== undefined) {
|
|
result.isPreferred = item.isPreferred;
|
|
}
|
|
if (item.disabled !== undefined) {
|
|
result.disabled = { reason: item.disabled.reason };
|
|
}
|
|
if (item.tags?.includes(ls.CodeActionTag.LLMGenerated)) {
|
|
result.isAI = true;
|
|
}
|
|
return result;
|
|
}
|
|
function asCodeActionResult(items, token) {
|
|
return async.mapAsync(items, async (item) => {
|
|
if (ls.Command.is(item)) {
|
|
return asCommand(item);
|
|
} else {
|
|
return asCodeAction(item, token);
|
|
}
|
|
}, token);
|
|
}
|
|
function asCodeLens(item) {
|
|
if (!item) {
|
|
return;
|
|
}
|
|
const result = new protocolCodeLens_1.default(asRange(item.range));
|
|
if (item.command) {
|
|
result.command = asCommand(item.command);
|
|
}
|
|
if (item.data !== undefined && item.data !== null) {
|
|
result.data = item.data;
|
|
}
|
|
return result;
|
|
}
|
|
async function asCodeLenses(items, token) {
|
|
if (!items) {
|
|
return;
|
|
}
|
|
return async.map(items, asCodeLens, token);
|
|
}
|
|
async function asWorkspaceEdit(item, token) {
|
|
if (!item) {
|
|
return;
|
|
}
|
|
const sharedMetadata = new Map;
|
|
if (item.changeAnnotations !== undefined) {
|
|
const changeAnnotations = item.changeAnnotations;
|
|
await async.forEach(Object.keys(changeAnnotations), (key) => {
|
|
const metaData = asWorkspaceEditEntryMetadata(changeAnnotations[key]);
|
|
sharedMetadata.set(key, metaData);
|
|
}, token);
|
|
}
|
|
const asMetadata = (annotation) => {
|
|
if (annotation === undefined) {
|
|
return;
|
|
} else {
|
|
return sharedMetadata.get(annotation);
|
|
}
|
|
};
|
|
const result = new code.WorkspaceEdit;
|
|
if (item.documentChanges) {
|
|
const documentChanges = item.documentChanges;
|
|
await async.forEach(documentChanges, (change) => {
|
|
if (ls.CreateFile.is(change)) {
|
|
result.createFile(_uriConverter(change.uri), change.options, asMetadata(change.annotationId));
|
|
} else if (ls.RenameFile.is(change)) {
|
|
result.renameFile(_uriConverter(change.oldUri), _uriConverter(change.newUri), change.options, asMetadata(change.annotationId));
|
|
} else if (ls.DeleteFile.is(change)) {
|
|
result.deleteFile(_uriConverter(change.uri), change.options, asMetadata(change.annotationId));
|
|
} else if (ls.TextDocumentEdit.is(change)) {
|
|
const uri = _uriConverter(change.textDocument.uri);
|
|
const edits = [];
|
|
for (const edit of change.edits) {
|
|
if (ls.AnnotatedTextEdit.is(edit)) {
|
|
edits.push([new code.TextEdit(asRange(edit.range), edit.newText), asMetadata(edit.annotationId)]);
|
|
} else if (ls.SnippetTextEdit.is(edit)) {
|
|
edits.push([new code.SnippetTextEdit(asRange(edit.range), new code.SnippetString(edit.snippet.value)), asMetadata(edit.annotationId)]);
|
|
} else {
|
|
edits.push([new code.TextEdit(asRange(edit.range), edit.newText), undefined]);
|
|
}
|
|
}
|
|
result.set(uri, edits);
|
|
} else {
|
|
throw new Error(`Unknown workspace edit change received:
|
|
${JSON.stringify(change, undefined, 4)}`);
|
|
}
|
|
}, token);
|
|
} else if (item.changes) {
|
|
const changes = item.changes;
|
|
await async.forEach(Object.keys(changes), (key) => {
|
|
result.set(_uriConverter(key), asTextEditsSync(changes[key]));
|
|
}, token);
|
|
}
|
|
return result;
|
|
}
|
|
function asWorkspaceEditEntryMetadata(annotation) {
|
|
if (annotation === undefined) {
|
|
return;
|
|
}
|
|
return { label: annotation.label, needsConfirmation: !!annotation.needsConfirmation, description: annotation.description };
|
|
}
|
|
function asDocumentLink(item) {
|
|
const range = asRange(item.range);
|
|
const target = item.target ? asUri(item.target) : undefined;
|
|
const link = new protocolDocumentLink_1.default(range, target);
|
|
if (item.tooltip !== undefined) {
|
|
link.tooltip = item.tooltip;
|
|
}
|
|
if (item.data !== undefined && item.data !== null) {
|
|
link.data = item.data;
|
|
}
|
|
return link;
|
|
}
|
|
async function asDocumentLinks(items, token) {
|
|
if (!items) {
|
|
return;
|
|
}
|
|
return async.map(items, asDocumentLink, token);
|
|
}
|
|
function asColor(color) {
|
|
return new code.Color(color.red, color.green, color.blue, color.alpha);
|
|
}
|
|
function asColorInformation(ci) {
|
|
return new code.ColorInformation(asRange(ci.range), asColor(ci.color));
|
|
}
|
|
async function asColorInformations(colorInformation, token) {
|
|
if (!colorInformation) {
|
|
return;
|
|
}
|
|
return async.map(colorInformation, asColorInformation, token);
|
|
}
|
|
function asColorPresentation(cp) {
|
|
const presentation = new code.ColorPresentation(cp.label);
|
|
presentation.additionalTextEdits = asTextEditsSync(cp.additionalTextEdits);
|
|
if (cp.textEdit) {
|
|
presentation.textEdit = asTextEdit(cp.textEdit);
|
|
}
|
|
return presentation;
|
|
}
|
|
async function asColorPresentations(colorPresentations, token) {
|
|
if (!colorPresentations) {
|
|
return;
|
|
}
|
|
return async.map(colorPresentations, asColorPresentation, token);
|
|
}
|
|
function asFoldingRangeKind(kind) {
|
|
if (kind) {
|
|
switch (kind) {
|
|
case ls.FoldingRangeKind.Comment:
|
|
return code.FoldingRangeKind.Comment;
|
|
case ls.FoldingRangeKind.Imports:
|
|
return code.FoldingRangeKind.Imports;
|
|
case ls.FoldingRangeKind.Region:
|
|
return code.FoldingRangeKind.Region;
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
function asFoldingRange(r) {
|
|
return new code.FoldingRange(r.startLine, r.endLine, asFoldingRangeKind(r.kind));
|
|
}
|
|
async function asFoldingRanges(foldingRanges, token) {
|
|
if (!foldingRanges) {
|
|
return;
|
|
}
|
|
return async.map(foldingRanges, asFoldingRange, token);
|
|
}
|
|
function asSelectionRange(selectionRange) {
|
|
return new code.SelectionRange(asRange(selectionRange.range), selectionRange.parent ? asSelectionRange(selectionRange.parent) : undefined);
|
|
}
|
|
async function asSelectionRanges(selectionRanges, token) {
|
|
if (!Array.isArray(selectionRanges)) {
|
|
return [];
|
|
}
|
|
return async.map(selectionRanges, asSelectionRange, token);
|
|
}
|
|
function asInlineValue(inlineValue) {
|
|
if (ls.InlineValueText.is(inlineValue)) {
|
|
return new code.InlineValueText(asRange(inlineValue.range), inlineValue.text);
|
|
} else if (ls.InlineValueVariableLookup.is(inlineValue)) {
|
|
return new code.InlineValueVariableLookup(asRange(inlineValue.range), inlineValue.variableName, inlineValue.caseSensitiveLookup);
|
|
} else {
|
|
return new code.InlineValueEvaluatableExpression(asRange(inlineValue.range), inlineValue.expression);
|
|
}
|
|
}
|
|
async function asInlineValues(inlineValues, token) {
|
|
if (!Array.isArray(inlineValues)) {
|
|
return [];
|
|
}
|
|
return async.map(inlineValues, asInlineValue, token);
|
|
}
|
|
async function asInlayHint(value, token) {
|
|
const label = typeof value.label === "string" ? value.label : await async.map(value.label, asInlayHintLabelPart, token);
|
|
const result = new protocolInlayHint_1.default(asPosition(value.position), label);
|
|
if (value.kind !== undefined) {
|
|
result.kind = value.kind;
|
|
}
|
|
if (value.textEdits !== undefined) {
|
|
result.textEdits = await asTextEdits(value.textEdits, token);
|
|
}
|
|
if (value.tooltip !== undefined) {
|
|
result.tooltip = asTooltip(value.tooltip);
|
|
}
|
|
if (value.paddingLeft !== undefined) {
|
|
result.paddingLeft = value.paddingLeft;
|
|
}
|
|
if (value.paddingRight !== undefined) {
|
|
result.paddingRight = value.paddingRight;
|
|
}
|
|
if (value.data !== undefined) {
|
|
result.data = value.data;
|
|
}
|
|
return result;
|
|
}
|
|
function asInlayHintLabelPart(part) {
|
|
const result = new code.InlayHintLabelPart(part.value);
|
|
if (part.location !== undefined) {
|
|
result.location = asLocation(part.location);
|
|
}
|
|
if (part.tooltip !== undefined) {
|
|
result.tooltip = asTooltip(part.tooltip);
|
|
}
|
|
if (part.command !== undefined) {
|
|
result.command = asCommand(part.command);
|
|
}
|
|
return result;
|
|
}
|
|
function asTooltip(value) {
|
|
if (typeof value === "string") {
|
|
return value;
|
|
}
|
|
return asMarkdownString(value);
|
|
}
|
|
async function asInlayHints(values, token) {
|
|
if (!Array.isArray(values)) {
|
|
return;
|
|
}
|
|
return async.mapAsync(values, asInlayHint, token);
|
|
}
|
|
function asCallHierarchyItem(item) {
|
|
if (item === null) {
|
|
return;
|
|
}
|
|
const result = new protocolCallHierarchyItem_1.default(asSymbolKind(item.kind), item.name, item.detail || "", asUri(item.uri), asRange(item.range), asRange(item.selectionRange), item.data);
|
|
if (item.tags !== undefined) {
|
|
result.tags = asSymbolTags(item.tags);
|
|
}
|
|
return result;
|
|
}
|
|
async function asCallHierarchyItems(items, token) {
|
|
if (items === null) {
|
|
return;
|
|
}
|
|
return async.map(items, asCallHierarchyItem, token);
|
|
}
|
|
async function asCallHierarchyIncomingCall(item, token) {
|
|
return new code.CallHierarchyIncomingCall(asCallHierarchyItem(item.from), await asRanges(item.fromRanges, token));
|
|
}
|
|
async function asCallHierarchyIncomingCalls(items, token) {
|
|
if (items === null) {
|
|
return;
|
|
}
|
|
return async.mapAsync(items, asCallHierarchyIncomingCall, token);
|
|
}
|
|
async function asCallHierarchyOutgoingCall(item, token) {
|
|
return new code.CallHierarchyOutgoingCall(asCallHierarchyItem(item.to), await asRanges(item.fromRanges, token));
|
|
}
|
|
async function asCallHierarchyOutgoingCalls(items, token) {
|
|
if (items === null) {
|
|
return;
|
|
}
|
|
return async.mapAsync(items, asCallHierarchyOutgoingCall, token);
|
|
}
|
|
async function asSemanticTokens(value, _token) {
|
|
if (value === undefined || value === null) {
|
|
return;
|
|
}
|
|
return new code.SemanticTokens(new Uint32Array(value.data), value.resultId);
|
|
}
|
|
function asSemanticTokensEdit(value) {
|
|
return new code.SemanticTokensEdit(value.start, value.deleteCount, value.data !== undefined ? new Uint32Array(value.data) : undefined);
|
|
}
|
|
async function asSemanticTokensEdits(value, _token) {
|
|
if (value === undefined || value === null) {
|
|
return;
|
|
}
|
|
return new code.SemanticTokensEdits(value.edits.map(asSemanticTokensEdit), value.resultId);
|
|
}
|
|
function asSemanticTokensLegend(value) {
|
|
return value;
|
|
}
|
|
async function asLinkedEditingRanges(value, token) {
|
|
if (value === null || value === undefined) {
|
|
return;
|
|
}
|
|
return new code.LinkedEditingRanges(await asRanges(value.ranges, token), asRegularExpression(value.wordPattern));
|
|
}
|
|
function asRegularExpression(value) {
|
|
if (value === null || value === undefined) {
|
|
return;
|
|
}
|
|
return new RegExp(value);
|
|
}
|
|
function asTypeHierarchyItem(item) {
|
|
if (item === null) {
|
|
return;
|
|
}
|
|
const result = new protocolTypeHierarchyItem_1.default(asSymbolKind(item.kind), item.name, item.detail || "", asUri(item.uri), asRange(item.range), asRange(item.selectionRange), item.data);
|
|
if (item.tags !== undefined) {
|
|
result.tags = asSymbolTags(item.tags);
|
|
}
|
|
return result;
|
|
}
|
|
async function asTypeHierarchyItems(items, token) {
|
|
if (items === null) {
|
|
return;
|
|
}
|
|
return async.map(items, asTypeHierarchyItem, token);
|
|
}
|
|
function asGlobPattern(pattern) {
|
|
if (Is.string(pattern)) {
|
|
return pattern;
|
|
}
|
|
if (ls.RelativePattern.is(pattern)) {
|
|
if (ls.URI.is(pattern.baseUri)) {
|
|
return new code.RelativePattern(asUri(pattern.baseUri), pattern.pattern);
|
|
} else if (ls.WorkspaceFolder.is(pattern.baseUri)) {
|
|
const workspaceFolder = code.workspace.getWorkspaceFolder(asUri(pattern.baseUri.uri));
|
|
return workspaceFolder !== undefined ? new code.RelativePattern(workspaceFolder, pattern.pattern) : undefined;
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
async function asInlineCompletionResult(value, token) {
|
|
if (!value) {
|
|
return;
|
|
}
|
|
if (Array.isArray(value)) {
|
|
return async.map(value, (item) => asInlineCompletionItem(item), token);
|
|
}
|
|
const list = value;
|
|
const converted = await async.map(list.items, (item) => {
|
|
return asInlineCompletionItem(item);
|
|
}, token);
|
|
return new code.InlineCompletionList(converted);
|
|
}
|
|
function asInlineCompletionItem(item) {
|
|
let insertText;
|
|
if (typeof item.insertText === "string") {
|
|
insertText = item.insertText;
|
|
} else {
|
|
insertText = new code.SnippetString(item.insertText.value);
|
|
}
|
|
let command = undefined;
|
|
if (item.command) {
|
|
command = asCommand(item.command);
|
|
}
|
|
const inlineCompletionItem = new code.InlineCompletionItem(insertText, asRange(item.range), command);
|
|
if (item.filterText) {
|
|
inlineCompletionItem.filterText = item.filterText;
|
|
}
|
|
return inlineCompletionItem;
|
|
}
|
|
return {
|
|
asUri,
|
|
asDocumentSelector,
|
|
asDiagnostics,
|
|
asDiagnostic,
|
|
asRange,
|
|
asRanges,
|
|
asPosition,
|
|
asDiagnosticSeverity,
|
|
asDiagnosticTag,
|
|
asHover,
|
|
asCompletionResult,
|
|
asCompletionItem,
|
|
asTextEdit,
|
|
asTextEdits,
|
|
asSignatureHelp,
|
|
asSignatureInformations,
|
|
asSignatureInformation,
|
|
asParameterInformations,
|
|
asParameterInformation,
|
|
asDeclarationResult,
|
|
asDefinitionResult,
|
|
asLocation,
|
|
asReferences,
|
|
asDocumentHighlights,
|
|
asDocumentHighlight,
|
|
asDocumentHighlightKind,
|
|
asSymbolKind,
|
|
asSymbolTag,
|
|
asSymbolTags,
|
|
asSymbolInformations,
|
|
asSymbolInformation,
|
|
asDocumentSymbols,
|
|
asDocumentSymbol,
|
|
asCommand,
|
|
asCommands,
|
|
asCodeAction,
|
|
asCodeActionKind,
|
|
asCodeActionKinds,
|
|
asCodeActionDocumentations,
|
|
asCodeActionResult,
|
|
asCodeLens,
|
|
asCodeLenses,
|
|
asWorkspaceEdit,
|
|
asDocumentLink,
|
|
asDocumentLinks,
|
|
asFoldingRangeKind,
|
|
asFoldingRange,
|
|
asFoldingRanges,
|
|
asColor,
|
|
asColorInformation,
|
|
asColorInformations,
|
|
asColorPresentation,
|
|
asColorPresentations,
|
|
asSelectionRange,
|
|
asSelectionRanges,
|
|
asInlineValue,
|
|
asInlineValues,
|
|
asInlayHint,
|
|
asInlayHints,
|
|
asSemanticTokensLegend,
|
|
asSemanticTokens,
|
|
asSemanticTokensEdit,
|
|
asSemanticTokensEdits,
|
|
asCallHierarchyItem,
|
|
asCallHierarchyItems,
|
|
asCallHierarchyIncomingCall,
|
|
asCallHierarchyIncomingCalls,
|
|
asCallHierarchyOutgoingCall,
|
|
asCallHierarchyOutgoingCalls,
|
|
asLinkedEditingRanges,
|
|
asTypeHierarchyItem,
|
|
asTypeHierarchyItems,
|
|
asGlobPattern,
|
|
asInlineCompletionResult,
|
|
asInlineCompletionItem
|
|
};
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/utils/uuid.js
|
|
var require_uuid = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.empty = undefined;
|
|
exports2.v4 = v4;
|
|
exports2.isUUID = isUUID;
|
|
exports2.parse = parse;
|
|
exports2.generateUuid = generateUuid;
|
|
|
|
class ValueUUID {
|
|
_value;
|
|
constructor(_value) {
|
|
this._value = _value;
|
|
}
|
|
asHex() {
|
|
return this._value;
|
|
}
|
|
equals(other) {
|
|
return this.asHex() === other.asHex();
|
|
}
|
|
}
|
|
|
|
class V4UUID extends ValueUUID {
|
|
static _chars = ["0", "1", "2", "3", "4", "5", "6", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
|
|
static _timeHighBits = ["8", "9", "a", "b"];
|
|
static _oneOf(array) {
|
|
return array[Math.floor(array.length * Math.random())];
|
|
}
|
|
static _randomHex() {
|
|
return V4UUID._oneOf(V4UUID._chars);
|
|
}
|
|
constructor() {
|
|
super([
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
"-",
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
"-",
|
|
"4",
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
"-",
|
|
V4UUID._oneOf(V4UUID._timeHighBits),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
"-",
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex(),
|
|
V4UUID._randomHex()
|
|
].join(""));
|
|
}
|
|
}
|
|
exports2.empty = new ValueUUID("00000000-0000-0000-0000-000000000000");
|
|
function v4() {
|
|
return new V4UUID;
|
|
}
|
|
var _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
function isUUID(value) {
|
|
return _UUIDPattern.test(value);
|
|
}
|
|
function parse(value) {
|
|
if (!isUUID(value)) {
|
|
throw new Error("invalid uuid");
|
|
}
|
|
return new ValueUUID(value);
|
|
}
|
|
function generateUuid() {
|
|
return v4().asHex();
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/progressPart.js
|
|
var require_progressPart = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ProgressPart = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var Is = __importStar(require_is());
|
|
|
|
class ProgressPart {
|
|
_client;
|
|
_token;
|
|
_infinite;
|
|
_reported;
|
|
_lspProgressDisposable;
|
|
_progress;
|
|
_cancellationToken;
|
|
_tokenDisposable;
|
|
_resolve;
|
|
_reject;
|
|
constructor(_client, _token, done) {
|
|
this._client = _client;
|
|
this._token = _token;
|
|
this._reported = 0;
|
|
this._infinite = false;
|
|
this._lspProgressDisposable = this._client.onProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, (value) => {
|
|
switch (value.kind) {
|
|
case "begin":
|
|
this.begin(value);
|
|
break;
|
|
case "report":
|
|
this.report(value);
|
|
break;
|
|
case "end":
|
|
this.done();
|
|
done && done(this);
|
|
break;
|
|
}
|
|
});
|
|
}
|
|
begin(params) {
|
|
this._infinite = params.percentage === undefined;
|
|
if (this._lspProgressDisposable === undefined) {
|
|
return;
|
|
}
|
|
vscode_1.window.withProgress({ location: vscode_1.ProgressLocation.Window, cancellable: params.cancellable, title: params.title }, async (progress, cancellationToken) => {
|
|
if (this._lspProgressDisposable === undefined) {
|
|
return;
|
|
}
|
|
this._progress = progress;
|
|
this._cancellationToken = cancellationToken;
|
|
this._tokenDisposable = this._cancellationToken.onCancellationRequested(() => {
|
|
this._client.sendNotification(vscode_languageserver_protocol_1.WorkDoneProgressCancelNotification.type, { token: this._token });
|
|
});
|
|
this.report(params);
|
|
return new Promise((resolve, reject) => {
|
|
this._resolve = resolve;
|
|
this._reject = reject;
|
|
});
|
|
});
|
|
}
|
|
report(params) {
|
|
if (this._infinite && Is.string(params.message)) {
|
|
this._progress !== undefined && this._progress.report({ message: params.message });
|
|
} else if (Is.number(params.percentage)) {
|
|
const percentage = Math.max(0, Math.min(params.percentage, 100));
|
|
const delta = Math.max(0, percentage - this._reported);
|
|
this._reported += delta;
|
|
this._progress !== undefined && this._progress.report({ message: params.message, increment: delta });
|
|
}
|
|
}
|
|
cancel() {
|
|
this.cleanup();
|
|
if (this._reject !== undefined) {
|
|
this._reject();
|
|
this._resolve = undefined;
|
|
this._reject = undefined;
|
|
}
|
|
}
|
|
done() {
|
|
this.cleanup();
|
|
if (this._resolve !== undefined) {
|
|
this._resolve();
|
|
this._resolve = undefined;
|
|
this._reject = undefined;
|
|
}
|
|
}
|
|
cleanup() {
|
|
if (this._lspProgressDisposable !== undefined) {
|
|
this._lspProgressDisposable.dispose();
|
|
this._lspProgressDisposable = undefined;
|
|
}
|
|
if (this._tokenDisposable !== undefined) {
|
|
this._tokenDisposable.dispose();
|
|
this._tokenDisposable = undefined;
|
|
}
|
|
this._progress = undefined;
|
|
this._cancellationToken = undefined;
|
|
}
|
|
}
|
|
exports2.ProgressPart = ProgressPart;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/features.js
|
|
var require_features = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DefaultDiagnosticCollectionProvider = exports2.DiagnosticCollectionSource = exports2.WorkspaceFeature = exports2.TextDocumentLanguageFeature = exports2.TextDocumentEventFeature = exports2.DynamicDocumentFeature = exports2.DynamicFeature = exports2.StaticFeature = exports2.LSPCancellationError = undefined;
|
|
exports2.ensure = ensure;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var Is = __importStar(require_is());
|
|
var UUID = __importStar(require_uuid());
|
|
|
|
class LSPCancellationError extends vscode_1.CancellationError {
|
|
data;
|
|
constructor(data) {
|
|
super();
|
|
this.data = data;
|
|
}
|
|
}
|
|
exports2.LSPCancellationError = LSPCancellationError;
|
|
function ensure(target, key) {
|
|
if (target[key] === undefined) {
|
|
target[key] = {};
|
|
}
|
|
return target[key];
|
|
}
|
|
var StaticFeature;
|
|
(function(StaticFeature2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate !== undefined && candidate !== null && Is.func(candidate.fillClientCapabilities) && Is.func(candidate.initialize) && Is.func(candidate.getState) && Is.func(candidate.clear) && (candidate.fillInitializeParams === undefined || Is.func(candidate.fillInitializeParams));
|
|
}
|
|
StaticFeature2.is = is;
|
|
})(StaticFeature || (exports2.StaticFeature = StaticFeature = {}));
|
|
var DynamicFeature;
|
|
(function(DynamicFeature2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate !== undefined && candidate !== null && Is.func(candidate.fillClientCapabilities) && Is.func(candidate.initialize) && Is.func(candidate.getState) && Is.func(candidate.clear) && (candidate.fillInitializeParams === undefined || Is.func(candidate.fillInitializeParams)) && Is.func(candidate.register) && Is.func(candidate.unregister) && candidate.registrationType !== undefined;
|
|
}
|
|
DynamicFeature2.is = is;
|
|
})(DynamicFeature || (exports2.DynamicFeature = DynamicFeature = {}));
|
|
|
|
class DynamicDocumentFeature {
|
|
_client;
|
|
constructor(client) {
|
|
this._client = client;
|
|
}
|
|
getState() {
|
|
const selectors = this.getDocumentSelectors();
|
|
let count = 0;
|
|
for (const selector of selectors) {
|
|
count++;
|
|
for (const document of vscode_1.workspace.textDocuments) {
|
|
if (vscode_1.languages.match(selector, document) > 0) {
|
|
return { kind: "document", id: this.registrationType.method, registrations: true, matches: true };
|
|
}
|
|
}
|
|
}
|
|
const registrations = count > 0;
|
|
return { kind: "document", id: this.registrationType.method, registrations, matches: false };
|
|
}
|
|
}
|
|
exports2.DynamicDocumentFeature = DynamicDocumentFeature;
|
|
|
|
class TextDocumentEventFeature extends DynamicDocumentFeature {
|
|
_event;
|
|
_type;
|
|
_middleware;
|
|
_createParams;
|
|
_textDocument;
|
|
_selectorFilter;
|
|
_listener;
|
|
_selectors;
|
|
_onAboutToSendNotification;
|
|
_onNotificationSent;
|
|
static textDocumentFilter(selectors, textDocument) {
|
|
for (const selector of selectors) {
|
|
if (vscode_1.languages.match(selector, textDocument) > 0) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
constructor(client, event, type, middleware, createParams, textDocument, selectorFilter) {
|
|
super(client);
|
|
this._event = event;
|
|
this._type = type;
|
|
this._middleware = middleware;
|
|
this._createParams = createParams;
|
|
this._textDocument = textDocument;
|
|
this._selectorFilter = selectorFilter;
|
|
this._selectors = new Map;
|
|
this._onAboutToSendNotification = new vscode_1.EventEmitter;
|
|
this._onNotificationSent = new vscode_1.EventEmitter;
|
|
}
|
|
getStateInfo() {
|
|
return [this._selectors.values(), false];
|
|
}
|
|
getDocumentSelectors() {
|
|
return this._selectors.values();
|
|
}
|
|
register(data) {
|
|
if (!data.registerOptions.documentSelector) {
|
|
return;
|
|
}
|
|
if (!this._listener) {
|
|
this._listener = this._event((data2) => {
|
|
this.callback(data2).catch((error) => {
|
|
this._client.error(`Sending document notification ${this._type.method} failed.`, error);
|
|
});
|
|
});
|
|
}
|
|
this._selectors.set(data.id, this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector));
|
|
}
|
|
async callback(data) {
|
|
const doSend = async (data2) => {
|
|
const textDocument = this.getTextDocument(data2);
|
|
const params = this._createParams(data2);
|
|
this.aboutToSendNotification(textDocument, this._type, params);
|
|
await this._client.sendNotification(this._type, params);
|
|
this.notificationSent(textDocument, this._type, params);
|
|
};
|
|
if (this.matches(data)) {
|
|
const middleware = this._middleware();
|
|
return middleware ? middleware(data, (data2) => doSend(data2)) : doSend(data);
|
|
}
|
|
}
|
|
matches(data) {
|
|
if (this._client.hasDedicatedTextSynchronizationFeature(this._textDocument(data))) {
|
|
return false;
|
|
}
|
|
return !this._selectorFilter || this._selectorFilter(this._selectors.values(), data);
|
|
}
|
|
get onAboutToSendNotification() {
|
|
return this._onAboutToSendNotification.event;
|
|
}
|
|
aboutToSendNotification(textDocument, type, params) {
|
|
this._onAboutToSendNotification.fire({ textDocument, type, params });
|
|
}
|
|
get onNotificationSent() {
|
|
return this._onNotificationSent.event;
|
|
}
|
|
notificationSent(textDocument, type, params) {
|
|
this._onNotificationSent.fire({ textDocument, type, params });
|
|
}
|
|
unregister(id) {
|
|
this._selectors.delete(id);
|
|
if (this._selectors.size === 0 && this._listener) {
|
|
this._listener.dispose();
|
|
this._listener = undefined;
|
|
}
|
|
}
|
|
clear() {
|
|
this._selectors.clear();
|
|
this._onNotificationSent.dispose();
|
|
this._onNotificationSent = new vscode_1.EventEmitter;
|
|
if (this._listener) {
|
|
this._listener.dispose();
|
|
this._listener = undefined;
|
|
}
|
|
}
|
|
getProvider(document) {
|
|
for (const selector of this._selectors.values()) {
|
|
if (vscode_1.languages.match(selector, document) > 0) {
|
|
return {
|
|
send: (data) => {
|
|
return this.callback(data);
|
|
}
|
|
};
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
exports2.TextDocumentEventFeature = TextDocumentEventFeature;
|
|
|
|
class TextDocumentLanguageFeature extends DynamicDocumentFeature {
|
|
_registrationType;
|
|
_registrations;
|
|
constructor(client, registrationType) {
|
|
super(client);
|
|
this._registrationType = registrationType;
|
|
this._registrations = new Map;
|
|
}
|
|
*getDocumentSelectors() {
|
|
for (const registration of this._registrations.values()) {
|
|
const selector = registration.data.registerOptions.documentSelector;
|
|
if (selector === null) {
|
|
continue;
|
|
}
|
|
yield this._client.protocol2CodeConverter.asDocumentSelector(selector);
|
|
}
|
|
}
|
|
get registrationType() {
|
|
return this._registrationType;
|
|
}
|
|
register(data) {
|
|
if (!data.registerOptions.documentSelector) {
|
|
return;
|
|
}
|
|
const registration = this.registerLanguageProvider(data.registerOptions, data.id);
|
|
this._registrations.set(data.id, { disposable: registration[0], data, provider: registration[1] });
|
|
}
|
|
unregister(id) {
|
|
const registration = this._registrations.get(id);
|
|
if (registration !== undefined) {
|
|
this._registrations.delete(id);
|
|
registration.disposable.dispose();
|
|
}
|
|
}
|
|
clear() {
|
|
this._registrations.forEach((value) => {
|
|
value.disposable.dispose();
|
|
});
|
|
this._registrations.clear();
|
|
}
|
|
getRegistration(documentSelector, capability) {
|
|
if (!capability) {
|
|
return [undefined, undefined];
|
|
} else if (vscode_languageserver_protocol_1.TextDocumentRegistrationOptions.is(capability)) {
|
|
const id = vscode_languageserver_protocol_1.StaticRegistrationOptions.hasId(capability) ? capability.id : UUID.generateUuid();
|
|
const selector = capability.documentSelector ?? documentSelector;
|
|
if (selector) {
|
|
return [id, Object.assign({}, capability, { documentSelector: selector })];
|
|
}
|
|
} else if (Is.boolean(capability) && capability === true || vscode_languageserver_protocol_1.WorkDoneProgressOptions.is(capability)) {
|
|
if (!documentSelector) {
|
|
return [undefined, undefined];
|
|
}
|
|
const options = Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector });
|
|
return [UUID.generateUuid(), options];
|
|
}
|
|
return [undefined, undefined];
|
|
}
|
|
getRegistrationOptions(documentSelector, capability) {
|
|
if (!documentSelector || !capability) {
|
|
return;
|
|
}
|
|
return Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector });
|
|
}
|
|
getProvider(textDocument) {
|
|
for (const registration of this._registrations.values()) {
|
|
const selector = registration.data.registerOptions.documentSelector;
|
|
if (selector !== null && vscode_1.languages.match(this._client.protocol2CodeConverter.asDocumentSelector(selector), textDocument) > 0) {
|
|
return registration.provider;
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
getAllProviders() {
|
|
const result = [];
|
|
for (const item of this._registrations.values()) {
|
|
result.push(item.provider);
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
exports2.TextDocumentLanguageFeature = TextDocumentLanguageFeature;
|
|
|
|
class WorkspaceFeature {
|
|
_client;
|
|
_registrationType;
|
|
_registrations;
|
|
constructor(client, registrationType) {
|
|
this._client = client;
|
|
this._registrationType = registrationType;
|
|
this._registrations = new Map;
|
|
}
|
|
getState() {
|
|
const registrations = this._registrations.size > 0;
|
|
return { kind: "workspace", id: this._registrationType.method, registrations };
|
|
}
|
|
get registrationType() {
|
|
return this._registrationType;
|
|
}
|
|
register(data) {
|
|
const registration = this.registerLanguageProvider(data.registerOptions);
|
|
this._registrations.set(data.id, { disposable: registration[0], provider: registration[1] });
|
|
}
|
|
unregister(id) {
|
|
const registration = this._registrations.get(id);
|
|
if (registration !== undefined) {
|
|
this._registrations.delete(id);
|
|
registration.disposable.dispose();
|
|
}
|
|
}
|
|
clear() {
|
|
this._registrations.forEach((registration) => {
|
|
registration.disposable.dispose();
|
|
});
|
|
this._registrations.clear();
|
|
}
|
|
getProviders() {
|
|
const result = [];
|
|
for (const registration of this._registrations.values()) {
|
|
result.push(registration.provider);
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
exports2.WorkspaceFeature = WorkspaceFeature;
|
|
var DiagnosticCollectionSource;
|
|
(function(DiagnosticCollectionSource2) {
|
|
DiagnosticCollectionSource2["push"] = "push";
|
|
DiagnosticCollectionSource2["pull"] = "pull";
|
|
})(DiagnosticCollectionSource || (exports2.DiagnosticCollectionSource = DiagnosticCollectionSource = {}));
|
|
|
|
class DefaultDiagnosticCollectionProvider {
|
|
create(name, _source) {
|
|
return name !== undefined ? vscode_1.languages.createDiagnosticCollection(name) : vscode_1.languages.createDiagnosticCollection();
|
|
}
|
|
dispose(collection, _source) {
|
|
collection.dispose();
|
|
}
|
|
}
|
|
exports2.DefaultDiagnosticCollectionProvider = DefaultDiagnosticCollectionProvider;
|
|
});
|
|
|
|
// editors/vscode/node_modules/balanced-match/dist/commonjs/index.js
|
|
var require_commonjs = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.range = exports2.balanced = undefined;
|
|
var balanced = (a, b, str) => {
|
|
const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
|
|
const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
|
|
const r = ma !== null && mb != null && (0, exports2.range)(ma, mb, str);
|
|
return r && {
|
|
start: r[0],
|
|
end: r[1],
|
|
pre: str.slice(0, r[0]),
|
|
body: str.slice(r[0] + ma.length, r[1]),
|
|
post: str.slice(r[1] + mb.length)
|
|
};
|
|
};
|
|
exports2.balanced = balanced;
|
|
var maybeMatch = (reg, str) => {
|
|
const m = str.match(reg);
|
|
return m ? m[0] : null;
|
|
};
|
|
var range = (a, b, str) => {
|
|
let begs, beg, left, right = undefined, result;
|
|
let ai = str.indexOf(a);
|
|
let bi = str.indexOf(b, ai + 1);
|
|
let i = ai;
|
|
if (ai >= 0 && bi > 0) {
|
|
if (a === b) {
|
|
return [ai, bi];
|
|
}
|
|
begs = [];
|
|
left = str.length;
|
|
while (i >= 0 && !result) {
|
|
if (i === ai) {
|
|
begs.push(i);
|
|
ai = str.indexOf(a, i + 1);
|
|
} else if (begs.length === 1) {
|
|
const r = begs.pop();
|
|
if (r !== undefined)
|
|
result = [r, bi];
|
|
} else {
|
|
beg = begs.pop();
|
|
if (beg !== undefined && beg < left) {
|
|
left = beg;
|
|
right = bi;
|
|
}
|
|
bi = str.indexOf(b, i + 1);
|
|
}
|
|
i = ai < bi && ai >= 0 ? ai : bi;
|
|
}
|
|
if (begs.length && right !== undefined) {
|
|
result = [left, right];
|
|
}
|
|
}
|
|
return result;
|
|
};
|
|
exports2.range = range;
|
|
});
|
|
|
|
// editors/vscode/node_modules/brace-expansion/dist/commonjs/index.js
|
|
var require_commonjs2 = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.EXPANSION_MAX_LENGTH = exports2.EXPANSION_MAX = undefined;
|
|
exports2.expand = expand;
|
|
var balanced_match_1 = require_commonjs();
|
|
var escSlash = "\x00SLASH" + Math.random() + "\x00";
|
|
var escOpen = "\x00OPEN" + Math.random() + "\x00";
|
|
var escClose = "\x00CLOSE" + Math.random() + "\x00";
|
|
var escComma = "\x00COMMA" + Math.random() + "\x00";
|
|
var escPeriod = "\x00PERIOD" + Math.random() + "\x00";
|
|
var escSlashPattern = new RegExp(escSlash, "g");
|
|
var escOpenPattern = new RegExp(escOpen, "g");
|
|
var escClosePattern = new RegExp(escClose, "g");
|
|
var escCommaPattern = new RegExp(escComma, "g");
|
|
var escPeriodPattern = new RegExp(escPeriod, "g");
|
|
var slashPattern = /\\\\/g;
|
|
var openPattern = /\\{/g;
|
|
var closePattern = /\\}/g;
|
|
var commaPattern = /\\,/g;
|
|
var periodPattern = /\\\./g;
|
|
exports2.EXPANSION_MAX = 1e5;
|
|
exports2.EXPANSION_MAX_LENGTH = 4000000;
|
|
function numeric(str) {
|
|
return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
|
|
}
|
|
function escapeBraces(str) {
|
|
return str.replace(slashPattern, escSlash).replace(openPattern, escOpen).replace(closePattern, escClose).replace(commaPattern, escComma).replace(periodPattern, escPeriod);
|
|
}
|
|
function unescapeBraces(str) {
|
|
return str.replace(escSlashPattern, "\\").replace(escOpenPattern, "{").replace(escClosePattern, "}").replace(escCommaPattern, ",").replace(escPeriodPattern, ".");
|
|
}
|
|
function parseCommaParts(str) {
|
|
if (!str) {
|
|
return [""];
|
|
}
|
|
const parts = [];
|
|
const m = (0, balanced_match_1.balanced)("{", "}", str);
|
|
if (!m) {
|
|
return str.split(",");
|
|
}
|
|
const { pre, body, post } = m;
|
|
const p = pre.split(",");
|
|
p[p.length - 1] += "{" + body + "}";
|
|
const postParts = parseCommaParts(post);
|
|
if (post.length) {
|
|
p[p.length - 1] += postParts.shift();
|
|
p.push.apply(p, postParts);
|
|
}
|
|
parts.push.apply(parts, p);
|
|
return parts;
|
|
}
|
|
function expand(str, options = {}) {
|
|
if (!str) {
|
|
return [];
|
|
}
|
|
const { max = exports2.EXPANSION_MAX, maxLength = exports2.EXPANSION_MAX_LENGTH } = options;
|
|
if (str.slice(0, 2) === "{}") {
|
|
str = "\\{\\}" + str.slice(2);
|
|
}
|
|
return expand_(escapeBraces(str), max, maxLength, true).map(unescapeBraces);
|
|
}
|
|
function embrace(str) {
|
|
return "{" + str + "}";
|
|
}
|
|
function isPadded(el) {
|
|
return /^-?0\d/.test(el);
|
|
}
|
|
function lte(i, y) {
|
|
return i <= y;
|
|
}
|
|
function gte(i, y) {
|
|
return i >= y;
|
|
}
|
|
function combine(acc, pre, values, max, maxLength, dropEmpties) {
|
|
const out = [];
|
|
let length = 0;
|
|
for (let a = 0;a < acc.length; a++) {
|
|
for (let v = 0;v < values.length; v++) {
|
|
if (out.length >= max)
|
|
return out;
|
|
const expansion = acc[a] + pre + values[v];
|
|
if (dropEmpties && !expansion)
|
|
continue;
|
|
if (length + expansion.length > maxLength)
|
|
return out;
|
|
out.push(expansion);
|
|
length += expansion.length;
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
function expandSequence(body, isAlphaSequence, max, maxLength) {
|
|
const n = body.split(/\.\./);
|
|
const N = [];
|
|
if (n[0] === undefined || n[1] === undefined) {
|
|
return N;
|
|
}
|
|
const x = numeric(n[0]);
|
|
const y = numeric(n[1]);
|
|
const width = Math.max(n[0].length, n[1].length);
|
|
let incr = n.length === 3 && n[2] !== undefined ? Math.max(Math.abs(numeric(n[2])), 1) : 1;
|
|
let test = lte;
|
|
const reverse = y < x;
|
|
if (reverse) {
|
|
incr *= -1;
|
|
test = gte;
|
|
}
|
|
const pad = n.some(isPadded);
|
|
let length = 0;
|
|
for (let i = x;test(i, y) && N.length < max; i += incr) {
|
|
let c;
|
|
if (isAlphaSequence) {
|
|
c = String.fromCharCode(i);
|
|
if (c === "\\") {
|
|
c = "";
|
|
}
|
|
} else {
|
|
c = String(i);
|
|
if (pad) {
|
|
const need = width - c.length;
|
|
if (need > 0) {
|
|
const z = new Array(need + 1).join("0");
|
|
if (i < 0) {
|
|
c = "-" + z + c.slice(1);
|
|
} else {
|
|
c = z + c;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (length + c.length > maxLength)
|
|
break;
|
|
N.push(c);
|
|
length += c.length;
|
|
}
|
|
return N;
|
|
}
|
|
function expand_(str, max, maxLength, isTop) {
|
|
let acc = [""];
|
|
let dropEmpties = false;
|
|
let firstGroup = true;
|
|
for (;; ) {
|
|
const m = (0, balanced_match_1.balanced)("{", "}", str);
|
|
if (!m) {
|
|
return combine(acc, str, [""], max, maxLength, dropEmpties);
|
|
}
|
|
const pre = m.pre;
|
|
if (/\$$/.test(pre)) {
|
|
acc = combine(acc, pre + "{" + m.body + "}", [""], max, maxLength, dropEmpties && !m.post.length);
|
|
firstGroup = false;
|
|
if (!m.post.length)
|
|
break;
|
|
str = m.post;
|
|
continue;
|
|
}
|
|
const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
|
|
const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
|
|
const isSequence = isNumericSequence || isAlphaSequence;
|
|
const isOptions = m.body.indexOf(",") >= 0;
|
|
if (!isSequence && !isOptions) {
|
|
if (m.post.match(/,(?!,).*\}/)) {
|
|
str = m.pre + "{" + m.body + escClose + m.post;
|
|
isTop = true;
|
|
continue;
|
|
}
|
|
return combine(acc, pre + "{" + m.body + "}" + m.post, [""], max, maxLength, dropEmpties);
|
|
}
|
|
if (firstGroup) {
|
|
dropEmpties = isTop && !isSequence;
|
|
firstGroup = false;
|
|
}
|
|
let values;
|
|
if (isSequence) {
|
|
values = expandSequence(m.body, isAlphaSequence, max, maxLength);
|
|
} else {
|
|
let n = parseCommaParts(m.body);
|
|
if (n.length === 1 && n[0] !== undefined) {
|
|
n = expand_(n[0], max, maxLength, false).map(embrace);
|
|
if (n.length === 1) {
|
|
acc = combine(acc, pre + n[0], [""], max, maxLength, dropEmpties && !m.post.length);
|
|
if (!m.post.length)
|
|
break;
|
|
str = m.post;
|
|
continue;
|
|
}
|
|
}
|
|
let dropsEmpties = dropEmpties && !m.post.length && !pre;
|
|
for (let d = 0;dropsEmpties && d < acc.length; d++) {
|
|
if (acc[d]) {
|
|
dropsEmpties = false;
|
|
}
|
|
}
|
|
values = [];
|
|
let valuesLength = 0;
|
|
outer:
|
|
for (let j = 0;j < n.length; j++) {
|
|
const expanded = expand_(n[j], max, maxLength, false);
|
|
for (let k = 0;k < expanded.length; k++) {
|
|
const v = expanded[k];
|
|
if (dropsEmpties && !v)
|
|
continue;
|
|
if (values.length >= max || valuesLength + v.length > maxLength) {
|
|
break outer;
|
|
}
|
|
values.push(v);
|
|
valuesLength += v.length;
|
|
}
|
|
}
|
|
}
|
|
acc = combine(acc, pre, values, max, maxLength, dropEmpties && !m.post.length);
|
|
if (!m.post.length)
|
|
break;
|
|
str = m.post;
|
|
}
|
|
return acc;
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js
|
|
var require_assert_valid_pattern = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.assertValidPattern = undefined;
|
|
var MAX_PATTERN_LENGTH = 1024 * 64;
|
|
var assertValidPattern = (pattern) => {
|
|
if (typeof pattern !== "string") {
|
|
throw new TypeError("invalid pattern");
|
|
}
|
|
if (pattern.length > MAX_PATTERN_LENGTH) {
|
|
throw new TypeError("pattern is too long");
|
|
}
|
|
};
|
|
exports2.assertValidPattern = assertValidPattern;
|
|
});
|
|
|
|
// editors/vscode/node_modules/minimatch/dist/commonjs/brace-expressions.js
|
|
var require_brace_expressions = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.parseClass = undefined;
|
|
var posixClasses = {
|
|
"[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
|
|
"[:alpha:]": ["\\p{L}\\p{Nl}", true],
|
|
"[:ascii:]": ["\\x" + "00-\\x" + "7f", false],
|
|
"[:blank:]": ["\\p{Zs}\\t", true],
|
|
"[:cntrl:]": ["\\p{Cc}", true],
|
|
"[:digit:]": ["\\p{Nd}", true],
|
|
"[:graph:]": ["\\p{Z}\\p{C}", true, true],
|
|
"[:lower:]": ["\\p{Ll}", true],
|
|
"[:print:]": ["\\p{C}", true],
|
|
"[:punct:]": ["\\p{P}", true],
|
|
"[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
|
|
"[:upper:]": ["\\p{Lu}", true],
|
|
"[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
|
|
"[:xdigit:]": ["A-Fa-f0-9", false]
|
|
};
|
|
var braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&");
|
|
var regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
|
|
var rangesToString = (ranges) => ranges.join("");
|
|
var parseClass = (glob, position) => {
|
|
const pos = position;
|
|
if (glob.charAt(pos) !== "[") {
|
|
throw new Error("not in a brace expression");
|
|
}
|
|
const ranges = [];
|
|
const negs = [];
|
|
let i = pos + 1;
|
|
let sawStart = false;
|
|
let uflag = false;
|
|
let escaping = false;
|
|
let negate = false;
|
|
let endPos = pos;
|
|
let rangeStart = "";
|
|
WHILE:
|
|
while (i < glob.length) {
|
|
const c = glob.charAt(i);
|
|
if ((c === "!" || c === "^") && i === pos + 1) {
|
|
negate = true;
|
|
i++;
|
|
continue;
|
|
}
|
|
if (c === "]" && sawStart && !escaping) {
|
|
endPos = i + 1;
|
|
break;
|
|
}
|
|
sawStart = true;
|
|
if (c === "\\") {
|
|
if (!escaping) {
|
|
escaping = true;
|
|
i++;
|
|
continue;
|
|
}
|
|
}
|
|
if (c === "[" && !escaping) {
|
|
for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
|
|
if (glob.startsWith(cls, i)) {
|
|
if (rangeStart) {
|
|
return ["$.", false, glob.length - pos, true];
|
|
}
|
|
i += cls.length;
|
|
if (neg)
|
|
negs.push(unip);
|
|
else
|
|
ranges.push(unip);
|
|
uflag = uflag || u;
|
|
continue WHILE;
|
|
}
|
|
}
|
|
}
|
|
escaping = false;
|
|
if (rangeStart) {
|
|
if (c > rangeStart) {
|
|
ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));
|
|
} else if (c === rangeStart) {
|
|
ranges.push(braceEscape(c));
|
|
}
|
|
rangeStart = "";
|
|
i++;
|
|
continue;
|
|
}
|
|
if (glob.startsWith("-]", i + 1)) {
|
|
ranges.push(braceEscape(c + "-"));
|
|
i += 2;
|
|
continue;
|
|
}
|
|
if (glob.startsWith("-", i + 1)) {
|
|
rangeStart = c;
|
|
i += 2;
|
|
continue;
|
|
}
|
|
ranges.push(braceEscape(c));
|
|
i++;
|
|
}
|
|
if (endPos < i) {
|
|
return ["", false, 0, false];
|
|
}
|
|
if (!ranges.length && !negs.length) {
|
|
return ["$.", false, glob.length - pos, true];
|
|
}
|
|
if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
|
|
const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
|
|
return [regexpEscape(r), false, endPos - pos, false];
|
|
}
|
|
const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
|
|
const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
|
|
const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
|
|
return [comb, uflag, endPos - pos, true];
|
|
};
|
|
exports2.parseClass = parseClass;
|
|
});
|
|
|
|
// editors/vscode/node_modules/minimatch/dist/commonjs/unescape.js
|
|
var require_unescape = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.unescape = undefined;
|
|
var unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true } = {}) => {
|
|
if (magicalBraces) {
|
|
return windowsPathsNoEscape ? s.replace(/\[([^/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^/\\])\]/g, "$1$2").replace(/\\([^/])/g, "$1");
|
|
}
|
|
return windowsPathsNoEscape ? s.replace(/\[([^/\\{}])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^/\\{}])\]/g, "$1$2").replace(/\\([^/{}])/g, "$1");
|
|
};
|
|
exports2.unescape = unescape;
|
|
});
|
|
|
|
// editors/vscode/node_modules/minimatch/dist/commonjs/ast.js
|
|
var require_ast = __commonJS((exports2) => {
|
|
var _a;
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.AST = undefined;
|
|
var brace_expressions_js_1 = require_brace_expressions();
|
|
var unescape_js_1 = require_unescape();
|
|
var types = new Set(["!", "?", "+", "*", "@"]);
|
|
var isExtglobType = (c) => types.has(c);
|
|
var isExtglobAST = (c) => isExtglobType(c.type);
|
|
var adoptionMap = new Map([
|
|
["!", ["@"]],
|
|
["?", ["?", "@"]],
|
|
["@", ["@"]],
|
|
["*", ["*", "+", "?", "@"]],
|
|
["+", ["+", "@"]]
|
|
]);
|
|
var adoptionWithSpaceMap = new Map([
|
|
["!", ["?"]],
|
|
["@", ["?"]],
|
|
["+", ["?", "*"]]
|
|
]);
|
|
var adoptionAnyMap = new Map([
|
|
["!", ["?", "@"]],
|
|
["?", ["?", "@"]],
|
|
["@", ["?", "@"]],
|
|
["*", ["*", "+", "?", "@"]],
|
|
["+", ["+", "@", "?", "*"]]
|
|
]);
|
|
var usurpMap = new Map([
|
|
["!", new Map([["!", "@"]])],
|
|
[
|
|
"?",
|
|
new Map([
|
|
["*", "*"],
|
|
["+", "*"]
|
|
])
|
|
],
|
|
[
|
|
"@",
|
|
new Map([
|
|
["!", "!"],
|
|
["?", "?"],
|
|
["@", "@"],
|
|
["*", "*"],
|
|
["+", "+"]
|
|
])
|
|
],
|
|
[
|
|
"+",
|
|
new Map([
|
|
["?", "*"],
|
|
["*", "*"]
|
|
])
|
|
]
|
|
]);
|
|
var startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
|
|
var startNoDot = "(?!\\.)";
|
|
var addPatternStart = new Set(["[", "."]);
|
|
var justDots = new Set(["..", "."]);
|
|
var reSpecials = new Set("().*{}+?[]^$\\!");
|
|
var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
|
|
var qmark = "[^/]";
|
|
var star = qmark + "*?";
|
|
var starNoEmpty = qmark + "+?";
|
|
var ID = 0;
|
|
|
|
class AST {
|
|
type;
|
|
#root;
|
|
#hasMagic;
|
|
#uflag = false;
|
|
#parts = [];
|
|
#parent;
|
|
#parentIndex;
|
|
#negs;
|
|
#filledNegs = false;
|
|
#options;
|
|
#toString;
|
|
#emptyExt = false;
|
|
id = ++ID;
|
|
get depth() {
|
|
return (this.#parent?.depth ?? -1) + 1;
|
|
}
|
|
[Symbol.for("nodejs.util.inspect.custom")]() {
|
|
return {
|
|
"@@type": "AST",
|
|
id: this.id,
|
|
type: this.type,
|
|
root: this.#root.id,
|
|
parent: this.#parent?.id,
|
|
depth: this.depth,
|
|
partsLength: this.#parts.length,
|
|
parts: this.#parts
|
|
};
|
|
}
|
|
constructor(type, parent, options = {}) {
|
|
this.type = type;
|
|
if (type)
|
|
this.#hasMagic = true;
|
|
this.#parent = parent;
|
|
this.#root = this.#parent ? this.#parent.#root : this;
|
|
this.#options = this.#root === this ? options : this.#root.#options;
|
|
this.#negs = this.#root === this ? [] : this.#root.#negs;
|
|
if (type === "!" && !this.#root.#filledNegs)
|
|
this.#negs.push(this);
|
|
this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
|
|
}
|
|
get hasMagic() {
|
|
if (this.#hasMagic !== undefined)
|
|
return this.#hasMagic;
|
|
for (const p of this.#parts) {
|
|
if (typeof p === "string")
|
|
continue;
|
|
if (p.type || p.hasMagic)
|
|
return this.#hasMagic = true;
|
|
}
|
|
return this.#hasMagic;
|
|
}
|
|
toString() {
|
|
return this.#toString !== undefined ? this.#toString : !this.type ? this.#toString = this.#parts.map((p) => String(p)).join("") : this.#toString = this.type + "(" + this.#parts.map((p) => String(p)).join("|") + ")";
|
|
}
|
|
#fillNegs() {
|
|
if (this !== this.#root)
|
|
throw new Error("should only call on root");
|
|
if (this.#filledNegs)
|
|
return this;
|
|
this.toString();
|
|
this.#filledNegs = true;
|
|
let n;
|
|
while (n = this.#negs.pop()) {
|
|
if (n.type !== "!")
|
|
continue;
|
|
let p = n;
|
|
let pp = p.#parent;
|
|
while (pp) {
|
|
for (let i = p.#parentIndex + 1;!pp.type && i < pp.#parts.length; i++) {
|
|
for (const part of n.#parts) {
|
|
if (typeof part === "string") {
|
|
throw new Error("string part in extglob AST??");
|
|
}
|
|
part.copyIn(pp.#parts[i]);
|
|
}
|
|
}
|
|
p = pp;
|
|
pp = p.#parent;
|
|
}
|
|
}
|
|
return this;
|
|
}
|
|
push(...parts) {
|
|
for (const p of parts) {
|
|
if (p === "")
|
|
continue;
|
|
if (typeof p !== "string" && !(p instanceof _a && p.#parent === this)) {
|
|
throw new Error("invalid part: " + p);
|
|
}
|
|
this.#parts.push(p);
|
|
}
|
|
}
|
|
toJSON() {
|
|
const ret = this.type === null ? this.#parts.slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...this.#parts.map((p) => p.toJSON())];
|
|
if (this.isStart() && !this.type)
|
|
ret.unshift([]);
|
|
if (this.isEnd() && (this === this.#root || this.#root.#filledNegs && this.#parent?.type === "!")) {
|
|
ret.push({});
|
|
}
|
|
return ret;
|
|
}
|
|
isStart() {
|
|
if (this.#root === this)
|
|
return true;
|
|
if (!this.#parent?.isStart())
|
|
return false;
|
|
if (this.#parentIndex === 0)
|
|
return true;
|
|
const p = this.#parent;
|
|
for (let i = 0;i < this.#parentIndex; i++) {
|
|
const pp = p.#parts[i];
|
|
if (!(pp instanceof _a && pp.type === "!")) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
isEnd() {
|
|
if (this.#root === this)
|
|
return true;
|
|
if (this.#parent?.type === "!")
|
|
return true;
|
|
if (!this.#parent?.isEnd())
|
|
return false;
|
|
if (!this.type)
|
|
return this.#parent?.isEnd();
|
|
const pl = this.#parent ? this.#parent.#parts.length : 0;
|
|
return this.#parentIndex === pl - 1;
|
|
}
|
|
copyIn(part) {
|
|
if (typeof part === "string")
|
|
this.push(part);
|
|
else
|
|
this.push(part.clone(this));
|
|
}
|
|
clone(parent) {
|
|
const c = new _a(this.type, parent);
|
|
for (const p of this.#parts) {
|
|
c.copyIn(p);
|
|
}
|
|
return c;
|
|
}
|
|
static #parseAST(str, ast, pos, opt, extDepth) {
|
|
const maxDepth = opt.maxExtglobRecursion ?? 2;
|
|
let escaping = false;
|
|
let inBrace = false;
|
|
let braceStart = -1;
|
|
let braceNeg = false;
|
|
if (ast.type === null) {
|
|
let i2 = pos;
|
|
let acc2 = "";
|
|
while (i2 < str.length) {
|
|
const c = str.charAt(i2++);
|
|
if (escaping || c === "\\") {
|
|
escaping = !escaping;
|
|
acc2 += c;
|
|
continue;
|
|
}
|
|
if (inBrace) {
|
|
if (i2 === braceStart + 1) {
|
|
if (c === "^" || c === "!") {
|
|
braceNeg = true;
|
|
}
|
|
} else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) {
|
|
inBrace = false;
|
|
}
|
|
acc2 += c;
|
|
continue;
|
|
} else if (c === "[") {
|
|
inBrace = true;
|
|
braceStart = i2;
|
|
braceNeg = false;
|
|
acc2 += c;
|
|
continue;
|
|
}
|
|
const doRecurse = !opt.noext && isExtglobType(c) && str.charAt(i2) === "(" && extDepth <= maxDepth;
|
|
if (doRecurse) {
|
|
ast.push(acc2);
|
|
acc2 = "";
|
|
const ext = new _a(c, ast);
|
|
i2 = _a.#parseAST(str, ext, i2, opt, extDepth + 1);
|
|
ast.push(ext);
|
|
continue;
|
|
}
|
|
acc2 += c;
|
|
}
|
|
ast.push(acc2);
|
|
return i2;
|
|
}
|
|
let i = pos + 1;
|
|
let part = new _a(null, ast);
|
|
const parts = [];
|
|
let acc = "";
|
|
while (i < str.length) {
|
|
const c = str.charAt(i++);
|
|
if (escaping || c === "\\") {
|
|
escaping = !escaping;
|
|
acc += c;
|
|
continue;
|
|
}
|
|
if (inBrace) {
|
|
if (i === braceStart + 1) {
|
|
if (c === "^" || c === "!") {
|
|
braceNeg = true;
|
|
}
|
|
} else if (c === "]" && !(i === braceStart + 2 && braceNeg)) {
|
|
inBrace = false;
|
|
}
|
|
acc += c;
|
|
continue;
|
|
} else if (c === "[") {
|
|
inBrace = true;
|
|
braceStart = i;
|
|
braceNeg = false;
|
|
acc += c;
|
|
continue;
|
|
}
|
|
const doRecurse = !opt.noext && isExtglobType(c) && str.charAt(i) === "(" && (extDepth <= maxDepth || ast && ast.#canAdoptType(c));
|
|
if (doRecurse) {
|
|
const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
|
|
part.push(acc);
|
|
acc = "";
|
|
const ext = new _a(c, part);
|
|
part.push(ext);
|
|
i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
|
|
continue;
|
|
}
|
|
if (c === "|") {
|
|
part.push(acc);
|
|
acc = "";
|
|
parts.push(part);
|
|
part = new _a(null, ast);
|
|
continue;
|
|
}
|
|
if (c === ")") {
|
|
if (acc === "" && ast.#parts.length === 0) {
|
|
ast.#emptyExt = true;
|
|
}
|
|
part.push(acc);
|
|
acc = "";
|
|
ast.push(...parts, part);
|
|
return i;
|
|
}
|
|
acc += c;
|
|
}
|
|
ast.type = null;
|
|
ast.#hasMagic = undefined;
|
|
ast.#parts = [str.substring(pos - 1)];
|
|
return i;
|
|
}
|
|
#canAdoptWithSpace(child) {
|
|
return this.#canAdopt(child, adoptionWithSpaceMap);
|
|
}
|
|
#canAdopt(child, map = adoptionMap) {
|
|
if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null) {
|
|
return false;
|
|
}
|
|
const gc = child.#parts[0];
|
|
if (!gc || typeof gc !== "object" || gc.type === null) {
|
|
return false;
|
|
}
|
|
return this.#canAdoptType(gc.type, map);
|
|
}
|
|
#canAdoptType(c, map = adoptionAnyMap) {
|
|
return !!map.get(this.type)?.includes(c);
|
|
}
|
|
#adoptWithSpace(child, index) {
|
|
const gc = child.#parts[0];
|
|
const blank = new _a(null, gc, this.options);
|
|
blank.#parts.push("");
|
|
gc.push(blank);
|
|
this.#adopt(child, index);
|
|
}
|
|
#adopt(child, index) {
|
|
const gc = child.#parts[0];
|
|
this.#parts.splice(index, 1, ...gc.#parts);
|
|
for (const p of gc.#parts) {
|
|
if (typeof p === "object")
|
|
p.#parent = this;
|
|
}
|
|
this.#toString = undefined;
|
|
}
|
|
#canUsurpType(c) {
|
|
const m = usurpMap.get(this.type);
|
|
return !!m?.has(c);
|
|
}
|
|
#canUsurp(child) {
|
|
if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null || this.#parts.length !== 1) {
|
|
return false;
|
|
}
|
|
const gc = child.#parts[0];
|
|
if (!gc || typeof gc !== "object" || gc.type === null) {
|
|
return false;
|
|
}
|
|
return this.#canUsurpType(gc.type);
|
|
}
|
|
#usurp(child) {
|
|
const m = usurpMap.get(this.type);
|
|
const gc = child.#parts[0];
|
|
const nt = m?.get(gc.type);
|
|
if (!nt)
|
|
return false;
|
|
this.#parts = gc.#parts;
|
|
for (const p of this.#parts) {
|
|
if (typeof p === "object") {
|
|
p.#parent = this;
|
|
}
|
|
}
|
|
this.type = nt;
|
|
this.#toString = undefined;
|
|
this.#emptyExt = false;
|
|
}
|
|
static fromGlob(pattern, options = {}) {
|
|
const ast = new _a(null, undefined, options);
|
|
_a.#parseAST(pattern, ast, 0, options, 0);
|
|
return ast;
|
|
}
|
|
toMMPattern() {
|
|
if (this !== this.#root)
|
|
return this.#root.toMMPattern();
|
|
const glob = this.toString();
|
|
const [re, body, hasMagic, uflag] = this.toRegExpSource();
|
|
const anyMagic = hasMagic || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob.toUpperCase() !== glob.toLowerCase();
|
|
if (!anyMagic) {
|
|
return body;
|
|
}
|
|
const flags = (this.#options.nocase ? "i" : "") + (uflag ? "u" : "");
|
|
return Object.assign(new RegExp(`^${re}$`, flags), {
|
|
_src: re,
|
|
_glob: glob
|
|
});
|
|
}
|
|
get options() {
|
|
return this.#options;
|
|
}
|
|
toRegExpSource(allowDot) {
|
|
const dot = allowDot ?? !!this.#options.dot;
|
|
if (this.#root === this) {
|
|
this.#flatten();
|
|
this.#fillNegs();
|
|
}
|
|
if (!isExtglobAST(this)) {
|
|
const noEmpty = this.isStart() && this.isEnd() && !this.#parts.some((s) => typeof s !== "string");
|
|
const src = this.#parts.map((p) => {
|
|
const [re, _, hasMagic, uflag] = typeof p === "string" ? _a.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot);
|
|
this.#hasMagic = this.#hasMagic || hasMagic;
|
|
this.#uflag = this.#uflag || uflag;
|
|
return re;
|
|
}).join("");
|
|
let start2 = "";
|
|
if (this.isStart()) {
|
|
if (typeof this.#parts[0] === "string") {
|
|
const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
|
|
if (!dotTravAllowed) {
|
|
const aps = addPatternStart;
|
|
const needNoTrav = dot && aps.has(src.charAt(0)) || src.startsWith("\\.") && aps.has(src.charAt(2)) || src.startsWith("\\.\\.") && aps.has(src.charAt(4));
|
|
const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
|
|
start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";
|
|
}
|
|
}
|
|
}
|
|
let end = "";
|
|
if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === "!") {
|
|
end = "(?:$|\\/)";
|
|
}
|
|
const final2 = start2 + src + end;
|
|
return [
|
|
final2,
|
|
(0, unescape_js_1.unescape)(src),
|
|
this.#hasMagic = !!this.#hasMagic,
|
|
this.#uflag
|
|
];
|
|
}
|
|
const repeated = this.type === "*" || this.type === "+";
|
|
const start = this.type === "!" ? "(?:(?!(?:" : "(?:";
|
|
let body = this.#partsToRegExp(dot);
|
|
if (this.isStart() && this.isEnd() && !body && this.type !== "!") {
|
|
const s = this.toString();
|
|
const me = this;
|
|
me.#parts = [s];
|
|
me.type = null;
|
|
me.#hasMagic = undefined;
|
|
return [s, (0, unescape_js_1.unescape)(this.toString()), false, false];
|
|
}
|
|
let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : this.#partsToRegExp(true);
|
|
if (bodyDotAllowed === body) {
|
|
bodyDotAllowed = "";
|
|
}
|
|
if (bodyDotAllowed) {
|
|
body = `(?:${body})(?:${bodyDotAllowed})*?`;
|
|
}
|
|
let final = "";
|
|
if (this.type === "!" && this.#emptyExt) {
|
|
final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty;
|
|
} else {
|
|
const close = this.type === "!" ? "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star + ")" : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`;
|
|
final = start + body + close;
|
|
}
|
|
return [
|
|
final,
|
|
(0, unescape_js_1.unescape)(body),
|
|
this.#hasMagic = !!this.#hasMagic,
|
|
this.#uflag
|
|
];
|
|
}
|
|
#flatten() {
|
|
if (!isExtglobAST(this)) {
|
|
for (const p of this.#parts) {
|
|
if (typeof p === "object") {
|
|
p.#flatten();
|
|
}
|
|
}
|
|
} else {
|
|
let iterations = 0;
|
|
let done = false;
|
|
do {
|
|
done = true;
|
|
for (let i = 0;i < this.#parts.length; i++) {
|
|
const c = this.#parts[i];
|
|
if (typeof c === "object") {
|
|
c.#flatten();
|
|
if (this.#canAdopt(c)) {
|
|
done = false;
|
|
this.#adopt(c, i);
|
|
} else if (this.#canAdoptWithSpace(c)) {
|
|
done = false;
|
|
this.#adoptWithSpace(c, i);
|
|
} else if (this.#canUsurp(c)) {
|
|
done = false;
|
|
this.#usurp(c);
|
|
}
|
|
}
|
|
}
|
|
} while (!done && ++iterations < 10);
|
|
}
|
|
this.#toString = undefined;
|
|
}
|
|
#partsToRegExp(dot) {
|
|
return this.#parts.map((p) => {
|
|
if (typeof p === "string") {
|
|
throw new Error("string type in extglob ast??");
|
|
}
|
|
const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
|
|
this.#uflag = this.#uflag || uflag;
|
|
return re;
|
|
}).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");
|
|
}
|
|
static #parseGlob(glob, hasMagic, noEmpty = false) {
|
|
let escaping = false;
|
|
let re = "";
|
|
let uflag = false;
|
|
let inStar = false;
|
|
for (let i = 0;i < glob.length; i++) {
|
|
const c = glob.charAt(i);
|
|
if (escaping) {
|
|
escaping = false;
|
|
re += (reSpecials.has(c) ? "\\" : "") + c;
|
|
continue;
|
|
}
|
|
if (c === "*") {
|
|
if (inStar)
|
|
continue;
|
|
inStar = true;
|
|
re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star;
|
|
hasMagic = true;
|
|
continue;
|
|
} else {
|
|
inStar = false;
|
|
}
|
|
if (c === "\\") {
|
|
if (i === glob.length - 1) {
|
|
re += "\\\\";
|
|
} else {
|
|
escaping = true;
|
|
}
|
|
continue;
|
|
}
|
|
if (c === "[") {
|
|
const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i);
|
|
if (consumed) {
|
|
re += src;
|
|
uflag = uflag || needUflag;
|
|
i += consumed - 1;
|
|
hasMagic = hasMagic || magic;
|
|
continue;
|
|
}
|
|
}
|
|
if (c === "?") {
|
|
re += qmark;
|
|
hasMagic = true;
|
|
continue;
|
|
}
|
|
re += regExpEscape(c);
|
|
}
|
|
return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag];
|
|
}
|
|
}
|
|
exports2.AST = AST;
|
|
_a = AST;
|
|
});
|
|
|
|
// editors/vscode/node_modules/minimatch/dist/commonjs/escape.js
|
|
var require_escape = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.escape = undefined;
|
|
var escape = (s, { windowsPathsNoEscape = false, magicalBraces = false } = {}) => {
|
|
if (magicalBraces) {
|
|
return windowsPathsNoEscape ? s.replace(/[?*()[\]{}]/g, "[$&]") : s.replace(/[?*()[\]\\{}]/g, "\\$&");
|
|
}
|
|
return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
|
|
};
|
|
exports2.escape = escape;
|
|
});
|
|
|
|
// editors/vscode/node_modules/minimatch/dist/commonjs/index.js
|
|
var require_commonjs3 = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.unescape = exports2.escape = exports2.AST = exports2.Minimatch = exports2.match = exports2.makeRe = exports2.braceExpand = exports2.defaults = exports2.filter = exports2.GLOBSTAR = exports2.sep = exports2.minimatch = undefined;
|
|
var brace_expansion_1 = require_commonjs2();
|
|
var assert_valid_pattern_js_1 = require_assert_valid_pattern();
|
|
var ast_js_1 = require_ast();
|
|
var escape_js_1 = require_escape();
|
|
var unescape_js_1 = require_unescape();
|
|
var minimatch = (p, pattern, options = {}) => {
|
|
(0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
|
|
if (!options.nocomment && pattern.charAt(0) === "#") {
|
|
return false;
|
|
}
|
|
return new Minimatch(pattern, options).match(p);
|
|
};
|
|
exports2.minimatch = minimatch;
|
|
var starDotExtRE = /^\*+([^+@!?*[(]*)$/;
|
|
var starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2);
|
|
var starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2);
|
|
var starDotExtTestNocase = (ext2) => {
|
|
ext2 = ext2.toLowerCase();
|
|
return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2);
|
|
};
|
|
var starDotExtTestNocaseDot = (ext2) => {
|
|
ext2 = ext2.toLowerCase();
|
|
return (f) => f.toLowerCase().endsWith(ext2);
|
|
};
|
|
var starDotStarRE = /^\*+\.\*+$/;
|
|
var starDotStarTest = (f) => !f.startsWith(".") && f.includes(".");
|
|
var starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes(".");
|
|
var dotStarRE = /^\.\*+$/;
|
|
var dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith(".");
|
|
var starRE = /^\*+$/;
|
|
var starTest = (f) => f.length !== 0 && !f.startsWith(".");
|
|
var starTestDot = (f) => f.length !== 0 && f !== "." && f !== "..";
|
|
var qmarksRE = /^\?+([^+@!?*[(]*)?$/;
|
|
var qmarksTestNocase = ([$0, ext2 = ""]) => {
|
|
const noext = qmarksTestNoExt([$0]);
|
|
if (!ext2)
|
|
return noext;
|
|
ext2 = ext2.toLowerCase();
|
|
return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
|
|
};
|
|
var qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
|
|
const noext = qmarksTestNoExtDot([$0]);
|
|
if (!ext2)
|
|
return noext;
|
|
ext2 = ext2.toLowerCase();
|
|
return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
|
|
};
|
|
var qmarksTestDot = ([$0, ext2 = ""]) => {
|
|
const noext = qmarksTestNoExtDot([$0]);
|
|
return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
|
|
};
|
|
var qmarksTest = ([$0, ext2 = ""]) => {
|
|
const noext = qmarksTestNoExt([$0]);
|
|
return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
|
|
};
|
|
var qmarksTestNoExt = ([$0]) => {
|
|
const len = $0.length;
|
|
return (f) => f.length === len && !f.startsWith(".");
|
|
};
|
|
var qmarksTestNoExtDot = ([$0]) => {
|
|
const len = $0.length;
|
|
return (f) => f.length === len && f !== "." && f !== "..";
|
|
};
|
|
var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
|
|
var path = {
|
|
win32: { sep: "\\" },
|
|
posix: { sep: "/" }
|
|
};
|
|
exports2.sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
|
|
exports2.minimatch.sep = exports2.sep;
|
|
exports2.GLOBSTAR = Symbol("globstar **");
|
|
exports2.minimatch.GLOBSTAR = exports2.GLOBSTAR;
|
|
var qmark = "[^/]";
|
|
var star = qmark + "*?";
|
|
var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
|
|
var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
|
|
var filter = (pattern, options = {}) => (p) => (0, exports2.minimatch)(p, pattern, options);
|
|
exports2.filter = filter;
|
|
exports2.minimatch.filter = exports2.filter;
|
|
var ext = (a, b = {}) => Object.assign({}, a, b);
|
|
var defaults = (def) => {
|
|
if (!def || typeof def !== "object" || !Object.keys(def).length) {
|
|
return exports2.minimatch;
|
|
}
|
|
const orig = exports2.minimatch;
|
|
const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
|
|
return Object.assign(m, {
|
|
Minimatch: class Minimatch2 extends orig.Minimatch {
|
|
constructor(pattern, options = {}) {
|
|
super(pattern, ext(def, options));
|
|
}
|
|
static defaults(options) {
|
|
return orig.defaults(ext(def, options)).Minimatch;
|
|
}
|
|
},
|
|
AST: class AST extends orig.AST {
|
|
constructor(type, parent, options = {}) {
|
|
super(type, parent, ext(def, options));
|
|
}
|
|
static fromGlob(pattern, options = {}) {
|
|
return orig.AST.fromGlob(pattern, ext(def, options));
|
|
}
|
|
},
|
|
unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
|
|
escape: (s, options = {}) => orig.escape(s, ext(def, options)),
|
|
filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
|
|
defaults: (options) => orig.defaults(ext(def, options)),
|
|
makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
|
|
braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
|
|
match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
|
|
sep: orig.sep,
|
|
GLOBSTAR: exports2.GLOBSTAR
|
|
});
|
|
};
|
|
exports2.defaults = defaults;
|
|
exports2.minimatch.defaults = exports2.defaults;
|
|
var braceExpand = (pattern, options = {}) => {
|
|
(0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
|
|
if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
|
|
return [pattern];
|
|
}
|
|
return (0, brace_expansion_1.expand)(pattern, { max: options.braceExpandMax });
|
|
};
|
|
exports2.braceExpand = braceExpand;
|
|
exports2.minimatch.braceExpand = exports2.braceExpand;
|
|
var makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
|
|
exports2.makeRe = makeRe;
|
|
exports2.minimatch.makeRe = exports2.makeRe;
|
|
var match = (list, pattern, options = {}) => {
|
|
const mm = new Minimatch(pattern, options);
|
|
list = list.filter((f) => mm.match(f));
|
|
if (mm.options.nonull && !list.length) {
|
|
list.push(pattern);
|
|
}
|
|
return list;
|
|
};
|
|
exports2.match = match;
|
|
exports2.minimatch.match = exports2.match;
|
|
var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
|
|
var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
|
|
|
|
class Minimatch {
|
|
options;
|
|
set;
|
|
pattern;
|
|
windowsPathsNoEscape;
|
|
nonegate;
|
|
negate;
|
|
comment;
|
|
empty;
|
|
preserveMultipleSlashes;
|
|
partial;
|
|
globSet;
|
|
globParts;
|
|
nocase;
|
|
isWindows;
|
|
platform;
|
|
windowsNoMagicRoot;
|
|
maxGlobstarRecursion;
|
|
regexp;
|
|
constructor(pattern, options = {}) {
|
|
(0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
|
|
options = options || {};
|
|
this.options = options;
|
|
this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;
|
|
this.pattern = pattern;
|
|
this.platform = options.platform || defaultPlatform;
|
|
this.isWindows = this.platform === "win32";
|
|
const awe = "allowWindow" + "sEscape";
|
|
this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options[awe] === false;
|
|
if (this.windowsPathsNoEscape) {
|
|
this.pattern = this.pattern.replace(/\\/g, "/");
|
|
}
|
|
this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
|
|
this.regexp = null;
|
|
this.negate = false;
|
|
this.nonegate = !!options.nonegate;
|
|
this.comment = false;
|
|
this.empty = false;
|
|
this.partial = !!options.partial;
|
|
this.nocase = !!this.options.nocase;
|
|
this.windowsNoMagicRoot = options.windowsNoMagicRoot !== undefined ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
|
|
this.globSet = [];
|
|
this.globParts = [];
|
|
this.set = [];
|
|
this.make();
|
|
}
|
|
hasMagic() {
|
|
if (this.options.magicalBraces && this.set.length > 1) {
|
|
return true;
|
|
}
|
|
for (const pattern of this.set) {
|
|
for (const part of pattern) {
|
|
if (typeof part !== "string")
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
debug(..._) {}
|
|
make() {
|
|
const pattern = this.pattern;
|
|
const options = this.options;
|
|
if (!options.nocomment && pattern.charAt(0) === "#") {
|
|
this.comment = true;
|
|
return;
|
|
}
|
|
if (!pattern) {
|
|
this.empty = true;
|
|
return;
|
|
}
|
|
this.parseNegate();
|
|
this.globSet = [...new Set(this.braceExpand())];
|
|
if (options.debug) {
|
|
this.debug = (...args) => console.error(...args);
|
|
}
|
|
this.debug(this.pattern, this.globSet);
|
|
const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));
|
|
this.globParts = this.preprocess(rawGlobParts);
|
|
this.debug(this.pattern, this.globParts);
|
|
let set = this.globParts.map((s, _, __) => {
|
|
if (this.isWindows && this.windowsNoMagicRoot) {
|
|
const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);
|
|
const isDrive = /^[a-z]:/i.test(s[0]);
|
|
if (isUNC) {
|
|
return [
|
|
...s.slice(0, 4),
|
|
...s.slice(4).map((ss) => this.parse(ss))
|
|
];
|
|
} else if (isDrive) {
|
|
return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];
|
|
}
|
|
}
|
|
return s.map((ss) => this.parse(ss));
|
|
});
|
|
this.debug(this.pattern, set);
|
|
this.set = set.filter((s) => s.indexOf(false) === -1);
|
|
if (this.isWindows) {
|
|
for (let i = 0;i < this.set.length; i++) {
|
|
const p = this.set[i];
|
|
if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {
|
|
p[2] = "?";
|
|
}
|
|
}
|
|
}
|
|
this.debug(this.pattern, this.set);
|
|
}
|
|
preprocess(globParts) {
|
|
if (this.options.noglobstar) {
|
|
for (const partset of globParts) {
|
|
for (let j = 0;j < partset.length; j++) {
|
|
if (partset[j] === "**") {
|
|
partset[j] = "*";
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const { optimizationLevel = 1 } = this.options;
|
|
if (optimizationLevel >= 2) {
|
|
globParts = this.firstPhasePreProcess(globParts);
|
|
globParts = this.secondPhasePreProcess(globParts);
|
|
} else if (optimizationLevel >= 1) {
|
|
globParts = this.levelOneOptimize(globParts);
|
|
} else {
|
|
globParts = this.adjascentGlobstarOptimize(globParts);
|
|
}
|
|
return globParts;
|
|
}
|
|
adjascentGlobstarOptimize(globParts) {
|
|
return globParts.map((parts) => {
|
|
let gs = -1;
|
|
while ((gs = parts.indexOf("**", gs + 1)) !== -1) {
|
|
let i = gs;
|
|
while (parts[i + 1] === "**") {
|
|
i++;
|
|
}
|
|
if (i !== gs) {
|
|
parts.splice(gs, i - gs);
|
|
}
|
|
}
|
|
return parts;
|
|
});
|
|
}
|
|
levelOneOptimize(globParts) {
|
|
return globParts.map((parts) => {
|
|
parts = parts.reduce((set, part) => {
|
|
const prev = set[set.length - 1];
|
|
if (part === "**" && prev === "**") {
|
|
return set;
|
|
}
|
|
if (part === "..") {
|
|
if (prev && prev !== ".." && prev !== "." && prev !== "**") {
|
|
set.pop();
|
|
return set;
|
|
}
|
|
}
|
|
set.push(part);
|
|
return set;
|
|
}, []);
|
|
return parts.length === 0 ? [""] : parts;
|
|
});
|
|
}
|
|
levelTwoFileOptimize(parts) {
|
|
if (!Array.isArray(parts)) {
|
|
parts = this.slashSplit(parts);
|
|
}
|
|
let didSomething = false;
|
|
do {
|
|
didSomething = false;
|
|
if (!this.preserveMultipleSlashes) {
|
|
for (let i = 1;i < parts.length - 1; i++) {
|
|
const p = parts[i];
|
|
if (i === 1 && p === "" && parts[0] === "")
|
|
continue;
|
|
if (p === "." || p === "") {
|
|
didSomething = true;
|
|
parts.splice(i, 1);
|
|
i--;
|
|
}
|
|
}
|
|
if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
|
|
didSomething = true;
|
|
parts.pop();
|
|
}
|
|
}
|
|
let dd = 0;
|
|
while ((dd = parts.indexOf("..", dd + 1)) !== -1) {
|
|
const p = parts[dd - 1];
|
|
if (p && p !== "." && p !== ".." && p !== "**" && !(this.isWindows && /^[a-z]:$/i.test(p))) {
|
|
didSomething = true;
|
|
parts.splice(dd - 1, 2);
|
|
dd -= 2;
|
|
}
|
|
}
|
|
} while (didSomething);
|
|
return parts.length === 0 ? [""] : parts;
|
|
}
|
|
firstPhasePreProcess(globParts) {
|
|
let didSomething = false;
|
|
do {
|
|
didSomething = false;
|
|
for (let parts of globParts) {
|
|
let gs = -1;
|
|
while ((gs = parts.indexOf("**", gs + 1)) !== -1) {
|
|
let gss = gs;
|
|
while (parts[gss + 1] === "**") {
|
|
gss++;
|
|
}
|
|
if (gss > gs) {
|
|
parts.splice(gs + 1, gss - gs);
|
|
}
|
|
let next = parts[gs + 1];
|
|
const p = parts[gs + 2];
|
|
const p2 = parts[gs + 3];
|
|
if (next !== "..")
|
|
continue;
|
|
if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
|
|
continue;
|
|
}
|
|
didSomething = true;
|
|
parts.splice(gs, 1);
|
|
const other = parts.slice(0);
|
|
other[gs] = "**";
|
|
globParts.push(other);
|
|
gs--;
|
|
}
|
|
if (!this.preserveMultipleSlashes) {
|
|
for (let i = 1;i < parts.length - 1; i++) {
|
|
const p = parts[i];
|
|
if (i === 1 && p === "" && parts[0] === "")
|
|
continue;
|
|
if (p === "." || p === "") {
|
|
didSomething = true;
|
|
parts.splice(i, 1);
|
|
i--;
|
|
}
|
|
}
|
|
if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
|
|
didSomething = true;
|
|
parts.pop();
|
|
}
|
|
}
|
|
let dd = 0;
|
|
while ((dd = parts.indexOf("..", dd + 1)) !== -1) {
|
|
const p = parts[dd - 1];
|
|
if (p && p !== "." && p !== ".." && p !== "**") {
|
|
didSomething = true;
|
|
const needDot = dd === 1 && parts[dd + 1] === "**";
|
|
const splin = needDot ? ["."] : [];
|
|
parts.splice(dd - 1, 2, ...splin);
|
|
if (parts.length === 0)
|
|
parts.push("");
|
|
dd -= 2;
|
|
}
|
|
}
|
|
}
|
|
} while (didSomething);
|
|
return globParts;
|
|
}
|
|
secondPhasePreProcess(globParts) {
|
|
for (let i = 0;i < globParts.length - 1; i++) {
|
|
for (let j = i + 1;j < globParts.length; j++) {
|
|
const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
|
|
if (matched) {
|
|
globParts[i] = [];
|
|
globParts[j] = matched;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return globParts.filter((gs) => gs.length);
|
|
}
|
|
partsMatch(a, b, emptyGSMatch = false) {
|
|
let ai = 0;
|
|
let bi = 0;
|
|
let result = [];
|
|
let which = "";
|
|
while (ai < a.length && bi < b.length) {
|
|
if (a[ai] === b[bi]) {
|
|
result.push(which === "b" ? b[bi] : a[ai]);
|
|
ai++;
|
|
bi++;
|
|
} else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
|
|
result.push(a[ai]);
|
|
ai++;
|
|
} else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
|
|
result.push(b[bi]);
|
|
bi++;
|
|
} else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
|
|
if (which === "b")
|
|
return false;
|
|
which = "a";
|
|
result.push(a[ai]);
|
|
ai++;
|
|
bi++;
|
|
} else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
|
|
if (which === "a")
|
|
return false;
|
|
which = "b";
|
|
result.push(b[bi]);
|
|
ai++;
|
|
bi++;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
return a.length === b.length && result;
|
|
}
|
|
parseNegate() {
|
|
if (this.nonegate)
|
|
return;
|
|
const pattern = this.pattern;
|
|
let negate = false;
|
|
let negateOffset = 0;
|
|
for (let i = 0;i < pattern.length && pattern.charAt(i) === "!"; i++) {
|
|
negate = !negate;
|
|
negateOffset++;
|
|
}
|
|
if (negateOffset)
|
|
this.pattern = pattern.slice(negateOffset);
|
|
this.negate = negate;
|
|
}
|
|
matchOne(file, pattern, partial = false) {
|
|
let fileStartIndex = 0;
|
|
let patternStartIndex = 0;
|
|
if (this.isWindows) {
|
|
const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
|
|
const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
|
|
const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);
|
|
const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
|
|
const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
|
|
const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
|
|
if (typeof fdi === "number" && typeof pdi === "number") {
|
|
const [fd, pd] = [
|
|
file[fdi],
|
|
pattern[pdi]
|
|
];
|
|
if (fd.toLowerCase() === pd.toLowerCase()) {
|
|
pattern[pdi] = fd;
|
|
patternStartIndex = pdi;
|
|
fileStartIndex = fdi;
|
|
}
|
|
}
|
|
}
|
|
const { optimizationLevel = 1 } = this.options;
|
|
if (optimizationLevel >= 2) {
|
|
file = this.levelTwoFileOptimize(file);
|
|
}
|
|
if (pattern.includes(exports2.GLOBSTAR)) {
|
|
return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
|
|
}
|
|
return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
|
|
}
|
|
#matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
|
|
const firstgs = pattern.indexOf(exports2.GLOBSTAR, patternIndex);
|
|
const lastgs = pattern.lastIndexOf(exports2.GLOBSTAR);
|
|
const [head, body, tail] = partial ? [
|
|
pattern.slice(patternIndex, firstgs),
|
|
pattern.slice(firstgs + 1),
|
|
[]
|
|
] : [
|
|
pattern.slice(patternIndex, firstgs),
|
|
pattern.slice(firstgs + 1, lastgs),
|
|
pattern.slice(lastgs + 1)
|
|
];
|
|
if (head.length) {
|
|
const fileHead = file.slice(fileIndex, fileIndex + head.length);
|
|
if (!this.#matchOne(fileHead, head, partial, 0, 0)) {
|
|
return false;
|
|
}
|
|
fileIndex += head.length;
|
|
patternIndex += head.length;
|
|
}
|
|
let fileTailMatch = 0;
|
|
if (tail.length) {
|
|
if (tail.length + fileIndex > file.length)
|
|
return false;
|
|
let tailStart = file.length - tail.length;
|
|
if (this.#matchOne(file, tail, partial, tailStart, 0)) {
|
|
fileTailMatch = tail.length;
|
|
} else {
|
|
if (file[file.length - 1] !== "" || fileIndex + tail.length === file.length) {
|
|
return false;
|
|
}
|
|
tailStart--;
|
|
if (!this.#matchOne(file, tail, partial, tailStart, 0)) {
|
|
return false;
|
|
}
|
|
fileTailMatch = tail.length + 1;
|
|
}
|
|
}
|
|
if (!body.length) {
|
|
let sawSome = !!fileTailMatch;
|
|
for (let i2 = fileIndex;i2 < file.length - fileTailMatch; i2++) {
|
|
const f = String(file[i2]);
|
|
sawSome = true;
|
|
if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {
|
|
return false;
|
|
}
|
|
}
|
|
return partial || sawSome;
|
|
}
|
|
const bodySegments = [[[], 0]];
|
|
let currentBody = bodySegments[0];
|
|
let nonGsParts = 0;
|
|
const nonGsPartsSums = [0];
|
|
for (const b of body) {
|
|
if (b === exports2.GLOBSTAR) {
|
|
nonGsPartsSums.push(nonGsParts);
|
|
currentBody = [[], 0];
|
|
bodySegments.push(currentBody);
|
|
} else {
|
|
currentBody[0].push(b);
|
|
nonGsParts++;
|
|
}
|
|
}
|
|
let i = bodySegments.length - 1;
|
|
const fileLength = file.length - fileTailMatch;
|
|
for (const b of bodySegments) {
|
|
b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);
|
|
}
|
|
return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
|
|
}
|
|
#matchGlobStarBodySections(file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
|
|
const bs = bodySegments[bodyIndex];
|
|
if (!bs) {
|
|
for (let i = fileIndex;i < file.length; i++) {
|
|
sawTail = true;
|
|
const f = file[i];
|
|
if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {
|
|
return false;
|
|
}
|
|
}
|
|
return sawTail;
|
|
}
|
|
const [body, after] = bs;
|
|
while (fileIndex <= after) {
|
|
const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);
|
|
if (m && globStarDepth < this.maxGlobstarRecursion) {
|
|
const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
|
|
if (sub !== false) {
|
|
return sub;
|
|
}
|
|
}
|
|
const f = file[fileIndex];
|
|
if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {
|
|
return false;
|
|
}
|
|
fileIndex++;
|
|
}
|
|
return partial || null;
|
|
}
|
|
#matchOne(file, pattern, partial, fileIndex, patternIndex) {
|
|
let fi;
|
|
let pi;
|
|
let pl;
|
|
let fl;
|
|
for (fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length;fi < fl && pi < pl; fi++, pi++) {
|
|
this.debug("matchOne loop");
|
|
let p = pattern[pi];
|
|
let f = file[fi];
|
|
this.debug(pattern, p, f);
|
|
if (p === false || p === exports2.GLOBSTAR) {
|
|
return false;
|
|
}
|
|
let hit;
|
|
if (typeof p === "string") {
|
|
hit = f === p;
|
|
this.debug("string match", p, f, hit);
|
|
} else {
|
|
hit = p.test(f);
|
|
this.debug("pattern match", p, f, hit);
|
|
}
|
|
if (!hit)
|
|
return false;
|
|
}
|
|
if (fi === fl && pi === pl) {
|
|
return true;
|
|
} else if (fi === fl) {
|
|
return partial;
|
|
} else if (pi === pl) {
|
|
return fi === fl - 1 && file[fi] === "";
|
|
} else {
|
|
throw new Error("wtf?");
|
|
}
|
|
}
|
|
braceExpand() {
|
|
return (0, exports2.braceExpand)(this.pattern, this.options);
|
|
}
|
|
parse(pattern) {
|
|
(0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
|
|
const options = this.options;
|
|
if (pattern === "**")
|
|
return exports2.GLOBSTAR;
|
|
if (pattern === "")
|
|
return "";
|
|
let m;
|
|
let fastTest = null;
|
|
if (m = pattern.match(starRE)) {
|
|
fastTest = options.dot ? starTestDot : starTest;
|
|
} else if (m = pattern.match(starDotExtRE)) {
|
|
fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
|
|
} else if (m = pattern.match(qmarksRE)) {
|
|
fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);
|
|
} else if (m = pattern.match(starDotStarRE)) {
|
|
fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
|
|
} else if (m = pattern.match(dotStarRE)) {
|
|
fastTest = dotStarTest;
|
|
}
|
|
const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern();
|
|
if (fastTest && typeof re === "object") {
|
|
Reflect.defineProperty(re, "test", { value: fastTest });
|
|
}
|
|
return re;
|
|
}
|
|
makeRe() {
|
|
if (this.regexp || this.regexp === false)
|
|
return this.regexp;
|
|
const set = this.set;
|
|
if (!set.length) {
|
|
this.regexp = false;
|
|
return this.regexp;
|
|
}
|
|
const options = this.options;
|
|
const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
|
|
const flags = new Set(options.nocase ? ["i"] : []);
|
|
let re = set.map((pattern) => {
|
|
const pp = pattern.map((p) => {
|
|
if (p instanceof RegExp) {
|
|
for (const f of p.flags.split(""))
|
|
flags.add(f);
|
|
}
|
|
return typeof p === "string" ? regExpEscape(p) : p === exports2.GLOBSTAR ? exports2.GLOBSTAR : p._src;
|
|
});
|
|
pp.forEach((p, i) => {
|
|
const next = pp[i + 1];
|
|
const prev = pp[i - 1];
|
|
if (p !== exports2.GLOBSTAR || prev === exports2.GLOBSTAR) {
|
|
return;
|
|
}
|
|
if (prev === undefined) {
|
|
if (next !== undefined && next !== exports2.GLOBSTAR) {
|
|
pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
|
|
} else {
|
|
pp[i] = twoStar;
|
|
}
|
|
} else if (next === undefined) {
|
|
pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + ")?";
|
|
} else if (next !== exports2.GLOBSTAR) {
|
|
pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
|
|
pp[i + 1] = exports2.GLOBSTAR;
|
|
}
|
|
});
|
|
const filtered = pp.filter((p) => p !== exports2.GLOBSTAR);
|
|
if (this.partial && filtered.length >= 1) {
|
|
const prefixes = [];
|
|
for (let i = 1;i <= filtered.length; i++) {
|
|
prefixes.push(filtered.slice(0, i).join("/"));
|
|
}
|
|
return "(?:" + prefixes.join("|") + ")";
|
|
}
|
|
return filtered.join("/");
|
|
}).join("|");
|
|
const [open, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];
|
|
re = "^" + open + re + close + "$";
|
|
if (this.partial) {
|
|
re = "^(?:\\/|" + open + re.slice(1, -1) + close + ")$";
|
|
}
|
|
if (this.negate)
|
|
re = "^(?!" + re + ").+$";
|
|
try {
|
|
this.regexp = new RegExp(re, [...flags].join(""));
|
|
} catch {
|
|
this.regexp = false;
|
|
}
|
|
return this.regexp;
|
|
}
|
|
slashSplit(p) {
|
|
if (this.preserveMultipleSlashes) {
|
|
return p.split("/");
|
|
} else if (this.isWindows && /^\/\/[^/]+/.test(p)) {
|
|
return ["", ...p.split(/\/+/)];
|
|
} else {
|
|
return p.split(/\/+/);
|
|
}
|
|
}
|
|
match(f, partial = this.partial) {
|
|
this.debug("match", f, this.pattern);
|
|
if (this.comment) {
|
|
return false;
|
|
}
|
|
if (this.empty) {
|
|
return f === "";
|
|
}
|
|
if (f === "/" && partial) {
|
|
return true;
|
|
}
|
|
const options = this.options;
|
|
if (this.isWindows) {
|
|
f = f.split("\\").join("/");
|
|
}
|
|
const ff = this.slashSplit(f);
|
|
this.debug(this.pattern, "split", ff);
|
|
const set = this.set;
|
|
this.debug(this.pattern, "set", set);
|
|
let filename = ff[ff.length - 1];
|
|
if (!filename) {
|
|
for (let i = ff.length - 2;!filename && i >= 0; i--) {
|
|
filename = ff[i];
|
|
}
|
|
}
|
|
for (const pattern of set) {
|
|
let file = ff;
|
|
if (options.matchBase && pattern.length === 1) {
|
|
file = [filename];
|
|
}
|
|
const hit = this.matchOne(file, pattern, partial);
|
|
if (hit) {
|
|
if (options.flipNegate) {
|
|
return true;
|
|
}
|
|
return !this.negate;
|
|
}
|
|
}
|
|
if (options.flipNegate) {
|
|
return false;
|
|
}
|
|
return this.negate;
|
|
}
|
|
static defaults(def) {
|
|
return exports2.minimatch.defaults(def).Minimatch;
|
|
}
|
|
}
|
|
exports2.Minimatch = Minimatch;
|
|
var ast_js_2 = require_ast();
|
|
Object.defineProperty(exports2, "AST", { enumerable: true, get: function() {
|
|
return ast_js_2.AST;
|
|
} });
|
|
var escape_js_2 = require_escape();
|
|
Object.defineProperty(exports2, "escape", { enumerable: true, get: function() {
|
|
return escape_js_2.escape;
|
|
} });
|
|
var unescape_js_2 = require_unescape();
|
|
Object.defineProperty(exports2, "unescape", { enumerable: true, get: function() {
|
|
return unescape_js_2.unescape;
|
|
} });
|
|
exports2.minimatch.AST = ast_js_1.AST;
|
|
exports2.minimatch.Minimatch = Minimatch;
|
|
exports2.minimatch.escape = escape_js_1.escape;
|
|
exports2.minimatch.unescape = unescape_js_1.unescape;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/utils/globPattern.js
|
|
var require_globPattern = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.matchGlobPattern = matchGlobPattern;
|
|
var minimatch = __importStar(require_commonjs3());
|
|
var vscode_1 = require("vscode");
|
|
function matchGlobPattern(pattern, resource) {
|
|
let miniMatchPattern;
|
|
if (typeof pattern === "string") {
|
|
miniMatchPattern = pattern.replace(/\\/g, "/");
|
|
} else {
|
|
try {
|
|
const baseUri = vscode_1.Uri.parse(typeof pattern.baseUri === "string" ? pattern.baseUri : pattern.baseUri.uri);
|
|
miniMatchPattern = baseUri.with({ path: baseUri.path + "/" + pattern.pattern }).fsPath.replace(/\\/g, "/");
|
|
} catch (error) {
|
|
return false;
|
|
}
|
|
}
|
|
const matcher = new minimatch.Minimatch(miniMatchPattern, { noext: true });
|
|
if (!matcher.makeRe()) {
|
|
return false;
|
|
}
|
|
return matcher.match(resource.fsPath);
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/diagnostic.js
|
|
var require_diagnostic = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DiagnosticFeature = exports2.DiagnosticPullMode = exports2.vsdiag = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var uuid_1 = require_uuid();
|
|
var globPattern_1 = require_globPattern();
|
|
var features_1 = require_features();
|
|
function ensure(target, key) {
|
|
if (target[key] === undefined) {
|
|
target[key] = {};
|
|
}
|
|
return target[key];
|
|
}
|
|
var vsdiag;
|
|
(function(vsdiag2) {
|
|
let DocumentDiagnosticReportKind;
|
|
(function(DocumentDiagnosticReportKind2) {
|
|
DocumentDiagnosticReportKind2["full"] = "full";
|
|
DocumentDiagnosticReportKind2["unChanged"] = "unChanged";
|
|
})(DocumentDiagnosticReportKind = vsdiag2.DocumentDiagnosticReportKind || (vsdiag2.DocumentDiagnosticReportKind = {}));
|
|
})(vsdiag || (exports2.vsdiag = vsdiag = {}));
|
|
var DiagnosticPullMode;
|
|
(function(DiagnosticPullMode2) {
|
|
DiagnosticPullMode2["onType"] = "onType";
|
|
DiagnosticPullMode2["onSave"] = "onSave";
|
|
DiagnosticPullMode2["onFocus"] = "onFocus";
|
|
})(DiagnosticPullMode || (exports2.DiagnosticPullMode = DiagnosticPullMode = {}));
|
|
var RequestStateKind;
|
|
(function(RequestStateKind2) {
|
|
RequestStateKind2["active"] = "open";
|
|
RequestStateKind2["reschedule"] = "reschedule";
|
|
RequestStateKind2["outDated"] = "drop";
|
|
})(RequestStateKind || (RequestStateKind = {}));
|
|
var PullState;
|
|
(function(PullState2) {
|
|
PullState2[PullState2["document"] = 1] = "document";
|
|
PullState2[PullState2["workspace"] = 2] = "workspace";
|
|
})(PullState || (PullState = {}));
|
|
var DocumentOrUri;
|
|
(function(DocumentOrUri2) {
|
|
function asKey(document) {
|
|
return document instanceof vscode_1.Uri ? document.toString() : document.uri.toString();
|
|
}
|
|
DocumentOrUri2.asKey = asKey;
|
|
})(DocumentOrUri || (DocumentOrUri = {}));
|
|
|
|
class DocumentPullStateTracker {
|
|
documentPullStates;
|
|
workspacePullStates;
|
|
constructor() {
|
|
this.documentPullStates = new Map;
|
|
this.workspacePullStates = new Map;
|
|
}
|
|
track(kind, document, arg1) {
|
|
const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates;
|
|
const [key, uri, version] = document instanceof vscode_1.Uri ? [document.toString(), document, arg1] : [document.uri.toString(), document.uri, document.version];
|
|
let state = states.get(key);
|
|
if (state === undefined) {
|
|
state = { document: uri, pulledVersion: version, resultId: undefined };
|
|
states.set(key, state);
|
|
}
|
|
return state;
|
|
}
|
|
update(kind, document, arg1, arg2) {
|
|
const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates;
|
|
const [key, uri, version, resultId] = document instanceof vscode_1.Uri ? [document.toString(), document, arg1, arg2] : [document.uri.toString(), document.uri, document.version, arg1];
|
|
let state = states.get(key);
|
|
if (state === undefined) {
|
|
state = { document: uri, pulledVersion: version, resultId };
|
|
states.set(key, state);
|
|
} else {
|
|
state.pulledVersion = version;
|
|
state.resultId = resultId;
|
|
}
|
|
}
|
|
unTrack(kind, document) {
|
|
const key = DocumentOrUri.asKey(document);
|
|
const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates;
|
|
states.delete(key);
|
|
}
|
|
tracks(kind, document) {
|
|
const key = DocumentOrUri.asKey(document);
|
|
const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates;
|
|
return states.has(key);
|
|
}
|
|
tracksSameVersion(kind, document) {
|
|
const key = document.uri.toString();
|
|
const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates;
|
|
const state = states.get(key);
|
|
return state !== undefined && state.pulledVersion === document.version;
|
|
}
|
|
getResultId(kind, document) {
|
|
const key = DocumentOrUri.asKey(document);
|
|
const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates;
|
|
return states.get(key)?.resultId;
|
|
}
|
|
getAllResultIds() {
|
|
const result = [];
|
|
for (let [uri, value] of this.workspacePullStates) {
|
|
if (this.documentPullStates.has(uri)) {
|
|
value = this.documentPullStates.get(uri);
|
|
}
|
|
if (value.resultId !== undefined) {
|
|
result.push({ uri, value: value.resultId });
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
|
|
class DiagnosticRequestor {
|
|
isDisposed;
|
|
client;
|
|
visibleDocuments;
|
|
options;
|
|
onDidChangeDiagnosticsEmitter;
|
|
provider;
|
|
diagnostics;
|
|
openRequests;
|
|
documentStates;
|
|
workspaceErrorCounter;
|
|
workspaceCancellation;
|
|
workspaceTimeout;
|
|
constructor(client, visibleDocuments, options) {
|
|
this.client = client;
|
|
this.visibleDocuments = visibleDocuments;
|
|
this.options = options;
|
|
this.isDisposed = false;
|
|
this.onDidChangeDiagnosticsEmitter = new vscode_1.EventEmitter;
|
|
this.provider = this.createProvider();
|
|
this.diagnostics = this.createDiagnosticCollection();
|
|
this.openRequests = new Map;
|
|
this.documentStates = new DocumentPullStateTracker;
|
|
this.workspaceErrorCounter = 0;
|
|
}
|
|
createDiagnosticCollection() {
|
|
if (this.client.clientOptions.diagnosticCollectionProvider === undefined) {
|
|
return vscode_1.languages.createDiagnosticCollection(this.options.identifier);
|
|
} else {
|
|
return this.client.clientOptions.diagnosticCollectionProvider.create(this.options.identifier, features_1.DiagnosticCollectionSource.pull);
|
|
}
|
|
}
|
|
knows(kind, document) {
|
|
const uri = document instanceof vscode_1.Uri ? document : document.uri;
|
|
return this.documentStates.tracks(kind, document) || this.openRequests.has(uri.toString());
|
|
}
|
|
knowsSameVersion(kind, document) {
|
|
const requestState = this.openRequests.get(document.uri.toString());
|
|
if (requestState === undefined) {
|
|
return this.documentStates.tracksSameVersion(kind, document);
|
|
}
|
|
if (requestState.state === RequestStateKind.reschedule) {
|
|
return true;
|
|
}
|
|
if (requestState.state === RequestStateKind.outDated) {
|
|
return false;
|
|
}
|
|
return requestState.version === document.version;
|
|
}
|
|
forget(kind, document) {
|
|
this.documentStates.unTrack(kind, document);
|
|
}
|
|
pull(document, cb) {
|
|
if (this.isDisposed) {
|
|
return;
|
|
}
|
|
const uri = document instanceof vscode_1.Uri ? document : document.uri;
|
|
this.pullAsync(document).then(() => {
|
|
if (cb) {
|
|
cb();
|
|
}
|
|
}, (error) => {
|
|
this.client.error(`Document pull failed for text document ${uri.toString()}`, error, false);
|
|
});
|
|
}
|
|
async pullAsync(document, version) {
|
|
if (this.isDisposed) {
|
|
return;
|
|
}
|
|
const isUri = document instanceof vscode_1.Uri;
|
|
const uri = isUri ? document : document.uri;
|
|
const key = uri.toString();
|
|
version = isUri ? version : document.version;
|
|
const currentRequestState = this.openRequests.get(key);
|
|
const documentState = isUri ? this.documentStates.track(PullState.document, document, version) : this.documentStates.track(PullState.document, document);
|
|
if (currentRequestState === undefined) {
|
|
const tokenSource = new vscode_1.CancellationTokenSource;
|
|
this.openRequests.set(key, { state: RequestStateKind.active, document, version, tokenSource });
|
|
let report;
|
|
let afterState;
|
|
try {
|
|
report = await this.provider.provideDiagnostics(document, documentState.resultId, tokenSource.token) ?? { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] };
|
|
} catch (error) {
|
|
if (error instanceof features_1.LSPCancellationError && vscode_languageserver_protocol_1.DiagnosticServerCancellationData.is(error.data) && error.data.retriggerRequest === false) {
|
|
afterState = { state: RequestStateKind.outDated, document };
|
|
}
|
|
if (afterState === undefined && error instanceof vscode_1.CancellationError) {
|
|
afterState = { state: RequestStateKind.reschedule, document };
|
|
} else {
|
|
throw error;
|
|
}
|
|
}
|
|
afterState = afterState ?? this.openRequests.get(key);
|
|
if (afterState === undefined) {
|
|
this.client.error(`Lost request state in diagnostic pull model. Clearing diagnostics for ${key}`);
|
|
this.diagnostics.delete(uri);
|
|
return;
|
|
}
|
|
this.openRequests.delete(key);
|
|
if (!this.visibleDocuments.isVisible(document)) {
|
|
this.documentStates.unTrack(PullState.document, document);
|
|
return;
|
|
}
|
|
if (afterState.state === RequestStateKind.outDated) {
|
|
return;
|
|
}
|
|
if (report !== undefined) {
|
|
if (report.kind === vsdiag.DocumentDiagnosticReportKind.full) {
|
|
this.diagnostics.set(uri, report.items);
|
|
}
|
|
documentState.pulledVersion = version;
|
|
documentState.resultId = report.resultId;
|
|
}
|
|
if (afterState.state === RequestStateKind.reschedule) {
|
|
this.pull(document);
|
|
}
|
|
} else {
|
|
if (currentRequestState.state === RequestStateKind.active) {
|
|
currentRequestState.tokenSource.cancel();
|
|
this.openRequests.set(key, { state: RequestStateKind.reschedule, document: currentRequestState.document });
|
|
} else if (currentRequestState.state === RequestStateKind.outDated) {
|
|
this.openRequests.set(key, { state: RequestStateKind.reschedule, document: currentRequestState.document });
|
|
}
|
|
}
|
|
}
|
|
forgetDocument(document) {
|
|
if (this.isDisposed) {
|
|
return;
|
|
}
|
|
const uri = document instanceof vscode_1.Uri ? document : document.uri;
|
|
const key = uri.toString();
|
|
const request = this.openRequests.get(key);
|
|
if (this.options.workspaceDiagnostics && uri.scheme !== "untitled") {
|
|
if (request !== undefined) {
|
|
this.openRequests.set(key, { state: RequestStateKind.reschedule, document });
|
|
} else {
|
|
this.pull(document, () => {
|
|
this.forget(PullState.document, document);
|
|
});
|
|
}
|
|
this.forget(PullState.workspace, document);
|
|
} else {
|
|
if (request !== undefined) {
|
|
if (request.state === RequestStateKind.active) {
|
|
request.tokenSource.cancel();
|
|
}
|
|
this.openRequests.set(key, { state: RequestStateKind.outDated, document });
|
|
}
|
|
this.diagnostics.delete(uri);
|
|
this.forget(PullState.document, document);
|
|
}
|
|
}
|
|
pullWorkspace() {
|
|
if (this.isDisposed) {
|
|
return;
|
|
}
|
|
this.pullWorkspaceAsync().then(() => {
|
|
this.workspaceTimeout = (0, vscode_languageserver_protocol_1.RAL)().timer.setTimeout(() => {
|
|
this.pullWorkspace();
|
|
}, 2000);
|
|
}, (error) => {
|
|
if (!(error instanceof features_1.LSPCancellationError) && !vscode_languageserver_protocol_1.DiagnosticServerCancellationData.is(error.data)) {
|
|
this.client.error(`Workspace diagnostic pull failed.`, error, false);
|
|
this.workspaceErrorCounter++;
|
|
}
|
|
if (this.workspaceErrorCounter <= 5) {
|
|
this.workspaceTimeout = (0, vscode_languageserver_protocol_1.RAL)().timer.setTimeout(() => {
|
|
this.pullWorkspace();
|
|
}, 2000);
|
|
}
|
|
});
|
|
}
|
|
async pullWorkspaceAsync() {
|
|
if (!this.provider.provideWorkspaceDiagnostics || this.isDisposed) {
|
|
return;
|
|
}
|
|
if (this.workspaceCancellation !== undefined) {
|
|
this.workspaceCancellation.cancel();
|
|
this.workspaceCancellation = undefined;
|
|
}
|
|
this.workspaceCancellation = new vscode_1.CancellationTokenSource;
|
|
const previousResultIds = this.documentStates.getAllResultIds().map((item) => {
|
|
return {
|
|
uri: this.client.protocol2CodeConverter.asUri(item.uri),
|
|
value: item.value
|
|
};
|
|
});
|
|
await this.provider.provideWorkspaceDiagnostics(previousResultIds, this.workspaceCancellation.token, (chunk) => {
|
|
if (!chunk || this.isDisposed) {
|
|
return;
|
|
}
|
|
for (const item of chunk.items) {
|
|
if (item.kind === vsdiag.DocumentDiagnosticReportKind.full) {
|
|
if (!this.documentStates.tracks(PullState.document, item.uri)) {
|
|
this.diagnostics.set(item.uri, item.items);
|
|
}
|
|
}
|
|
this.documentStates.update(PullState.workspace, item.uri, item.version ?? undefined, item.resultId);
|
|
}
|
|
});
|
|
}
|
|
createProvider() {
|
|
const result = {
|
|
onDidChangeDiagnostics: this.onDidChangeDiagnosticsEmitter.event,
|
|
provideDiagnostics: (document, previousResultId, token) => {
|
|
const provideDiagnostics = (document2, previousResultId2, token2) => {
|
|
const params = {
|
|
identifier: this.options.identifier,
|
|
textDocument: { uri: this.client.code2ProtocolConverter.asUri(document2 instanceof vscode_1.Uri ? document2 : document2.uri) },
|
|
previousResultId: previousResultId2
|
|
};
|
|
if (this.isDisposed === true || !this.client.isRunning()) {
|
|
return { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] };
|
|
}
|
|
return this.client.sendRequest(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type, params, token2).then(async (result2) => {
|
|
if (this.isDisposed) {
|
|
return { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] };
|
|
}
|
|
if (token2.isCancellationRequested) {
|
|
throw new vscode_1.CancellationError;
|
|
}
|
|
if (result2 === undefined || result2 === null) {
|
|
return { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] };
|
|
}
|
|
if (result2.kind === vscode_languageserver_protocol_1.DocumentDiagnosticReportKind.Full) {
|
|
return { kind: vsdiag.DocumentDiagnosticReportKind.full, resultId: result2.resultId, items: await this.client.protocol2CodeConverter.asDiagnostics(result2.items, token2) };
|
|
} else {
|
|
return { kind: vsdiag.DocumentDiagnosticReportKind.unChanged, resultId: result2.resultId };
|
|
}
|
|
}, (error) => {
|
|
return this.client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type, token2, error, { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] }, true, true);
|
|
});
|
|
};
|
|
const middleware = this.client.middleware;
|
|
return middleware.provideDiagnostics ? middleware.provideDiagnostics(document, previousResultId, token, provideDiagnostics) : provideDiagnostics(document, previousResultId, token);
|
|
}
|
|
};
|
|
if (this.options.workspaceDiagnostics) {
|
|
result.provideWorkspaceDiagnostics = (resultIds, token, resultReporter) => {
|
|
const convertReport = async (report) => {
|
|
if (report.kind === vscode_languageserver_protocol_1.DocumentDiagnosticReportKind.Full) {
|
|
return {
|
|
kind: vsdiag.DocumentDiagnosticReportKind.full,
|
|
uri: this.client.protocol2CodeConverter.asUri(report.uri),
|
|
resultId: report.resultId,
|
|
version: report.version,
|
|
items: await this.client.protocol2CodeConverter.asDiagnostics(report.items, token)
|
|
};
|
|
} else {
|
|
return {
|
|
kind: vsdiag.DocumentDiagnosticReportKind.unChanged,
|
|
uri: this.client.protocol2CodeConverter.asUri(report.uri),
|
|
resultId: report.resultId,
|
|
version: report.version
|
|
};
|
|
}
|
|
};
|
|
const convertPreviousResultIds = (resultIds2) => {
|
|
const converted = [];
|
|
for (const item of resultIds2) {
|
|
converted.push({ uri: this.client.code2ProtocolConverter.asUri(item.uri), value: item.value });
|
|
}
|
|
return converted;
|
|
};
|
|
const provideDiagnostics = (resultIds2, token2, resultReporter2) => {
|
|
const partialResultToken = (0, uuid_1.generateUuid)();
|
|
const disposable = this.client.onProgress(vscode_languageserver_protocol_1.WorkspaceDiagnosticRequest.partialResult, partialResultToken, async (partialResult) => {
|
|
if (partialResult === undefined || partialResult === null) {
|
|
resultReporter2(null);
|
|
return;
|
|
}
|
|
const converted = {
|
|
items: []
|
|
};
|
|
for (const item of partialResult.items) {
|
|
try {
|
|
converted.items.push(await convertReport(item));
|
|
} catch (error) {
|
|
this.client.error(`Converting workspace diagnostics failed.`, error);
|
|
}
|
|
}
|
|
resultReporter2(converted);
|
|
});
|
|
const params = {
|
|
identifier: this.options.identifier,
|
|
previousResultIds: convertPreviousResultIds(resultIds2),
|
|
partialResultToken
|
|
};
|
|
if (this.isDisposed === true || !this.client.isRunning()) {
|
|
return { items: [] };
|
|
}
|
|
return this.client.sendRequest(vscode_languageserver_protocol_1.WorkspaceDiagnosticRequest.type, params, token2).then(async (result2) => {
|
|
if (token2.isCancellationRequested) {
|
|
return { items: [] };
|
|
}
|
|
const converted = {
|
|
items: []
|
|
};
|
|
for (const item of result2.items) {
|
|
converted.items.push(await convertReport(item));
|
|
}
|
|
disposable.dispose();
|
|
resultReporter2(converted);
|
|
return { items: [] };
|
|
}, (error) => {
|
|
disposable.dispose();
|
|
return this.client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type, token2, error, { items: [] });
|
|
});
|
|
};
|
|
const middleware = this.client.middleware;
|
|
return middleware.provideWorkspaceDiagnostics ? middleware.provideWorkspaceDiagnostics(resultIds, token, resultReporter, provideDiagnostics) : provideDiagnostics(resultIds, token, resultReporter);
|
|
};
|
|
}
|
|
return result;
|
|
}
|
|
dispose() {
|
|
this.isDisposed = true;
|
|
this.workspaceCancellation?.cancel();
|
|
this.workspaceTimeout?.dispose();
|
|
for (const [key, request] of this.openRequests) {
|
|
if (request.state === RequestStateKind.active) {
|
|
request.tokenSource.cancel();
|
|
}
|
|
this.openRequests.set(key, { state: RequestStateKind.outDated, document: request.document });
|
|
}
|
|
if (this.client.clientOptions.diagnosticCollectionProvider !== undefined) {
|
|
this.client.clientOptions.diagnosticCollectionProvider.dispose(this.diagnostics, features_1.DiagnosticCollectionSource.pull);
|
|
} else {
|
|
this.diagnostics.dispose();
|
|
}
|
|
}
|
|
}
|
|
|
|
class BackgroundScheduler {
|
|
client;
|
|
diagnosticRequestor;
|
|
lastDocumentToPull;
|
|
documents;
|
|
timeoutHandle;
|
|
isDisposed;
|
|
constructor(client, diagnosticRequestor) {
|
|
this.client = client;
|
|
this.diagnosticRequestor = diagnosticRequestor;
|
|
this.documents = new vscode_languageserver_protocol_1.LinkedMap;
|
|
this.isDisposed = false;
|
|
}
|
|
add(document) {
|
|
if (this.isDisposed === true) {
|
|
return;
|
|
}
|
|
const key = DocumentOrUri.asKey(document);
|
|
if (this.documents.has(key)) {
|
|
return;
|
|
}
|
|
this.documents.set(key, document, vscode_languageserver_protocol_1.Touch.Last);
|
|
this.lastDocumentToPull = document;
|
|
}
|
|
remove(document) {
|
|
const key = DocumentOrUri.asKey(document);
|
|
this.documents.delete(key);
|
|
if (this.documents.size === 0) {
|
|
this.stop();
|
|
return;
|
|
} else if (key === this.lastDocumentToPullKey()) {
|
|
const before = this.documents.before(key);
|
|
if (before === undefined) {
|
|
this.stop();
|
|
} else {
|
|
this.lastDocumentToPull = before;
|
|
}
|
|
}
|
|
}
|
|
trigger() {
|
|
this.lastDocumentToPull = this.documents.last;
|
|
this.runLoop();
|
|
}
|
|
runLoop() {
|
|
if (this.isDisposed === true) {
|
|
return;
|
|
}
|
|
if (this.documents.size === 0) {
|
|
this.stop();
|
|
return;
|
|
}
|
|
if (this.lastDocumentToPull === undefined) {
|
|
return;
|
|
}
|
|
if (this.timeoutHandle !== undefined) {
|
|
return;
|
|
}
|
|
this.timeoutHandle = (0, vscode_languageserver_protocol_1.RAL)().timer.setTimeout(() => {
|
|
const document = this.documents.first;
|
|
if (document === undefined) {
|
|
return;
|
|
}
|
|
const key = DocumentOrUri.asKey(document);
|
|
this.diagnosticRequestor.pullAsync(document).catch((error) => {
|
|
this.client.error(`Document pull failed for text document ${key}`, error, false);
|
|
}).finally(() => {
|
|
this.timeoutHandle = undefined;
|
|
this.documents.set(key, document, vscode_languageserver_protocol_1.Touch.Last);
|
|
if (key !== this.lastDocumentToPullKey()) {
|
|
this.runLoop();
|
|
}
|
|
});
|
|
}, 500);
|
|
}
|
|
dispose() {
|
|
this.isDisposed = true;
|
|
this.stop();
|
|
this.documents.clear();
|
|
this.lastDocumentToPull = undefined;
|
|
}
|
|
stop() {
|
|
this.timeoutHandle?.dispose();
|
|
this.timeoutHandle = undefined;
|
|
this.lastDocumentToPull = undefined;
|
|
}
|
|
lastDocumentToPullKey() {
|
|
return this.lastDocumentToPull !== undefined ? DocumentOrUri.asKey(this.lastDocumentToPull) : undefined;
|
|
}
|
|
}
|
|
|
|
class DiagnosticFeatureProviderImpl {
|
|
disposable;
|
|
diagnosticRequestor;
|
|
activeTextDocument;
|
|
backgroundScheduler;
|
|
constructor(client, visibleDocuments, options) {
|
|
const diagnosticPullOptions = Object.assign({ onChange: false, onSave: false, onFocus: false }, client.clientOptions.diagnosticPullOptions);
|
|
const documentSelector = client.protocol2CodeConverter.asDocumentSelector(options.documentSelector);
|
|
const disposables = [];
|
|
const matchFilter = (filter, resource) => {
|
|
if (typeof filter === "string") {
|
|
return false;
|
|
}
|
|
if (filter.language !== undefined && filter.language !== "*") {
|
|
return false;
|
|
}
|
|
if (filter.scheme !== undefined && filter.scheme !== "*" && filter.scheme !== resource.scheme) {
|
|
return false;
|
|
}
|
|
if (filter.pattern !== undefined && !(0, globPattern_1.matchGlobPattern)(filter.pattern, resource)) {
|
|
return false;
|
|
}
|
|
return true;
|
|
};
|
|
const matchResource = (resource) => {
|
|
const selector = options.documentSelector;
|
|
if (diagnosticPullOptions.match !== undefined) {
|
|
return diagnosticPullOptions.match(selector, resource);
|
|
}
|
|
for (const filter of selector) {
|
|
if (!vscode_languageserver_protocol_1.TextDocumentFilter.is(filter)) {
|
|
continue;
|
|
}
|
|
if (matchFilter(filter, resource)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
};
|
|
const matches = (document) => {
|
|
return document instanceof vscode_1.Uri ? matchResource(document) : vscode_1.languages.match(documentSelector, document) > 0 && visibleDocuments.isVisible(document);
|
|
};
|
|
const matchesCell = (cell) => {
|
|
return vscode_1.languages.match(documentSelector, cell.document) > 0 && visibleDocuments.isVisible(cell.notebook.uri);
|
|
};
|
|
const isActiveDocument = (document) => {
|
|
return document instanceof vscode_1.Uri ? this.activeTextDocument?.uri.toString() === document.toString() : this.activeTextDocument === document;
|
|
};
|
|
this.diagnosticRequestor = new DiagnosticRequestor(client, visibleDocuments, options);
|
|
this.backgroundScheduler = new BackgroundScheduler(client, this.diagnosticRequestor);
|
|
const addToBackgroundIfNeeded = (document) => {
|
|
if (!matches(document) || !options.interFileDependencies || isActiveDocument(document) || diagnosticPullOptions.onChange === false) {
|
|
return;
|
|
}
|
|
this.backgroundScheduler.add(document);
|
|
};
|
|
const considerDocument = (textDocument, mode) => {
|
|
return (diagnosticPullOptions.filter === undefined || !diagnosticPullOptions.filter(textDocument, mode)) && this.diagnosticRequestor.knows(PullState.document, textDocument);
|
|
};
|
|
this.activeTextDocument = vscode_1.window.activeTextEditor?.document;
|
|
disposables.push(vscode_1.window.onDidChangeActiveTextEditor((editor) => {
|
|
const oldActive = this.activeTextDocument;
|
|
this.activeTextDocument = editor?.document;
|
|
if (oldActive !== undefined) {
|
|
addToBackgroundIfNeeded(oldActive);
|
|
}
|
|
if (this.activeTextDocument !== undefined) {
|
|
this.backgroundScheduler.remove(this.activeTextDocument);
|
|
if (diagnosticPullOptions.onFocus === true && matches(this.activeTextDocument) && considerDocument(this.activeTextDocument, DiagnosticPullMode.onFocus)) {
|
|
this.diagnosticRequestor.pull(this.activeTextDocument);
|
|
}
|
|
}
|
|
}));
|
|
const openFeature = client.getFeature(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.method);
|
|
disposables.push(openFeature.onNotificationSent((event) => {
|
|
const textDocument = event.textDocument;
|
|
if (this.diagnosticRequestor.knowsSameVersion(PullState.document, textDocument)) {
|
|
return;
|
|
}
|
|
if (matches(textDocument)) {
|
|
this.diagnosticRequestor.pull(textDocument, () => {
|
|
addToBackgroundIfNeeded(textDocument);
|
|
});
|
|
}
|
|
}));
|
|
const notebookFeature = client.getFeature(vscode_languageserver_protocol_1.NotebookDocumentSyncRegistrationType.method);
|
|
disposables.push(notebookFeature.onOpenNotificationSent((event) => {
|
|
for (const cell of event.getCells()) {
|
|
if (matchesCell(cell)) {
|
|
this.diagnosticRequestor.pull(cell.document, () => {
|
|
addToBackgroundIfNeeded(cell.document);
|
|
});
|
|
}
|
|
}
|
|
}));
|
|
disposables.push(visibleDocuments.onOpen((opened) => {
|
|
for (const resource of opened) {
|
|
if (this.diagnosticRequestor.knows(PullState.document, resource)) {
|
|
continue;
|
|
}
|
|
const uriStr = resource.toString();
|
|
let textDocument;
|
|
for (const item of vscode_1.workspace.textDocuments) {
|
|
if (uriStr === item.uri.toString()) {
|
|
textDocument = item;
|
|
break;
|
|
}
|
|
}
|
|
if (textDocument !== undefined && matches(textDocument)) {
|
|
this.diagnosticRequestor.pull(textDocument, () => {
|
|
addToBackgroundIfNeeded(textDocument);
|
|
});
|
|
}
|
|
}
|
|
}));
|
|
const pulledTextDocuments = new Set;
|
|
for (const textDocument of vscode_1.workspace.textDocuments) {
|
|
if (matches(textDocument)) {
|
|
this.diagnosticRequestor.pull(textDocument, () => {
|
|
addToBackgroundIfNeeded(textDocument);
|
|
});
|
|
pulledTextDocuments.add(textDocument.uri.toString());
|
|
}
|
|
}
|
|
for (const notebookDocument of vscode_1.workspace.notebookDocuments) {
|
|
for (const cell of notebookDocument.getCells()) {
|
|
if (matchesCell(cell)) {
|
|
this.diagnosticRequestor.pull(cell.document, () => {
|
|
addToBackgroundIfNeeded(cell.document);
|
|
});
|
|
pulledTextDocuments.add(cell.document.uri.toString());
|
|
}
|
|
}
|
|
}
|
|
if (diagnosticPullOptions.onTabs === true) {
|
|
for (const resource of visibleDocuments.getResources()) {
|
|
if (!pulledTextDocuments.has(resource.toString()) && matches(resource)) {
|
|
this.diagnosticRequestor.pull(resource, () => {
|
|
addToBackgroundIfNeeded(resource);
|
|
});
|
|
}
|
|
}
|
|
}
|
|
if (diagnosticPullOptions.onChange === true) {
|
|
const changeFeature = client.getFeature(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.method);
|
|
disposables.push(changeFeature.onNotificationSent(async (event) => {
|
|
const textDocument = event.textDocument;
|
|
if (considerDocument(textDocument, DiagnosticPullMode.onType)) {
|
|
this.diagnosticRequestor.pull(textDocument, () => {
|
|
this.backgroundScheduler.trigger();
|
|
});
|
|
}
|
|
}));
|
|
disposables.push(notebookFeature.onChangeNotificationSent(async (event) => {
|
|
const textEvents = event.cells?.textContent || [];
|
|
const changedCells = textEvents.map((c) => event.notebook.getCells().find((cell) => cell.document.uri.toString() === c.document.uri.toString()));
|
|
for (const cell of changedCells) {
|
|
if (cell && matchesCell(cell)) {
|
|
this.diagnosticRequestor.pull(cell.document, () => {
|
|
this.backgroundScheduler.trigger();
|
|
});
|
|
}
|
|
}
|
|
const closedCells = event.cells?.structure?.didClose || [];
|
|
for (const cell of closedCells) {
|
|
this.diagnosticRequestor.forgetDocument(cell.document);
|
|
}
|
|
const openedCells = event.cells?.structure?.didOpen || [];
|
|
for (const cell of openedCells) {
|
|
if (matchesCell(cell)) {
|
|
this.diagnosticRequestor.pull(cell.document, () => {
|
|
this.backgroundScheduler.trigger();
|
|
});
|
|
}
|
|
}
|
|
}));
|
|
}
|
|
if (diagnosticPullOptions.onSave === true) {
|
|
const saveFeature = client.getFeature(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.method);
|
|
disposables.push(saveFeature.onNotificationSent((event) => {
|
|
const textDocument = event.textDocument;
|
|
if (considerDocument(textDocument, DiagnosticPullMode.onSave)) {
|
|
this.diagnosticRequestor.pull(event.textDocument);
|
|
}
|
|
}));
|
|
disposables.push(notebookFeature.onSaveNotificationSent((event) => {
|
|
for (const cell of event.getCells()) {
|
|
if (matchesCell(cell)) {
|
|
this.diagnosticRequestor.pull(cell.document);
|
|
}
|
|
}
|
|
}));
|
|
}
|
|
const closeFeature = client.getFeature(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.method);
|
|
disposables.push(closeFeature.onAboutToSendNotification((event) => {
|
|
this.cleanUpDocument(event.textDocument);
|
|
}));
|
|
disposables.push(notebookFeature.onCloseNotificationSent((event) => {
|
|
for (const cell of event.getCells()) {
|
|
this.cleanUpDocument(cell.document);
|
|
}
|
|
}));
|
|
disposables.push(visibleDocuments.onClose((closed) => {
|
|
for (const document of closed) {
|
|
this.cleanUpDocument(document);
|
|
}
|
|
}));
|
|
this.diagnosticRequestor.onDidChangeDiagnosticsEmitter.event(() => {
|
|
for (const textDocument of vscode_1.workspace.textDocuments) {
|
|
if (matches(textDocument)) {
|
|
this.diagnosticRequestor.pull(textDocument);
|
|
}
|
|
}
|
|
});
|
|
if (options.workspaceDiagnostics === true && options.identifier !== "da348dc5-c30a-4515-9d98-31ff3be38d14") {
|
|
this.diagnosticRequestor.pullWorkspace();
|
|
}
|
|
this.disposable = vscode_1.Disposable.from(...disposables, this.backgroundScheduler, this.diagnosticRequestor);
|
|
}
|
|
get onDidChangeDiagnosticsEmitter() {
|
|
return this.diagnosticRequestor.onDidChangeDiagnosticsEmitter;
|
|
}
|
|
get diagnostics() {
|
|
return this.diagnosticRequestor.provider;
|
|
}
|
|
forget(document) {
|
|
this.cleanUpDocument(document);
|
|
}
|
|
cleanUpDocument(document) {
|
|
this.backgroundScheduler.remove(document);
|
|
if (this.diagnosticRequestor.knows(PullState.document, document)) {
|
|
this.diagnosticRequestor.forgetDocument(document);
|
|
}
|
|
}
|
|
}
|
|
|
|
class DiagnosticFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const capability = ensure(ensure(capabilities, "textDocument"), "diagnostic");
|
|
capability.relatedInformation = true;
|
|
capability.tagSupport = { valueSet: [vscode_languageserver_protocol_1.DiagnosticTag.Unnecessary, vscode_languageserver_protocol_1.DiagnosticTag.Deprecated] };
|
|
capability.codeDescriptionSupport = true;
|
|
capability.dataSupport = true;
|
|
capability.dynamicRegistration = true;
|
|
capability.relatedDocumentSupport = false;
|
|
capability.markupMessageSupport = false;
|
|
ensure(ensure(capabilities, "workspace"), "diagnostics").refreshSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const client = this._client;
|
|
client.onRequest(vscode_languageserver_protocol_1.DiagnosticRefreshRequest.type, async () => {
|
|
for (const provider of this.getAllProviders()) {
|
|
provider.onDidChangeDiagnosticsEmitter.fire();
|
|
}
|
|
});
|
|
const [id, options] = this.getRegistration(documentSelector, capabilities.diagnosticProvider);
|
|
if (!id || !options) {
|
|
return;
|
|
}
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
clear() {
|
|
super.clear();
|
|
}
|
|
refresh() {
|
|
for (const provider of this.getAllProviders()) {
|
|
provider.onDidChangeDiagnosticsEmitter.fire();
|
|
}
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const provider = new DiagnosticFeatureProviderImpl(this._client, this._client.visibleDocuments, options);
|
|
return [provider.disposable, provider];
|
|
}
|
|
}
|
|
exports2.DiagnosticFeature = DiagnosticFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/notebook.js
|
|
var require_notebook = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.NotebookDocumentSyncFeature = undefined;
|
|
var vscode = __importStar(require("vscode"));
|
|
var proto = __importStar(require_api2());
|
|
var UUID = __importStar(require_uuid());
|
|
var Is = __importStar(require_is());
|
|
var globPattern_1 = require_globPattern();
|
|
function ensure(target, key) {
|
|
if (target[key] === undefined) {
|
|
target[key] = {};
|
|
}
|
|
return target[key];
|
|
}
|
|
var Converter;
|
|
(function(Converter2) {
|
|
let c2p;
|
|
(function(c2p2) {
|
|
function asVersionedNotebookDocumentIdentifier(notebookDocument, base) {
|
|
return {
|
|
version: notebookDocument.version,
|
|
uri: base.asUri(notebookDocument.uri)
|
|
};
|
|
}
|
|
c2p2.asVersionedNotebookDocumentIdentifier = asVersionedNotebookDocumentIdentifier;
|
|
function asNotebookDocument(notebookDocument, cells, base) {
|
|
const result = proto.NotebookDocument.create(base.asUri(notebookDocument.uri), notebookDocument.notebookType, notebookDocument.version, asNotebookCells(cells, base));
|
|
if (Object.keys(notebookDocument.metadata).length > 0) {
|
|
result.metadata = asMetadata(notebookDocument.metadata);
|
|
}
|
|
return result;
|
|
}
|
|
c2p2.asNotebookDocument = asNotebookDocument;
|
|
function asNotebookCells(cells, base) {
|
|
return cells.map((cell) => asNotebookCell(cell, base));
|
|
}
|
|
c2p2.asNotebookCells = asNotebookCells;
|
|
function asMetadata(metadata) {
|
|
const seen = new Set;
|
|
return deepCopy(seen, metadata);
|
|
}
|
|
c2p2.asMetadata = asMetadata;
|
|
function asNotebookCell(cell, base) {
|
|
const result = proto.NotebookCell.create(asNotebookCellKind(cell.kind), base.asUri(cell.document.uri));
|
|
if (Object.keys(cell.metadata).length > 0) {
|
|
result.metadata = asMetadata(cell.metadata);
|
|
}
|
|
if (cell.executionSummary !== undefined && (Is.number(cell.executionSummary.executionOrder) && Is.boolean(cell.executionSummary.success))) {
|
|
result.executionSummary = {
|
|
executionOrder: cell.executionSummary.executionOrder,
|
|
success: cell.executionSummary.success
|
|
};
|
|
}
|
|
return result;
|
|
}
|
|
c2p2.asNotebookCell = asNotebookCell;
|
|
function asNotebookCellKind(kind) {
|
|
switch (kind) {
|
|
case vscode.NotebookCellKind.Markup:
|
|
return proto.NotebookCellKind.Markup;
|
|
case vscode.NotebookCellKind.Code:
|
|
return proto.NotebookCellKind.Code;
|
|
}
|
|
}
|
|
function deepCopy(seen, value) {
|
|
if (seen.has(value)) {
|
|
throw new Error(`Can't deep copy cyclic structures.`);
|
|
}
|
|
if (Array.isArray(value)) {
|
|
const result = [];
|
|
for (const elem of value) {
|
|
if (elem !== null && typeof elem === "object" || Array.isArray(elem)) {
|
|
result.push(deepCopy(seen, elem));
|
|
} else {
|
|
if (elem instanceof RegExp) {
|
|
throw new Error(`Can't transfer regular expressions to the server`);
|
|
}
|
|
result.push(elem);
|
|
}
|
|
}
|
|
return result;
|
|
} else {
|
|
const props = Object.keys(value);
|
|
const result = Object.create(null);
|
|
for (const prop of props) {
|
|
const elem = value[prop];
|
|
if (elem !== null && typeof elem === "object" || Array.isArray(elem)) {
|
|
result[prop] = deepCopy(seen, elem);
|
|
} else {
|
|
if (elem instanceof RegExp) {
|
|
throw new Error(`Can't transfer regular expressions to the server`);
|
|
}
|
|
result[prop] = elem;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
function asTextContentChange(event, base) {
|
|
const params = base.asChangeTextDocumentParams(event, event.document.uri, event.document.version);
|
|
return { document: params.textDocument, changes: params.contentChanges };
|
|
}
|
|
c2p2.asTextContentChange = asTextContentChange;
|
|
function asNotebookDocumentChangeEvent(event, base) {
|
|
const result = Object.create(null);
|
|
if (event.metadata) {
|
|
result.metadata = Converter2.c2p.asMetadata(event.metadata);
|
|
}
|
|
if (event.cells !== undefined) {
|
|
const cells = Object.create(null);
|
|
const changedCells = event.cells;
|
|
if (changedCells.structure) {
|
|
cells.structure = {
|
|
array: {
|
|
start: changedCells.structure.array.start,
|
|
deleteCount: changedCells.structure.array.deleteCount,
|
|
cells: changedCells.structure.array.cells !== undefined ? changedCells.structure.array.cells.map((cell) => Converter2.c2p.asNotebookCell(cell, base)) : undefined
|
|
},
|
|
didOpen: changedCells.structure.didOpen !== undefined ? changedCells.structure.didOpen.map((cell) => base.asOpenTextDocumentParams(cell.document).textDocument) : undefined,
|
|
didClose: changedCells.structure.didClose !== undefined ? changedCells.structure.didClose.map((cell) => base.asCloseTextDocumentParams(cell.document).textDocument) : undefined
|
|
};
|
|
}
|
|
if (changedCells.data !== undefined) {
|
|
cells.data = changedCells.data.map((cell) => Converter2.c2p.asNotebookCell(cell, base));
|
|
}
|
|
if (changedCells.textContent !== undefined) {
|
|
cells.textContent = changedCells.textContent.map((event2) => Converter2.c2p.asTextContentChange(event2, base));
|
|
}
|
|
if (Object.keys(cells).length > 0) {
|
|
result.cells = cells;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
c2p2.asNotebookDocumentChangeEvent = asNotebookDocumentChangeEvent;
|
|
})(c2p = Converter2.c2p || (Converter2.c2p = {}));
|
|
})(Converter || (Converter = {}));
|
|
var $NotebookCell;
|
|
(function($NotebookCell2) {
|
|
function computeDiff(originalCells, modifiedCells, compareMetadata) {
|
|
const originalLength = originalCells.length;
|
|
const modifiedLength = modifiedCells.length;
|
|
let startIndex = 0;
|
|
while (startIndex < modifiedLength && startIndex < originalLength && equals(originalCells[startIndex], modifiedCells[startIndex], compareMetadata)) {
|
|
startIndex++;
|
|
}
|
|
if (startIndex < modifiedLength && startIndex < originalLength) {
|
|
let originalEndIndex = originalLength - 1;
|
|
let modifiedEndIndex = modifiedLength - 1;
|
|
while (originalEndIndex >= 0 && modifiedEndIndex >= 0 && equals(originalCells[originalEndIndex], modifiedCells[modifiedEndIndex], compareMetadata)) {
|
|
originalEndIndex--;
|
|
modifiedEndIndex--;
|
|
}
|
|
const deleteCount = originalEndIndex + 1 - startIndex;
|
|
const newCells = startIndex === modifiedEndIndex + 1 ? undefined : modifiedCells.slice(startIndex, modifiedEndIndex + 1);
|
|
return newCells !== undefined ? { start: startIndex, deleteCount, cells: newCells } : { start: startIndex, deleteCount };
|
|
} else if (startIndex < modifiedLength) {
|
|
return { start: startIndex, deleteCount: 0, cells: modifiedCells.slice(startIndex) };
|
|
} else if (startIndex < originalLength) {
|
|
return { start: startIndex, deleteCount: originalLength - startIndex };
|
|
} else {
|
|
return;
|
|
}
|
|
}
|
|
$NotebookCell2.computeDiff = computeDiff;
|
|
function equals(one, other, compareMetaData = true) {
|
|
if (one.kind !== other.kind || one.document.uri.toString() !== other.document.uri.toString() || one.document.languageId !== other.document.languageId || !equalsExecution(one.executionSummary, other.executionSummary)) {
|
|
return false;
|
|
}
|
|
return !compareMetaData || compareMetaData && equalsMetadata(one.metadata, other.metadata);
|
|
}
|
|
function equalsExecution(one, other) {
|
|
if (one === other) {
|
|
return true;
|
|
}
|
|
if (one === undefined || other === undefined) {
|
|
return false;
|
|
}
|
|
return one.executionOrder === other.executionOrder && one.success === other.success && equalsTiming(one.timing, other.timing);
|
|
}
|
|
function equalsTiming(one, other) {
|
|
if (one === other) {
|
|
return true;
|
|
}
|
|
if (one === undefined || other === undefined) {
|
|
return false;
|
|
}
|
|
return one.startTime === other.startTime && one.endTime === other.endTime;
|
|
}
|
|
function equalsMetadata(one, other) {
|
|
if (one === other) {
|
|
return true;
|
|
}
|
|
if (one === null || one === undefined || other === null || other === undefined) {
|
|
return false;
|
|
}
|
|
if (typeof one !== typeof other) {
|
|
return false;
|
|
}
|
|
if (typeof one !== "object") {
|
|
return false;
|
|
}
|
|
const oneArray = Array.isArray(one);
|
|
const otherArray = Array.isArray(other);
|
|
if (oneArray !== otherArray) {
|
|
return false;
|
|
}
|
|
if (oneArray && otherArray) {
|
|
if (one.length !== other.length) {
|
|
return false;
|
|
}
|
|
for (let i = 0;i < one.length; i++) {
|
|
if (!equalsMetadata(one[i], other[i])) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
if (isObjectLiteral(one) && isObjectLiteral(other)) {
|
|
const oneKeys = Object.keys(one);
|
|
const otherKeys = Object.keys(other);
|
|
if (oneKeys.length !== otherKeys.length) {
|
|
return false;
|
|
}
|
|
oneKeys.sort();
|
|
otherKeys.sort();
|
|
if (!equalsMetadata(oneKeys, otherKeys)) {
|
|
return false;
|
|
}
|
|
for (let i = 0;i < oneKeys.length; i++) {
|
|
const prop = oneKeys[i];
|
|
if (!equalsMetadata(one[prop], other[prop])) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
function isObjectLiteral(value) {
|
|
return value !== null && typeof value === "object";
|
|
}
|
|
$NotebookCell2.isObjectLiteral = isObjectLiteral;
|
|
})($NotebookCell || ($NotebookCell = {}));
|
|
var $NotebookDocumentFilter;
|
|
(function($NotebookDocumentFilter2) {
|
|
function matchNotebook(filter, notebookDocument) {
|
|
if (typeof filter === "string") {
|
|
return filter === "*" || notebookDocument.notebookType === filter;
|
|
}
|
|
if (filter.notebookType !== undefined && filter.notebookType !== "*" && notebookDocument.notebookType !== filter.notebookType) {
|
|
return false;
|
|
}
|
|
const uri = notebookDocument.uri;
|
|
if (filter.scheme !== undefined && filter.scheme !== "*" && uri.scheme !== filter.scheme) {
|
|
return false;
|
|
}
|
|
if (filter.pattern !== undefined) {
|
|
if (!(0, globPattern_1.matchGlobPattern)(filter.pattern, uri)) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
$NotebookDocumentFilter2.matchNotebook = matchNotebook;
|
|
})($NotebookDocumentFilter || ($NotebookDocumentFilter = {}));
|
|
var $NotebookDocumentSyncOptions;
|
|
(function($NotebookDocumentSyncOptions2) {
|
|
function asDocumentSelector(options) {
|
|
const selector = options.notebookSelector;
|
|
const result = [];
|
|
for (const element of selector) {
|
|
const notebookType = (typeof element.notebook === "string" ? element.notebook : element.notebook?.notebookType) ?? "*";
|
|
const scheme = typeof element.notebook === "string" ? undefined : element.notebook?.scheme;
|
|
const pattern = typeof element.notebook === "string" ? undefined : element.notebook?.pattern;
|
|
if (element.cells !== undefined) {
|
|
for (const cell of element.cells) {
|
|
result.push(asDocumentFilter(notebookType, scheme, pattern, cell.language));
|
|
}
|
|
} else {
|
|
result.push(asDocumentFilter(notebookType, scheme, pattern, undefined));
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
$NotebookDocumentSyncOptions2.asDocumentSelector = asDocumentSelector;
|
|
function asDocumentFilter(notebookType, scheme, pattern, language) {
|
|
return scheme === undefined && pattern === undefined ? { notebook: notebookType, language } : { notebook: { notebookType, scheme, pattern }, language };
|
|
}
|
|
})($NotebookDocumentSyncOptions || ($NotebookDocumentSyncOptions = {}));
|
|
var SyncInfo;
|
|
(function(SyncInfo2) {
|
|
function create(cells) {
|
|
return {
|
|
cells,
|
|
uris: new Set(cells.map((cell) => cell.document.uri.toString()))
|
|
};
|
|
}
|
|
SyncInfo2.create = create;
|
|
})(SyncInfo || (SyncInfo = {}));
|
|
|
|
class NotebookDocumentSyncFeatureProvider {
|
|
client;
|
|
options;
|
|
notebookSyncInfo;
|
|
notebookDidOpen;
|
|
disposables;
|
|
selector;
|
|
onChangeNotificationSent;
|
|
onOpenNotificationSent;
|
|
onCloseNotificationSent;
|
|
onSaveNotificationSent;
|
|
constructor(client, options, onChangeNotificationSent, onOpenNotificationSent, onCloseNotificationSent, onSaveNotificationSent) {
|
|
this.client = client;
|
|
this.options = options;
|
|
this.notebookSyncInfo = new Map;
|
|
this.notebookDidOpen = new Set;
|
|
this.disposables = [];
|
|
this.selector = client.protocol2CodeConverter.asDocumentSelector($NotebookDocumentSyncOptions.asDocumentSelector(options));
|
|
this.onChangeNotificationSent = onChangeNotificationSent;
|
|
this.onOpenNotificationSent = onOpenNotificationSent;
|
|
this.onCloseNotificationSent = onCloseNotificationSent;
|
|
this.onSaveNotificationSent = onSaveNotificationSent;
|
|
vscode.workspace.onDidOpenNotebookDocument((notebookDocument) => {
|
|
this.notebookDidOpen.add(notebookDocument.uri.toString());
|
|
this.didOpen(notebookDocument);
|
|
}, undefined, this.disposables);
|
|
for (const notebookDocument of vscode.workspace.notebookDocuments) {
|
|
this.notebookDidOpen.add(notebookDocument.uri.toString());
|
|
this.didOpen(notebookDocument);
|
|
}
|
|
vscode.workspace.onDidChangeNotebookDocument((event) => this.didChangeNotebookDocument(event), undefined, this.disposables);
|
|
if (this.options.save === true) {
|
|
vscode.workspace.onDidSaveNotebookDocument((notebookDocument) => this.didSave(notebookDocument), undefined, this.disposables);
|
|
}
|
|
vscode.workspace.onDidCloseNotebookDocument((notebookDocument) => {
|
|
this.didClose(notebookDocument);
|
|
this.notebookDidOpen.delete(notebookDocument.uri.toString());
|
|
}, undefined, this.disposables);
|
|
}
|
|
getState() {
|
|
for (const notebook of vscode.workspace.notebookDocuments) {
|
|
const matchingCells = this.getMatchingCellsConsideringSyncInfo(notebook);
|
|
if (matchingCells !== undefined) {
|
|
return { kind: "document", id: "$internal", registrations: true, matches: true };
|
|
}
|
|
}
|
|
return { kind: "document", id: "$internal", registrations: true, matches: false };
|
|
}
|
|
get mode() {
|
|
return "notebook";
|
|
}
|
|
handles(textDocument) {
|
|
if (vscode.languages.match(this.selector, textDocument) > 0) {
|
|
return true;
|
|
}
|
|
const key = textDocument.uri.toString();
|
|
for (const syncInfo of this.notebookSyncInfo.values()) {
|
|
if (syncInfo.uris.has(key)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
didOpenNotebookCellTextDocument(notebookDocument, cell) {
|
|
if (vscode.languages.match(this.selector, cell.document) === 0) {
|
|
return;
|
|
}
|
|
if (!this.notebookDidOpen.has(notebookDocument.uri.toString())) {
|
|
return;
|
|
}
|
|
const syncInfo = this.getSyncInfo(notebookDocument);
|
|
const cellMatches = this.cellMatches(notebookDocument, cell);
|
|
if (syncInfo !== undefined) {
|
|
const cellIsSynced = syncInfo.uris.has(cell.document.uri.toString());
|
|
if (cellMatches && cellIsSynced || !cellMatches && !cellIsSynced) {
|
|
return;
|
|
}
|
|
if (cellMatches) {
|
|
const matchingCells = this.mergeCells(notebookDocument, syncInfo, [cell]);
|
|
if (matchingCells !== undefined) {
|
|
const event = this.asNotebookDocumentChangeEvent(notebookDocument, undefined, syncInfo, matchingCells);
|
|
if (event !== undefined) {
|
|
this.doSendChange(event, matchingCells).catch(() => {});
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
if (cellMatches) {
|
|
this.doSendOpen(notebookDocument, [cell]).catch(() => {});
|
|
}
|
|
}
|
|
}
|
|
didChangeNotebookCellTextDocument(notebookDocument, cell, event) {
|
|
if (vscode.languages.match(this.selector, event.document) === 0) {
|
|
return;
|
|
}
|
|
const syncInfo = this.getSyncInfo(notebookDocument);
|
|
if (syncInfo === undefined || !syncInfo.uris.has(cell.document.uri.toString())) {
|
|
return;
|
|
}
|
|
this.doSendChange({
|
|
notebook: notebookDocument,
|
|
cells: { textContent: [event] }
|
|
}, syncInfo.cells).catch(() => {});
|
|
}
|
|
didCloseNotebookCellTextDocument(notebookDocument, cell) {
|
|
const syncInfo = this.getSyncInfo(notebookDocument);
|
|
if (syncInfo === undefined) {
|
|
return;
|
|
}
|
|
const cellUri = cell.document.uri;
|
|
const index = syncInfo.cells.findIndex((item) => item.document.uri.toString() === cellUri.toString());
|
|
if (index === -1) {
|
|
return;
|
|
}
|
|
if (index === 0 && syncInfo.cells.length === 1) {
|
|
this.doSendClose(notebookDocument, syncInfo.cells).catch(() => {});
|
|
} else {
|
|
const newCells = syncInfo.cells.slice();
|
|
const deleted = newCells.splice(index, 1);
|
|
this.doSendChange({
|
|
notebook: notebookDocument,
|
|
cells: {
|
|
structure: {
|
|
array: { start: index, deleteCount: 1 },
|
|
didClose: deleted
|
|
}
|
|
}
|
|
}, newCells).catch(() => {});
|
|
}
|
|
}
|
|
dispose() {
|
|
for (const disposable of this.disposables) {
|
|
disposable.dispose();
|
|
}
|
|
}
|
|
didOpen(notebookDocument, matchingCells, syncInfo = this.getSyncInfo(notebookDocument)) {
|
|
if (syncInfo !== undefined) {
|
|
if (matchingCells === undefined) {
|
|
matchingCells = syncInfo.cells.slice();
|
|
}
|
|
if (matchingCells !== undefined) {
|
|
const event = this.asNotebookDocumentChangeEvent(notebookDocument, undefined, syncInfo, matchingCells);
|
|
if (event !== undefined) {
|
|
this.doSendChange(event, matchingCells).catch(() => {});
|
|
}
|
|
} else {
|
|
this.doSendClose(notebookDocument, []).catch(() => {});
|
|
}
|
|
} else {
|
|
matchingCells = this.getMatchingCells(notebookDocument);
|
|
if (matchingCells === undefined) {
|
|
return;
|
|
}
|
|
this.doSendOpen(notebookDocument, matchingCells).catch(() => {});
|
|
}
|
|
}
|
|
didChangeNotebookDocument(event) {
|
|
const notebookDocument = event.notebook;
|
|
const syncInfo = this.getSyncInfo(notebookDocument);
|
|
if (syncInfo === undefined) {
|
|
if (event.contentChanges.length === 0) {
|
|
return;
|
|
}
|
|
const cells = this.getMatchingCells(notebookDocument);
|
|
if (cells === undefined) {
|
|
return;
|
|
}
|
|
this.didOpen(notebookDocument, cells, syncInfo);
|
|
} else {
|
|
const cells = this.getMatchingCellsFromEvent(notebookDocument, syncInfo, event);
|
|
if (cells === undefined) {
|
|
this.didClose(notebookDocument, syncInfo);
|
|
return;
|
|
}
|
|
const newEvent = this.asNotebookDocumentChangeEvent(event.notebook, event, syncInfo, cells);
|
|
if (newEvent !== undefined) {
|
|
this.doSendChange(newEvent, cells).catch(() => {});
|
|
}
|
|
}
|
|
}
|
|
didSave(notebookDocument) {
|
|
const syncInfo = this.getSyncInfo(notebookDocument);
|
|
if (syncInfo === undefined) {
|
|
return;
|
|
}
|
|
this.doSendSave(notebookDocument).catch(() => {});
|
|
}
|
|
didClose(notebookDocument, syncInfo = this.getSyncInfo(notebookDocument)) {
|
|
if (syncInfo === undefined) {
|
|
return;
|
|
}
|
|
const syncedCells = notebookDocument.getCells().filter((cell) => syncInfo.uris.has(cell.document.uri.toString()));
|
|
this.doSendClose(notebookDocument, syncedCells).catch(() => {});
|
|
}
|
|
async sendDidOpenNotebookDocument(notebookDocument) {
|
|
const syncInfo = this.getSyncInfo(notebookDocument);
|
|
if (syncInfo !== undefined) {
|
|
throw new Error(`Notebook document ${notebookDocument.uri.toString()} is already open`);
|
|
}
|
|
const cells = this.getMatchingCells(notebookDocument);
|
|
if (cells === undefined) {
|
|
return;
|
|
}
|
|
return this.doSendOpen(notebookDocument, cells);
|
|
}
|
|
async doSendOpen(notebookDocument, cells) {
|
|
const send = async (notebookDocument2, cells2) => {
|
|
const cellDocuments = cells2.map((cell) => this.client.code2ProtocolConverter.asTextDocumentItem(cell.document));
|
|
try {
|
|
await this.client.sendNotification(proto.DidOpenNotebookDocumentNotification.type, {
|
|
notebookDocument: Converter.c2p.asNotebookDocument(notebookDocument2, cells2, this.client.code2ProtocolConverter),
|
|
cellTextDocuments: cellDocuments
|
|
});
|
|
this.onOpenNotificationSent.fire(notebookDocument2);
|
|
} catch (error) {
|
|
this.client.error("Sending DidOpenNotebookDocumentNotification failed", error);
|
|
throw error;
|
|
}
|
|
};
|
|
const middleware = this.client.middleware?.notebooks;
|
|
this.notebookSyncInfo.set(notebookDocument.uri.toString(), SyncInfo.create(cells));
|
|
return middleware?.didOpen !== undefined ? middleware.didOpen(notebookDocument, cells, send) : send(notebookDocument, cells);
|
|
}
|
|
async sendDidChangeNotebookDocument(event) {
|
|
const cells = this.getMatchingCellsFromSyncInfo(event.notebook);
|
|
if (cells === undefined) {
|
|
throw new Error(`Received changed event for un-synced notebook ${event.notebook.uri.toString()}`);
|
|
}
|
|
return this.doSendChange(event, cells);
|
|
}
|
|
async doSendChange(event, cells) {
|
|
const send = async (event2) => {
|
|
try {
|
|
await this.client.sendNotification(proto.DidChangeNotebookDocumentNotification.type, {
|
|
notebookDocument: Converter.c2p.asVersionedNotebookDocumentIdentifier(event2.notebook, this.client.code2ProtocolConverter),
|
|
change: Converter.c2p.asNotebookDocumentChangeEvent(event2, this.client.code2ProtocolConverter)
|
|
});
|
|
this.onChangeNotificationSent.fire(event2);
|
|
} catch (error) {
|
|
this.client.error("Sending DidChangeNotebookDocumentNotification failed", error);
|
|
throw error;
|
|
}
|
|
};
|
|
const middleware = this.client.middleware?.notebooks;
|
|
if (event.cells?.structure !== undefined) {
|
|
this.notebookSyncInfo.set(event.notebook.uri.toString(), SyncInfo.create(cells));
|
|
}
|
|
return middleware?.didChange !== undefined ? middleware?.didChange(event, send) : send(event);
|
|
}
|
|
async sendDidSaveNotebookDocument(notebookDocument) {
|
|
return this.doSendSave(notebookDocument);
|
|
}
|
|
async doSendSave(notebookDocument) {
|
|
const send = async (notebookDocument2) => {
|
|
try {
|
|
await this.client.sendNotification(proto.DidSaveNotebookDocumentNotification.type, {
|
|
notebookDocument: { uri: this.client.code2ProtocolConverter.asUri(notebookDocument2.uri) }
|
|
});
|
|
this.onSaveNotificationSent.fire(notebookDocument2);
|
|
} catch (error) {
|
|
this.client.error("Sending DidSaveNotebookDocumentNotification failed", error);
|
|
throw error;
|
|
}
|
|
};
|
|
const middleware = this.client.middleware?.notebooks;
|
|
return middleware?.didSave !== undefined ? middleware.didSave(notebookDocument, send) : send(notebookDocument);
|
|
}
|
|
async sendDidCloseNotebookDocument(notebookDocument) {
|
|
const cells = this.getMatchingCellsFromSyncInfo(notebookDocument);
|
|
if (cells === undefined) {
|
|
throw new Error(`Received close event for un-synced notebook ${notebookDocument.uri.toString()}`);
|
|
}
|
|
return this.doSendClose(notebookDocument, cells);
|
|
}
|
|
async doSendClose(notebookDocument, cells) {
|
|
const send = async (notebookDocument2, cells2) => {
|
|
try {
|
|
await this.client.sendNotification(proto.DidCloseNotebookDocumentNotification.type, {
|
|
notebookDocument: { uri: this.client.code2ProtocolConverter.asUri(notebookDocument2.uri) },
|
|
cellTextDocuments: cells2.map((cell) => this.client.code2ProtocolConverter.asTextDocumentIdentifier(cell.document))
|
|
});
|
|
this.onCloseNotificationSent.fire(notebookDocument2);
|
|
} catch (error) {
|
|
this.client.error("Sending DidCloseNotebookDocumentNotification failed", error);
|
|
throw error;
|
|
}
|
|
};
|
|
const middleware = this.client.middleware?.notebooks;
|
|
this.notebookSyncInfo.delete(notebookDocument.uri.toString());
|
|
return middleware?.didClose !== undefined ? middleware.didClose(notebookDocument, cells, send) : send(notebookDocument, cells);
|
|
}
|
|
getSynchronizedCells(notebookDocument) {
|
|
const syncInfo = this.getSyncInfo(notebookDocument);
|
|
return syncInfo?.cells;
|
|
}
|
|
asNotebookDocumentChangeEvent(notebook, event, syncInfo, matchingCells) {
|
|
if (event !== undefined && event.notebook !== notebook) {
|
|
throw new Error("Notebook must be identical");
|
|
}
|
|
const result = {
|
|
notebook
|
|
};
|
|
if (event?.metadata !== undefined) {
|
|
result.metadata = Converter.c2p.asMetadata(event.metadata);
|
|
}
|
|
let matchingCellsSet;
|
|
if (event?.cellChanges !== undefined && event.cellChanges.length > 0) {
|
|
const data = [];
|
|
matchingCellsSet = new Set(matchingCells.map((cell) => cell.document.uri.toString()));
|
|
for (const cellChange of event.cellChanges) {
|
|
if (matchingCellsSet.has(cellChange.cell.document.uri.toString()) && (cellChange.executionSummary !== undefined || cellChange.metadata !== undefined)) {
|
|
data.push(cellChange.cell);
|
|
}
|
|
}
|
|
if (data.length > 0) {
|
|
result.cells = result.cells ?? {};
|
|
result.cells.data = data;
|
|
}
|
|
}
|
|
if ((event?.contentChanges !== undefined && event.contentChanges.length > 0 || event === undefined) && syncInfo !== undefined && matchingCells !== undefined) {
|
|
const oldCells = syncInfo.cells;
|
|
const newCells = matchingCells;
|
|
const diff = $NotebookCell.computeDiff(oldCells, newCells, false);
|
|
let addedCells;
|
|
let removedCells;
|
|
if (diff !== undefined) {
|
|
addedCells = diff.cells === undefined ? new Map : new Map(diff.cells.map((cell) => [cell.document.uri.toString(), cell]));
|
|
removedCells = diff.deleteCount === 0 ? new Map : new Map(oldCells.slice(diff.start, diff.start + diff.deleteCount).map((cell) => [cell.document.uri.toString(), cell]));
|
|
for (const key of Array.from(removedCells.keys())) {
|
|
if (addedCells.has(key)) {
|
|
removedCells.delete(key);
|
|
addedCells.delete(key);
|
|
}
|
|
}
|
|
result.cells = result.cells ?? {};
|
|
const didOpen = [];
|
|
const didClose = [];
|
|
if (addedCells.size > 0 || removedCells.size > 0) {
|
|
for (const cell of addedCells.values()) {
|
|
didOpen.push(cell);
|
|
}
|
|
for (const cell of removedCells.values()) {
|
|
didClose.push(cell);
|
|
}
|
|
}
|
|
result.cells.structure = {
|
|
array: diff,
|
|
didOpen,
|
|
didClose
|
|
};
|
|
}
|
|
}
|
|
return Object.keys(result).length > 1 ? result : undefined;
|
|
}
|
|
getMatchingCells(notebookDocument, cells = notebookDocument.getCells()) {
|
|
if (this.options.notebookSelector === undefined) {
|
|
return;
|
|
}
|
|
for (const item of this.options.notebookSelector) {
|
|
if (item.notebook === undefined || $NotebookDocumentFilter.matchNotebook(item.notebook, notebookDocument)) {
|
|
const filtered = this.filterCells(notebookDocument, cells, item.cells);
|
|
return filtered.length === 0 ? undefined : filtered;
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
getMatchingCellsFromEvent(notebookDocument, syncInfo, event) {
|
|
if (this.options.notebookSelector === undefined) {
|
|
return;
|
|
}
|
|
let selector;
|
|
for (const item of this.options.notebookSelector) {
|
|
if (item.notebook === undefined || $NotebookDocumentFilter.matchNotebook(item.notebook, notebookDocument)) {
|
|
selector = item;
|
|
break;
|
|
}
|
|
}
|
|
if (selector === undefined) {
|
|
return;
|
|
}
|
|
if ((event.cellChanges === undefined || event.cellChanges.length === 0) && (event.contentChanges === undefined || event.contentChanges.length === 0)) {
|
|
return syncInfo.cells;
|
|
}
|
|
let cells;
|
|
if (event.cellChanges !== undefined && event.cellChanges.length > 0) {
|
|
const changedCells = event.cellChanges.map((item) => item.cell);
|
|
const filtered = this.filterCells(notebookDocument, changedCells, selector.cells);
|
|
if (filtered.length !== changedCells.length) {
|
|
cells = new Set(syncInfo.uris);
|
|
for (const cell of changedCells) {
|
|
cells.delete(cell.document.uri.toString());
|
|
}
|
|
for (const cell of filtered) {
|
|
cells.add(cell.document.uri.toString());
|
|
}
|
|
}
|
|
}
|
|
if (event.contentChanges !== undefined && event.contentChanges.length > 0) {
|
|
if (cells === undefined) {
|
|
cells = new Set(syncInfo.uris);
|
|
}
|
|
for (const item of event.contentChanges) {
|
|
for (const cell of item.removedCells) {
|
|
cells.delete(cell.document.uri.toString());
|
|
}
|
|
const filtered = this.filterCells(notebookDocument, new Array(...item.addedCells), selector.cells);
|
|
for (const cell of filtered) {
|
|
cells.add(cell.document.uri.toString());
|
|
}
|
|
}
|
|
}
|
|
if (cells === undefined) {
|
|
return syncInfo.cells;
|
|
}
|
|
const result = [];
|
|
const current = notebookDocument.getCells();
|
|
for (const cell of current) {
|
|
if (cells.has(cell.document.uri.toString())) {
|
|
result.push(cell);
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
getMatchingCellsFromSyncInfo(notebook) {
|
|
const syncInfo = this.getSyncInfo(notebook);
|
|
return syncInfo !== undefined ? syncInfo.cells : undefined;
|
|
}
|
|
getMatchingCellsConsideringSyncInfo(notebook) {
|
|
const syncInfo = this.getSyncInfo(notebook);
|
|
return syncInfo !== undefined ? syncInfo.cells : this.getMatchingCells(notebook);
|
|
}
|
|
mergeCells(notebookDocument, syncInfo, cells) {
|
|
const result = [];
|
|
const merged = new Set(syncInfo.uris);
|
|
for (const cell of cells) {
|
|
merged.add(cell.document.uri.toString());
|
|
}
|
|
for (const cell of notebookDocument.getCells()) {
|
|
if (merged.has(cell.document.uri.toString())) {
|
|
result.push(cell);
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
cellMatches(notebookDocument, cell) {
|
|
const cells = this.getMatchingCells(notebookDocument, [cell]);
|
|
return cells !== undefined && cells[0] === cell;
|
|
}
|
|
filterCells(notebookDocument, cells, cellSelector) {
|
|
const filtered = cellSelector !== undefined ? cells.filter((cell) => {
|
|
const cellLanguage = cell.document.languageId;
|
|
return cellSelector.some((filter) => filter.language === "*" || cellLanguage === filter.language);
|
|
}) : cells;
|
|
return typeof this.client.clientOptions.notebookDocumentOptions?.filterCells === "function" ? this.client.clientOptions.notebookDocumentOptions.filterCells(notebookDocument, filtered) : filtered;
|
|
}
|
|
getSyncInfo(notebook) {
|
|
return this.notebookSyncInfo.get(notebook.uri.toString());
|
|
}
|
|
}
|
|
|
|
class NotebookDocumentSyncFeature {
|
|
static CellScheme = "vscode-notebook-cell";
|
|
client;
|
|
registrations;
|
|
dedicatedChannel;
|
|
_onChangeNotificationSent;
|
|
_onOpenNotificationSent;
|
|
_onCloseNotificationSent;
|
|
_onSaveNotificationSent;
|
|
constructor(client) {
|
|
this.client = client;
|
|
this.registrations = new Map;
|
|
this.registrationType = proto.NotebookDocumentSyncRegistrationType.type;
|
|
this._onChangeNotificationSent = new vscode.EventEmitter;
|
|
this._onOpenNotificationSent = new vscode.EventEmitter;
|
|
this._onCloseNotificationSent = new vscode.EventEmitter;
|
|
this._onSaveNotificationSent = new vscode.EventEmitter;
|
|
vscode.workspace.onDidOpenTextDocument((textDocument) => {
|
|
if (textDocument.uri.scheme !== NotebookDocumentSyncFeature.CellScheme) {
|
|
return;
|
|
}
|
|
const [notebookDocument, notebookCell] = this.findNotebookDocumentAndCell(textDocument);
|
|
if (notebookDocument === undefined || notebookCell === undefined) {
|
|
return;
|
|
}
|
|
for (const provider of this.registrations.values()) {
|
|
if (provider instanceof NotebookDocumentSyncFeatureProvider) {
|
|
provider.didOpenNotebookCellTextDocument(notebookDocument, notebookCell);
|
|
}
|
|
}
|
|
});
|
|
vscode.workspace.onDidChangeTextDocument((event) => {
|
|
if (event.contentChanges.length === 0) {
|
|
return;
|
|
}
|
|
const textDocument = event.document;
|
|
if (textDocument.uri.scheme !== NotebookDocumentSyncFeature.CellScheme) {
|
|
return;
|
|
}
|
|
const [notebookDocument, cell] = this.findNotebookDocumentAndCell(textDocument);
|
|
if (notebookDocument === undefined || cell === undefined) {
|
|
return;
|
|
}
|
|
for (const provider of this.registrations.values()) {
|
|
if (provider instanceof NotebookDocumentSyncFeatureProvider) {
|
|
provider.didChangeNotebookCellTextDocument(notebookDocument, cell, event);
|
|
}
|
|
}
|
|
});
|
|
vscode.workspace.onDidCloseTextDocument((textDocument) => {
|
|
if (textDocument.uri.scheme !== NotebookDocumentSyncFeature.CellScheme) {
|
|
return;
|
|
}
|
|
const [notebookDocument, notebookCell] = this.findNotebookDocumentAndCell(textDocument);
|
|
if (notebookDocument === undefined || notebookCell === undefined) {
|
|
return;
|
|
}
|
|
for (const provider of this.registrations.values()) {
|
|
if (provider instanceof NotebookDocumentSyncFeatureProvider) {
|
|
provider.didCloseNotebookCellTextDocument(notebookDocument, notebookCell);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
getState() {
|
|
if (this.registrations.size === 0) {
|
|
return { kind: "document", id: this.registrationType.method, registrations: false, matches: false };
|
|
}
|
|
for (const provider of this.registrations.values()) {
|
|
const state = provider.getState();
|
|
if (state.kind === "document" && state.registrations === true && state.matches === true) {
|
|
return { kind: "document", id: this.registrationType.method, registrations: true, matches: true };
|
|
}
|
|
}
|
|
return { kind: "document", id: this.registrationType.method, registrations: true, matches: false };
|
|
}
|
|
registrationType;
|
|
get onOpenNotificationSent() {
|
|
return this._onOpenNotificationSent.event;
|
|
}
|
|
get onChangeNotificationSent() {
|
|
return this._onChangeNotificationSent.event;
|
|
}
|
|
get onCloseNotificationSent() {
|
|
return this._onCloseNotificationSent.event;
|
|
}
|
|
get onSaveNotificationSent() {
|
|
return this._onSaveNotificationSent.event;
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const synchronization = ensure(ensure(capabilities, "notebookDocument"), "synchronization");
|
|
synchronization.dynamicRegistration = true;
|
|
synchronization.executionSummarySupport = true;
|
|
}
|
|
preInitialize(capabilities) {
|
|
const options = capabilities.notebookDocumentSync;
|
|
if (options === undefined) {
|
|
return;
|
|
}
|
|
this.dedicatedChannel = this.client.protocol2CodeConverter.asDocumentSelector($NotebookDocumentSyncOptions.asDocumentSelector(options));
|
|
}
|
|
initialize(capabilities) {
|
|
const options = capabilities.notebookDocumentSync;
|
|
if (options === undefined) {
|
|
return;
|
|
}
|
|
const id = options.id ?? UUID.generateUuid();
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
register(data) {
|
|
const provider = new NotebookDocumentSyncFeatureProvider(this.client, data.registerOptions, this._onChangeNotificationSent, this._onOpenNotificationSent, this._onCloseNotificationSent, this._onSaveNotificationSent);
|
|
this.registrations.set(data.id, provider);
|
|
}
|
|
unregister(id) {
|
|
const provider = this.registrations.get(id);
|
|
if (provider !== undefined) {
|
|
this.registrations.delete(id);
|
|
provider.dispose();
|
|
}
|
|
}
|
|
clear() {
|
|
for (const provider of this.registrations.values()) {
|
|
provider.dispose();
|
|
}
|
|
this.registrations.clear();
|
|
this._onChangeNotificationSent.dispose();
|
|
this._onChangeNotificationSent = new vscode.EventEmitter;
|
|
this._onOpenNotificationSent.dispose();
|
|
this._onOpenNotificationSent = new vscode.EventEmitter;
|
|
this._onCloseNotificationSent.dispose();
|
|
this._onCloseNotificationSent = new vscode.EventEmitter;
|
|
this._onSaveNotificationSent.dispose();
|
|
this._onSaveNotificationSent = new vscode.EventEmitter;
|
|
}
|
|
handles(textDocument) {
|
|
if (textDocument.uri.scheme !== NotebookDocumentSyncFeature.CellScheme) {
|
|
return false;
|
|
}
|
|
if (this.dedicatedChannel !== undefined && vscode.languages.match(this.dedicatedChannel, textDocument) > 0) {
|
|
return true;
|
|
}
|
|
for (const provider of this.registrations.values()) {
|
|
if (provider.handles(textDocument)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
getProvider(notebookCell) {
|
|
for (const provider of this.registrations.values()) {
|
|
if (provider.handles(notebookCell.document)) {
|
|
return provider;
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
findNotebookDocumentAndCell(textDocument) {
|
|
const uri = textDocument.uri.toString();
|
|
for (const notebookDocument of vscode.workspace.notebookDocuments) {
|
|
for (const cell of notebookDocument.getCells()) {
|
|
if (cell.document.uri.toString() === uri) {
|
|
return [notebookDocument, cell];
|
|
}
|
|
}
|
|
}
|
|
return [undefined, undefined];
|
|
}
|
|
}
|
|
exports2.NotebookDocumentSyncFeature = NotebookDocumentSyncFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/configuration.js
|
|
var require_configuration = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.SyncConfigurationFeature = exports2.ConfigurationFeature = undefined;
|
|
exports2.toJSONObject = toJSONObject;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var Is = __importStar(require_is());
|
|
var UUID = __importStar(require_uuid());
|
|
var features_1 = require_features();
|
|
|
|
class ConfigurationFeature {
|
|
_client;
|
|
constructor(client) {
|
|
this._client = client;
|
|
}
|
|
getState() {
|
|
return { kind: "static" };
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
capabilities.workspace = capabilities.workspace || {};
|
|
capabilities.workspace.configuration = true;
|
|
}
|
|
initialize() {
|
|
const client = this._client;
|
|
client.onRequest(vscode_languageserver_protocol_1.ConfigurationRequest.type, (params, token) => {
|
|
const configuration = (params2) => {
|
|
const result = [];
|
|
for (const item of params2.items) {
|
|
const resource = item.scopeUri !== undefined && item.scopeUri !== null ? this._client.protocol2CodeConverter.asUri(item.scopeUri) : undefined;
|
|
result.push(this.getConfiguration(resource, item.section !== null ? item.section : undefined));
|
|
}
|
|
return result;
|
|
};
|
|
const middleware = client.middleware.workspace;
|
|
return middleware && middleware.configuration ? middleware.configuration(params, token, configuration) : configuration(params, token);
|
|
});
|
|
}
|
|
getConfiguration(resource, section) {
|
|
let result = null;
|
|
if (section) {
|
|
const index = section.lastIndexOf(".");
|
|
if (index === -1) {
|
|
result = toJSONObject(vscode_1.workspace.getConfiguration(undefined, resource).get(section));
|
|
} else {
|
|
const config = vscode_1.workspace.getConfiguration(section.substr(0, index), resource);
|
|
if (config) {
|
|
result = toJSONObject(config.get(section.substr(index + 1)));
|
|
}
|
|
}
|
|
} else {
|
|
const config = vscode_1.workspace.getConfiguration(undefined, resource);
|
|
result = {};
|
|
for (const key of Object.keys(config)) {
|
|
if (config.has(key)) {
|
|
result[key] = toJSONObject(config.get(key));
|
|
}
|
|
}
|
|
}
|
|
if (result === undefined) {
|
|
result = null;
|
|
}
|
|
return result;
|
|
}
|
|
clear() {}
|
|
}
|
|
exports2.ConfigurationFeature = ConfigurationFeature;
|
|
function toJSONObject(obj) {
|
|
if (obj) {
|
|
if (Array.isArray(obj)) {
|
|
return obj.map(toJSONObject);
|
|
} else if (typeof obj === "object") {
|
|
const res = Object.create(null);
|
|
for (const key in obj) {
|
|
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
res[key] = toJSONObject(obj[key]);
|
|
}
|
|
}
|
|
return res;
|
|
}
|
|
}
|
|
return obj;
|
|
}
|
|
|
|
class SyncConfigurationFeature {
|
|
_client;
|
|
isCleared;
|
|
_listeners;
|
|
constructor(_client) {
|
|
this._client = _client;
|
|
this.isCleared = false;
|
|
this._listeners = new Map;
|
|
}
|
|
getState() {
|
|
return { kind: "workspace", id: this.registrationType.method, registrations: this._listeners.size > 0 };
|
|
}
|
|
get registrationType() {
|
|
return vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type;
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "didChangeConfiguration").dynamicRegistration = true;
|
|
}
|
|
initialize() {
|
|
this.isCleared = false;
|
|
const section = this._client.clientOptions.synchronize?.configurationSection;
|
|
if (section !== undefined) {
|
|
this.register({
|
|
id: UUID.generateUuid(),
|
|
registerOptions: {
|
|
section
|
|
}
|
|
});
|
|
}
|
|
}
|
|
register(data) {
|
|
const disposable = vscode_1.workspace.onDidChangeConfiguration((event) => {
|
|
this.onDidChangeConfiguration(data.registerOptions.section, event);
|
|
});
|
|
this._listeners.set(data.id, disposable);
|
|
if (data.registerOptions.section !== undefined) {
|
|
this.onDidChangeConfiguration(data.registerOptions.section, undefined);
|
|
}
|
|
}
|
|
unregister(id) {
|
|
const disposable = this._listeners.get(id);
|
|
if (disposable) {
|
|
this._listeners.delete(id);
|
|
disposable.dispose();
|
|
}
|
|
}
|
|
clear() {
|
|
for (const disposable of this._listeners.values()) {
|
|
disposable.dispose();
|
|
}
|
|
this._listeners.clear();
|
|
this.isCleared = true;
|
|
}
|
|
onDidChangeConfiguration(configurationSection, event) {
|
|
if (this.isCleared) {
|
|
return;
|
|
}
|
|
let sections;
|
|
if (Is.string(configurationSection)) {
|
|
sections = [configurationSection];
|
|
} else {
|
|
sections = configurationSection;
|
|
}
|
|
if (sections !== undefined && event !== undefined) {
|
|
const affected = sections.some((section) => event.affectsConfiguration(section));
|
|
if (!affected) {
|
|
return;
|
|
}
|
|
}
|
|
const didChangeConfiguration = async (sections2) => {
|
|
if (sections2 === undefined) {
|
|
return this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: null });
|
|
} else {
|
|
return this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: this.extractSettingsInformation(sections2) });
|
|
}
|
|
};
|
|
const middleware = this._client.middleware.workspace?.didChangeConfiguration;
|
|
(middleware ? middleware(sections, didChangeConfiguration) : didChangeConfiguration(sections)).catch((error) => {
|
|
this._client.error(`Sending notification ${vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type.method} failed`, error);
|
|
});
|
|
}
|
|
extractSettingsInformation(keys) {
|
|
function ensurePath(config, path) {
|
|
let current = config;
|
|
for (let i = 0;i < path.length - 1; i++) {
|
|
let obj = current[path[i]];
|
|
if (!obj) {
|
|
obj = Object.create(null);
|
|
current[path[i]] = obj;
|
|
}
|
|
current = obj;
|
|
}
|
|
return current;
|
|
}
|
|
const resource = this._client.clientOptions.workspaceFolder ? this._client.clientOptions.workspaceFolder.uri : undefined;
|
|
const result = Object.create(null);
|
|
for (let i = 0;i < keys.length; i++) {
|
|
const key = keys[i];
|
|
const index = key.indexOf(".");
|
|
let config = null;
|
|
if (index >= 0) {
|
|
config = vscode_1.workspace.getConfiguration(key.substr(0, index), resource).get(key.substr(index + 1));
|
|
} else {
|
|
config = vscode_1.workspace.getConfiguration(undefined, resource).get(key);
|
|
}
|
|
if (config) {
|
|
const path = keys[i].split(".");
|
|
ensurePath(result, path)[path[path.length - 1]] = toJSONObject(config);
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
exports2.SyncConfigurationFeature = SyncConfigurationFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-textdocument/lib/umd/main.js
|
|
var require_main2 = __commonJS((exports2, module2) => {
|
|
var __spreadArray = exports2 && exports2.__spreadArray || function(to, from, pack) {
|
|
if (pack || arguments.length === 2)
|
|
for (var i = 0, l = from.length, ar;i < l; i++) {
|
|
if (ar || !(i in from)) {
|
|
if (!ar)
|
|
ar = Array.prototype.slice.call(from, 0, i);
|
|
ar[i] = from[i];
|
|
}
|
|
}
|
|
return to.concat(ar || Array.prototype.slice.call(from));
|
|
};
|
|
(function(factory) {
|
|
if (typeof module2 === "object" && typeof module2.exports === "object") {
|
|
var v = factory(require, exports2);
|
|
if (v !== undefined)
|
|
module2.exports = v;
|
|
} else if (typeof define === "function" && define.amd) {
|
|
define(["require", "exports"], factory);
|
|
}
|
|
})(function(require2, exports3) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.TextDocument = undefined;
|
|
var FullTextDocument = function() {
|
|
function FullTextDocument2(uri, languageId, version, content) {
|
|
this._uri = uri;
|
|
this._languageId = languageId;
|
|
this._version = version;
|
|
this._content = content;
|
|
this._lineOffsets = undefined;
|
|
}
|
|
Object.defineProperty(FullTextDocument2.prototype, "uri", {
|
|
get: function() {
|
|
return this._uri;
|
|
},
|
|
enumerable: false,
|
|
configurable: true
|
|
});
|
|
Object.defineProperty(FullTextDocument2.prototype, "languageId", {
|
|
get: function() {
|
|
return this._languageId;
|
|
},
|
|
enumerable: false,
|
|
configurable: true
|
|
});
|
|
Object.defineProperty(FullTextDocument2.prototype, "version", {
|
|
get: function() {
|
|
return this._version;
|
|
},
|
|
enumerable: false,
|
|
configurable: true
|
|
});
|
|
FullTextDocument2.prototype.getText = function(range) {
|
|
if (range) {
|
|
var start = this.offsetAt(range.start);
|
|
var end = this.offsetAt(range.end);
|
|
return this._content.substring(start, end);
|
|
}
|
|
return this._content;
|
|
};
|
|
FullTextDocument2.prototype.update = function(changes, version) {
|
|
for (var _i = 0, changes_1 = changes;_i < changes_1.length; _i++) {
|
|
var change = changes_1[_i];
|
|
if (FullTextDocument2.isIncremental(change)) {
|
|
var range = getWellformedRange(change.range);
|
|
var startOffset = this.offsetAt(range.start);
|
|
var endOffset = this.offsetAt(range.end);
|
|
this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length);
|
|
var startLine = Math.max(range.start.line, 0);
|
|
var endLine = Math.max(range.end.line, 0);
|
|
var lineOffsets = this._lineOffsets;
|
|
var addedLineOffsets = computeLineOffsets(change.text, false, startOffset);
|
|
if (endLine - startLine === addedLineOffsets.length) {
|
|
for (var i = 0, len = addedLineOffsets.length;i < len; i++) {
|
|
lineOffsets[i + startLine + 1] = addedLineOffsets[i];
|
|
}
|
|
} else {
|
|
if (addedLineOffsets.length < 1e4) {
|
|
lineOffsets.splice.apply(lineOffsets, __spreadArray([startLine + 1, endLine - startLine], addedLineOffsets, false));
|
|
} else {
|
|
this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1));
|
|
}
|
|
}
|
|
var diff = change.text.length - (endOffset - startOffset);
|
|
if (diff !== 0) {
|
|
for (var i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length;i < len; i++) {
|
|
lineOffsets[i] = lineOffsets[i] + diff;
|
|
}
|
|
}
|
|
} else if (FullTextDocument2.isFull(change)) {
|
|
this._content = change.text;
|
|
this._lineOffsets = undefined;
|
|
} else {
|
|
throw new Error("Unknown change event received");
|
|
}
|
|
}
|
|
this._version = version;
|
|
};
|
|
FullTextDocument2.prototype.getLineOffsets = function() {
|
|
if (this._lineOffsets === undefined) {
|
|
this._lineOffsets = computeLineOffsets(this._content, true);
|
|
}
|
|
return this._lineOffsets;
|
|
};
|
|
FullTextDocument2.prototype.positionAt = function(offset) {
|
|
offset = Math.max(Math.min(offset, this._content.length), 0);
|
|
var lineOffsets = this.getLineOffsets();
|
|
var low = 0, high = lineOffsets.length;
|
|
if (high === 0) {
|
|
return { line: 0, character: offset };
|
|
}
|
|
while (low < high) {
|
|
var mid = Math.floor((low + high) / 2);
|
|
if (lineOffsets[mid] > offset) {
|
|
high = mid;
|
|
} else {
|
|
low = mid + 1;
|
|
}
|
|
}
|
|
var line = low - 1;
|
|
offset = this.ensureBeforeEOL(offset, lineOffsets[line]);
|
|
return { line, character: offset - lineOffsets[line] };
|
|
};
|
|
FullTextDocument2.prototype.offsetAt = function(position) {
|
|
var lineOffsets = this.getLineOffsets();
|
|
if (position.line >= lineOffsets.length) {
|
|
return this._content.length;
|
|
} else if (position.line < 0) {
|
|
return 0;
|
|
}
|
|
var lineOffset = lineOffsets[position.line];
|
|
if (position.character <= 0) {
|
|
return lineOffset;
|
|
}
|
|
var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length;
|
|
var offset = Math.min(lineOffset + position.character, nextLineOffset);
|
|
return this.ensureBeforeEOL(offset, lineOffset);
|
|
};
|
|
FullTextDocument2.prototype.getLineRange = function(line) {
|
|
var lineOffsets = this.getLineOffsets();
|
|
if (line >= lineOffsets.length) {
|
|
var lastLine = lineOffsets.length - 1;
|
|
return { start: { line: lastLine, character: 0 }, end: { line: lastLine, character: this._content.length - lineOffsets[lastLine] } };
|
|
} else if (line < 0) {
|
|
return { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } };
|
|
}
|
|
var startOffset = lineOffsets[line];
|
|
var nextLineOffset = line + 1 < lineOffsets.length ? lineOffsets[line + 1] : this._content.length;
|
|
var endOffset = this.ensureBeforeEOL(nextLineOffset, startOffset);
|
|
return { start: { line, character: 0 }, end: { line, character: endOffset - startOffset } };
|
|
};
|
|
FullTextDocument2.prototype.getEOLCharacters = function(line) {
|
|
var lineOffsets = this.getLineOffsets();
|
|
if (line >= lineOffsets.length) {
|
|
return "";
|
|
} else if (line < 0) {
|
|
return "";
|
|
}
|
|
var nextLineOffset = line + 1 < lineOffsets.length ? lineOffsets[line + 1] : this._content.length;
|
|
var eolOffset = this.ensureBeforeEOL(nextLineOffset, lineOffsets[line]);
|
|
return this._content.substring(eolOffset, nextLineOffset);
|
|
};
|
|
FullTextDocument2.prototype.ensureBeforeEOL = function(offset, lineOffset) {
|
|
while (offset > lineOffset && isEOL(this._content.charCodeAt(offset - 1))) {
|
|
offset--;
|
|
}
|
|
return offset;
|
|
};
|
|
Object.defineProperty(FullTextDocument2.prototype, "lineCount", {
|
|
get: function() {
|
|
return this.getLineOffsets().length;
|
|
},
|
|
enumerable: false,
|
|
configurable: true
|
|
});
|
|
FullTextDocument2.isIncremental = function(event) {
|
|
var candidate = event;
|
|
return candidate !== undefined && candidate !== null && typeof candidate.text === "string" && candidate.range !== undefined && (candidate.rangeLength === undefined || typeof candidate.rangeLength === "number");
|
|
};
|
|
FullTextDocument2.isFull = function(event) {
|
|
var candidate = event;
|
|
return candidate !== undefined && candidate !== null && typeof candidate.text === "string" && candidate.range === undefined && candidate.rangeLength === undefined;
|
|
};
|
|
return FullTextDocument2;
|
|
}();
|
|
var TextDocument;
|
|
(function(TextDocument2) {
|
|
function create(uri, languageId, version, content) {
|
|
return new FullTextDocument(uri, languageId, version, content);
|
|
}
|
|
TextDocument2.create = create;
|
|
function update(document, changes, version) {
|
|
if (document instanceof FullTextDocument) {
|
|
document.update(changes, version);
|
|
return document;
|
|
} else {
|
|
throw new Error("TextDocument.update: document must be created by TextDocument.create");
|
|
}
|
|
}
|
|
TextDocument2.update = update;
|
|
function applyEdits(document, edits) {
|
|
var text = document.getText();
|
|
var sortedEdits = mergeSort(edits.map(getWellformedEdit), function(a, b) {
|
|
var diff = a.range.start.line - b.range.start.line;
|
|
if (diff === 0) {
|
|
return a.range.start.character - b.range.start.character;
|
|
}
|
|
return diff;
|
|
});
|
|
var lastModifiedOffset = 0;
|
|
var spans = [];
|
|
for (var _i = 0, sortedEdits_1 = sortedEdits;_i < sortedEdits_1.length; _i++) {
|
|
var e = sortedEdits_1[_i];
|
|
var startOffset = document.offsetAt(e.range.start);
|
|
if (startOffset < lastModifiedOffset) {
|
|
throw new Error("Overlapping edit");
|
|
} else if (startOffset > lastModifiedOffset) {
|
|
spans.push(text.substring(lastModifiedOffset, startOffset));
|
|
}
|
|
if (e.newText.length) {
|
|
spans.push(e.newText);
|
|
}
|
|
lastModifiedOffset = document.offsetAt(e.range.end);
|
|
}
|
|
spans.push(text.substr(lastModifiedOffset));
|
|
return spans.join("");
|
|
}
|
|
TextDocument2.applyEdits = applyEdits;
|
|
})(TextDocument || (exports3.TextDocument = TextDocument = {}));
|
|
function mergeSort(data, compare) {
|
|
if (data.length <= 1) {
|
|
return data;
|
|
}
|
|
var p = data.length / 2 | 0;
|
|
var left = data.slice(0, p);
|
|
var right = data.slice(p);
|
|
mergeSort(left, compare);
|
|
mergeSort(right, compare);
|
|
var leftIdx = 0;
|
|
var rightIdx = 0;
|
|
var i = 0;
|
|
while (leftIdx < left.length && rightIdx < right.length) {
|
|
var ret = compare(left[leftIdx], right[rightIdx]);
|
|
if (ret <= 0) {
|
|
data[i++] = left[leftIdx++];
|
|
} else {
|
|
data[i++] = right[rightIdx++];
|
|
}
|
|
}
|
|
while (leftIdx < left.length) {
|
|
data[i++] = left[leftIdx++];
|
|
}
|
|
while (rightIdx < right.length) {
|
|
data[i++] = right[rightIdx++];
|
|
}
|
|
return data;
|
|
}
|
|
function computeLineOffsets(text, isAtLineStart, textOffset) {
|
|
if (textOffset === undefined) {
|
|
textOffset = 0;
|
|
}
|
|
var result = isAtLineStart ? [textOffset] : [];
|
|
for (var i = 0;i < text.length; i++) {
|
|
var ch = text.charCodeAt(i);
|
|
if (isEOL(ch)) {
|
|
if (ch === 13 && i + 1 < text.length && text.charCodeAt(i + 1) === 10) {
|
|
i++;
|
|
}
|
|
result.push(textOffset + i + 1);
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
function isEOL(char) {
|
|
return char === 13 || char === 10;
|
|
}
|
|
function getWellformedRange(range) {
|
|
var start = range.start;
|
|
var end = range.end;
|
|
if (start.line > end.line || start.line === end.line && start.character > end.character) {
|
|
return { start: end, end: start };
|
|
}
|
|
return range;
|
|
}
|
|
function getWellformedEdit(textEdit) {
|
|
var range = getWellformedRange(textEdit.range);
|
|
if (range !== textEdit.range) {
|
|
return { newText: textEdit.newText, range };
|
|
}
|
|
return textEdit;
|
|
}
|
|
});
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/textSynchronization.js
|
|
var require_textSynchronization = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DidSaveTextDocumentFeature = exports2.WillSaveWaitUntilFeature = exports2.WillSaveFeature = exports2.DidChangeTextDocumentFeature = exports2.DidCloseTextDocumentFeature = exports2.DidOpenTextDocumentFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
var UUID = __importStar(require_uuid());
|
|
var vscode_languageserver_textdocument_1 = require_main2();
|
|
|
|
class DidOpenTextDocumentFeature extends features_1.TextDocumentEventFeature {
|
|
_syncedDocuments;
|
|
_pendingOpenNotifications;
|
|
_delayOpen;
|
|
_pendingOpenListeners;
|
|
constructor(client, syncedDocuments) {
|
|
super(client, vscode_1.workspace.onDidOpenTextDocument, vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, () => client.middleware.didOpen, (textDocument) => client.code2ProtocolConverter.asOpenTextDocumentParams(textDocument), (data) => data, features_1.TextDocumentEventFeature.textDocumentFilter);
|
|
this._syncedDocuments = syncedDocuments;
|
|
this._pendingOpenNotifications = new Map;
|
|
this._delayOpen = client.clientOptions.textSynchronization?.delayOpenNotifications ?? false;
|
|
}
|
|
async callback(document) {
|
|
if (!this._delayOpen) {
|
|
return super.callback(document);
|
|
} else {
|
|
if (!this.matches(document)) {
|
|
return;
|
|
}
|
|
const visibleDocuments = this._client.visibleDocuments;
|
|
if (visibleDocuments.isVisible(document)) {
|
|
return super.callback(document);
|
|
} else {
|
|
const snapshot = new TextDocumentSnapshot(document);
|
|
this._pendingOpenNotifications.set(snapshot.uri.toString(), snapshot);
|
|
}
|
|
}
|
|
}
|
|
get openDocuments() {
|
|
return this._syncedDocuments.values();
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "synchronization").dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;
|
|
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) {
|
|
this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector } });
|
|
}
|
|
}
|
|
get registrationType() {
|
|
return vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type;
|
|
}
|
|
register(data) {
|
|
super.register(data);
|
|
if (!data.registerOptions.documentSelector) {
|
|
return;
|
|
}
|
|
const documentSelector = this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector);
|
|
vscode_1.workspace.textDocuments.forEach((textDocument) => {
|
|
const uri = textDocument.uri.toString();
|
|
if (this._syncedDocuments.has(uri)) {
|
|
return;
|
|
}
|
|
if (vscode_1.languages.match(documentSelector, textDocument) > 0 && !this._client.hasDedicatedTextSynchronizationFeature(textDocument)) {
|
|
const visibleDocuments = this._client.visibleDocuments;
|
|
if (visibleDocuments.isVisible(textDocument)) {
|
|
const middleware = this._client.middleware;
|
|
const didOpen = (textDocument2) => {
|
|
return this._client.sendNotification(this._type, this._createParams(textDocument2));
|
|
};
|
|
(middleware.didOpen ? middleware.didOpen(textDocument, didOpen) : didOpen(textDocument)).catch((error) => {
|
|
this._client.error(`Sending document notification ${this._type.method} failed`, error);
|
|
});
|
|
this._syncedDocuments.set(uri, textDocument);
|
|
} else {
|
|
this._pendingOpenNotifications.set(uri, textDocument);
|
|
}
|
|
}
|
|
});
|
|
if (this._delayOpen && this._pendingOpenListeners === undefined) {
|
|
this._pendingOpenListeners = [];
|
|
const visibleDocuments = this._client.visibleDocuments;
|
|
this._pendingOpenListeners.push(visibleDocuments.onClose((closed) => {
|
|
for (const uri of closed) {
|
|
this._pendingOpenNotifications.delete(uri.toString());
|
|
}
|
|
}));
|
|
this._pendingOpenListeners.push(visibleDocuments.onOpen((opened) => {
|
|
for (const uri of opened) {
|
|
const document = this._pendingOpenNotifications.get(uri.toString());
|
|
if (document !== undefined) {
|
|
super.callback(document).catch((error) => {
|
|
this._client.error(`Sending document notification ${this._type.method} failed`, error);
|
|
});
|
|
this._pendingOpenNotifications.delete(uri.toString());
|
|
}
|
|
}
|
|
}));
|
|
this._pendingOpenListeners.push(vscode_1.workspace.onDidCloseTextDocument((document) => {
|
|
this._pendingOpenNotifications.delete(document.uri.toString());
|
|
}));
|
|
}
|
|
}
|
|
async sendPendingOpenNotifications(closingDocument) {
|
|
const notifications = Array.from(this._pendingOpenNotifications.values());
|
|
this._pendingOpenNotifications.clear();
|
|
let didDropOpenNotification = false;
|
|
for (const notification of notifications) {
|
|
if (closingDocument !== undefined && notification.uri.toString() === closingDocument) {
|
|
didDropOpenNotification = true;
|
|
continue;
|
|
}
|
|
await super.callback(notification);
|
|
}
|
|
return didDropOpenNotification;
|
|
}
|
|
getTextDocument(data) {
|
|
return data;
|
|
}
|
|
notificationSent(textDocument, type, params) {
|
|
this._syncedDocuments.set(textDocument.uri.toString(), textDocument);
|
|
super.notificationSent(textDocument, type, params);
|
|
}
|
|
clear() {
|
|
this._pendingOpenNotifications.clear();
|
|
if (this._pendingOpenListeners !== undefined) {
|
|
for (const listener of this._pendingOpenListeners) {
|
|
listener.dispose();
|
|
}
|
|
this._pendingOpenListeners = undefined;
|
|
}
|
|
super.clear();
|
|
}
|
|
}
|
|
exports2.DidOpenTextDocumentFeature = DidOpenTextDocumentFeature;
|
|
|
|
class DidCloseTextDocumentFeature extends features_1.TextDocumentEventFeature {
|
|
_syncedDocuments;
|
|
_pendingTextDocumentChanges;
|
|
constructor(client, syncedDocuments, pendingTextDocumentChanges) {
|
|
super(client, vscode_1.workspace.onDidCloseTextDocument, vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, () => client.middleware.didClose, (textDocument) => client.code2ProtocolConverter.asCloseTextDocumentParams(textDocument), (data) => data, features_1.TextDocumentEventFeature.textDocumentFilter);
|
|
this._syncedDocuments = syncedDocuments;
|
|
this._pendingTextDocumentChanges = pendingTextDocumentChanges;
|
|
}
|
|
get registrationType() {
|
|
return vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type;
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "synchronization").dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;
|
|
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) {
|
|
this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector } });
|
|
}
|
|
}
|
|
async callback(data) {
|
|
await super.callback(data);
|
|
this._pendingTextDocumentChanges.delete(data.uri.toString());
|
|
}
|
|
getTextDocument(data) {
|
|
return data;
|
|
}
|
|
notificationSent(textDocument, type, params) {
|
|
this._syncedDocuments.delete(textDocument.uri.toString());
|
|
super.notificationSent(textDocument, type, params);
|
|
}
|
|
unregister(id) {
|
|
const selector = this._selectors.get(id);
|
|
if (selector === undefined) {
|
|
return;
|
|
}
|
|
super.unregister(id);
|
|
const selectors = this._selectors.values();
|
|
this._syncedDocuments.forEach((textDocument) => {
|
|
if (vscode_1.languages.match(selector, textDocument) > 0 && !this._selectorFilter(selectors, textDocument) && !this._client.hasDedicatedTextSynchronizationFeature(textDocument)) {
|
|
const middleware = this._client.middleware;
|
|
const didClose = (textDocument2) => {
|
|
return this._client.sendNotification(this._type, this._createParams(textDocument2));
|
|
};
|
|
this._syncedDocuments.delete(textDocument.uri.toString());
|
|
(middleware.didClose ? middleware.didClose(textDocument, didClose) : didClose(textDocument)).catch((error) => {
|
|
this._client.error(`Sending document notification ${this._type.method} failed`, error);
|
|
});
|
|
}
|
|
});
|
|
}
|
|
}
|
|
exports2.DidCloseTextDocumentFeature = DidCloseTextDocumentFeature;
|
|
|
|
class DidChangeTextDocumentFeature extends features_1.DynamicDocumentFeature {
|
|
_listener;
|
|
_changeData;
|
|
_onAboutToSendNotification;
|
|
_onNotificationSent;
|
|
_onPendingChangeAdded;
|
|
_pendingTextDocumentChanges;
|
|
_syncKind;
|
|
constructor(client, pendingTextDocumentChanges) {
|
|
super(client);
|
|
this._changeData = new Map;
|
|
this._onAboutToSendNotification = new vscode_1.EventEmitter;
|
|
this._onNotificationSent = new vscode_1.EventEmitter;
|
|
this._onPendingChangeAdded = new vscode_1.EventEmitter;
|
|
this._pendingTextDocumentChanges = pendingTextDocumentChanges;
|
|
this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
|
|
}
|
|
get onAboutToSendNotification() {
|
|
return this._onAboutToSendNotification.event;
|
|
}
|
|
get onNotificationSent() {
|
|
return this._onNotificationSent.event;
|
|
}
|
|
get onPendingChangeAdded() {
|
|
return this._onPendingChangeAdded.event;
|
|
}
|
|
get syncKind() {
|
|
return this._syncKind;
|
|
}
|
|
get registrationType() {
|
|
return vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type;
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "synchronization").dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;
|
|
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.change !== undefined && textDocumentSyncOptions.change !== vscode_languageserver_protocol_1.TextDocumentSyncKind.None) {
|
|
this.register({
|
|
id: UUID.generateUuid(),
|
|
registerOptions: Object.assign({}, { documentSelector }, { syncKind: textDocumentSyncOptions.change })
|
|
});
|
|
}
|
|
}
|
|
register(data) {
|
|
if (!data.registerOptions.documentSelector) {
|
|
return;
|
|
}
|
|
if (!this._listener) {
|
|
this._listener = vscode_1.workspace.onDidChangeTextDocument(this.callback, this);
|
|
}
|
|
this._changeData.set(data.id, {
|
|
syncKind: data.registerOptions.syncKind,
|
|
documentSelector: this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector)
|
|
});
|
|
this.updateSyncKind(data.registerOptions.syncKind);
|
|
}
|
|
*getDocumentSelectors() {
|
|
for (const data of this._changeData.values()) {
|
|
yield data.documentSelector;
|
|
}
|
|
}
|
|
async callback(event) {
|
|
if (event.contentChanges.length === 0) {
|
|
return;
|
|
}
|
|
const uri = event.document.uri;
|
|
const version = event.document.version;
|
|
const promises = [];
|
|
for (const changeData of this._changeData.values()) {
|
|
if (vscode_1.languages.match(changeData.documentSelector, event.document) > 0 && !this._client.hasDedicatedTextSynchronizationFeature(event.document)) {
|
|
const middleware = this._client.middleware;
|
|
if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental) {
|
|
const didChange = async (event2) => {
|
|
const params = this._client.code2ProtocolConverter.asChangeTextDocumentParams(event2, uri, version);
|
|
this.aboutToSendNotification(event2.document, vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params);
|
|
await this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params);
|
|
this.notificationSent(event2.document, vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params);
|
|
};
|
|
promises.push(middleware.didChange ? middleware.didChange(event, (event2) => didChange(event2)) : didChange(event));
|
|
} else if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) {
|
|
const didChange = async (event2) => {
|
|
const eventUri = event2.document.uri.toString();
|
|
this._pendingTextDocumentChanges.set(eventUri, event2.document);
|
|
this._onPendingChangeAdded.fire();
|
|
};
|
|
promises.push(middleware.didChange ? middleware.didChange(event, (event2) => didChange(event2)) : didChange(event));
|
|
}
|
|
}
|
|
}
|
|
return Promise.all(promises).then(undefined, (error) => {
|
|
this._client.error(`Sending document notification ${vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type.method} failed`, error);
|
|
throw error;
|
|
});
|
|
}
|
|
aboutToSendNotification(textDocument, type, params) {
|
|
this._onAboutToSendNotification.fire({ textDocument, type, params });
|
|
}
|
|
notificationSent(textDocument, type, params) {
|
|
this._onNotificationSent.fire({ textDocument, type, params });
|
|
}
|
|
unregister(id) {
|
|
this._changeData.delete(id);
|
|
if (this._changeData.size === 0) {
|
|
if (this._listener) {
|
|
this._listener.dispose();
|
|
this._listener = undefined;
|
|
}
|
|
this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
|
|
} else {
|
|
this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
|
|
for (const changeData of this._changeData.values()) {
|
|
this.updateSyncKind(changeData.syncKind);
|
|
if (this._syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
clear() {
|
|
this._pendingTextDocumentChanges.clear();
|
|
this._changeData.clear();
|
|
this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
|
|
if (this._listener) {
|
|
this._listener.dispose();
|
|
this._listener = undefined;
|
|
}
|
|
}
|
|
getPendingDocumentChanges(excludes) {
|
|
if (this._pendingTextDocumentChanges.size === 0) {
|
|
return [];
|
|
}
|
|
let result;
|
|
if (excludes.size === 0) {
|
|
result = Array.from(this._pendingTextDocumentChanges.values());
|
|
this._pendingTextDocumentChanges.clear();
|
|
} else {
|
|
result = [];
|
|
for (const entry of this._pendingTextDocumentChanges) {
|
|
if (!excludes.has(entry[0])) {
|
|
result.push(entry[1]);
|
|
this._pendingTextDocumentChanges.delete(entry[0]);
|
|
}
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
getProvider(document) {
|
|
for (const changeData of this._changeData.values()) {
|
|
if (vscode_1.languages.match(changeData.documentSelector, document) > 0) {
|
|
return {
|
|
send: (event) => {
|
|
return this.callback(event);
|
|
}
|
|
};
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
updateSyncKind(syncKind) {
|
|
if (this._syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) {
|
|
return;
|
|
}
|
|
switch (syncKind) {
|
|
case vscode_languageserver_protocol_1.TextDocumentSyncKind.Full:
|
|
this._syncKind = syncKind;
|
|
break;
|
|
case vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental:
|
|
if (this._syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.None) {
|
|
this._syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
exports2.DidChangeTextDocumentFeature = DidChangeTextDocumentFeature;
|
|
|
|
class WillSaveFeature extends features_1.TextDocumentEventFeature {
|
|
constructor(client) {
|
|
super(client, vscode_1.workspace.onWillSaveTextDocument, vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, () => client.middleware.willSave, (willSaveEvent) => client.code2ProtocolConverter.asWillSaveTextDocumentParams(willSaveEvent), (event) => event.document, (selectors, willSaveEvent) => features_1.TextDocumentEventFeature.textDocumentFilter(selectors, willSaveEvent.document));
|
|
}
|
|
get registrationType() {
|
|
return vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type;
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const value = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "synchronization");
|
|
value.willSave = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;
|
|
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSave) {
|
|
this.register({
|
|
id: UUID.generateUuid(),
|
|
registerOptions: { documentSelector }
|
|
});
|
|
}
|
|
}
|
|
getTextDocument(data) {
|
|
return data.document;
|
|
}
|
|
}
|
|
exports2.WillSaveFeature = WillSaveFeature;
|
|
|
|
class WillSaveWaitUntilFeature extends features_1.DynamicDocumentFeature {
|
|
_listener;
|
|
_selectors;
|
|
constructor(client) {
|
|
super(client);
|
|
this._selectors = new Map;
|
|
}
|
|
getDocumentSelectors() {
|
|
return this._selectors.values();
|
|
}
|
|
get registrationType() {
|
|
return vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type;
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const value = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "synchronization");
|
|
value.willSaveWaitUntil = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;
|
|
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSaveWaitUntil) {
|
|
this.register({
|
|
id: UUID.generateUuid(),
|
|
registerOptions: { documentSelector }
|
|
});
|
|
}
|
|
}
|
|
register(data) {
|
|
if (!data.registerOptions.documentSelector) {
|
|
return;
|
|
}
|
|
if (!this._listener) {
|
|
this._listener = vscode_1.workspace.onWillSaveTextDocument(this.callback, this);
|
|
}
|
|
this._selectors.set(data.id, this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector));
|
|
}
|
|
callback(event) {
|
|
if (features_1.TextDocumentEventFeature.textDocumentFilter(this._selectors.values(), event.document) && !this._client.hasDedicatedTextSynchronizationFeature(event.document)) {
|
|
const middleware = this._client.middleware;
|
|
const willSaveWaitUntil = (event2) => {
|
|
return this._client.sendRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, this._client.code2ProtocolConverter.asWillSaveTextDocumentParams(event2)).then(async (edits) => {
|
|
const vEdits = await this._client.protocol2CodeConverter.asTextEdits(edits);
|
|
return vEdits === undefined ? [] : vEdits;
|
|
});
|
|
};
|
|
event.waitUntil(middleware.willSaveWaitUntil ? middleware.willSaveWaitUntil(event, willSaveWaitUntil) : willSaveWaitUntil(event));
|
|
}
|
|
}
|
|
unregister(id) {
|
|
this._selectors.delete(id);
|
|
if (this._selectors.size === 0 && this._listener) {
|
|
this._listener.dispose();
|
|
this._listener = undefined;
|
|
}
|
|
}
|
|
clear() {
|
|
this._selectors.clear();
|
|
if (this._listener) {
|
|
this._listener.dispose();
|
|
this._listener = undefined;
|
|
}
|
|
}
|
|
}
|
|
exports2.WillSaveWaitUntilFeature = WillSaveWaitUntilFeature;
|
|
|
|
class DidSaveTextDocumentFeature extends features_1.TextDocumentEventFeature {
|
|
_includeText;
|
|
constructor(client) {
|
|
super(client, vscode_1.workspace.onDidSaveTextDocument, vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, () => client.middleware.didSave, (textDocument) => client.code2ProtocolConverter.asSaveTextDocumentParams(textDocument, this._includeText), (data) => data, features_1.TextDocumentEventFeature.textDocumentFilter);
|
|
this._includeText = false;
|
|
}
|
|
get registrationType() {
|
|
return vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type;
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "synchronization").didSave = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const textDocumentSyncOptions = capabilities.resolvedTextDocumentSync;
|
|
if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.save) {
|
|
const saveOptions = typeof textDocumentSyncOptions.save === "boolean" ? { includeText: false } : { includeText: !!textDocumentSyncOptions.save.includeText };
|
|
this.register({
|
|
id: UUID.generateUuid(),
|
|
registerOptions: Object.assign({}, { documentSelector }, saveOptions)
|
|
});
|
|
}
|
|
}
|
|
register(data) {
|
|
this._includeText = !!data.registerOptions.includeText;
|
|
super.register(data);
|
|
}
|
|
getTextDocument(data) {
|
|
return data;
|
|
}
|
|
}
|
|
exports2.DidSaveTextDocumentFeature = DidSaveTextDocumentFeature;
|
|
var USUAL_WORD_SEPARATORS = "`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?";
|
|
function createWordRegExp(allowInWords = "") {
|
|
let source = "(-?\\d*\\.\\d\\w*)|([^";
|
|
for (const sep of USUAL_WORD_SEPARATORS) {
|
|
if (allowInWords.indexOf(sep) >= 0) {
|
|
continue;
|
|
}
|
|
source += "\\" + sep;
|
|
}
|
|
source += "\\s]+)";
|
|
return new RegExp(source, "g");
|
|
}
|
|
var DEFAULT_WORD_REGEXP = createWordRegExp();
|
|
|
|
class TextDocumentSnapshot {
|
|
_extTextDocument;
|
|
_capturedTextDocument;
|
|
_content;
|
|
_uri;
|
|
_fileName;
|
|
_languageId;
|
|
_version;
|
|
_eol;
|
|
_isUntitled;
|
|
_encoding;
|
|
_isDirty;
|
|
_isClosed;
|
|
constructor(textDocument) {
|
|
this._extTextDocument = textDocument;
|
|
this._content = textDocument.getText();
|
|
this._uri = textDocument.uri;
|
|
this._fileName = textDocument.fileName;
|
|
this._languageId = textDocument.languageId;
|
|
this._version = textDocument.version;
|
|
this._eol = textDocument.eol;
|
|
this._isUntitled = textDocument.isUntitled;
|
|
this._encoding = textDocument.encoding;
|
|
this._isDirty = textDocument.isDirty;
|
|
this._isClosed = textDocument.isClosed;
|
|
this._capturedTextDocument = vscode_languageserver_textdocument_1.TextDocument.create(this._uri.toString(), this._languageId, this._version, this._content);
|
|
}
|
|
get uri() {
|
|
return this._uri;
|
|
}
|
|
get languageId() {
|
|
return this._languageId;
|
|
}
|
|
get version() {
|
|
return this._version;
|
|
}
|
|
get eol() {
|
|
return this._eol;
|
|
}
|
|
get isUntitled() {
|
|
return this._isUntitled;
|
|
}
|
|
get encoding() {
|
|
return this._encoding;
|
|
}
|
|
get fileName() {
|
|
return this._fileName;
|
|
}
|
|
get isDirty() {
|
|
return this._isDirty;
|
|
}
|
|
get isClosed() {
|
|
return this._isClosed;
|
|
}
|
|
save() {
|
|
return this.version === this._extTextDocument.version ? this._extTextDocument.save() : Promise.resolve(false);
|
|
}
|
|
get lineCount() {
|
|
return this._capturedTextDocument.lineCount;
|
|
}
|
|
offsetAt(position) {
|
|
return this._capturedTextDocument.offsetAt(position);
|
|
}
|
|
positionAt(offset) {
|
|
const position = this._capturedTextDocument.positionAt(offset);
|
|
return new vscode_1.Position(position.line, position.character);
|
|
}
|
|
getText(range) {
|
|
return this._capturedTextDocument.getText(range);
|
|
}
|
|
lineAt(lineOrPosition) {
|
|
const line = typeof lineOrPosition === "number" ? lineOrPosition : this.validatePosition(lineOrPosition).line;
|
|
if (line < 0 || line >= this.lineCount) {
|
|
throw new RangeError(`Illegal value for line: ${line}`);
|
|
}
|
|
const lineRange = this._capturedTextDocument.getLineRange(line);
|
|
const text = this._capturedTextDocument.getText(lineRange);
|
|
const firstNonWhitespaceCharacterIndex = text.search(/\S/);
|
|
const range = new vscode_1.Range(lineRange.start.line, lineRange.start.character, lineRange.end.line, lineRange.end.character);
|
|
const rangeIncludingLineBreak = line + 1 < this.lineCount ? new vscode_1.Range(range.start.line, range.start.character, line + 1, 0) : range;
|
|
return {
|
|
lineNumber: line,
|
|
text,
|
|
range,
|
|
rangeIncludingLineBreak,
|
|
firstNonWhitespaceCharacterIndex: firstNonWhitespaceCharacterIndex === -1 ? text.length : firstNonWhitespaceCharacterIndex,
|
|
isEmptyOrWhitespace: firstNonWhitespaceCharacterIndex === -1
|
|
};
|
|
}
|
|
getWordRangeAtPosition(position, regex) {
|
|
const lineNumber = this.validatePosition(position).line;
|
|
const lineText = this.lineAt(lineNumber).text;
|
|
const wordRegex = TextDocumentSnapshot.getWordRegExp(regex);
|
|
let match;
|
|
wordRegex.lastIndex = 0;
|
|
while ((match = wordRegex.exec(lineText)) !== null) {
|
|
if (match.index <= position.character && wordRegex.lastIndex >= position.character) {
|
|
return new vscode_1.Range(lineNumber, match.index, lineNumber, wordRegex.lastIndex);
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
validateRange(range) {
|
|
const start = this.validatePosition(range.start);
|
|
const end = this.validatePosition(range.end);
|
|
if (start === range.start && end === range.end) {
|
|
return range;
|
|
}
|
|
return new vscode_1.Range(start.line, start.character, end.line, end.character);
|
|
}
|
|
validatePosition(position) {
|
|
const line = Math.min(Math.max(position.line, 0), this.lineCount - 1);
|
|
const lineRange = this._capturedTextDocument.getLineRange(line);
|
|
const character = Math.min(Math.max(position.character, 0), lineRange.end.character);
|
|
if (line === position.line && character === position.character) {
|
|
return position;
|
|
}
|
|
return new vscode_1.Position(line, character);
|
|
}
|
|
static getWordRegExp(regex) {
|
|
const result = regex ?? DEFAULT_WORD_REGEXP;
|
|
if (result.flags.includes("g")) {
|
|
return result;
|
|
}
|
|
const flags = `${result.flags}g`;
|
|
return new RegExp(result.source, flags);
|
|
}
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/completion.js
|
|
var require_completion = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.CompletionItemFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
var UUID = __importStar(require_uuid());
|
|
var SupportedCompletionItemKinds = [
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Text,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Method,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Function,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Constructor,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Field,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Variable,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Class,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Interface,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Module,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Property,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Unit,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Value,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Enum,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Keyword,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Snippet,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Color,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.File,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Reference,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Folder,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.EnumMember,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Constant,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Struct,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Event,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.Operator,
|
|
vscode_languageserver_protocol_1.CompletionItemKind.TypeParameter
|
|
];
|
|
|
|
class CompletionItemFeature extends features_1.TextDocumentLanguageFeature {
|
|
labelDetailsSupport;
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.CompletionRequest.type);
|
|
this.labelDetailsSupport = new Map;
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const completion = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "completion");
|
|
completion.dynamicRegistration = true;
|
|
completion.contextSupport = true;
|
|
completion.completionItem = {
|
|
snippetSupport: true,
|
|
commitCharactersSupport: true,
|
|
documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText],
|
|
deprecatedSupport: true,
|
|
preselectSupport: true,
|
|
tagSupport: { valueSet: [vscode_languageserver_protocol_1.CompletionItemTag.Deprecated] },
|
|
insertReplaceSupport: true,
|
|
resolveSupport: {
|
|
properties: ["documentation", "detail", "additionalTextEdits"]
|
|
},
|
|
insertTextModeSupport: { valueSet: [vscode_languageserver_protocol_1.InsertTextMode.asIs, vscode_languageserver_protocol_1.InsertTextMode.adjustIndentation] },
|
|
labelDetailsSupport: true
|
|
};
|
|
completion.insertTextMode = vscode_languageserver_protocol_1.InsertTextMode.adjustIndentation;
|
|
completion.completionItemKind = { valueSet: SupportedCompletionItemKinds };
|
|
completion.completionList = {
|
|
itemDefaults: [
|
|
"commitCharacters",
|
|
"editRange",
|
|
"insertTextFormat",
|
|
"insertTextMode",
|
|
"data"
|
|
],
|
|
applyKindSupport: true
|
|
};
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.completionProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({
|
|
id: UUID.generateUuid(),
|
|
registerOptions: options
|
|
});
|
|
}
|
|
registerLanguageProvider(options, id) {
|
|
this.labelDetailsSupport.set(id, !!options.completionItem?.labelDetailsSupport);
|
|
const triggerCharacters = options.triggerCharacters ?? [];
|
|
const defaultCommitCharacters = options.allCommitCharacters;
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideCompletionItems: (document, position, token, context) => {
|
|
const client = this._client;
|
|
const middleware = this._client.middleware;
|
|
const provideCompletionItems = (document2, position2, context2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.CompletionRequest.type, client.code2ProtocolConverter.asCompletionParams(document2, position2, context2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asCompletionResult(result, defaultCommitCharacters, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.CompletionRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
return middleware.provideCompletionItem ? middleware.provideCompletionItem(document, position, context, token, provideCompletionItems) : provideCompletionItems(document, position, context, token);
|
|
},
|
|
resolveCompletionItem: options.resolveProvider ? (item, token) => {
|
|
const client = this._client;
|
|
const middleware = this._client.middleware;
|
|
const resolveCompletionItem = (item2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, client.code2ProtocolConverter.asCompletionItem(item2, !!this.labelDetailsSupport.get(id)), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asCompletionItem(result);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, token2, error, item2);
|
|
});
|
|
};
|
|
return middleware.resolveCompletionItem ? middleware.resolveCompletionItem(item, token, resolveCompletionItem) : resolveCompletionItem(item, token);
|
|
} : undefined
|
|
};
|
|
return [vscode_1.languages.registerCompletionItemProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider, ...triggerCharacters), provider];
|
|
}
|
|
}
|
|
exports2.CompletionItemFeature = CompletionItemFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/hover.js
|
|
var require_hover = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.HoverFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
var UUID = __importStar(require_uuid());
|
|
|
|
class HoverFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.HoverRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const hoverCapability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "hover");
|
|
hoverCapability.dynamicRegistration = true;
|
|
hoverCapability.contentFormat = [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText];
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.hoverProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({
|
|
id: UUID.generateUuid(),
|
|
registerOptions: options
|
|
});
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideHover: (document, position, token) => {
|
|
const client = this._client;
|
|
const provideHover = (document2, position2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.HoverRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asHover(result);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.HoverRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideHover ? middleware.provideHover(document, position, token, provideHover) : provideHover(document, position, token);
|
|
}
|
|
};
|
|
return [this.registerProvider(selector, provider), provider];
|
|
}
|
|
registerProvider(selector, provider) {
|
|
return vscode_1.languages.registerHoverProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);
|
|
}
|
|
}
|
|
exports2.HoverFeature = HoverFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/definition.js
|
|
var require_definition = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DefinitionFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
var UUID = __importStar(require_uuid());
|
|
|
|
class DefinitionFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.DefinitionRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const definitionSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "definition");
|
|
definitionSupport.dynamicRegistration = true;
|
|
definitionSupport.linkSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.definitionProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({ id: UUID.generateUuid(), registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideDefinition: (document, position, token) => {
|
|
const client = this._client;
|
|
const provideDefinition = (document2, position2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asDefinitionResult(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideDefinition ? middleware.provideDefinition(document, position, token, provideDefinition) : provideDefinition(document, position, token);
|
|
}
|
|
};
|
|
return [this.registerProvider(selector, provider), provider];
|
|
}
|
|
registerProvider(selector, provider) {
|
|
return vscode_1.languages.registerDefinitionProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);
|
|
}
|
|
}
|
|
exports2.DefinitionFeature = DefinitionFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/signatureHelp.js
|
|
var require_signatureHelp = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.SignatureHelpFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
var UUID = __importStar(require_uuid());
|
|
|
|
class SignatureHelpFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.SignatureHelpRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const config = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "signatureHelp");
|
|
config.dynamicRegistration = true;
|
|
config.signatureInformation = { documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText] };
|
|
config.signatureInformation.parameterInformation = { labelOffsetSupport: true };
|
|
config.signatureInformation.activeParameterSupport = true;
|
|
config.signatureInformation.noActiveParameterSupport = true;
|
|
config.contextSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.signatureHelpProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({
|
|
id: UUID.generateUuid(),
|
|
registerOptions: options
|
|
});
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const provider = {
|
|
provideSignatureHelp: (document, position, token, context) => {
|
|
const client = this._client;
|
|
const providerSignatureHelp = (document2, position2, context2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, client.code2ProtocolConverter.asSignatureHelpParams(document2, position2, context2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asSignatureHelp(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideSignatureHelp ? middleware.provideSignatureHelp(document, position, context, token, providerSignatureHelp) : providerSignatureHelp(document, position, context, token);
|
|
}
|
|
};
|
|
return [this.registerProvider(options, provider), provider];
|
|
}
|
|
registerProvider(options, provider) {
|
|
const selector = this._client.protocol2CodeConverter.asDocumentSelector(options.documentSelector);
|
|
if (options.retriggerCharacters === undefined) {
|
|
const triggerCharacters = options.triggerCharacters || [];
|
|
return vscode_1.languages.registerSignatureHelpProvider(selector, provider, ...triggerCharacters);
|
|
} else {
|
|
const metaData = {
|
|
triggerCharacters: options.triggerCharacters || [],
|
|
retriggerCharacters: options.retriggerCharacters || []
|
|
};
|
|
return vscode_1.languages.registerSignatureHelpProvider(selector, provider, metaData);
|
|
}
|
|
}
|
|
}
|
|
exports2.SignatureHelpFeature = SignatureHelpFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/documentHighlight.js
|
|
var require_documentHighlight = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DocumentHighlightFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
var UUID = __importStar(require_uuid());
|
|
|
|
class DocumentHighlightFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.DocumentHighlightRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "documentHighlight").dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.documentHighlightProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({ id: UUID.generateUuid(), registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideDocumentHighlights: (document, position, token) => {
|
|
const client = this._client;
|
|
const _provideDocumentHighlights = (document2, position2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asDocumentHighlights(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideDocumentHighlights ? middleware.provideDocumentHighlights(document, position, token, _provideDocumentHighlights) : _provideDocumentHighlights(document, position, token);
|
|
}
|
|
};
|
|
return [vscode_1.languages.registerDocumentHighlightProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];
|
|
}
|
|
}
|
|
exports2.DocumentHighlightFeature = DocumentHighlightFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/documentSymbol.js
|
|
var require_documentSymbol = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DocumentSymbolFeature = exports2.SupportedSymbolTags = exports2.SupportedSymbolKinds = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
var UUID = __importStar(require_uuid());
|
|
exports2.SupportedSymbolKinds = [
|
|
vscode_languageserver_protocol_1.SymbolKind.File,
|
|
vscode_languageserver_protocol_1.SymbolKind.Module,
|
|
vscode_languageserver_protocol_1.SymbolKind.Namespace,
|
|
vscode_languageserver_protocol_1.SymbolKind.Package,
|
|
vscode_languageserver_protocol_1.SymbolKind.Class,
|
|
vscode_languageserver_protocol_1.SymbolKind.Method,
|
|
vscode_languageserver_protocol_1.SymbolKind.Property,
|
|
vscode_languageserver_protocol_1.SymbolKind.Field,
|
|
vscode_languageserver_protocol_1.SymbolKind.Constructor,
|
|
vscode_languageserver_protocol_1.SymbolKind.Enum,
|
|
vscode_languageserver_protocol_1.SymbolKind.Interface,
|
|
vscode_languageserver_protocol_1.SymbolKind.Function,
|
|
vscode_languageserver_protocol_1.SymbolKind.Variable,
|
|
vscode_languageserver_protocol_1.SymbolKind.Constant,
|
|
vscode_languageserver_protocol_1.SymbolKind.String,
|
|
vscode_languageserver_protocol_1.SymbolKind.Number,
|
|
vscode_languageserver_protocol_1.SymbolKind.Boolean,
|
|
vscode_languageserver_protocol_1.SymbolKind.Array,
|
|
vscode_languageserver_protocol_1.SymbolKind.Object,
|
|
vscode_languageserver_protocol_1.SymbolKind.Key,
|
|
vscode_languageserver_protocol_1.SymbolKind.Null,
|
|
vscode_languageserver_protocol_1.SymbolKind.EnumMember,
|
|
vscode_languageserver_protocol_1.SymbolKind.Struct,
|
|
vscode_languageserver_protocol_1.SymbolKind.Event,
|
|
vscode_languageserver_protocol_1.SymbolKind.Operator,
|
|
vscode_languageserver_protocol_1.SymbolKind.TypeParameter
|
|
];
|
|
exports2.SupportedSymbolTags = [
|
|
vscode_languageserver_protocol_1.SymbolTag.Deprecated
|
|
];
|
|
|
|
class DocumentSymbolFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.DocumentSymbolRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const symbolCapabilities = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "documentSymbol");
|
|
symbolCapabilities.dynamicRegistration = true;
|
|
symbolCapabilities.symbolKind = {
|
|
valueSet: exports2.SupportedSymbolKinds
|
|
};
|
|
symbolCapabilities.hierarchicalDocumentSymbolSupport = true;
|
|
symbolCapabilities.tagSupport = {
|
|
valueSet: exports2.SupportedSymbolTags
|
|
};
|
|
symbolCapabilities.labelSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.documentSymbolProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({ id: UUID.generateUuid(), registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideDocumentSymbols: (document, token) => {
|
|
const client = this._client;
|
|
const _provideDocumentSymbols = async (document2, token2) => {
|
|
try {
|
|
const data = await client.sendRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, client.code2ProtocolConverter.asDocumentSymbolParams(document2), token2);
|
|
if (token2.isCancellationRequested || data === undefined || data === null) {
|
|
return null;
|
|
}
|
|
if (data.length === 0) {
|
|
return [];
|
|
} else {
|
|
const first = data[0];
|
|
if (vscode_languageserver_protocol_1.DocumentSymbol.is(first)) {
|
|
return await client.protocol2CodeConverter.asDocumentSymbols(data, token2);
|
|
} else {
|
|
return await client.protocol2CodeConverter.asSymbolInformations(data, token2);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, token2, error, null);
|
|
}
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideDocumentSymbols ? middleware.provideDocumentSymbols(document, token, _provideDocumentSymbols) : _provideDocumentSymbols(document, token);
|
|
}
|
|
};
|
|
const metaData = options.label !== undefined ? { label: options.label } : undefined;
|
|
return [vscode_1.languages.registerDocumentSymbolProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider, metaData), provider];
|
|
}
|
|
}
|
|
exports2.DocumentSymbolFeature = DocumentSymbolFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/workspaceSymbol.js
|
|
var require_workspaceSymbol = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.WorkspaceSymbolFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
var documentSymbol_1 = require_documentSymbol();
|
|
var UUID = __importStar(require_uuid());
|
|
|
|
class WorkspaceSymbolFeature extends features_1.WorkspaceFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const symbolCapabilities = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "symbol");
|
|
symbolCapabilities.dynamicRegistration = true;
|
|
symbolCapabilities.symbolKind = {
|
|
valueSet: documentSymbol_1.SupportedSymbolKinds
|
|
};
|
|
symbolCapabilities.tagSupport = {
|
|
valueSet: documentSymbol_1.SupportedSymbolTags
|
|
};
|
|
symbolCapabilities.resolveSupport = { properties: ["location.range"] };
|
|
}
|
|
initialize(capabilities) {
|
|
if (!capabilities.workspaceSymbolProvider) {
|
|
return;
|
|
}
|
|
this.register({
|
|
id: UUID.generateUuid(),
|
|
registerOptions: capabilities.workspaceSymbolProvider === true ? { workDoneProgress: false } : capabilities.workspaceSymbolProvider
|
|
});
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const provider = {
|
|
provideWorkspaceSymbols: (query, token) => {
|
|
const client = this._client;
|
|
const provideWorkspaceSymbols = (query2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, { query: query2 }, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asSymbolInformations(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideWorkspaceSymbols ? middleware.provideWorkspaceSymbols(query, token, provideWorkspaceSymbols) : provideWorkspaceSymbols(query, token);
|
|
},
|
|
resolveWorkspaceSymbol: options.resolveProvider === true ? (item, token) => {
|
|
const client = this._client;
|
|
const resolveWorkspaceSymbol = (item2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.WorkspaceSymbolResolveRequest.type, client.code2ProtocolConverter.asWorkspaceSymbol(item2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asSymbolInformation(result);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.WorkspaceSymbolResolveRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.resolveWorkspaceSymbol ? middleware.resolveWorkspaceSymbol(item, token, resolveWorkspaceSymbol) : resolveWorkspaceSymbol(item, token);
|
|
} : undefined
|
|
};
|
|
return [vscode_1.languages.registerWorkspaceSymbolProvider(provider), provider];
|
|
}
|
|
}
|
|
exports2.WorkspaceSymbolFeature = WorkspaceSymbolFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/reference.js
|
|
var require_reference = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ReferencesFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
var UUID = __importStar(require_uuid());
|
|
|
|
class ReferencesFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.ReferencesRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "references").dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.referencesProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({ id: UUID.generateUuid(), registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideReferences: (document, position, options2, token) => {
|
|
const client = this._client;
|
|
const _providerReferences = (document2, position2, options3, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, client.code2ProtocolConverter.asReferenceParams(document2, position2, options3), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asReferences(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideReferences ? middleware.provideReferences(document, position, options2, token, _providerReferences) : _providerReferences(document, position, options2, token);
|
|
}
|
|
};
|
|
return [this.registerProvider(selector, provider), provider];
|
|
}
|
|
registerProvider(selector, provider) {
|
|
return vscode_1.languages.registerReferenceProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);
|
|
}
|
|
}
|
|
exports2.ReferencesFeature = ReferencesFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/typeDefinition.js
|
|
var require_typeDefinition = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.TypeDefinitionFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
|
|
class TypeDefinitionFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.TypeDefinitionRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "typeDefinition").dynamicRegistration = true;
|
|
const typeDefinitionSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "typeDefinition");
|
|
typeDefinitionSupport.dynamicRegistration = true;
|
|
typeDefinitionSupport.linkSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const [id, options] = this.getRegistration(documentSelector, capabilities.typeDefinitionProvider);
|
|
if (!id || !options) {
|
|
return;
|
|
}
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideTypeDefinition: (document, position, token) => {
|
|
const client = this._client;
|
|
const provideTypeDefinition = (document2, position2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asDefinitionResult(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideTypeDefinition ? middleware.provideTypeDefinition(document, position, token, provideTypeDefinition) : provideTypeDefinition(document, position, token);
|
|
}
|
|
};
|
|
return [this.registerProvider(selector, provider), provider];
|
|
}
|
|
registerProvider(selector, provider) {
|
|
return vscode_1.languages.registerTypeDefinitionProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);
|
|
}
|
|
}
|
|
exports2.TypeDefinitionFeature = TypeDefinitionFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/implementation.js
|
|
var require_implementation = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ImplementationFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
|
|
class ImplementationFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.ImplementationRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const implementationSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "implementation");
|
|
implementationSupport.dynamicRegistration = true;
|
|
implementationSupport.linkSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const [id, options] = this.getRegistration(documentSelector, capabilities.implementationProvider);
|
|
if (!id || !options) {
|
|
return;
|
|
}
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideImplementation: (document, position, token) => {
|
|
const client = this._client;
|
|
const provideImplementation = (document2, position2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asDefinitionResult(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideImplementation ? middleware.provideImplementation(document, position, token, provideImplementation) : provideImplementation(document, position, token);
|
|
}
|
|
};
|
|
return [this.registerProvider(selector, provider), provider];
|
|
}
|
|
registerProvider(selector, provider) {
|
|
return vscode_1.languages.registerImplementationProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);
|
|
}
|
|
}
|
|
exports2.ImplementationFeature = ImplementationFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/colorProvider.js
|
|
var require_colorProvider = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ColorProviderFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
|
|
class ColorProviderFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.DocumentColorRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "colorProvider").dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const [id, options] = this.getRegistration(documentSelector, capabilities.colorProvider);
|
|
if (!id || !options) {
|
|
return;
|
|
}
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideColorPresentations: (color, context, token) => {
|
|
const client = this._client;
|
|
const provideColorPresentations = (color2, context2, token2) => {
|
|
const requestParams = {
|
|
color: color2,
|
|
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(context2.document),
|
|
range: client.code2ProtocolConverter.asRange(context2.range)
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, requestParams, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return this._client.protocol2CodeConverter.asColorPresentations(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideColorPresentations ? middleware.provideColorPresentations(color, context, token, provideColorPresentations) : provideColorPresentations(color, context, token);
|
|
},
|
|
provideDocumentColors: (document, token) => {
|
|
const client = this._client;
|
|
const provideDocumentColors = (document2, token2) => {
|
|
const requestParams = {
|
|
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document2)
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, requestParams, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return this._client.protocol2CodeConverter.asColorInformations(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideDocumentColors ? middleware.provideDocumentColors(document, token, provideDocumentColors) : provideDocumentColors(document, token);
|
|
}
|
|
};
|
|
return [vscode_1.languages.registerColorProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];
|
|
}
|
|
}
|
|
exports2.ColorProviderFeature = ColorProviderFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/codeAction.js
|
|
var require_codeAction = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.CodeActionFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var UUID = __importStar(require_uuid());
|
|
var features_1 = require_features();
|
|
|
|
class CodeActionFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.CodeActionRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const cap = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "codeAction");
|
|
cap.dynamicRegistration = true;
|
|
cap.isPreferredSupport = true;
|
|
cap.disabledSupport = true;
|
|
cap.dataSupport = true;
|
|
cap.resolveSupport = {
|
|
properties: ["edit", "command"]
|
|
};
|
|
cap.codeActionLiteralSupport = {
|
|
codeActionKind: {
|
|
valueSet: [
|
|
vscode_languageserver_protocol_1.CodeActionKind.Empty,
|
|
vscode_languageserver_protocol_1.CodeActionKind.QuickFix,
|
|
vscode_languageserver_protocol_1.CodeActionKind.Refactor,
|
|
vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract,
|
|
vscode_languageserver_protocol_1.CodeActionKind.RefactorInline,
|
|
vscode_languageserver_protocol_1.CodeActionKind.RefactorMove,
|
|
vscode_languageserver_protocol_1.CodeActionKind.RefactorRewrite,
|
|
vscode_languageserver_protocol_1.CodeActionKind.Source,
|
|
vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports,
|
|
vscode_languageserver_protocol_1.CodeActionKind.Notebook
|
|
]
|
|
}
|
|
};
|
|
cap.honorsChangeAnnotations = true;
|
|
cap.documentationSupport = true;
|
|
cap.tagSupport = {
|
|
valueSet: [vscode_languageserver_protocol_1.CodeActionTag.LLMGenerated]
|
|
};
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.codeActionProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({ id: UUID.generateUuid(), registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideCodeActions: (document, range, context, token) => {
|
|
const client = this._client;
|
|
const _provideCodeActions = async (document2, range2, context2, token2) => {
|
|
const params = {
|
|
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document2),
|
|
range: client.code2ProtocolConverter.asRange(range2),
|
|
context: client.code2ProtocolConverter.asCodeActionContextSync(context2)
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, params, token2).then((values) => {
|
|
if (token2.isCancellationRequested || values === null || values === undefined) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asCodeActionResult(values, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideCodeActions ? middleware.provideCodeActions(document, range, context, token, _provideCodeActions) : _provideCodeActions(document, range, context, token);
|
|
},
|
|
resolveCodeAction: options.resolveProvider ? (item, token) => {
|
|
const client = this._client;
|
|
const middleware = this._client.middleware;
|
|
const resolveCodeAction = async (item2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.CodeActionResolveRequest.type, client.code2ProtocolConverter.asCodeActionSync(item2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return item2;
|
|
}
|
|
return client.protocol2CodeConverter.asCodeAction(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.CodeActionResolveRequest.type, token2, error, item2);
|
|
});
|
|
};
|
|
return middleware.resolveCodeAction ? middleware.resolveCodeAction(item, token, resolveCodeAction) : resolveCodeAction(item, token);
|
|
} : undefined
|
|
};
|
|
return [vscode_1.languages.registerCodeActionsProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider, this.getMetadata(options)), provider];
|
|
}
|
|
getMetadata(options) {
|
|
if (options.codeActionKinds === undefined && options.documentation === undefined) {
|
|
return;
|
|
}
|
|
return {
|
|
providedCodeActionKinds: this._client.protocol2CodeConverter.asCodeActionKinds(options.codeActionKinds),
|
|
documentation: this._client.protocol2CodeConverter.asCodeActionDocumentations(options.documentation)
|
|
};
|
|
}
|
|
}
|
|
exports2.CodeActionFeature = CodeActionFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/codeLens.js
|
|
var require_codeLens = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.CodeLensFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var UUID = __importStar(require_uuid());
|
|
var features_1 = require_features();
|
|
|
|
class CodeLensFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.CodeLensRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const clc = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "codeLens");
|
|
clc.dynamicRegistration = true;
|
|
clc.resolveSupport = { properties: ["command"] };
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "codeLens").refreshSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const client = this._client;
|
|
client.onRequest(vscode_languageserver_protocol_1.CodeLensRefreshRequest.type, async () => {
|
|
for (const provider of this.getAllProviders()) {
|
|
provider.onDidChangeCodeLensEmitter.fire();
|
|
}
|
|
});
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.codeLensProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({ id: UUID.generateUuid(), registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const eventEmitter = new vscode_1.EventEmitter;
|
|
const provider = {
|
|
onDidChangeCodeLenses: eventEmitter.event,
|
|
provideCodeLenses: (document, token) => {
|
|
const client = this._client;
|
|
const provideCodeLenses = (document2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, client.code2ProtocolConverter.asCodeLensParams(document2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asCodeLenses(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideCodeLenses ? middleware.provideCodeLenses(document, token, provideCodeLenses) : provideCodeLenses(document, token);
|
|
},
|
|
resolveCodeLens: options.resolveProvider ? (codeLens, token) => {
|
|
const client = this._client;
|
|
const resolveCodeLens = (codeLens2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, client.code2ProtocolConverter.asCodeLens(codeLens2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return codeLens2;
|
|
}
|
|
return client.protocol2CodeConverter.asCodeLens(result);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, token2, error, codeLens2);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.resolveCodeLens ? middleware.resolveCodeLens(codeLens, token, resolveCodeLens) : resolveCodeLens(codeLens, token);
|
|
} : undefined
|
|
};
|
|
return [vscode_1.languages.registerCodeLensProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), { provider, onDidChangeCodeLensEmitter: eventEmitter }];
|
|
}
|
|
}
|
|
exports2.CodeLensFeature = CodeLensFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/formatting.js
|
|
var require_formatting = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DocumentOnTypeFormattingFeature = exports2.DocumentRangeFormattingFeature = exports2.DocumentFormattingFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var UUID = __importStar(require_uuid());
|
|
var features_1 = require_features();
|
|
var FileFormattingOptions;
|
|
(function(FileFormattingOptions2) {
|
|
function fromConfiguration(document) {
|
|
const filesConfig = vscode_1.workspace.getConfiguration("files", document);
|
|
return {
|
|
trimTrailingWhitespace: filesConfig.get("trimTrailingWhitespace"),
|
|
trimFinalNewlines: filesConfig.get("trimFinalNewlines"),
|
|
insertFinalNewline: filesConfig.get("insertFinalNewline")
|
|
};
|
|
}
|
|
FileFormattingOptions2.fromConfiguration = fromConfiguration;
|
|
})(FileFormattingOptions || (FileFormattingOptions = {}));
|
|
|
|
class DocumentFormattingFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.DocumentFormattingRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "formatting").dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.documentFormattingProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({ id: UUID.generateUuid(), registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideDocumentFormattingEdits: (document, options2, token) => {
|
|
const client = this._client;
|
|
const provideDocumentFormattingEdits = (document2, options3, token2) => {
|
|
const params = {
|
|
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document2),
|
|
options: client.code2ProtocolConverter.asFormattingOptions(options3, FileFormattingOptions.fromConfiguration(document2))
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asTextEdits(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideDocumentFormattingEdits ? middleware.provideDocumentFormattingEdits(document, options2, token, provideDocumentFormattingEdits) : provideDocumentFormattingEdits(document, options2, token);
|
|
}
|
|
};
|
|
return [vscode_1.languages.registerDocumentFormattingEditProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];
|
|
}
|
|
}
|
|
exports2.DocumentFormattingFeature = DocumentFormattingFeature;
|
|
|
|
class DocumentRangeFormattingFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "rangeFormatting");
|
|
capability.dynamicRegistration = true;
|
|
capability.rangesSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.documentRangeFormattingProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({ id: UUID.generateUuid(), registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideDocumentRangeFormattingEdits: (document, range, options2, token) => {
|
|
const client = this._client;
|
|
const provideDocumentRangeFormattingEdits = (document2, range2, options3, token2) => {
|
|
const params = {
|
|
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document2),
|
|
range: client.code2ProtocolConverter.asRange(range2),
|
|
options: client.code2ProtocolConverter.asFormattingOptions(options3, FileFormattingOptions.fromConfiguration(document2))
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asTextEdits(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideDocumentRangeFormattingEdits ? middleware.provideDocumentRangeFormattingEdits(document, range, options2, token, provideDocumentRangeFormattingEdits) : provideDocumentRangeFormattingEdits(document, range, options2, token);
|
|
}
|
|
};
|
|
if (options.rangesSupport) {
|
|
provider.provideDocumentRangesFormattingEdits = (document, ranges, options2, token) => {
|
|
const client = this._client;
|
|
const provideDocumentRangesFormattingEdits = (document2, ranges2, options3, token2) => {
|
|
const params = {
|
|
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document2),
|
|
ranges: client.code2ProtocolConverter.asRanges(ranges2),
|
|
options: client.code2ProtocolConverter.asFormattingOptions(options3, FileFormattingOptions.fromConfiguration(document2))
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.DocumentRangesFormattingRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asTextEdits(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentRangesFormattingRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideDocumentRangesFormattingEdits ? middleware.provideDocumentRangesFormattingEdits(document, ranges, options2, token, provideDocumentRangesFormattingEdits) : provideDocumentRangesFormattingEdits(document, ranges, options2, token);
|
|
};
|
|
}
|
|
return [vscode_1.languages.registerDocumentRangeFormattingEditProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];
|
|
}
|
|
}
|
|
exports2.DocumentRangeFormattingFeature = DocumentRangeFormattingFeature;
|
|
|
|
class DocumentOnTypeFormattingFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "onTypeFormatting").dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.documentOnTypeFormattingProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({ id: UUID.generateUuid(), registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideOnTypeFormattingEdits: (document, position, ch, options2, token) => {
|
|
const client = this._client;
|
|
const provideOnTypeFormattingEdits = (document2, position2, ch2, options3, token2) => {
|
|
const params = {
|
|
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document2),
|
|
position: client.code2ProtocolConverter.asPosition(position2),
|
|
ch: ch2,
|
|
options: client.code2ProtocolConverter.asFormattingOptions(options3, FileFormattingOptions.fromConfiguration(document2))
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asTextEdits(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideOnTypeFormattingEdits ? middleware.provideOnTypeFormattingEdits(document, position, ch, options2, token, provideOnTypeFormattingEdits) : provideOnTypeFormattingEdits(document, position, ch, options2, token);
|
|
}
|
|
};
|
|
const moreTriggerCharacter = options.moreTriggerCharacter || [];
|
|
return [vscode_1.languages.registerOnTypeFormattingEditProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider, options.firstTriggerCharacter, ...moreTriggerCharacter), provider];
|
|
}
|
|
}
|
|
exports2.DocumentOnTypeFormattingFeature = DocumentOnTypeFormattingFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/rename.js
|
|
var require_rename = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.RenameFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var UUID = __importStar(require_uuid());
|
|
var Is = __importStar(require_is());
|
|
var features_1 = require_features();
|
|
|
|
class RenameFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.RenameRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const rename = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "rename");
|
|
rename.dynamicRegistration = true;
|
|
rename.prepareSupport = true;
|
|
rename.prepareSupportDefaultBehavior = vscode_languageserver_protocol_1.PrepareSupportDefaultBehavior.Identifier;
|
|
rename.honorsChangeAnnotations = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.renameProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
if (Is.boolean(capabilities.renameProvider)) {
|
|
options.prepareProvider = false;
|
|
}
|
|
this.register({ id: UUID.generateUuid(), registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideRenameEdits: (document, position, newName, token) => {
|
|
const client = this._client;
|
|
const provideRenameEdits = async (document2, position2, newName2, token2) => {
|
|
const params = {
|
|
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document2),
|
|
position: client.code2ProtocolConverter.asPosition(position2),
|
|
newName: newName2
|
|
};
|
|
let result = null;
|
|
try {
|
|
result = await client.sendRequest(vscode_languageserver_protocol_1.RenameRequest.type, params, token2);
|
|
} catch (error) {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.RenameRequest.type, token2, error, null, false);
|
|
}
|
|
if (token2.isCancellationRequested || result === null) {
|
|
return null;
|
|
}
|
|
const converted = await client.protocol2CodeConverter.asWorkspaceEdit(result, token2);
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
if (!client.validateWorkspaceEdit(result)) {
|
|
throw new Error(`The rename edit returned from the server is not valid anymore and cannot be applied.`);
|
|
}
|
|
return converted;
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideRenameEdits ? middleware.provideRenameEdits(document, position, newName, token, provideRenameEdits) : provideRenameEdits(document, position, newName, token);
|
|
},
|
|
prepareRename: options.prepareProvider ? (document, position, token) => {
|
|
const client = this._client;
|
|
const prepareRename = (document2, position2, token2) => {
|
|
const params = {
|
|
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document2),
|
|
position: client.code2ProtocolConverter.asPosition(position2)
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
if (vscode_languageserver_protocol_1.Range.is(result)) {
|
|
return client.protocol2CodeConverter.asRange(result);
|
|
} else if (this.isDefaultBehavior(result)) {
|
|
return result.defaultBehavior === true ? null : Promise.reject(new Error(`The element can't be renamed.`));
|
|
} else if (result && vscode_languageserver_protocol_1.Range.is(result.range)) {
|
|
return {
|
|
range: client.protocol2CodeConverter.asRange(result.range),
|
|
placeholder: result.placeholder
|
|
};
|
|
}
|
|
return Promise.reject(new Error(`The element can't be renamed.`));
|
|
}, (error) => {
|
|
if (typeof error.message === "string") {
|
|
throw new Error(error.message);
|
|
} else {
|
|
throw new Error(`The element can't be renamed.`);
|
|
}
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.prepareRename ? middleware.prepareRename(document, position, token, prepareRename) : prepareRename(document, position, token);
|
|
} : undefined
|
|
};
|
|
return [this.registerProvider(selector, provider), provider];
|
|
}
|
|
registerProvider(selector, provider) {
|
|
return vscode_1.languages.registerRenameProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);
|
|
}
|
|
isDefaultBehavior(value) {
|
|
const candidate = value;
|
|
return candidate && Is.boolean(candidate.defaultBehavior);
|
|
}
|
|
}
|
|
exports2.RenameFeature = RenameFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/documentLink.js
|
|
var require_documentLink = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DocumentLinkFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
var UUID = __importStar(require_uuid());
|
|
|
|
class DocumentLinkFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.DocumentLinkRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const documentLinkCapabilities = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "documentLink");
|
|
documentLinkCapabilities.dynamicRegistration = true;
|
|
documentLinkCapabilities.tooltipSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.documentLinkProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({ id: UUID.generateUuid(), registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideDocumentLinks: (document, token) => {
|
|
const client = this._client;
|
|
const provideDocumentLinks = (document2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, client.code2ProtocolConverter.asDocumentLinkParams(document2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asDocumentLinks(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideDocumentLinks ? middleware.provideDocumentLinks(document, token, provideDocumentLinks) : provideDocumentLinks(document, token);
|
|
},
|
|
resolveDocumentLink: options.resolveProvider ? (link, token) => {
|
|
const client = this._client;
|
|
const resolveDocumentLink = (link2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, client.code2ProtocolConverter.asDocumentLink(link2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return link2;
|
|
}
|
|
return client.protocol2CodeConverter.asDocumentLink(result);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, token2, error, link2);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.resolveDocumentLink ? middleware.resolveDocumentLink(link, token, resolveDocumentLink) : resolveDocumentLink(link, token);
|
|
} : undefined
|
|
};
|
|
return [vscode_1.languages.registerDocumentLinkProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];
|
|
}
|
|
}
|
|
exports2.DocumentLinkFeature = DocumentLinkFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/executeCommand.js
|
|
var require_executeCommand = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ExecuteCommandFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var UUID = __importStar(require_uuid());
|
|
var features_1 = require_features();
|
|
|
|
class ExecuteCommandFeature {
|
|
_client;
|
|
_commands;
|
|
constructor(client) {
|
|
this._client = client;
|
|
this._commands = new Map;
|
|
}
|
|
getState() {
|
|
return { kind: "workspace", id: this.registrationType.method, registrations: this._commands.size > 0 };
|
|
}
|
|
get registrationType() {
|
|
return vscode_languageserver_protocol_1.ExecuteCommandRequest.type;
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "executeCommand").dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities) {
|
|
if (!capabilities.executeCommandProvider) {
|
|
return;
|
|
}
|
|
this.register({
|
|
id: UUID.generateUuid(),
|
|
registerOptions: Object.assign({}, capabilities.executeCommandProvider)
|
|
});
|
|
}
|
|
register(data) {
|
|
const client = this._client;
|
|
const middleware = client.middleware;
|
|
const executeCommand = (command, args) => {
|
|
const params = {
|
|
command,
|
|
arguments: args
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, params).then(undefined, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, undefined, error, undefined);
|
|
});
|
|
};
|
|
if (data.registerOptions.commands) {
|
|
const disposables = [];
|
|
for (const command of data.registerOptions.commands) {
|
|
disposables.push(vscode_1.commands.registerCommand(command, (...args) => {
|
|
return middleware.executeCommand ? middleware.executeCommand(command, args, executeCommand) : executeCommand(command, args);
|
|
}));
|
|
}
|
|
this._commands.set(data.id, disposables);
|
|
}
|
|
}
|
|
unregister(id) {
|
|
const disposables = this._commands.get(id);
|
|
if (disposables) {
|
|
this._commands.delete(id);
|
|
disposables.forEach((disposable) => disposable.dispose());
|
|
}
|
|
}
|
|
clear() {
|
|
this._commands.forEach((value) => {
|
|
value.forEach((disposable) => disposable.dispose());
|
|
});
|
|
this._commands.clear();
|
|
}
|
|
}
|
|
exports2.ExecuteCommandFeature = ExecuteCommandFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/foldingRange.js
|
|
var require_foldingRange = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.FoldingRangeFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
|
|
class FoldingRangeFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.FoldingRangeRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "foldingRange");
|
|
capability.dynamicRegistration = true;
|
|
capability.rangeLimit = 5000;
|
|
capability.lineFoldingOnly = true;
|
|
capability.foldingRangeKind = { valueSet: [vscode_languageserver_protocol_1.FoldingRangeKind.Comment, vscode_languageserver_protocol_1.FoldingRangeKind.Imports, vscode_languageserver_protocol_1.FoldingRangeKind.Region] };
|
|
capability.foldingRange = { collapsedText: false };
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "foldingRange").refreshSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
this._client.onRequest(vscode_languageserver_protocol_1.FoldingRangeRefreshRequest.type, async () => {
|
|
for (const provider of this.getAllProviders()) {
|
|
provider.onDidChangeFoldingRange.fire();
|
|
}
|
|
});
|
|
const [id, options] = this.getRegistration(documentSelector, capabilities.foldingRangeProvider);
|
|
if (!id || !options) {
|
|
return;
|
|
}
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const eventEmitter = new vscode_1.EventEmitter;
|
|
const provider = {
|
|
onDidChangeFoldingRanges: eventEmitter.event,
|
|
provideFoldingRanges: (document, context, token) => {
|
|
const client = this._client;
|
|
const provideFoldingRanges = (document2, _, token2) => {
|
|
const requestParams = {
|
|
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document2)
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, requestParams, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asFoldingRanges(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideFoldingRanges ? middleware.provideFoldingRanges(document, context, token, provideFoldingRanges) : provideFoldingRanges(document, context, token);
|
|
}
|
|
};
|
|
return [vscode_1.languages.registerFoldingRangeProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), { provider, onDidChangeFoldingRange: eventEmitter }];
|
|
}
|
|
}
|
|
exports2.FoldingRangeFeature = FoldingRangeFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/declaration.js
|
|
var require_declaration = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DeclarationFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
|
|
class DeclarationFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.DeclarationRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const declarationSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "declaration");
|
|
declarationSupport.dynamicRegistration = true;
|
|
declarationSupport.linkSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const [id, options] = this.getRegistration(documentSelector, capabilities.declarationProvider);
|
|
if (!id || !options) {
|
|
return;
|
|
}
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideDeclaration: (document, position, token) => {
|
|
const client = this._client;
|
|
const provideDeclaration = (document2, position2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asDeclarationResult(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideDeclaration ? middleware.provideDeclaration(document, position, token, provideDeclaration) : provideDeclaration(document, position, token);
|
|
}
|
|
};
|
|
return [this.registerProvider(selector, provider), provider];
|
|
}
|
|
registerProvider(selector, provider) {
|
|
return vscode_1.languages.registerDeclarationProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);
|
|
}
|
|
}
|
|
exports2.DeclarationFeature = DeclarationFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/selectionRange.js
|
|
var require_selectionRange = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.SelectionRangeFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
|
|
class SelectionRangeFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.SelectionRangeRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "selectionRange");
|
|
capability.dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const [id, options] = this.getRegistration(documentSelector, capabilities.selectionRangeProvider);
|
|
if (!id || !options) {
|
|
return;
|
|
}
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideSelectionRanges: (document, positions, token) => {
|
|
const client = this._client;
|
|
const provideSelectionRanges = async (document2, positions2, token2) => {
|
|
const requestParams = {
|
|
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document2),
|
|
positions: client.code2ProtocolConverter.asPositionsSync(positions2, token2)
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, requestParams, token2).then((ranges) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asSelectionRanges(ranges, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideSelectionRanges ? middleware.provideSelectionRanges(document, positions, token, provideSelectionRanges) : provideSelectionRanges(document, positions, token);
|
|
}
|
|
};
|
|
return [this.registerProvider(selector, provider), provider];
|
|
}
|
|
registerProvider(selector, provider) {
|
|
return vscode_1.languages.registerSelectionRangeProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);
|
|
}
|
|
}
|
|
exports2.SelectionRangeFeature = SelectionRangeFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/callHierarchy.js
|
|
var require_callHierarchy = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.CallHierarchyFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
|
|
class CallHierarchyProvider {
|
|
client;
|
|
middleware;
|
|
constructor(client) {
|
|
this.client = client;
|
|
this.middleware = client.middleware;
|
|
}
|
|
prepareCallHierarchy(document, position, token) {
|
|
const client = this.client;
|
|
const middleware = this.middleware;
|
|
const prepareCallHierarchy = (document2, position2, token2) => {
|
|
const params = client.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2);
|
|
return client.sendRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asCallHierarchyItems(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
return middleware.prepareCallHierarchy ? middleware.prepareCallHierarchy(document, position, token, prepareCallHierarchy) : prepareCallHierarchy(document, position, token);
|
|
}
|
|
provideCallHierarchyIncomingCalls(item, token) {
|
|
const client = this.client;
|
|
const middleware = this.middleware;
|
|
const provideCallHierarchyIncomingCalls = (item2, token2) => {
|
|
const params = {
|
|
item: client.code2ProtocolConverter.asCallHierarchyItem(item2)
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asCallHierarchyIncomingCalls(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
return middleware.provideCallHierarchyIncomingCalls ? middleware.provideCallHierarchyIncomingCalls(item, token, provideCallHierarchyIncomingCalls) : provideCallHierarchyIncomingCalls(item, token);
|
|
}
|
|
provideCallHierarchyOutgoingCalls(item, token) {
|
|
const client = this.client;
|
|
const middleware = this.middleware;
|
|
const provideCallHierarchyOutgoingCalls = (item2, token2) => {
|
|
const params = {
|
|
item: client.code2ProtocolConverter.asCallHierarchyItem(item2)
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asCallHierarchyOutgoingCalls(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
return middleware.provideCallHierarchyOutgoingCalls ? middleware.provideCallHierarchyOutgoingCalls(item, token, provideCallHierarchyOutgoingCalls) : provideCallHierarchyOutgoingCalls(item, token);
|
|
}
|
|
}
|
|
|
|
class CallHierarchyFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type);
|
|
}
|
|
fillClientCapabilities(cap) {
|
|
const capabilities = cap;
|
|
const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "callHierarchy");
|
|
capability.dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const [id, options] = this.getRegistration(documentSelector, capabilities.callHierarchyProvider);
|
|
if (!id || !options) {
|
|
return;
|
|
}
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const client = this._client;
|
|
const provider = new CallHierarchyProvider(client);
|
|
return [vscode_1.languages.registerCallHierarchyProvider(this._client.protocol2CodeConverter.asDocumentSelector(options.documentSelector), provider), provider];
|
|
}
|
|
}
|
|
exports2.CallHierarchyFeature = CallHierarchyFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/semanticTokens.js
|
|
var require_semanticTokens = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.SemanticTokensFeature = undefined;
|
|
var vscode = __importStar(require("vscode"));
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
var Is = __importStar(require_is());
|
|
|
|
class SemanticTokensFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.SemanticTokensRegistrationType.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "semanticTokens");
|
|
capability.dynamicRegistration = true;
|
|
capability.tokenTypes = [
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.namespace,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.type,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.class,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.enum,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.interface,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.struct,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.typeParameter,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.parameter,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.variable,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.property,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.enumMember,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.event,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.function,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.method,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.macro,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.keyword,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.comment,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.string,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.number,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.regexp,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.operator,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.decorator,
|
|
vscode_languageserver_protocol_1.SemanticTokenTypes.label
|
|
];
|
|
capability.tokenModifiers = [
|
|
vscode_languageserver_protocol_1.SemanticTokenModifiers.declaration,
|
|
vscode_languageserver_protocol_1.SemanticTokenModifiers.definition,
|
|
vscode_languageserver_protocol_1.SemanticTokenModifiers.readonly,
|
|
vscode_languageserver_protocol_1.SemanticTokenModifiers.static,
|
|
vscode_languageserver_protocol_1.SemanticTokenModifiers.deprecated,
|
|
vscode_languageserver_protocol_1.SemanticTokenModifiers.abstract,
|
|
vscode_languageserver_protocol_1.SemanticTokenModifiers.async,
|
|
vscode_languageserver_protocol_1.SemanticTokenModifiers.modification,
|
|
vscode_languageserver_protocol_1.SemanticTokenModifiers.documentation,
|
|
vscode_languageserver_protocol_1.SemanticTokenModifiers.defaultLibrary
|
|
];
|
|
capability.formats = [vscode_languageserver_protocol_1.TokenFormat.Relative];
|
|
capability.requests = {
|
|
range: true,
|
|
full: {
|
|
delta: true
|
|
}
|
|
};
|
|
capability.multilineTokenSupport = false;
|
|
capability.overlappingTokenSupport = false;
|
|
capability.serverCancelSupport = true;
|
|
capability.augmentsSyntaxTokens = true;
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "semanticTokens").refreshSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const client = this._client;
|
|
client.onRequest(vscode_languageserver_protocol_1.SemanticTokensRefreshRequest.type, async () => {
|
|
for (const provider of this.getAllProviders()) {
|
|
provider.onDidChangeSemanticTokensEmitter.fire();
|
|
}
|
|
});
|
|
const [id, options] = this.getRegistration(documentSelector, capabilities.semanticTokensProvider);
|
|
if (!id || !options) {
|
|
return;
|
|
}
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const fullProvider = Is.boolean(options.full) ? options.full : options.full !== undefined;
|
|
const hasEditProvider = options.full !== undefined && typeof options.full !== "boolean" && options.full.delta === true;
|
|
const eventEmitter = new vscode.EventEmitter;
|
|
const documentProvider = fullProvider ? {
|
|
onDidChangeSemanticTokens: eventEmitter.event,
|
|
provideDocumentSemanticTokens: (document, token) => {
|
|
const client2 = this._client;
|
|
const middleware = client2.middleware;
|
|
const provideDocumentSemanticTokens = (document2, token2) => {
|
|
const params = {
|
|
textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2)
|
|
};
|
|
return client2.sendRequest(vscode_languageserver_protocol_1.SemanticTokensRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client2.protocol2CodeConverter.asSemanticTokens(result, token2);
|
|
}, (error) => {
|
|
return client2.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
return middleware.provideDocumentSemanticTokens ? middleware.provideDocumentSemanticTokens(document, token, provideDocumentSemanticTokens) : provideDocumentSemanticTokens(document, token);
|
|
},
|
|
provideDocumentSemanticTokensEdits: hasEditProvider ? (document, previousResultId, token) => {
|
|
const client2 = this._client;
|
|
const middleware = client2.middleware;
|
|
const provideDocumentSemanticTokensEdits = (document2, previousResultId2, token2) => {
|
|
const params = {
|
|
textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2),
|
|
previousResultId: previousResultId2
|
|
};
|
|
return client2.sendRequest(vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.type, params, token2).then(async (result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
if (vscode_languageserver_protocol_1.SemanticTokens.is(result)) {
|
|
return await client2.protocol2CodeConverter.asSemanticTokens(result, token2);
|
|
} else {
|
|
return await client2.protocol2CodeConverter.asSemanticTokensEdits(result, token2);
|
|
}
|
|
}, (error) => {
|
|
return client2.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
return middleware.provideDocumentSemanticTokensEdits ? middleware.provideDocumentSemanticTokensEdits(document, previousResultId, token, provideDocumentSemanticTokensEdits) : provideDocumentSemanticTokensEdits(document, previousResultId, token);
|
|
} : undefined
|
|
} : undefined;
|
|
const hasRangeProvider = options.range === true;
|
|
const rangeProvider = hasRangeProvider ? {
|
|
onDidChangeSemanticTokens: eventEmitter.event,
|
|
provideDocumentRangeSemanticTokens: (document, range, token) => {
|
|
const client2 = this._client;
|
|
const middleware = client2.middleware;
|
|
const provideDocumentRangeSemanticTokens = (document2, range2, token2) => {
|
|
const params = {
|
|
textDocument: client2.code2ProtocolConverter.asTextDocumentIdentifier(document2),
|
|
range: client2.code2ProtocolConverter.asRange(range2)
|
|
};
|
|
return client2.sendRequest(vscode_languageserver_protocol_1.SemanticTokensRangeRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client2.protocol2CodeConverter.asSemanticTokens(result, token2);
|
|
}, (error) => {
|
|
return client2.handleFailedRequest(vscode_languageserver_protocol_1.SemanticTokensRangeRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
return middleware.provideDocumentRangeSemanticTokens ? middleware.provideDocumentRangeSemanticTokens(document, range, token, provideDocumentRangeSemanticTokens) : provideDocumentRangeSemanticTokens(document, range, token);
|
|
}
|
|
} : undefined;
|
|
const disposables = [];
|
|
const client = this._client;
|
|
const legend = client.protocol2CodeConverter.asSemanticTokensLegend(options.legend);
|
|
const documentSelector = client.protocol2CodeConverter.asDocumentSelector(selector);
|
|
if (documentProvider !== undefined) {
|
|
disposables.push(vscode.languages.registerDocumentSemanticTokensProvider(documentSelector, documentProvider, legend));
|
|
}
|
|
if (rangeProvider !== undefined) {
|
|
disposables.push(vscode.languages.registerDocumentRangeSemanticTokensProvider(documentSelector, rangeProvider, legend));
|
|
}
|
|
return [new vscode.Disposable(() => disposables.forEach((item) => item.dispose())), { range: rangeProvider, full: documentProvider, onDidChangeSemanticTokensEmitter: eventEmitter }];
|
|
}
|
|
}
|
|
exports2.SemanticTokensFeature = SemanticTokensFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/linkedEditingRange.js
|
|
var require_linkedEditingRange = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.LinkedEditingFeature = undefined;
|
|
var code = __importStar(require("vscode"));
|
|
var proto = __importStar(require_api2());
|
|
var features_1 = require_features();
|
|
|
|
class LinkedEditingFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, proto.LinkedEditingRangeRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const linkedEditingSupport = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "linkedEditingRange");
|
|
linkedEditingSupport.dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const [id, options] = this.getRegistration(documentSelector, capabilities.linkedEditingRangeProvider);
|
|
if (!id || !options) {
|
|
return;
|
|
}
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideLinkedEditingRanges: (document, position, token) => {
|
|
const client = this._client;
|
|
const provideLinkedEditing = (document2, position2, token2) => {
|
|
return client.sendRequest(proto.LinkedEditingRangeRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asLinkedEditingRanges(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(proto.LinkedEditingRangeRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideLinkedEditingRange ? middleware.provideLinkedEditingRange(document, position, token, provideLinkedEditing) : provideLinkedEditing(document, position, token);
|
|
}
|
|
};
|
|
return [this.registerProvider(selector, provider), provider];
|
|
}
|
|
registerProvider(selector, provider) {
|
|
return code.languages.registerLinkedEditingRangeProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);
|
|
}
|
|
}
|
|
exports2.LinkedEditingFeature = LinkedEditingFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/typeHierarchy.js
|
|
var require_typeHierarchy = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.TypeHierarchyFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
|
|
class TypeHierarchyProvider {
|
|
client;
|
|
middleware;
|
|
constructor(client) {
|
|
this.client = client;
|
|
this.middleware = client.middleware;
|
|
}
|
|
prepareTypeHierarchy(document, position, token) {
|
|
const client = this.client;
|
|
const middleware = this.middleware;
|
|
const prepareTypeHierarchy = (document2, position2, token2) => {
|
|
const params = client.code2ProtocolConverter.asTextDocumentPositionParams(document2, position2);
|
|
return client.sendRequest(vscode_languageserver_protocol_1.TypeHierarchyPrepareRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asTypeHierarchyItems(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.TypeHierarchyPrepareRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
return middleware.prepareTypeHierarchy ? middleware.prepareTypeHierarchy(document, position, token, prepareTypeHierarchy) : prepareTypeHierarchy(document, position, token);
|
|
}
|
|
provideTypeHierarchySupertypes(item, token) {
|
|
const client = this.client;
|
|
const middleware = this.middleware;
|
|
const provideTypeHierarchySupertypes = (item2, token2) => {
|
|
const params = {
|
|
item: client.code2ProtocolConverter.asTypeHierarchyItem(item2)
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.TypeHierarchySupertypesRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asTypeHierarchyItems(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.TypeHierarchySupertypesRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
return middleware.provideTypeHierarchySupertypes ? middleware.provideTypeHierarchySupertypes(item, token, provideTypeHierarchySupertypes) : provideTypeHierarchySupertypes(item, token);
|
|
}
|
|
provideTypeHierarchySubtypes(item, token) {
|
|
const client = this.client;
|
|
const middleware = this.middleware;
|
|
const provideTypeHierarchySubtypes = (item2, token2) => {
|
|
const params = {
|
|
item: client.code2ProtocolConverter.asTypeHierarchyItem(item2)
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.TypeHierarchySubtypesRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asTypeHierarchyItems(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.TypeHierarchySubtypesRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
return middleware.provideTypeHierarchySubtypes ? middleware.provideTypeHierarchySubtypes(item, token, provideTypeHierarchySubtypes) : provideTypeHierarchySubtypes(item, token);
|
|
}
|
|
}
|
|
|
|
class TypeHierarchyFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.TypeHierarchyPrepareRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const capability = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "typeHierarchy");
|
|
capability.dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const [id, options] = this.getRegistration(documentSelector, capabilities.typeHierarchyProvider);
|
|
if (!id || !options) {
|
|
return;
|
|
}
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const client = this._client;
|
|
const provider = new TypeHierarchyProvider(client);
|
|
return [vscode_1.languages.registerTypeHierarchyProvider(client.protocol2CodeConverter.asDocumentSelector(options.documentSelector), provider), provider];
|
|
}
|
|
}
|
|
exports2.TypeHierarchyFeature = TypeHierarchyFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/inlineValue.js
|
|
var require_inlineValue = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.InlineValueFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
|
|
class InlineValueFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.InlineValueRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "inlineValue").dynamicRegistration = true;
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "inlineValue").refreshSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
this._client.onRequest(vscode_languageserver_protocol_1.InlineValueRefreshRequest.type, async () => {
|
|
for (const provider of this.getAllProviders()) {
|
|
provider.onDidChangeInlineValues.fire();
|
|
}
|
|
});
|
|
const [id, options] = this.getRegistration(documentSelector, capabilities.inlineValueProvider);
|
|
if (!id || !options) {
|
|
return;
|
|
}
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const eventEmitter = new vscode_1.EventEmitter;
|
|
const provider = {
|
|
onDidChangeInlineValues: eventEmitter.event,
|
|
provideInlineValues: (document, viewPort, context, token) => {
|
|
const client = this._client;
|
|
const provideInlineValues = (document2, viewPort2, context2, token2) => {
|
|
const requestParams = {
|
|
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document2),
|
|
range: client.code2ProtocolConverter.asRange(viewPort2),
|
|
context: client.code2ProtocolConverter.asInlineValueContext(context2)
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.InlineValueRequest.type, requestParams, token2).then((values) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asInlineValues(values, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.InlineValueRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideInlineValues ? middleware.provideInlineValues(document, viewPort, context, token, provideInlineValues) : provideInlineValues(document, viewPort, context, token);
|
|
}
|
|
};
|
|
return [this.registerProvider(selector, provider), { provider, onDidChangeInlineValues: eventEmitter }];
|
|
}
|
|
registerProvider(selector, provider) {
|
|
return vscode_1.languages.registerInlineValuesProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);
|
|
}
|
|
}
|
|
exports2.InlineValueFeature = InlineValueFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/inlayHint.js
|
|
var require_inlayHint = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.InlayHintsFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
|
|
class InlayHintsFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.InlayHintRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const inlayHint = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "inlayHint");
|
|
inlayHint.dynamicRegistration = true;
|
|
inlayHint.resolveSupport = {
|
|
properties: ["tooltip", "textEdits", "label.tooltip", "label.location", "label.command"]
|
|
};
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "inlayHint").refreshSupport = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
this._client.onRequest(vscode_languageserver_protocol_1.InlayHintRefreshRequest.type, async () => {
|
|
for (const provider of this.getAllProviders()) {
|
|
provider.onDidChangeInlayHints.fire();
|
|
}
|
|
});
|
|
const [id, options] = this.getRegistration(documentSelector, capabilities.inlayHintProvider);
|
|
if (!id || !options) {
|
|
return;
|
|
}
|
|
this.register({ id, registerOptions: options });
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const eventEmitter = new vscode_1.EventEmitter;
|
|
const provider = {
|
|
onDidChangeInlayHints: eventEmitter.event,
|
|
provideInlayHints: (document, viewPort, token) => {
|
|
const client = this._client;
|
|
const provideInlayHints = async (document2, viewPort2, token2) => {
|
|
const requestParams = {
|
|
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document2),
|
|
range: client.code2ProtocolConverter.asRange(viewPort2)
|
|
};
|
|
try {
|
|
const values = await client.sendRequest(vscode_languageserver_protocol_1.InlayHintRequest.type, requestParams, token2);
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asInlayHints(values, token2);
|
|
} catch (error) {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.InlayHintRequest.type, token2, error, null);
|
|
}
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideInlayHints ? middleware.provideInlayHints(document, viewPort, token, provideInlayHints) : provideInlayHints(document, viewPort, token);
|
|
}
|
|
};
|
|
provider.resolveInlayHint = options.resolveProvider === true ? (hint, token) => {
|
|
const client = this._client;
|
|
const resolveInlayHint = async (item, token2) => {
|
|
try {
|
|
const value = await client.sendRequest(vscode_languageserver_protocol_1.InlayHintResolveRequest.type, client.code2ProtocolConverter.asInlayHint(item), token2);
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
const result = client.protocol2CodeConverter.asInlayHint(value, token2);
|
|
return token2.isCancellationRequested ? null : result;
|
|
} catch (error) {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.InlayHintResolveRequest.type, token2, error, null);
|
|
}
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.resolveInlayHint ? middleware.resolveInlayHint(hint, token, resolveInlayHint) : resolveInlayHint(hint, token);
|
|
} : undefined;
|
|
return [this.registerProvider(selector, provider), { provider, onDidChangeInlayHints: eventEmitter }];
|
|
}
|
|
registerProvider(selector, provider) {
|
|
return vscode_1.languages.registerInlayHintsProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider);
|
|
}
|
|
}
|
|
exports2.InlayHintsFeature = InlayHintsFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/workspaceFolder.js
|
|
var require_workspaceFolder = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.WorkspaceFoldersFeature = undefined;
|
|
exports2.arrayDiff = arrayDiff;
|
|
var UUID = __importStar(require_uuid());
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
function access(target, key) {
|
|
if (target === undefined || target === null) {
|
|
return;
|
|
}
|
|
return target[key];
|
|
}
|
|
function arrayDiff(left, right) {
|
|
return left.filter((element) => right.indexOf(element) < 0);
|
|
}
|
|
|
|
class WorkspaceFoldersFeature {
|
|
_client;
|
|
_listeners;
|
|
_initialFolders;
|
|
constructor(client) {
|
|
this._client = client;
|
|
this._listeners = new Map;
|
|
}
|
|
getState() {
|
|
return { kind: "workspace", id: this.registrationType.method, registrations: this._listeners.size > 0 };
|
|
}
|
|
get registrationType() {
|
|
return vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type;
|
|
}
|
|
fillInitializeParams(params) {
|
|
const folders = vscode_1.workspace.workspaceFolders;
|
|
this.initializeWithFolders(folders);
|
|
if (folders === undefined) {
|
|
params.workspaceFolders = null;
|
|
} else {
|
|
params.workspaceFolders = folders.map((folder) => this.asProtocol(folder));
|
|
}
|
|
}
|
|
initializeWithFolders(currentWorkspaceFolders) {
|
|
this._initialFolders = currentWorkspaceFolders;
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
capabilities.workspace = capabilities.workspace || {};
|
|
capabilities.workspace.workspaceFolders = true;
|
|
}
|
|
initialize(capabilities) {
|
|
const client = this._client;
|
|
client.onRequest(vscode_languageserver_protocol_1.WorkspaceFoldersRequest.type, (token) => {
|
|
const workspaceFolders = () => {
|
|
const folders = vscode_1.workspace.workspaceFolders;
|
|
if (folders === undefined) {
|
|
return null;
|
|
}
|
|
const result = folders.map((folder) => {
|
|
return this.asProtocol(folder);
|
|
});
|
|
return result;
|
|
};
|
|
const middleware = client.middleware.workspace;
|
|
return middleware && middleware.workspaceFolders ? middleware.workspaceFolders(token, workspaceFolders) : workspaceFolders(token);
|
|
});
|
|
const value = access(access(access(capabilities, "workspace"), "workspaceFolders"), "changeNotifications");
|
|
let id;
|
|
if (typeof value === "string") {
|
|
id = value;
|
|
} else if (value === true) {
|
|
id = UUID.generateUuid();
|
|
}
|
|
if (id) {
|
|
this.register({ id, registerOptions: undefined });
|
|
}
|
|
}
|
|
sendInitialEvent(currentWorkspaceFolders) {
|
|
let promise;
|
|
if (this._initialFolders && currentWorkspaceFolders) {
|
|
const removed = arrayDiff(this._initialFolders, currentWorkspaceFolders);
|
|
const added = arrayDiff(currentWorkspaceFolders, this._initialFolders);
|
|
if (added.length > 0 || removed.length > 0) {
|
|
promise = this.doSendEvent(added, removed);
|
|
}
|
|
} else if (this._initialFolders) {
|
|
promise = this.doSendEvent([], this._initialFolders);
|
|
} else if (currentWorkspaceFolders) {
|
|
promise = this.doSendEvent(currentWorkspaceFolders, []);
|
|
}
|
|
if (promise !== undefined) {
|
|
promise.catch((error) => {
|
|
this._client.error(`Sending notification ${vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type.method} failed`, error);
|
|
});
|
|
}
|
|
}
|
|
doSendEvent(addedFolders, removedFolders) {
|
|
const params = {
|
|
event: {
|
|
added: addedFolders.map((folder) => this.asProtocol(folder)),
|
|
removed: removedFolders.map((folder) => this.asProtocol(folder))
|
|
}
|
|
};
|
|
return this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type, params);
|
|
}
|
|
register(data) {
|
|
const id = data.id;
|
|
const client = this._client;
|
|
const disposable = vscode_1.workspace.onDidChangeWorkspaceFolders((event) => {
|
|
const didChangeWorkspaceFolders = (event2) => {
|
|
return this.doSendEvent(event2.added, event2.removed);
|
|
};
|
|
const middleware = client.middleware.workspace;
|
|
const promise = middleware && middleware.didChangeWorkspaceFolders ? middleware.didChangeWorkspaceFolders(event, didChangeWorkspaceFolders) : didChangeWorkspaceFolders(event);
|
|
promise.catch((error) => {
|
|
this._client.error(`Sending notification ${vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type.method} failed`, error);
|
|
});
|
|
});
|
|
this._listeners.set(id, disposable);
|
|
this.sendInitialEvent(vscode_1.workspace.workspaceFolders);
|
|
}
|
|
unregister(id) {
|
|
const disposable = this._listeners.get(id);
|
|
if (disposable === undefined) {
|
|
return;
|
|
}
|
|
this._listeners.delete(id);
|
|
disposable.dispose();
|
|
}
|
|
clear() {
|
|
for (const disposable of this._listeners.values()) {
|
|
disposable.dispose();
|
|
}
|
|
this._listeners.clear();
|
|
}
|
|
asProtocol(workspaceFolder) {
|
|
if (workspaceFolder === undefined) {
|
|
return null;
|
|
}
|
|
return { uri: this._client.code2ProtocolConverter.asUri(workspaceFolder.uri), name: workspaceFolder.name };
|
|
}
|
|
}
|
|
exports2.WorkspaceFoldersFeature = WorkspaceFoldersFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/fileOperations.js
|
|
var require_fileOperations = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.WillDeleteFilesFeature = exports2.WillRenameFilesFeature = exports2.WillCreateFilesFeature = exports2.DidDeleteFilesFeature = exports2.DidRenameFilesFeature = exports2.DidCreateFilesFeature = undefined;
|
|
var code = __importStar(require("vscode"));
|
|
var minimatch = __importStar(require_commonjs3());
|
|
var proto = __importStar(require_api2());
|
|
var UUID = __importStar(require_uuid());
|
|
function ensure(target, key) {
|
|
if (target[key] === undefined) {
|
|
target[key] = {};
|
|
}
|
|
return target[key];
|
|
}
|
|
function access(target, key) {
|
|
return target[key];
|
|
}
|
|
function assign(target, key, value) {
|
|
target[key] = value;
|
|
}
|
|
|
|
class FileOperationFeature {
|
|
_client;
|
|
_event;
|
|
_registrationType;
|
|
_clientCapability;
|
|
_serverCapability;
|
|
_listener;
|
|
_filters;
|
|
constructor(client, event, registrationType, clientCapability, serverCapability) {
|
|
this._client = client;
|
|
this._event = event;
|
|
this._registrationType = registrationType;
|
|
this._clientCapability = clientCapability;
|
|
this._serverCapability = serverCapability;
|
|
this._filters = new Map;
|
|
}
|
|
getState() {
|
|
return { kind: "workspace", id: this._registrationType.method, registrations: this._filters.size > 0 };
|
|
}
|
|
filterSize() {
|
|
return this._filters.size;
|
|
}
|
|
get registrationType() {
|
|
return this._registrationType;
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const value = ensure(ensure(capabilities, "workspace"), "fileOperations");
|
|
assign(value, "dynamicRegistration", true);
|
|
assign(value, this._clientCapability, true);
|
|
}
|
|
initialize(capabilities) {
|
|
const options = capabilities.workspace?.fileOperations;
|
|
const capability = options !== undefined ? access(options, this._serverCapability) : undefined;
|
|
if (capability?.filters !== undefined) {
|
|
try {
|
|
this.register({
|
|
id: UUID.generateUuid(),
|
|
registerOptions: { filters: capability.filters }
|
|
});
|
|
} catch (e) {
|
|
this._client.warn(`Ignoring invalid glob pattern for ${this._serverCapability} registration: ${e}`);
|
|
}
|
|
}
|
|
}
|
|
register(data) {
|
|
if (!this._listener) {
|
|
this._listener = this._event(this.send, this);
|
|
}
|
|
const minimatchFilter = data.registerOptions.filters.map((filter) => {
|
|
const matcher = new minimatch.Minimatch(filter.pattern.glob, FileOperationFeature.asMinimatchOptions(filter.pattern.options));
|
|
if (!matcher.makeRe()) {
|
|
throw new Error(`Invalid pattern ${filter.pattern.glob}!`);
|
|
}
|
|
return { scheme: filter.scheme, matcher, kind: filter.pattern.matches };
|
|
});
|
|
this._filters.set(data.id, minimatchFilter);
|
|
}
|
|
unregister(id) {
|
|
this._filters.delete(id);
|
|
if (this._filters.size === 0 && this._listener) {
|
|
this._listener.dispose();
|
|
this._listener = undefined;
|
|
}
|
|
}
|
|
clear() {
|
|
this._filters.clear();
|
|
if (this._listener) {
|
|
this._listener.dispose();
|
|
this._listener = undefined;
|
|
}
|
|
}
|
|
getFileType(uri) {
|
|
return FileOperationFeature.getFileType(uri);
|
|
}
|
|
async filter(event, prop) {
|
|
const fileMatches = await Promise.all(event.files.map(async (item) => {
|
|
const uri = prop(item);
|
|
const path = uri.fsPath.replace(/\\/g, "/");
|
|
for (const filters of this._filters.values()) {
|
|
for (const filter of filters) {
|
|
if (filter.scheme !== undefined && filter.scheme !== uri.scheme) {
|
|
continue;
|
|
}
|
|
if (filter.matcher.match(path)) {
|
|
if (filter.kind === undefined) {
|
|
return true;
|
|
}
|
|
const fileType = await this.getFileType(uri);
|
|
if (fileType === undefined) {
|
|
this._client.info(`Unable to determine file type for ${uri.toString()}. Treating as a match.`);
|
|
return true;
|
|
}
|
|
if (fileType === code.FileType.File && filter.kind === proto.FileOperationPatternKind.file || fileType === code.FileType.Directory && filter.kind === proto.FileOperationPatternKind.folder) {
|
|
return true;
|
|
}
|
|
} else if (filter.kind === proto.FileOperationPatternKind.folder) {
|
|
const fileType = await FileOperationFeature.getFileType(uri);
|
|
if (fileType === code.FileType.Directory && filter.matcher.match(`${path}/`)) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}));
|
|
const files = event.files.filter((_, index) => fileMatches[index]);
|
|
return { ...event, files };
|
|
}
|
|
static async getFileType(uri) {
|
|
try {
|
|
return (await code.workspace.fs.stat(uri)).type;
|
|
} catch (e) {
|
|
return;
|
|
}
|
|
}
|
|
static asMinimatchOptions(options) {
|
|
const result = { dot: true };
|
|
if (options?.ignoreCase === true) {
|
|
result.nocase = true;
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
|
|
class NotificationFileOperationFeature extends FileOperationFeature {
|
|
_notificationType;
|
|
_accessUri;
|
|
_createParams;
|
|
constructor(client, event, notificationType, clientCapability, serverCapability, accessUri, createParams) {
|
|
super(client, event, notificationType, clientCapability, serverCapability);
|
|
this._notificationType = notificationType;
|
|
this._accessUri = accessUri;
|
|
this._createParams = createParams;
|
|
}
|
|
async send(originalEvent) {
|
|
const filteredEvent = await this.filter(originalEvent, this._accessUri);
|
|
if (filteredEvent.files.length) {
|
|
const next = async (event) => {
|
|
return this._client.sendNotification(this._notificationType, this._createParams(event));
|
|
};
|
|
return this.doSend(filteredEvent, next);
|
|
}
|
|
}
|
|
}
|
|
|
|
class CachingNotificationFileOperationFeature extends NotificationFileOperationFeature {
|
|
_willListener;
|
|
_fsPathFileTypes = new Map;
|
|
async getFileType(uri) {
|
|
const fsPath = uri.fsPath;
|
|
if (this._fsPathFileTypes.has(fsPath)) {
|
|
return this._fsPathFileTypes.get(fsPath);
|
|
}
|
|
const type = await FileOperationFeature.getFileType(uri);
|
|
if (type) {
|
|
this._fsPathFileTypes.set(fsPath, type);
|
|
}
|
|
return type;
|
|
}
|
|
async cacheFileTypes(event, prop) {
|
|
await this.filter(event, prop);
|
|
}
|
|
clearFileTypeCache() {
|
|
this._fsPathFileTypes.clear();
|
|
}
|
|
unregister(id) {
|
|
super.unregister(id);
|
|
if (this.filterSize() === 0 && this._willListener) {
|
|
this._willListener.dispose();
|
|
this._willListener = undefined;
|
|
}
|
|
}
|
|
clear() {
|
|
super.clear();
|
|
if (this._willListener) {
|
|
this._willListener.dispose();
|
|
this._willListener = undefined;
|
|
}
|
|
}
|
|
}
|
|
|
|
class DidCreateFilesFeature extends NotificationFileOperationFeature {
|
|
constructor(client) {
|
|
super(client, code.workspace.onDidCreateFiles, proto.DidCreateFilesNotification.type, "didCreate", "didCreate", (i) => i, client.code2ProtocolConverter.asDidCreateFilesParams);
|
|
}
|
|
doSend(event, next) {
|
|
const middleware = this._client.middleware.workspace;
|
|
return middleware?.didCreateFiles ? middleware.didCreateFiles(event, next) : next(event);
|
|
}
|
|
}
|
|
exports2.DidCreateFilesFeature = DidCreateFilesFeature;
|
|
|
|
class DidRenameFilesFeature extends CachingNotificationFileOperationFeature {
|
|
constructor(client) {
|
|
super(client, code.workspace.onDidRenameFiles, proto.DidRenameFilesNotification.type, "didRename", "didRename", (i) => i.oldUri, client.code2ProtocolConverter.asDidRenameFilesParams);
|
|
}
|
|
register(data) {
|
|
if (!this._willListener) {
|
|
this._willListener = code.workspace.onWillRenameFiles(this.willRename, this);
|
|
}
|
|
super.register(data);
|
|
}
|
|
willRename(e) {
|
|
e.waitUntil(this.cacheFileTypes(e, (i) => i.oldUri));
|
|
}
|
|
doSend(event, next) {
|
|
this.clearFileTypeCache();
|
|
const middleware = this._client.middleware.workspace;
|
|
return middleware?.didRenameFiles ? middleware.didRenameFiles(event, next) : next(event);
|
|
}
|
|
}
|
|
exports2.DidRenameFilesFeature = DidRenameFilesFeature;
|
|
|
|
class DidDeleteFilesFeature extends CachingNotificationFileOperationFeature {
|
|
constructor(client) {
|
|
super(client, code.workspace.onDidDeleteFiles, proto.DidDeleteFilesNotification.type, "didDelete", "didDelete", (i) => i, client.code2ProtocolConverter.asDidDeleteFilesParams);
|
|
}
|
|
register(data) {
|
|
if (!this._willListener) {
|
|
this._willListener = code.workspace.onWillDeleteFiles(this.willDelete, this);
|
|
}
|
|
super.register(data);
|
|
}
|
|
willDelete(e) {
|
|
e.waitUntil(this.cacheFileTypes(e, (i) => i));
|
|
}
|
|
doSend(event, next) {
|
|
this.clearFileTypeCache();
|
|
const middleware = this._client.middleware.workspace;
|
|
return middleware?.didDeleteFiles ? middleware.didDeleteFiles(event, next) : next(event);
|
|
}
|
|
}
|
|
exports2.DidDeleteFilesFeature = DidDeleteFilesFeature;
|
|
|
|
class RequestFileOperationFeature extends FileOperationFeature {
|
|
_requestType;
|
|
_accessUri;
|
|
_createParams;
|
|
constructor(client, event, requestType, clientCapability, serverCapability, accessUri, createParams) {
|
|
super(client, event, requestType, clientCapability, serverCapability);
|
|
this._requestType = requestType;
|
|
this._accessUri = accessUri;
|
|
this._createParams = createParams;
|
|
}
|
|
async send(originalEvent) {
|
|
const waitUntil = this.waitUntil(originalEvent);
|
|
originalEvent.waitUntil(waitUntil);
|
|
}
|
|
async waitUntil(originalEvent) {
|
|
const filteredEvent = await this.filter(originalEvent, this._accessUri);
|
|
if (filteredEvent.files.length) {
|
|
const next = (event) => {
|
|
return this._client.sendRequest(this._requestType, this._createParams(event), event.token).then(this._client.protocol2CodeConverter.asWorkspaceEdit);
|
|
};
|
|
return this.doSend(filteredEvent, next);
|
|
} else {
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
class WillCreateFilesFeature extends RequestFileOperationFeature {
|
|
constructor(client) {
|
|
super(client, code.workspace.onWillCreateFiles, proto.WillCreateFilesRequest.type, "willCreate", "willCreate", (i) => i, client.code2ProtocolConverter.asWillCreateFilesParams);
|
|
}
|
|
doSend(event, next) {
|
|
const middleware = this._client.middleware.workspace;
|
|
return middleware?.willCreateFiles ? middleware.willCreateFiles(event, next) : next(event);
|
|
}
|
|
}
|
|
exports2.WillCreateFilesFeature = WillCreateFilesFeature;
|
|
|
|
class WillRenameFilesFeature extends RequestFileOperationFeature {
|
|
constructor(client) {
|
|
super(client, code.workspace.onWillRenameFiles, proto.WillRenameFilesRequest.type, "willRename", "willRename", (i) => i.oldUri, client.code2ProtocolConverter.asWillRenameFilesParams);
|
|
}
|
|
doSend(event, next) {
|
|
const middleware = this._client.middleware.workspace;
|
|
return middleware?.willRenameFiles ? middleware.willRenameFiles(event, next) : next(event);
|
|
}
|
|
}
|
|
exports2.WillRenameFilesFeature = WillRenameFilesFeature;
|
|
|
|
class WillDeleteFilesFeature extends RequestFileOperationFeature {
|
|
constructor(client) {
|
|
super(client, code.workspace.onWillDeleteFiles, proto.WillDeleteFilesRequest.type, "willDelete", "willDelete", (i) => i, client.code2ProtocolConverter.asWillDeleteFilesParams);
|
|
}
|
|
doSend(event, next) {
|
|
const middleware = this._client.middleware.workspace;
|
|
return middleware?.willDeleteFiles ? middleware.willDeleteFiles(event, next) : next(event);
|
|
}
|
|
}
|
|
exports2.WillDeleteFilesFeature = WillDeleteFilesFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/inlineCompletion.js
|
|
var require_inlineCompletion = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.InlineCompletionItemFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
var UUID = __importStar(require_uuid());
|
|
|
|
class InlineCompletionItemFeature extends features_1.TextDocumentLanguageFeature {
|
|
constructor(client) {
|
|
super(client, vscode_languageserver_protocol_1.InlineCompletionRequest.type);
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const inlineCompletion = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "textDocument"), "inlineCompletion");
|
|
inlineCompletion.dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities, documentSelector) {
|
|
const options = this.getRegistrationOptions(documentSelector, capabilities.inlineCompletionProvider);
|
|
if (!options) {
|
|
return;
|
|
}
|
|
this.register({
|
|
id: UUID.generateUuid(),
|
|
registerOptions: options
|
|
});
|
|
}
|
|
registerLanguageProvider(options) {
|
|
const selector = options.documentSelector;
|
|
const provider = {
|
|
provideInlineCompletionItems: (document, position, context, token) => {
|
|
const client = this._client;
|
|
const middleware = this._client.middleware;
|
|
const provideInlineCompletionItems = (document2, position2, context2, token2) => {
|
|
return client.sendRequest(vscode_languageserver_protocol_1.InlineCompletionRequest.type, client.code2ProtocolConverter.asInlineCompletionParams(document2, position2, context2), token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return client.protocol2CodeConverter.asInlineCompletionResult(result, token2);
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.InlineCompletionRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
return middleware.provideInlineCompletionItems ? middleware.provideInlineCompletionItems(document, position, context, token, provideInlineCompletionItems) : provideInlineCompletionItems(document, position, context, token);
|
|
}
|
|
};
|
|
return [vscode_1.languages.registerInlineCompletionItemProvider(this._client.protocol2CodeConverter.asDocumentSelector(selector), provider), provider];
|
|
}
|
|
}
|
|
exports2.InlineCompletionItemFeature = InlineCompletionItemFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/textDocumentContent.js
|
|
var require_textDocumentContent = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.TextDocumentContentFeature = undefined;
|
|
var vscode = __importStar(require("vscode"));
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
var UUID = __importStar(require_uuid());
|
|
|
|
class TextDocumentContentFeature {
|
|
_client;
|
|
_registrations = new Map;
|
|
constructor(client) {
|
|
this._client = client;
|
|
}
|
|
getState() {
|
|
const registrations = this._registrations.size > 0;
|
|
return { kind: "workspace", id: vscode_languageserver_protocol_1.TextDocumentContentRequest.method, registrations };
|
|
}
|
|
get registrationType() {
|
|
return vscode_languageserver_protocol_1.TextDocumentContentRequest.type;
|
|
}
|
|
getProviders() {
|
|
const result = [];
|
|
for (const registration of this._registrations.values()) {
|
|
result.push(...registration.providers);
|
|
}
|
|
return result;
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
const textDocumentContent = (0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "textDocumentContent");
|
|
textDocumentContent.dynamicRegistration = true;
|
|
}
|
|
initialize(capabilities) {
|
|
const client = this._client;
|
|
client.onRequest(vscode_languageserver_protocol_1.TextDocumentContentRefreshRequest.type, async (params) => {
|
|
const uri = client.protocol2CodeConverter.asUri(params.uri);
|
|
for (const registrations of this._registrations.values()) {
|
|
for (const provider of registrations.providers) {
|
|
if (provider.scheme === uri.scheme) {
|
|
provider.onDidChangeEmitter.fire(uri);
|
|
}
|
|
}
|
|
}
|
|
});
|
|
if (!capabilities?.workspace?.textDocumentContent) {
|
|
return;
|
|
}
|
|
const capability = capabilities.workspace.textDocumentContent;
|
|
const id = vscode_languageserver_protocol_1.StaticRegistrationOptions.hasId(capability) ? capability.id : UUID.generateUuid();
|
|
this.register({
|
|
id,
|
|
registerOptions: capability
|
|
});
|
|
}
|
|
register(data) {
|
|
const registrations = [];
|
|
const disposables = [];
|
|
for (const scheme of data.registerOptions.schemes) {
|
|
const [disposable, registration] = this.registerTextDocumentContentProvider(scheme);
|
|
registrations.push(registration);
|
|
disposables.push(disposable);
|
|
}
|
|
this._registrations.set(data.id, { disposable: vscode.Disposable.from(...disposables), providers: registrations });
|
|
}
|
|
registerTextDocumentContentProvider(scheme) {
|
|
const eventEmitter = new vscode.EventEmitter;
|
|
const provider = {
|
|
onDidChange: eventEmitter.event,
|
|
provideTextDocumentContent: (uri, token) => {
|
|
const client = this._client;
|
|
const provideTextDocumentContent = (uri2, token2) => {
|
|
const params = {
|
|
uri: client.code2ProtocolConverter.asUri(uri2)
|
|
};
|
|
return client.sendRequest(vscode_languageserver_protocol_1.TextDocumentContentRequest.type, params, token2).then((result) => {
|
|
if (token2.isCancellationRequested) {
|
|
return null;
|
|
}
|
|
return result.text;
|
|
}, (error) => {
|
|
return client.handleFailedRequest(vscode_languageserver_protocol_1.TextDocumentContentRequest.type, token2, error, null);
|
|
});
|
|
};
|
|
const middleware = client.middleware;
|
|
return middleware.provideTextDocumentContent ? middleware.provideTextDocumentContent(uri, token, provideTextDocumentContent) : provideTextDocumentContent(uri, token);
|
|
}
|
|
};
|
|
return [vscode.workspace.registerTextDocumentContentProvider(scheme, provider), { scheme, onDidChangeEmitter: eventEmitter, provider }];
|
|
}
|
|
unregister(id) {
|
|
const registration = this._registrations.get(id);
|
|
if (registration !== undefined) {
|
|
this._registrations.delete(id);
|
|
registration.disposable.dispose();
|
|
}
|
|
}
|
|
clear() {
|
|
this._registrations.forEach((registration) => {
|
|
registration.disposable.dispose();
|
|
});
|
|
this._registrations.clear();
|
|
}
|
|
}
|
|
exports2.TextDocumentContentFeature = TextDocumentContentFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/fileSystemWatcher.js
|
|
var require_fileSystemWatcher = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.FileSystemWatcherFeature = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var features_1 = require_features();
|
|
|
|
class FileSystemWatcherFeature {
|
|
_client;
|
|
_notifyFileEvent;
|
|
_watchers;
|
|
constructor(client, notifyFileEvent) {
|
|
this._client = client;
|
|
this._notifyFileEvent = notifyFileEvent;
|
|
this._watchers = new Map;
|
|
}
|
|
getState() {
|
|
return { kind: "workspace", id: this.registrationType.method, registrations: this._watchers.size > 0 };
|
|
}
|
|
get registrationType() {
|
|
return vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type;
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "didChangeWatchedFiles").dynamicRegistration = true;
|
|
(0, features_1.ensure)((0, features_1.ensure)(capabilities, "workspace"), "didChangeWatchedFiles").relativePatternSupport = true;
|
|
}
|
|
initialize(_capabilities, _documentSelector) {}
|
|
register(data) {
|
|
if (!Array.isArray(data.registerOptions.watchers)) {
|
|
return;
|
|
}
|
|
const disposables = [];
|
|
for (const watcher of data.registerOptions.watchers) {
|
|
const globPattern = this._client.protocol2CodeConverter.asGlobPattern(watcher.globPattern);
|
|
if (globPattern === undefined) {
|
|
continue;
|
|
}
|
|
let watchCreate = true, watchChange = true, watchDelete = true;
|
|
if (watcher.kind !== undefined && watcher.kind !== null) {
|
|
watchCreate = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Create) !== 0;
|
|
watchChange = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Change) !== 0;
|
|
watchDelete = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Delete) !== 0;
|
|
}
|
|
const fileSystemWatcher = vscode_1.workspace.createFileSystemWatcher(globPattern, !watchCreate, !watchChange, !watchDelete);
|
|
this.hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete, disposables);
|
|
disposables.push(fileSystemWatcher);
|
|
}
|
|
this._watchers.set(data.id, disposables);
|
|
}
|
|
registerRaw(id, fileSystemWatchers) {
|
|
const disposables = [];
|
|
for (const fileSystemWatcher of fileSystemWatchers) {
|
|
this.hookListeners(fileSystemWatcher, true, true, true, disposables);
|
|
}
|
|
this._watchers.set(id, disposables);
|
|
}
|
|
hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete, listeners) {
|
|
if (watchCreate) {
|
|
fileSystemWatcher.onDidCreate((resource) => this._notifyFileEvent({
|
|
uri: this._client.code2ProtocolConverter.asUri(resource),
|
|
type: vscode_languageserver_protocol_1.FileChangeType.Created
|
|
}), null, listeners);
|
|
}
|
|
if (watchChange) {
|
|
fileSystemWatcher.onDidChange((resource) => this._notifyFileEvent({
|
|
uri: this._client.code2ProtocolConverter.asUri(resource),
|
|
type: vscode_languageserver_protocol_1.FileChangeType.Changed
|
|
}), null, listeners);
|
|
}
|
|
if (watchDelete) {
|
|
fileSystemWatcher.onDidDelete((resource) => this._notifyFileEvent({
|
|
uri: this._client.code2ProtocolConverter.asUri(resource),
|
|
type: vscode_languageserver_protocol_1.FileChangeType.Deleted
|
|
}), null, listeners);
|
|
}
|
|
}
|
|
unregister(id) {
|
|
const disposables = this._watchers.get(id);
|
|
if (disposables) {
|
|
this._watchers.delete(id);
|
|
for (const disposable of disposables) {
|
|
disposable.dispose();
|
|
}
|
|
}
|
|
}
|
|
clear() {
|
|
this._watchers.forEach((disposables) => {
|
|
for (const disposable of disposables) {
|
|
disposable.dispose();
|
|
}
|
|
});
|
|
this._watchers.clear();
|
|
}
|
|
}
|
|
exports2.FileSystemWatcherFeature = FileSystemWatcherFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/progress.js
|
|
var require_progress = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ProgressFeature = undefined;
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var progressPart_1 = require_progressPart();
|
|
function ensure(target, key) {
|
|
if (target[key] === undefined) {
|
|
target[key] = Object.create(null);
|
|
}
|
|
return target[key];
|
|
}
|
|
|
|
class ProgressFeature {
|
|
_client;
|
|
activeParts;
|
|
constructor(_client) {
|
|
this._client = _client;
|
|
this.activeParts = new Set;
|
|
}
|
|
getState() {
|
|
return { kind: "window", id: vscode_languageserver_protocol_1.WorkDoneProgressCreateRequest.method, registrations: this.activeParts.size > 0 };
|
|
}
|
|
fillClientCapabilities(capabilities) {
|
|
ensure(capabilities, "window").workDoneProgress = true;
|
|
}
|
|
initialize() {
|
|
const client = this._client;
|
|
const deleteHandler = (part) => {
|
|
this.activeParts.delete(part);
|
|
};
|
|
const createHandler = (params) => {
|
|
this.activeParts.add(new progressPart_1.ProgressPart(this._client, params.token, deleteHandler));
|
|
};
|
|
client.onRequest(vscode_languageserver_protocol_1.WorkDoneProgressCreateRequest.type, createHandler);
|
|
}
|
|
clear() {
|
|
for (const part of this.activeParts) {
|
|
part.done();
|
|
}
|
|
this.activeParts.clear();
|
|
}
|
|
}
|
|
exports2.ProgressFeature = ProgressFeature;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/client.js
|
|
var require_client = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.ProposedFeatures = exports2.LanguageClient = exports2.BaseLanguageClient = exports2.ShutdownMode = exports2.MessageTransports = exports2.SuspendMode = exports2.State = exports2.CloseAction = exports2.ErrorAction = exports2.RevealOutputChannelOn = undefined;
|
|
var vscode_1 = require("vscode");
|
|
var vscode_languageserver_protocol_1 = require_api2();
|
|
var c2p = __importStar(require_codeConverter());
|
|
var p2c = __importStar(require_protocolConverter());
|
|
var Is = __importStar(require_is());
|
|
var async_1 = require_async();
|
|
var UUID = __importStar(require_uuid());
|
|
var progressPart_1 = require_progressPart();
|
|
var features_1 = require_features();
|
|
var diagnostic_1 = require_diagnostic();
|
|
var notebook_1 = require_notebook();
|
|
var configuration_1 = require_configuration();
|
|
var textSynchronization_1 = require_textSynchronization();
|
|
var completion_1 = require_completion();
|
|
var hover_1 = require_hover();
|
|
var definition_1 = require_definition();
|
|
var signatureHelp_1 = require_signatureHelp();
|
|
var documentHighlight_1 = require_documentHighlight();
|
|
var documentSymbol_1 = require_documentSymbol();
|
|
var workspaceSymbol_1 = require_workspaceSymbol();
|
|
var reference_1 = require_reference();
|
|
var typeDefinition_1 = require_typeDefinition();
|
|
var implementation_1 = require_implementation();
|
|
var colorProvider_1 = require_colorProvider();
|
|
var codeAction_1 = require_codeAction();
|
|
var codeLens_1 = require_codeLens();
|
|
var formatting_1 = require_formatting();
|
|
var rename_1 = require_rename();
|
|
var documentLink_1 = require_documentLink();
|
|
var executeCommand_1 = require_executeCommand();
|
|
var foldingRange_1 = require_foldingRange();
|
|
var declaration_1 = require_declaration();
|
|
var selectionRange_1 = require_selectionRange();
|
|
var callHierarchy_1 = require_callHierarchy();
|
|
var semanticTokens_1 = require_semanticTokens();
|
|
var linkedEditingRange_1 = require_linkedEditingRange();
|
|
var typeHierarchy_1 = require_typeHierarchy();
|
|
var inlineValue_1 = require_inlineValue();
|
|
var inlayHint_1 = require_inlayHint();
|
|
var workspaceFolder_1 = require_workspaceFolder();
|
|
var fileOperations_1 = require_fileOperations();
|
|
var inlineCompletion_1 = require_inlineCompletion();
|
|
var textDocumentContent_1 = require_textDocumentContent();
|
|
var fileSystemWatcher_1 = require_fileSystemWatcher();
|
|
var progress_1 = require_progress();
|
|
var RevealOutputChannelOn;
|
|
(function(RevealOutputChannelOn2) {
|
|
RevealOutputChannelOn2[RevealOutputChannelOn2["Debug"] = 0] = "Debug";
|
|
RevealOutputChannelOn2[RevealOutputChannelOn2["Info"] = 1] = "Info";
|
|
RevealOutputChannelOn2[RevealOutputChannelOn2["Warn"] = 2] = "Warn";
|
|
RevealOutputChannelOn2[RevealOutputChannelOn2["Error"] = 3] = "Error";
|
|
RevealOutputChannelOn2[RevealOutputChannelOn2["Never"] = 4] = "Never";
|
|
})(RevealOutputChannelOn || (exports2.RevealOutputChannelOn = RevealOutputChannelOn = {}));
|
|
var ErrorAction;
|
|
(function(ErrorAction2) {
|
|
ErrorAction2[ErrorAction2["Continue"] = 1] = "Continue";
|
|
ErrorAction2[ErrorAction2["Shutdown"] = 2] = "Shutdown";
|
|
})(ErrorAction || (exports2.ErrorAction = ErrorAction = {}));
|
|
var CloseAction;
|
|
(function(CloseAction2) {
|
|
CloseAction2[CloseAction2["DoNotRestart"] = 1] = "DoNotRestart";
|
|
CloseAction2[CloseAction2["Restart"] = 2] = "Restart";
|
|
})(CloseAction || (exports2.CloseAction = CloseAction = {}));
|
|
var State;
|
|
(function(State2) {
|
|
State2[State2["Stopped"] = 1] = "Stopped";
|
|
State2[State2["Starting"] = 3] = "Starting";
|
|
State2[State2["StartFailed"] = 4] = "StartFailed";
|
|
State2[State2["Running"] = 2] = "Running";
|
|
})(State || (exports2.State = State = {}));
|
|
var SuspendMode;
|
|
(function(SuspendMode2) {
|
|
SuspendMode2["off"] = "off";
|
|
SuspendMode2["on"] = "on";
|
|
})(SuspendMode || (exports2.SuspendMode = SuspendMode = {}));
|
|
var ResolvedClientOptions;
|
|
(function(ResolvedClientOptions2) {
|
|
function sanitizeIsTrusted(isTrusted) {
|
|
if (isTrusted === undefined || isTrusted === null) {
|
|
return false;
|
|
}
|
|
if (typeof isTrusted === "boolean" || typeof isTrusted === "object" && isTrusted !== null && Is.stringArray(isTrusted.enabledCommands)) {
|
|
return isTrusted;
|
|
}
|
|
return false;
|
|
}
|
|
ResolvedClientOptions2.sanitizeIsTrusted = sanitizeIsTrusted;
|
|
})(ResolvedClientOptions || (ResolvedClientOptions = {}));
|
|
|
|
class DefaultErrorHandler {
|
|
client;
|
|
maxRestartCount;
|
|
restarts;
|
|
constructor(client, maxRestartCount) {
|
|
this.client = client;
|
|
this.maxRestartCount = maxRestartCount;
|
|
this.restarts = [];
|
|
}
|
|
error(_error, _message, count) {
|
|
if (count && count <= 3) {
|
|
return { action: ErrorAction.Continue };
|
|
}
|
|
return { action: ErrorAction.Shutdown };
|
|
}
|
|
closed() {
|
|
this.restarts.push(Date.now());
|
|
if (this.restarts.length <= this.maxRestartCount) {
|
|
return { action: CloseAction.Restart };
|
|
} else {
|
|
const diff = this.restarts[this.restarts.length - 1] - this.restarts[0];
|
|
if (diff <= 3 * 60 * 1000) {
|
|
return { action: CloseAction.DoNotRestart, message: `The ${this.client.name} server crashed ${this.maxRestartCount + 1} times in the last 3 minutes. The server will not be restarted. See the output for more information.` };
|
|
} else {
|
|
this.restarts.shift();
|
|
return { action: CloseAction.Restart };
|
|
}
|
|
}
|
|
}
|
|
}
|
|
var ClientState;
|
|
(function(ClientState2) {
|
|
ClientState2["Initial"] = "initial";
|
|
ClientState2["Starting"] = "starting";
|
|
ClientState2["StartFailed"] = "startFailed";
|
|
ClientState2["Running"] = "running";
|
|
ClientState2["Stopping"] = "stopping";
|
|
ClientState2["Stopped"] = "stopped";
|
|
})(ClientState || (ClientState = {}));
|
|
var MessageTransports;
|
|
(function(MessageTransports2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && vscode_languageserver_protocol_1.MessageReader.is(value.reader) && vscode_languageserver_protocol_1.MessageWriter.is(value.writer);
|
|
}
|
|
MessageTransports2.is = is;
|
|
})(MessageTransports || (exports2.MessageTransports = MessageTransports = {}));
|
|
var ShutdownMode;
|
|
(function(ShutdownMode2) {
|
|
ShutdownMode2["Restart"] = "restart";
|
|
ShutdownMode2["Stop"] = "stop";
|
|
})(ShutdownMode || (exports2.ShutdownMode = ShutdownMode = {}));
|
|
|
|
class VisibleDocumentsImpl {
|
|
open;
|
|
_onOpen;
|
|
_onClose;
|
|
disposables;
|
|
constructor() {
|
|
this.disposables = [];
|
|
this.open = new Set;
|
|
this._onOpen = new vscode_1.EventEmitter;
|
|
this._onClose = new vscode_1.EventEmitter;
|
|
VisibleDocumentsImpl.fillVisibleResources(this.open);
|
|
const updateVisibleDocuments = () => {
|
|
const oldTabs = this.open;
|
|
const currentTabs = new Set;
|
|
VisibleDocumentsImpl.fillVisibleResources(currentTabs);
|
|
const closed = new Set;
|
|
const opened = new Set(currentTabs);
|
|
for (const tab of oldTabs.values()) {
|
|
if (currentTabs.has(tab)) {
|
|
opened.delete(tab);
|
|
} else {
|
|
closed.add(tab);
|
|
}
|
|
}
|
|
this.open = currentTabs;
|
|
if (closed.size > 0) {
|
|
const toFire = new Set;
|
|
for (const item of closed) {
|
|
toFire.add(vscode_1.Uri.parse(item));
|
|
}
|
|
this._onClose.fire(toFire);
|
|
}
|
|
if (opened.size > 0) {
|
|
const toFire = new Set;
|
|
for (const item of opened) {
|
|
toFire.add(vscode_1.Uri.parse(item));
|
|
}
|
|
this._onOpen.fire(toFire);
|
|
}
|
|
};
|
|
this.disposables.push(vscode_1.window.tabGroups.onDidChangeTabs((event) => {
|
|
if (event.closed.length === 0 && event.opened.length === 0) {
|
|
return;
|
|
}
|
|
updateVisibleDocuments();
|
|
}));
|
|
this.disposables.push(vscode_1.window.onDidChangeVisibleTextEditors((_editors) => {
|
|
updateVisibleDocuments();
|
|
}));
|
|
}
|
|
get onClose() {
|
|
return this._onClose.event;
|
|
}
|
|
get onOpen() {
|
|
return this._onOpen.event;
|
|
}
|
|
dispose() {
|
|
this.disposables.forEach((disposable) => disposable.dispose());
|
|
}
|
|
isActive(document) {
|
|
return document instanceof vscode_1.Uri ? vscode_1.window.activeTextEditor?.document.uri === document : vscode_1.window.activeTextEditor?.document === document;
|
|
}
|
|
isVisible(document) {
|
|
const uri = document instanceof vscode_1.Uri ? document : document.uri;
|
|
if (uri.scheme === notebook_1.NotebookDocumentSyncFeature.CellScheme) {
|
|
return vscode_1.workspace.notebookDocuments.some((notebook) => {
|
|
if (this.open.has(notebook.uri.toString())) {
|
|
const cell = notebook.getCells().find((cell2) => cell2.document.uri.toString() === uri.toString());
|
|
return cell !== undefined;
|
|
}
|
|
return false;
|
|
});
|
|
}
|
|
return this.open.has(uri.toString());
|
|
}
|
|
getResources() {
|
|
const result = new Set;
|
|
VisibleDocumentsImpl.fillVisibleResources(new Set, result);
|
|
return result;
|
|
}
|
|
static fillVisibleResources(strings, uris) {
|
|
const seen = strings ?? new Set;
|
|
for (const group of vscode_1.window.tabGroups.all) {
|
|
for (const tab of group.tabs) {
|
|
const input = tab.input;
|
|
let uri;
|
|
if (input instanceof vscode_1.TabInputText) {
|
|
uri = input.uri;
|
|
} else if (input instanceof vscode_1.TabInputTextDiff) {
|
|
uri = input.modified;
|
|
} else if (input instanceof vscode_1.TabInputCustom) {
|
|
uri = input.uri;
|
|
} else if (input instanceof vscode_1.TabInputNotebook) {
|
|
uri = input.uri;
|
|
}
|
|
if (uri !== undefined && !seen.has(uri.toString())) {
|
|
seen.add(uri.toString());
|
|
uris !== undefined && uris.add(uri);
|
|
}
|
|
}
|
|
}
|
|
for (const editor of vscode_1.window.visibleTextEditors) {
|
|
const uri = editor.document.uri;
|
|
if (!seen.has(uri.toString())) {
|
|
seen.add(uri.toString());
|
|
uris !== undefined && uris.add(uri);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
class BaseLanguageClient {
|
|
_id;
|
|
_name;
|
|
_clientOptions;
|
|
_state;
|
|
_onStart;
|
|
_onStop;
|
|
_connection;
|
|
_idleInterval;
|
|
_ignoredRegistrations;
|
|
_listeners;
|
|
_disposed;
|
|
_notificationHandlers;
|
|
_notificationDisposables;
|
|
_pendingNotificationHandlers;
|
|
_requestHandlers;
|
|
_requestDisposables;
|
|
_pendingRequestHandlers;
|
|
_progressHandlers;
|
|
_pendingProgressHandlers;
|
|
_progressDisposables;
|
|
_initializeResult;
|
|
_outputChannel;
|
|
_disposeOutputChannel;
|
|
_traceOutputChannel;
|
|
_traceLogLevel;
|
|
_capabilities;
|
|
_diagnostics;
|
|
_syncedDocuments;
|
|
_didChangeTextDocumentFeature;
|
|
_inFlightOpenNotifications;
|
|
_pendingChangeSemaphore;
|
|
_pendingChangeDelayer;
|
|
_didOpenTextDocumentFeature;
|
|
_fileEvents;
|
|
_fileEventDelayer;
|
|
_telemetryEmitter;
|
|
_stateChangeEmitter;
|
|
_trace;
|
|
_traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text;
|
|
_tracer;
|
|
_c2p;
|
|
_p2c;
|
|
_visibleDocuments;
|
|
constructor(id, name, clientOptions) {
|
|
this._id = id;
|
|
this._name = name;
|
|
clientOptions = clientOptions || {};
|
|
const markdown = {
|
|
isTrusted: false,
|
|
supportHtml: false,
|
|
supportThemeIcons: false
|
|
};
|
|
if (clientOptions.markdown !== undefined) {
|
|
markdown.isTrusted = ResolvedClientOptions.sanitizeIsTrusted(clientOptions.markdown.isTrusted);
|
|
markdown.supportHtml = clientOptions.markdown.supportHtml === true;
|
|
markdown.supportThemeIcons = clientOptions.markdown.supportThemeIcons === true;
|
|
}
|
|
this._clientOptions = {
|
|
documentSelector: clientOptions.documentSelector ?? [],
|
|
synchronize: clientOptions.synchronize ?? {},
|
|
diagnosticCollectionName: clientOptions.diagnosticCollectionName,
|
|
outputChannelName: clientOptions.outputChannelName ?? this._name,
|
|
revealOutputChannelOn: clientOptions.revealOutputChannelOn ?? RevealOutputChannelOn.Error,
|
|
stdioEncoding: clientOptions.stdioEncoding ?? "utf8",
|
|
initializationOptions: clientOptions.initializationOptions,
|
|
initializationFailedHandler: clientOptions.initializationFailedHandler,
|
|
progressOnInitialization: !!clientOptions.progressOnInitialization,
|
|
errorHandler: clientOptions.errorHandler ?? this.createDefaultErrorHandler(clientOptions.connectionOptions?.maxRestartCount),
|
|
middleware: clientOptions.middleware ?? {},
|
|
uriConverters: clientOptions.uriConverters,
|
|
workspaceFolder: clientOptions.workspaceFolder,
|
|
connectionOptions: clientOptions.connectionOptions,
|
|
markdown,
|
|
diagnosticPullOptions: clientOptions.diagnosticPullOptions ?? { onChange: true, onSave: false },
|
|
diagnosticCollectionProvider: clientOptions.diagnosticCollectionProvider ?? new features_1.DefaultDiagnosticCollectionProvider,
|
|
notebookDocumentOptions: clientOptions.notebookDocumentOptions ?? {},
|
|
textSynchronization: this.createTextSynchronizationOptions(clientOptions.textSynchronization)
|
|
};
|
|
this._clientOptions.synchronize = this._clientOptions.synchronize || {};
|
|
this._state = ClientState.Initial;
|
|
this._ignoredRegistrations = new Set;
|
|
this._listeners = [];
|
|
this._notificationHandlers = new Map;
|
|
this._pendingNotificationHandlers = new Map;
|
|
this._notificationDisposables = new Map;
|
|
this._requestHandlers = new Map;
|
|
this._pendingRequestHandlers = new Map;
|
|
this._requestDisposables = new Map;
|
|
this._progressHandlers = new Map;
|
|
this._pendingProgressHandlers = new Map;
|
|
this._progressDisposables = new Map;
|
|
this._connection = undefined;
|
|
this._initializeResult = undefined;
|
|
if (clientOptions.outputChannel) {
|
|
this._outputChannel = clientOptions.outputChannel;
|
|
this._disposeOutputChannel = false;
|
|
this._traceLogLevel = this._outputChannel.logLevel;
|
|
} else {
|
|
this._outputChannel = undefined;
|
|
this._disposeOutputChannel = true;
|
|
this._traceLogLevel = vscode_1.LogLevel.Info;
|
|
}
|
|
this._traceOutputChannel = clientOptions.traceOutputChannel;
|
|
if (this._traceOutputChannel !== undefined) {
|
|
this._traceLogLevel = this._traceOutputChannel.logLevel;
|
|
}
|
|
this._diagnostics = undefined;
|
|
this._inFlightOpenNotifications = new Set;
|
|
this._pendingChangeSemaphore = new async_1.Semaphore(1);
|
|
this._pendingChangeDelayer = new async_1.Delayer(250);
|
|
this._fileEvents = [];
|
|
this._fileEventDelayer = new async_1.Delayer(250);
|
|
this._onStop = undefined;
|
|
this._telemetryEmitter = new vscode_languageserver_protocol_1.Emitter;
|
|
this._stateChangeEmitter = new vscode_languageserver_protocol_1.Emitter;
|
|
this._trace = vscode_languageserver_protocol_1.Trace.Off;
|
|
this._tracer = {
|
|
log: (messageOrDataObject, data) => {
|
|
if (Is.string(messageOrDataObject)) {
|
|
this.trace(messageOrDataObject, data);
|
|
} else {
|
|
this.traceObject(messageOrDataObject);
|
|
}
|
|
}
|
|
};
|
|
this._c2p = c2p.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.code2Protocol : undefined);
|
|
this._p2c = p2c.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.protocol2Code : undefined, this._clientOptions.markdown.isTrusted, this._clientOptions.markdown.supportHtml, this._clientOptions.markdown.supportThemeIcons);
|
|
this._syncedDocuments = new Map;
|
|
this.registerBuiltinFeatures();
|
|
}
|
|
createTextSynchronizationOptions(options) {
|
|
if (!options) {
|
|
return { delayOpenNotifications: false };
|
|
}
|
|
if (typeof options.delayOpenNotifications === "boolean") {
|
|
return { delayOpenNotifications: options.delayOpenNotifications };
|
|
}
|
|
return { delayOpenNotifications: false };
|
|
}
|
|
get name() {
|
|
return this._name;
|
|
}
|
|
get middleware() {
|
|
return this._clientOptions.middleware ?? Object.create(null);
|
|
}
|
|
get clientOptions() {
|
|
return this._clientOptions;
|
|
}
|
|
get protocol2CodeConverter() {
|
|
return this._p2c;
|
|
}
|
|
get code2ProtocolConverter() {
|
|
return this._c2p;
|
|
}
|
|
get visibleDocuments() {
|
|
if (this._visibleDocuments === undefined) {
|
|
this._visibleDocuments = new VisibleDocumentsImpl;
|
|
}
|
|
return this._visibleDocuments;
|
|
}
|
|
get onTelemetry() {
|
|
return this._telemetryEmitter.event;
|
|
}
|
|
get onDidChangeState() {
|
|
return this._stateChangeEmitter.event;
|
|
}
|
|
get outputChannel() {
|
|
if (!this._outputChannel) {
|
|
this._outputChannel = vscode_1.window.createOutputChannel(this._clientOptions.outputChannelName ? this._clientOptions.outputChannelName : this._name, { log: true });
|
|
if (this._traceOutputChannel === undefined) {
|
|
this._traceLogLevel = this._outputChannel.logLevel;
|
|
}
|
|
}
|
|
return this._outputChannel;
|
|
}
|
|
get traceOutputChannel() {
|
|
return this._traceOutputChannel ? this._traceOutputChannel : this.outputChannel;
|
|
}
|
|
get diagnostics() {
|
|
if (this._diagnostics === null) {
|
|
return;
|
|
}
|
|
if (this._diagnostics === undefined) {
|
|
this._diagnostics = this._clientOptions.diagnosticCollectionProvider.create(this._clientOptions.diagnosticCollectionName ?? this._id, features_1.DiagnosticCollectionSource.push);
|
|
}
|
|
return this._diagnostics;
|
|
}
|
|
get state() {
|
|
return this.getPublicState();
|
|
}
|
|
get $state() {
|
|
return this._state;
|
|
}
|
|
set $state(value) {
|
|
const oldState = this.getPublicState();
|
|
this._state = value;
|
|
const newState = this.getPublicState();
|
|
if (newState !== oldState) {
|
|
this._stateChangeEmitter.fire({ oldState, newState });
|
|
}
|
|
}
|
|
getPublicState() {
|
|
switch (this.$state) {
|
|
case ClientState.Starting:
|
|
return State.Starting;
|
|
case ClientState.Running:
|
|
return State.Running;
|
|
case ClientState.StartFailed:
|
|
return State.StartFailed;
|
|
default:
|
|
return State.Stopped;
|
|
}
|
|
}
|
|
get initializeResult() {
|
|
return this._initializeResult;
|
|
}
|
|
async sendRequest(type, ...params) {
|
|
if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) {
|
|
return Promise.reject(new vscode_languageserver_protocol_1.ResponseError(vscode_languageserver_protocol_1.ErrorCodes.ConnectionInactive, `Client is not running`));
|
|
}
|
|
const connection = await this.$start();
|
|
await this._didOpenTextDocumentFeature.sendPendingOpenNotifications();
|
|
if (this._didChangeTextDocumentFeature.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) {
|
|
await this.sendPendingFullTextDocumentChanges(connection);
|
|
}
|
|
let param = undefined;
|
|
let token = undefined;
|
|
if (params.length === 1) {
|
|
if (vscode_languageserver_protocol_1.CancellationToken.is(params[0])) {
|
|
token = params[0];
|
|
} else {
|
|
param = params[0];
|
|
}
|
|
} else if (params.length === 2) {
|
|
param = params[0];
|
|
token = params[1];
|
|
}
|
|
if (token !== undefined && token.isCancellationRequested) {
|
|
return Promise.reject(new vscode_languageserver_protocol_1.ResponseError(vscode_languageserver_protocol_1.LSPErrorCodes.RequestCancelled, "Request got cancelled"));
|
|
}
|
|
const _sendRequest = this._clientOptions.middleware?.sendRequest;
|
|
if (_sendRequest !== undefined) {
|
|
return _sendRequest(type, param, token, (type2, param2, token2) => {
|
|
const params2 = [];
|
|
if (param2 !== undefined) {
|
|
params2.push(param2);
|
|
}
|
|
if (token2 !== undefined) {
|
|
params2.push(token2);
|
|
}
|
|
return connection.sendRequest(type2, ...params2);
|
|
});
|
|
} else {
|
|
return connection.sendRequest(type, ...params);
|
|
}
|
|
}
|
|
onRequest(type, handler) {
|
|
const method = typeof type === "string" ? type : type.method;
|
|
this._requestHandlers.set(method, handler);
|
|
const connection = this.activeConnection();
|
|
let disposable;
|
|
if (connection !== undefined) {
|
|
this._requestDisposables.set(method, connection.onRequest(type, handler));
|
|
disposable = {
|
|
dispose: () => {
|
|
const disposable2 = this._requestDisposables.get(method);
|
|
if (disposable2 !== undefined) {
|
|
disposable2.dispose();
|
|
this._requestDisposables.delete(method);
|
|
}
|
|
}
|
|
};
|
|
} else {
|
|
this._pendingRequestHandlers.set(method, handler);
|
|
disposable = {
|
|
dispose: () => {
|
|
this._pendingRequestHandlers.delete(method);
|
|
const disposable2 = this._requestDisposables.get(method);
|
|
if (disposable2 !== undefined) {
|
|
disposable2.dispose();
|
|
this._requestDisposables.delete(method);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
return {
|
|
dispose: () => {
|
|
this._requestHandlers.delete(method);
|
|
disposable.dispose();
|
|
}
|
|
};
|
|
}
|
|
async sendNotification(type, params) {
|
|
if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) {
|
|
return Promise.reject(new vscode_languageserver_protocol_1.ResponseError(vscode_languageserver_protocol_1.ErrorCodes.ConnectionInactive, `Client is not running`));
|
|
}
|
|
const needsPendingFullTextDocumentSync = this._didChangeTextDocumentFeature.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full;
|
|
let openNotification;
|
|
if (needsPendingFullTextDocumentSync && typeof type !== "string" && type.method === vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.method) {
|
|
openNotification = params?.textDocument.uri;
|
|
this._inFlightOpenNotifications.add(openNotification);
|
|
}
|
|
let documentToClose;
|
|
if (typeof type !== "string" && type.method === vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.method) {
|
|
documentToClose = params.textDocument.uri;
|
|
}
|
|
const connection = await this.$start();
|
|
const didDropOpenNotification = await this._didOpenTextDocumentFeature.sendPendingOpenNotifications(documentToClose);
|
|
if (didDropOpenNotification) {
|
|
return;
|
|
}
|
|
if (needsPendingFullTextDocumentSync) {
|
|
await this.sendPendingFullTextDocumentChanges(connection);
|
|
}
|
|
if (openNotification !== undefined) {
|
|
this._inFlightOpenNotifications.delete(openNotification);
|
|
}
|
|
const _sendNotification = this._clientOptions.middleware?.sendNotification;
|
|
return _sendNotification ? _sendNotification(type, connection.sendNotification.bind(connection), params) : connection.sendNotification(type, params);
|
|
}
|
|
onNotification(type, handler) {
|
|
const method = typeof type === "string" ? type : type.method;
|
|
this._notificationHandlers.set(method, handler);
|
|
const connection = this.activeConnection();
|
|
let disposable;
|
|
if (connection !== undefined) {
|
|
this._notificationDisposables.set(method, connection.onNotification(type, handler));
|
|
disposable = {
|
|
dispose: () => {
|
|
const disposable2 = this._notificationDisposables.get(method);
|
|
if (disposable2 !== undefined) {
|
|
disposable2.dispose();
|
|
this._notificationDisposables.delete(method);
|
|
}
|
|
}
|
|
};
|
|
} else {
|
|
this._pendingNotificationHandlers.set(method, handler);
|
|
disposable = {
|
|
dispose: () => {
|
|
this._pendingNotificationHandlers.delete(method);
|
|
const disposable2 = this._notificationDisposables.get(method);
|
|
if (disposable2 !== undefined) {
|
|
disposable2.dispose();
|
|
this._notificationDisposables.delete(method);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
return {
|
|
dispose: () => {
|
|
this._notificationHandlers.delete(method);
|
|
disposable.dispose();
|
|
}
|
|
};
|
|
}
|
|
async sendProgress(type, token, value) {
|
|
if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) {
|
|
return Promise.reject(new vscode_languageserver_protocol_1.ResponseError(vscode_languageserver_protocol_1.ErrorCodes.ConnectionInactive, `Client is not running`));
|
|
}
|
|
try {
|
|
const connection = await this.$start();
|
|
return connection.sendProgress(type, token, value);
|
|
} catch (error) {
|
|
this.error(`Sending progress for token ${token} failed.`, error);
|
|
throw error;
|
|
}
|
|
}
|
|
onProgress(type, token, handler) {
|
|
this._progressHandlers.set(token, { type, handler });
|
|
const connection = this.activeConnection();
|
|
let disposable;
|
|
const handleWorkDoneProgress = this._clientOptions.middleware?.handleWorkDoneProgress;
|
|
const realHandler = vscode_languageserver_protocol_1.WorkDoneProgress.is(type) && handleWorkDoneProgress !== undefined ? (params) => {
|
|
handleWorkDoneProgress(token, params, () => handler(params));
|
|
} : handler;
|
|
if (connection !== undefined) {
|
|
this._progressDisposables.set(token, connection.onProgress(type, token, realHandler));
|
|
disposable = {
|
|
dispose: () => {
|
|
const disposable2 = this._progressDisposables.get(token);
|
|
if (disposable2 !== undefined) {
|
|
disposable2.dispose();
|
|
this._progressDisposables.delete(token);
|
|
}
|
|
}
|
|
};
|
|
} else {
|
|
this._pendingProgressHandlers.set(token, { type, handler });
|
|
disposable = {
|
|
dispose: () => {
|
|
this._pendingProgressHandlers.delete(token);
|
|
const disposable2 = this._progressDisposables.get(token);
|
|
if (disposable2 !== undefined) {
|
|
disposable2.dispose();
|
|
this._progressDisposables.delete(token);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
return {
|
|
dispose: () => {
|
|
this._progressHandlers.delete(token);
|
|
disposable.dispose();
|
|
}
|
|
};
|
|
}
|
|
createDefaultErrorHandler(maxRestartCount) {
|
|
if (maxRestartCount !== undefined && maxRestartCount < 0) {
|
|
throw new Error(`Invalid maxRestartCount: ${maxRestartCount}`);
|
|
}
|
|
return new DefaultErrorHandler(this, maxRestartCount ?? 4);
|
|
}
|
|
async setTrace(value) {
|
|
this._trace = value;
|
|
const connection = this.activeConnection();
|
|
if (connection !== undefined) {
|
|
await connection.trace(this._trace, this._tracer, {
|
|
sendNotification: false,
|
|
traceFormat: this._traceFormat
|
|
});
|
|
}
|
|
}
|
|
data2String(data) {
|
|
if (data instanceof vscode_languageserver_protocol_1.ResponseError) {
|
|
const responseError = data;
|
|
return ` Message: ${responseError.message}
|
|
Code: ${responseError.code} ${responseError.data ? `
|
|
` + responseError.data.toString() : ""}`;
|
|
}
|
|
if (data instanceof Error) {
|
|
if (Is.string(data.stack)) {
|
|
return data.stack;
|
|
}
|
|
return data.message;
|
|
}
|
|
if (Is.string(data)) {
|
|
return data;
|
|
}
|
|
return data.toString();
|
|
}
|
|
shouldLogToOutputChannel() {
|
|
if (this.$state !== ClientState.Stopped) {
|
|
return true;
|
|
}
|
|
return this._outputChannel !== undefined;
|
|
}
|
|
error(message, data, showNotification = true) {
|
|
if (this.shouldLogToOutputChannel()) {
|
|
this.outputChannel.error(this.getLogMessage(message, data));
|
|
}
|
|
if (showNotification === "force" || showNotification && this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Error) {
|
|
this.showNotificationMessage(vscode_languageserver_protocol_1.MessageType.Error, message, data);
|
|
}
|
|
}
|
|
warn(message, data, showNotification = true) {
|
|
if (this.shouldLogToOutputChannel()) {
|
|
this.outputChannel.warn(this.getLogMessage(message, data));
|
|
}
|
|
if (showNotification && this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Warn) {
|
|
this.showNotificationMessage(vscode_languageserver_protocol_1.MessageType.Warning, message, data);
|
|
}
|
|
}
|
|
info(message, data, showNotification = true) {
|
|
if (this.shouldLogToOutputChannel()) {
|
|
this.outputChannel.info(this.getLogMessage(message, data));
|
|
}
|
|
if (showNotification && this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Info) {
|
|
this.showNotificationMessage(vscode_languageserver_protocol_1.MessageType.Info, message, data);
|
|
}
|
|
}
|
|
debug(message, data, showNotification = true) {
|
|
if (this.shouldLogToOutputChannel()) {
|
|
this.outputChannel.debug(this.getLogMessage(message, data));
|
|
}
|
|
if (showNotification && this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Debug) {
|
|
this.showNotificationMessage(vscode_languageserver_protocol_1.MessageType.Debug, message, data);
|
|
}
|
|
}
|
|
trace(message, data) {
|
|
this.traceOutputChannel.trace(this.getLogMessage(message, data));
|
|
}
|
|
traceObject(data) {
|
|
this.traceOutputChannel.trace(JSON.stringify(data));
|
|
}
|
|
showNotificationMessage(type, message, data) {
|
|
message = message ?? "A request has failed. See the output for more information.";
|
|
if (data) {
|
|
message += `
|
|
` + this.data2String(data);
|
|
}
|
|
const messageFunc = type === vscode_languageserver_protocol_1.MessageType.Error ? vscode_1.window.showErrorMessage : type === vscode_languageserver_protocol_1.MessageType.Warning ? vscode_1.window.showWarningMessage : vscode_1.window.showInformationMessage;
|
|
messageFunc(message, "Go to output").then((selection) => {
|
|
if (selection !== undefined) {
|
|
this.outputChannel.show(true);
|
|
}
|
|
});
|
|
}
|
|
getLogMessage(message, data) {
|
|
return data !== null && data !== undefined ? `${message}
|
|
${this.data2String(data)}` : message;
|
|
}
|
|
needsStart() {
|
|
return this.$state === ClientState.Initial || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped;
|
|
}
|
|
needsStop() {
|
|
return this.$state === ClientState.Starting || this.$state === ClientState.Running;
|
|
}
|
|
activeConnection() {
|
|
return this.$state === ClientState.Running && this._connection !== undefined ? this._connection : undefined;
|
|
}
|
|
isRunning() {
|
|
return this.$state === ClientState.Running;
|
|
}
|
|
async start() {
|
|
if (this._disposed === "disposing" || this._disposed === "disposed") {
|
|
throw new Error(`Client got disposed and can't be restarted.`);
|
|
}
|
|
if (this.$state === ClientState.Stopping) {
|
|
throw new Error(`Client is currently stopping. Can only restart a full stopped client`);
|
|
}
|
|
if (this._onStart !== undefined) {
|
|
return this._onStart;
|
|
}
|
|
const [promise, resolve, reject] = this.createOnStartPromise();
|
|
this._onStart = promise;
|
|
this._diagnostics = undefined;
|
|
for (const [method, handler] of this._notificationHandlers) {
|
|
if (!this._pendingNotificationHandlers.has(method)) {
|
|
this._pendingNotificationHandlers.set(method, handler);
|
|
}
|
|
}
|
|
for (const [method, handler] of this._requestHandlers) {
|
|
if (!this._pendingRequestHandlers.has(method)) {
|
|
this._pendingRequestHandlers.set(method, handler);
|
|
}
|
|
}
|
|
for (const [token, data] of this._progressHandlers) {
|
|
if (!this._pendingProgressHandlers.has(token)) {
|
|
this._pendingProgressHandlers.set(token, data);
|
|
}
|
|
}
|
|
this.$state = ClientState.Starting;
|
|
try {
|
|
const connection = await this.createConnection();
|
|
connection.onNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, (message) => {
|
|
switch (message.type) {
|
|
case vscode_languageserver_protocol_1.MessageType.Error:
|
|
this.error(message.message, undefined, false);
|
|
break;
|
|
case vscode_languageserver_protocol_1.MessageType.Warning:
|
|
this.warn(message.message, undefined, false);
|
|
break;
|
|
case vscode_languageserver_protocol_1.MessageType.Info:
|
|
this.info(message.message, undefined, false);
|
|
break;
|
|
case vscode_languageserver_protocol_1.MessageType.Debug:
|
|
this.debug(message.message, undefined, false);
|
|
break;
|
|
default:
|
|
this.outputChannel.appendLine(message.message);
|
|
}
|
|
});
|
|
connection.onNotification(vscode_languageserver_protocol_1.ShowMessageNotification.type, (message) => {
|
|
switch (message.type) {
|
|
case vscode_languageserver_protocol_1.MessageType.Error:
|
|
vscode_1.window.showErrorMessage(message.message);
|
|
break;
|
|
case vscode_languageserver_protocol_1.MessageType.Warning:
|
|
vscode_1.window.showWarningMessage(message.message);
|
|
break;
|
|
case vscode_languageserver_protocol_1.MessageType.Info:
|
|
vscode_1.window.showInformationMessage(message.message);
|
|
break;
|
|
default:
|
|
vscode_1.window.showInformationMessage(message.message);
|
|
}
|
|
});
|
|
connection.onRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, (params) => {
|
|
let messageFunc;
|
|
switch (params.type) {
|
|
case vscode_languageserver_protocol_1.MessageType.Error:
|
|
messageFunc = vscode_1.window.showErrorMessage;
|
|
break;
|
|
case vscode_languageserver_protocol_1.MessageType.Warning:
|
|
messageFunc = vscode_1.window.showWarningMessage;
|
|
break;
|
|
case vscode_languageserver_protocol_1.MessageType.Info:
|
|
messageFunc = vscode_1.window.showInformationMessage;
|
|
break;
|
|
default:
|
|
messageFunc = vscode_1.window.showInformationMessage;
|
|
}
|
|
const actions = params.actions || [];
|
|
return messageFunc(params.message, ...actions);
|
|
});
|
|
connection.onNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, (data) => {
|
|
this._telemetryEmitter.fire(data);
|
|
});
|
|
connection.onRequest(vscode_languageserver_protocol_1.ShowDocumentRequest.type, async (params, token) => {
|
|
const showDocument = async (params2) => {
|
|
const uri = this.protocol2CodeConverter.asUri(params2.uri);
|
|
try {
|
|
if (params2.external === true) {
|
|
const success = await vscode_1.env.openExternal(uri);
|
|
return { success };
|
|
} else {
|
|
const options = {};
|
|
if (params2.selection !== undefined) {
|
|
options.selection = this.protocol2CodeConverter.asRange(params2.selection);
|
|
}
|
|
if (params2.takeFocus === undefined || params2.takeFocus === false) {
|
|
options.preserveFocus = true;
|
|
} else if (params2.takeFocus === true) {
|
|
options.preserveFocus = false;
|
|
}
|
|
await vscode_1.window.showTextDocument(uri, options);
|
|
return { success: true };
|
|
}
|
|
} catch (error) {
|
|
return { success: false };
|
|
}
|
|
};
|
|
const middleware = this._clientOptions.middleware.window?.showDocument;
|
|
if (middleware !== undefined) {
|
|
return middleware(params, token, showDocument);
|
|
} else {
|
|
return showDocument(params);
|
|
}
|
|
});
|
|
connection.listen();
|
|
await this.initialize(connection);
|
|
resolve();
|
|
} catch (error) {
|
|
this.$state = ClientState.StartFailed;
|
|
this.error(`${this._name} client: couldn't create connection to server.`, error, "force");
|
|
reject(error);
|
|
}
|
|
return this._onStart;
|
|
}
|
|
createOnStartPromise() {
|
|
let resolve;
|
|
let reject;
|
|
const promise = new Promise((_resolve, _reject) => {
|
|
resolve = _resolve;
|
|
reject = _reject;
|
|
});
|
|
return [promise, resolve, reject];
|
|
}
|
|
async initialize(connection) {
|
|
this.refreshTrace(connection, false);
|
|
const initOption = this._clientOptions.initializationOptions;
|
|
const [rootPath, workspaceFolders] = this._clientOptions.workspaceFolder !== undefined ? [this._clientOptions.workspaceFolder.uri.fsPath, [{ uri: this._c2p.asUri(this._clientOptions.workspaceFolder.uri), name: this._clientOptions.workspaceFolder.name }]] : [this._clientGetRootPath(), null];
|
|
const initParams = {
|
|
processId: null,
|
|
clientInfo: {
|
|
name: vscode_1.env.appName,
|
|
version: vscode_1.version
|
|
},
|
|
locale: this.getLocale(),
|
|
rootPath: rootPath ? rootPath : null,
|
|
rootUri: rootPath ? this._c2p.asUri(vscode_1.Uri.file(rootPath)) : null,
|
|
capabilities: this.computeClientCapabilities(),
|
|
initializationOptions: Is.func(initOption) ? initOption() : initOption,
|
|
trace: vscode_languageserver_protocol_1.Trace.toString(this._trace),
|
|
workspaceFolders
|
|
};
|
|
this.fillInitializeParams(initParams);
|
|
if (this._clientOptions.progressOnInitialization) {
|
|
const token = UUID.generateUuid();
|
|
const part = new progressPart_1.ProgressPart(connection, token);
|
|
initParams.workDoneToken = token;
|
|
try {
|
|
const result = await this.doInitialize(connection, initParams);
|
|
part.done();
|
|
return result;
|
|
} catch (error) {
|
|
part.cancel();
|
|
throw error;
|
|
}
|
|
} else {
|
|
return this.doInitialize(connection, initParams);
|
|
}
|
|
}
|
|
async doInitialize(connection, initParams) {
|
|
try {
|
|
const result = await connection.initialize(initParams);
|
|
if (result.capabilities.positionEncoding !== undefined && result.capabilities.positionEncoding !== vscode_languageserver_protocol_1.PositionEncodingKind.UTF16) {
|
|
throw new Error(`Unsupported position encoding (${result.capabilities.positionEncoding}) received from server ${this.name}`);
|
|
}
|
|
this._initializeResult = result;
|
|
this.$state = ClientState.Running;
|
|
let textDocumentSyncOptions = undefined;
|
|
if (Is.number(result.capabilities.textDocumentSync)) {
|
|
if (result.capabilities.textDocumentSync === vscode_languageserver_protocol_1.TextDocumentSyncKind.None) {
|
|
textDocumentSyncOptions = {
|
|
openClose: false,
|
|
change: vscode_languageserver_protocol_1.TextDocumentSyncKind.None,
|
|
save: undefined
|
|
};
|
|
} else {
|
|
textDocumentSyncOptions = {
|
|
openClose: true,
|
|
change: result.capabilities.textDocumentSync,
|
|
save: {
|
|
includeText: false
|
|
}
|
|
};
|
|
}
|
|
} else if (result.capabilities.textDocumentSync !== undefined && result.capabilities.textDocumentSync !== null) {
|
|
textDocumentSyncOptions = result.capabilities.textDocumentSync;
|
|
}
|
|
this._capabilities = Object.assign({}, result.capabilities, { resolvedTextDocumentSync: textDocumentSyncOptions });
|
|
connection.onNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, (params) => this.handleDiagnostics(params));
|
|
connection.onRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, (params) => this.handleRegistrationRequest(params));
|
|
connection.onRequest("client/registerFeature", (params) => this.handleRegistrationRequest(params));
|
|
connection.onRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, (params) => this.handleUnregistrationRequest(params));
|
|
connection.onRequest("client/unregisterFeature", (params) => this.handleUnregistrationRequest(params));
|
|
connection.onRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, (params) => this.handleApplyWorkspaceEdit(params));
|
|
for (const [method, handler] of this._pendingNotificationHandlers) {
|
|
this._notificationDisposables.set(method, connection.onNotification(method, handler));
|
|
}
|
|
this._pendingNotificationHandlers.clear();
|
|
for (const [method, handler] of this._pendingRequestHandlers) {
|
|
this._requestDisposables.set(method, connection.onRequest(method, handler));
|
|
}
|
|
this._pendingRequestHandlers.clear();
|
|
for (const [token, data] of this._pendingProgressHandlers) {
|
|
this._progressDisposables.set(token, connection.onProgress(data.type, token, data.handler));
|
|
}
|
|
this._pendingProgressHandlers.clear();
|
|
await connection.sendNotification(vscode_languageserver_protocol_1.InitializedNotification.type, {});
|
|
this.hookFileEvents(connection);
|
|
this.hookLogLevelChanged(connection);
|
|
this.hookConfigurationChanged(connection);
|
|
this.initializeFeatures(connection);
|
|
return result;
|
|
} catch (error) {
|
|
if (this._clientOptions.initializationFailedHandler) {
|
|
if (this._clientOptions.initializationFailedHandler(error)) {
|
|
this.initialize(connection);
|
|
} else {
|
|
this.stop();
|
|
}
|
|
} else if (error instanceof vscode_languageserver_protocol_1.ResponseError && error.data && error.data.retry) {
|
|
vscode_1.window.showErrorMessage(error.message, { title: "Retry", id: "retry" }).then((item) => {
|
|
if (item && item.id === "retry") {
|
|
this.initialize(connection);
|
|
} else {
|
|
this.stop();
|
|
}
|
|
});
|
|
} else {
|
|
if (error && error.message) {
|
|
vscode_1.window.showErrorMessage(error.message);
|
|
}
|
|
this.error("Server initialization failed.", error);
|
|
this.stop();
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
_clientGetRootPath() {
|
|
const folders = vscode_1.workspace.workspaceFolders;
|
|
if (!folders || folders.length === 0) {
|
|
return;
|
|
}
|
|
const folder = folders[0];
|
|
if (folder.uri.scheme === "file") {
|
|
return folder.uri.fsPath;
|
|
}
|
|
return;
|
|
}
|
|
stop(timeout = 2000) {
|
|
return this.shutdown(ShutdownMode.Stop, timeout);
|
|
}
|
|
dispose(timeout = 2000) {
|
|
try {
|
|
this._disposed = "disposing";
|
|
return this.stop(timeout);
|
|
} finally {
|
|
this._disposed = "disposed";
|
|
}
|
|
}
|
|
async shutdown(mode, timeout = 2000) {
|
|
if (this.$state === ClientState.Stopped || this.$state === ClientState.Initial) {
|
|
return;
|
|
}
|
|
if (this.$state === ClientState.Stopping) {
|
|
if (this._onStop !== undefined) {
|
|
return this._onStop;
|
|
} else {
|
|
throw new Error(`Client is stopping but no stop promise available.`);
|
|
}
|
|
}
|
|
const connection = this.activeConnection();
|
|
if (connection === undefined || this.$state !== ClientState.Running) {
|
|
throw new Error(`Client is not running and can't be stopped. It's current state is: ${this.$state}`);
|
|
}
|
|
this._initializeResult = undefined;
|
|
this.$state = ClientState.Stopping;
|
|
this.cleanUp(mode);
|
|
const tp = new Promise((c) => {
|
|
(0, vscode_languageserver_protocol_1.RAL)().timer.setTimeout(c, timeout);
|
|
});
|
|
const shutdown = (async (connection2) => {
|
|
await connection2.shutdown();
|
|
await connection2.exit();
|
|
return connection2;
|
|
})(connection);
|
|
return this._onStop = Promise.race([tp, shutdown]).then((connection2) => {
|
|
if (connection2 !== undefined) {
|
|
connection2.end();
|
|
connection2.dispose();
|
|
} else {
|
|
this.error(`Stopping server timed out`, undefined, false);
|
|
throw new Error(`Stopping the server timed out`);
|
|
}
|
|
}, (error) => {
|
|
this.error(`Stopping server failed`, error, false);
|
|
throw error;
|
|
}).finally(() => {
|
|
this.$state = ClientState.Stopped;
|
|
mode === ShutdownMode.Stop && this.cleanUpChannel();
|
|
this._onStart = undefined;
|
|
this._onStop = undefined;
|
|
this._connection = undefined;
|
|
this._ignoredRegistrations.clear();
|
|
});
|
|
}
|
|
cleanUp(mode) {
|
|
this._fileEvents = [];
|
|
this._fileEventDelayer.cancel();
|
|
const disposables = this._listeners.splice(0, this._listeners.length);
|
|
for (const disposable of disposables) {
|
|
disposable.dispose();
|
|
}
|
|
if (this._syncedDocuments) {
|
|
this._syncedDocuments.clear();
|
|
}
|
|
for (const feature of Array.from(this._features.entries()).map((entry) => entry[1]).reverse()) {
|
|
feature.clear();
|
|
}
|
|
if (mode === ShutdownMode.Stop || mode === ShutdownMode.Restart) {
|
|
if (this._diagnostics === undefined) {
|
|
this._diagnostics = null;
|
|
}
|
|
if (this._diagnostics !== null) {
|
|
this._clientOptions.diagnosticCollectionProvider.dispose(this._diagnostics, features_1.DiagnosticCollectionSource.push);
|
|
this._diagnostics = null;
|
|
}
|
|
}
|
|
if (this._idleInterval !== undefined) {
|
|
this._idleInterval.dispose();
|
|
this._idleInterval = undefined;
|
|
}
|
|
}
|
|
cleanUpChannel() {
|
|
if (this._outputChannel !== undefined && this._disposeOutputChannel) {
|
|
this._outputChannel.dispose();
|
|
this._outputChannel = undefined;
|
|
}
|
|
}
|
|
notifyFileEvent(event) {
|
|
const client = this;
|
|
async function didChangeWatchedFile(event2) {
|
|
client._fileEvents.push(event2);
|
|
return client._fileEventDelayer.trigger(async () => {
|
|
const fileEvents = client._fileEvents;
|
|
client._fileEvents = [];
|
|
try {
|
|
await client.sendNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, { changes: fileEvents });
|
|
} catch (error) {
|
|
client._fileEvents.push(...fileEvents);
|
|
throw error;
|
|
}
|
|
});
|
|
}
|
|
const workSpaceMiddleware = this.clientOptions.middleware?.workspace;
|
|
((workSpaceMiddleware?.didChangeWatchedFile) ? workSpaceMiddleware.didChangeWatchedFile(event, didChangeWatchedFile) : didChangeWatchedFile(event)).catch((error) => {
|
|
client.error(`Notifying file events failed.`, error);
|
|
});
|
|
}
|
|
async sendPendingFullTextDocumentChanges(connection) {
|
|
return this._pendingChangeSemaphore.lock(async () => {
|
|
try {
|
|
const changes = this._didChangeTextDocumentFeature.getPendingDocumentChanges(this._inFlightOpenNotifications);
|
|
if (changes.length === 0) {
|
|
return;
|
|
}
|
|
for (const document of changes) {
|
|
const params = this.code2ProtocolConverter.asChangeTextDocumentParams(document);
|
|
this._didChangeTextDocumentFeature.aboutToSendNotification(document, vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params);
|
|
await connection.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params);
|
|
this._didChangeTextDocumentFeature.notificationSent(document, vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params);
|
|
}
|
|
} catch (error) {
|
|
this.error(`Sending pending changes failed`, error, false);
|
|
throw error;
|
|
}
|
|
});
|
|
}
|
|
triggerPendingChangeDelivery() {
|
|
this._pendingChangeDelayer.trigger(async () => {
|
|
const connection = this.activeConnection();
|
|
if (connection === undefined) {
|
|
this.triggerPendingChangeDelivery();
|
|
return;
|
|
}
|
|
await this.sendPendingFullTextDocumentChanges(connection);
|
|
}).catch((error) => this.error(`Delivering pending changes failed`, error, false));
|
|
}
|
|
_diagnosticQueue = new Map;
|
|
_diagnosticQueueState = { state: "idle" };
|
|
handleDiagnostics(params) {
|
|
if (this._diagnostics === null) {
|
|
return;
|
|
}
|
|
const key = params.uri;
|
|
if (this._diagnosticQueueState.state === "busy" && this._diagnosticQueueState.document === key) {
|
|
this._diagnosticQueueState.tokenSource.cancel();
|
|
}
|
|
this._diagnosticQueue.set(params.uri, params.diagnostics);
|
|
this.triggerDiagnosticQueue();
|
|
}
|
|
triggerDiagnosticQueue() {
|
|
(0, vscode_languageserver_protocol_1.RAL)().timer.setImmediate(() => {
|
|
this.workDiagnosticQueue();
|
|
});
|
|
}
|
|
workDiagnosticQueue() {
|
|
if (this._diagnosticQueueState.state === "busy") {
|
|
return;
|
|
}
|
|
const next = this._diagnosticQueue.entries().next();
|
|
if (next.done === true) {
|
|
return;
|
|
}
|
|
const [document, diagnostics] = next.value;
|
|
this._diagnosticQueue.delete(document);
|
|
const tokenSource = new vscode_1.CancellationTokenSource;
|
|
this._diagnosticQueueState = { state: "busy", document, tokenSource };
|
|
this._p2c.asDiagnostics(diagnostics, tokenSource.token).then((converted) => {
|
|
if (!tokenSource.token.isCancellationRequested) {
|
|
const uri = this._p2c.asUri(document);
|
|
const middleware = this.clientOptions.middleware;
|
|
if (middleware.handleDiagnostics) {
|
|
middleware.handleDiagnostics(uri, converted, (uri2, diagnostics2) => this.setDiagnostics(uri2, diagnostics2));
|
|
} else {
|
|
this.setDiagnostics(uri, converted);
|
|
}
|
|
}
|
|
}).catch((error) => {
|
|
this.error(`Processing diagnostic queue failed.`, error);
|
|
}).finally(() => {
|
|
this._diagnosticQueueState = { state: "idle" };
|
|
this.triggerDiagnosticQueue();
|
|
});
|
|
}
|
|
setDiagnostics(uri, diagnostics) {
|
|
if (this._diagnostics === null) {
|
|
return;
|
|
}
|
|
const diagnosticsCollection = this.diagnostics;
|
|
if (diagnosticsCollection !== undefined) {
|
|
diagnosticsCollection.set(uri, diagnostics);
|
|
}
|
|
}
|
|
getLocale() {
|
|
return vscode_1.env.language;
|
|
}
|
|
async $start() {
|
|
if (this.$state === ClientState.StartFailed) {
|
|
throw new Error(`Previous start failed. Can't restart server.`);
|
|
}
|
|
await this.start();
|
|
const connection = this.activeConnection();
|
|
if (connection === undefined) {
|
|
throw new Error(`Starting server failed`);
|
|
}
|
|
return connection;
|
|
}
|
|
async createConnection() {
|
|
const errorHandler = (error, message, count) => {
|
|
this.handleConnectionError(error, message, count).catch((error2) => this.error(`Handling connection error failed`, error2));
|
|
};
|
|
const closeHandler = () => {
|
|
this.handleConnectionClosed().catch((error) => this.error(`Handling connection close failed`, error));
|
|
};
|
|
const transports = await this.createMessageTransports(this._clientOptions.stdioEncoding || "utf8");
|
|
this._connection = createConnection(transports.reader, transports.writer, errorHandler, closeHandler, this._clientOptions.connectionOptions);
|
|
return this._connection;
|
|
}
|
|
async handleConnectionClosed() {
|
|
if (this.$state === ClientState.Stopped) {
|
|
return;
|
|
}
|
|
try {
|
|
if (this._connection !== undefined) {
|
|
this._connection.dispose();
|
|
}
|
|
} catch (error) {}
|
|
let handlerResult = { action: CloseAction.DoNotRestart };
|
|
if (this.$state !== ClientState.Stopping) {
|
|
try {
|
|
handlerResult = await this._clientOptions.errorHandler.closed();
|
|
} catch (error) {}
|
|
}
|
|
this._connection = undefined;
|
|
if (handlerResult.action === CloseAction.DoNotRestart) {
|
|
this.error(handlerResult.message ?? "Connection to server got closed. Server will not be restarted.", undefined, handlerResult.handled === true ? false : "force");
|
|
this.cleanUp(ShutdownMode.Stop);
|
|
if (this.$state === ClientState.Starting) {
|
|
this.$state = ClientState.StartFailed;
|
|
} else {
|
|
this.$state = ClientState.Stopped;
|
|
}
|
|
this._onStop = Promise.resolve();
|
|
this._onStart = undefined;
|
|
} else if (handlerResult.action === CloseAction.Restart) {
|
|
this.info(handlerResult.message ?? "Connection to server got closed. Server will restart.", undefined, !handlerResult.handled);
|
|
this.cleanUp(ShutdownMode.Restart);
|
|
this.$state = ClientState.Initial;
|
|
this._onStop = Promise.resolve();
|
|
this._onStart = undefined;
|
|
this.start().catch((error) => this.error(`Restarting server failed`, error, "force"));
|
|
}
|
|
}
|
|
async handleConnectionError(error, message, count) {
|
|
const handlerResult = await this._clientOptions.errorHandler.error(error, message, count);
|
|
if (handlerResult.action === ErrorAction.Shutdown) {
|
|
this.error(handlerResult.message ?? `Client ${this._name}: connection to server is erroring.
|
|
${error.message}
|
|
Shutting down server.`, undefined, handlerResult.handled === true ? false : "force");
|
|
this.stop().catch((error2) => {
|
|
this.error(`Stopping server failed`, error2, false);
|
|
});
|
|
} else {
|
|
this.error(handlerResult.message ?? `Client ${this._name}: connection to server is erroring.
|
|
${error.message}`, undefined, handlerResult.handled === true ? false : "force");
|
|
}
|
|
}
|
|
hookConfigurationChanged(connection) {
|
|
this._listeners.push(vscode_1.workspace.onDidChangeConfiguration(() => {
|
|
this.refreshTrace(connection, true);
|
|
}));
|
|
}
|
|
hookLogLevelChanged(connection) {
|
|
this._listeners.push(this.traceOutputChannel.onDidChangeLogLevel((level) => {
|
|
this._traceLogLevel = level;
|
|
this.refreshTrace(connection, true);
|
|
}));
|
|
}
|
|
refreshTrace(connection, sendNotification = false) {
|
|
const config = vscode_1.workspace.getConfiguration(this._id);
|
|
let trace = this._traceLogLevel !== vscode_1.LogLevel.Trace ? vscode_languageserver_protocol_1.Trace.Off : vscode_languageserver_protocol_1.Trace.Messages;
|
|
let traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text;
|
|
if (config && trace !== vscode_languageserver_protocol_1.Trace.Off) {
|
|
const traceConfig = config.get("trace.server", "messages");
|
|
if (typeof traceConfig === "string") {
|
|
trace = vscode_languageserver_protocol_1.Trace.fromString(traceConfig);
|
|
if (trace === vscode_languageserver_protocol_1.Trace.Off) {
|
|
trace = vscode_languageserver_protocol_1.Trace.Messages;
|
|
}
|
|
} else {
|
|
trace = vscode_languageserver_protocol_1.Trace.fromString(config.get("trace.server.verbosity", "messages"));
|
|
if (trace === vscode_languageserver_protocol_1.Trace.Off) {
|
|
trace = vscode_languageserver_protocol_1.Trace.Messages;
|
|
}
|
|
traceFormat = vscode_languageserver_protocol_1.TraceFormat.fromString(config.get("trace.server.format", "text"));
|
|
}
|
|
}
|
|
this._trace = trace;
|
|
this._traceFormat = traceFormat;
|
|
connection.trace(this._trace, this._tracer, {
|
|
sendNotification,
|
|
traceFormat: this._traceFormat
|
|
}).catch((error) => {
|
|
this.error(`Updating trace failed with error`, error, false);
|
|
});
|
|
}
|
|
hookFileEvents(_connection) {
|
|
const fileEvents = this._clientOptions.synchronize.fileEvents;
|
|
if (!fileEvents) {
|
|
return;
|
|
}
|
|
let watchers;
|
|
if (Is.array(fileEvents)) {
|
|
watchers = fileEvents;
|
|
} else {
|
|
watchers = [fileEvents];
|
|
}
|
|
if (!watchers) {
|
|
return;
|
|
}
|
|
this._dynamicFeatures.get(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type.method).registerRaw(UUID.generateUuid(), watchers);
|
|
}
|
|
_features = [];
|
|
_dynamicFeatures = new Map;
|
|
registerFeatures(features) {
|
|
for (const feature of features) {
|
|
this.registerFeature(feature);
|
|
}
|
|
}
|
|
registerFeature(feature) {
|
|
this._features.push(feature);
|
|
if (features_1.DynamicFeature.is(feature)) {
|
|
const registrationType = feature.registrationType;
|
|
this._dynamicFeatures.set(registrationType.method, feature);
|
|
}
|
|
}
|
|
getFeature(request) {
|
|
return this._dynamicFeatures.get(request);
|
|
}
|
|
hasDedicatedTextSynchronizationFeature(textDocument) {
|
|
const feature = this.getFeature(vscode_languageserver_protocol_1.NotebookDocumentSyncRegistrationType.method);
|
|
if (feature === undefined || !(feature instanceof notebook_1.NotebookDocumentSyncFeature)) {
|
|
return false;
|
|
}
|
|
return feature.handles(textDocument);
|
|
}
|
|
registerBuiltinFeatures() {
|
|
const pendingFullTextDocumentChanges = new Map;
|
|
this.registerFeature(new configuration_1.ConfigurationFeature(this));
|
|
this._didOpenTextDocumentFeature = new textSynchronization_1.DidOpenTextDocumentFeature(this, this._syncedDocuments);
|
|
this.registerFeature(this._didOpenTextDocumentFeature);
|
|
this._didChangeTextDocumentFeature = new textSynchronization_1.DidChangeTextDocumentFeature(this, pendingFullTextDocumentChanges);
|
|
this._didChangeTextDocumentFeature.onPendingChangeAdded(() => {
|
|
this.triggerPendingChangeDelivery();
|
|
});
|
|
this.registerFeature(this._didChangeTextDocumentFeature);
|
|
this.registerFeature(new textSynchronization_1.WillSaveFeature(this));
|
|
this.registerFeature(new textSynchronization_1.WillSaveWaitUntilFeature(this));
|
|
this.registerFeature(new textSynchronization_1.DidSaveTextDocumentFeature(this));
|
|
this.registerFeature(new textSynchronization_1.DidCloseTextDocumentFeature(this, this._syncedDocuments, pendingFullTextDocumentChanges));
|
|
this.registerFeature(new fileSystemWatcher_1.FileSystemWatcherFeature(this, (event) => this.notifyFileEvent(event)));
|
|
this.registerFeature(new completion_1.CompletionItemFeature(this));
|
|
this.registerFeature(new hover_1.HoverFeature(this));
|
|
this.registerFeature(new signatureHelp_1.SignatureHelpFeature(this));
|
|
this.registerFeature(new definition_1.DefinitionFeature(this));
|
|
this.registerFeature(new reference_1.ReferencesFeature(this));
|
|
this.registerFeature(new documentHighlight_1.DocumentHighlightFeature(this));
|
|
this.registerFeature(new documentSymbol_1.DocumentSymbolFeature(this));
|
|
this.registerFeature(new workspaceSymbol_1.WorkspaceSymbolFeature(this));
|
|
this.registerFeature(new codeAction_1.CodeActionFeature(this));
|
|
this.registerFeature(new codeLens_1.CodeLensFeature(this));
|
|
this.registerFeature(new formatting_1.DocumentFormattingFeature(this));
|
|
this.registerFeature(new formatting_1.DocumentRangeFormattingFeature(this));
|
|
this.registerFeature(new formatting_1.DocumentOnTypeFormattingFeature(this));
|
|
this.registerFeature(new rename_1.RenameFeature(this));
|
|
this.registerFeature(new documentLink_1.DocumentLinkFeature(this));
|
|
this.registerFeature(new executeCommand_1.ExecuteCommandFeature(this));
|
|
this.registerFeature(new configuration_1.SyncConfigurationFeature(this));
|
|
this.registerFeature(new typeDefinition_1.TypeDefinitionFeature(this));
|
|
this.registerFeature(new implementation_1.ImplementationFeature(this));
|
|
this.registerFeature(new colorProvider_1.ColorProviderFeature(this));
|
|
if (this.clientOptions.workspaceFolder === undefined) {
|
|
this.registerFeature(new workspaceFolder_1.WorkspaceFoldersFeature(this));
|
|
}
|
|
this.registerFeature(new foldingRange_1.FoldingRangeFeature(this));
|
|
this.registerFeature(new declaration_1.DeclarationFeature(this));
|
|
this.registerFeature(new selectionRange_1.SelectionRangeFeature(this));
|
|
this.registerFeature(new progress_1.ProgressFeature(this));
|
|
this.registerFeature(new callHierarchy_1.CallHierarchyFeature(this));
|
|
this.registerFeature(new semanticTokens_1.SemanticTokensFeature(this));
|
|
this.registerFeature(new linkedEditingRange_1.LinkedEditingFeature(this));
|
|
this.registerFeature(new fileOperations_1.DidCreateFilesFeature(this));
|
|
this.registerFeature(new fileOperations_1.DidRenameFilesFeature(this));
|
|
this.registerFeature(new fileOperations_1.DidDeleteFilesFeature(this));
|
|
this.registerFeature(new fileOperations_1.WillCreateFilesFeature(this));
|
|
this.registerFeature(new fileOperations_1.WillRenameFilesFeature(this));
|
|
this.registerFeature(new fileOperations_1.WillDeleteFilesFeature(this));
|
|
this.registerFeature(new typeHierarchy_1.TypeHierarchyFeature(this));
|
|
this.registerFeature(new inlineValue_1.InlineValueFeature(this));
|
|
this.registerFeature(new inlayHint_1.InlayHintsFeature(this));
|
|
this.registerFeature(new diagnostic_1.DiagnosticFeature(this));
|
|
this.registerFeature(new notebook_1.NotebookDocumentSyncFeature(this));
|
|
this.registerFeature(new inlineCompletion_1.InlineCompletionItemFeature(this));
|
|
this.registerFeature(new textDocumentContent_1.TextDocumentContentFeature(this));
|
|
}
|
|
registerProposedFeatures() {
|
|
this.registerFeatures(ProposedFeatures.createAll(this));
|
|
}
|
|
fillInitializeParams(params) {
|
|
for (const feature of this._features) {
|
|
if (Is.func(feature.fillInitializeParams)) {
|
|
feature.fillInitializeParams(params);
|
|
}
|
|
}
|
|
}
|
|
computeClientCapabilities() {
|
|
const result = {};
|
|
(0, features_1.ensure)(result, "workspace").applyEdit = true;
|
|
const workspaceEdit = (0, features_1.ensure)((0, features_1.ensure)(result, "workspace"), "workspaceEdit");
|
|
workspaceEdit.documentChanges = true;
|
|
workspaceEdit.resourceOperations = [vscode_languageserver_protocol_1.ResourceOperationKind.Create, vscode_languageserver_protocol_1.ResourceOperationKind.Rename, vscode_languageserver_protocol_1.ResourceOperationKind.Delete];
|
|
workspaceEdit.failureHandling = vscode_languageserver_protocol_1.FailureHandlingKind.TextOnlyTransactional;
|
|
workspaceEdit.normalizesLineEndings = true;
|
|
workspaceEdit.changeAnnotationSupport = {
|
|
groupsOnLabel: true
|
|
};
|
|
workspaceEdit.metadataSupport = true;
|
|
workspaceEdit.snippetEditSupport = true;
|
|
const diagnostics = (0, features_1.ensure)((0, features_1.ensure)(result, "textDocument"), "publishDiagnostics");
|
|
diagnostics.relatedInformation = true;
|
|
diagnostics.versionSupport = false;
|
|
diagnostics.tagSupport = { valueSet: [vscode_languageserver_protocol_1.DiagnosticTag.Unnecessary, vscode_languageserver_protocol_1.DiagnosticTag.Deprecated] };
|
|
diagnostics.codeDescriptionSupport = true;
|
|
diagnostics.dataSupport = true;
|
|
const textDocumentFilter = (0, features_1.ensure)((0, features_1.ensure)(result, "textDocument"), "filters");
|
|
textDocumentFilter.relativePatternSupport = true;
|
|
const windowCapabilities = (0, features_1.ensure)(result, "window");
|
|
const showMessage = (0, features_1.ensure)(windowCapabilities, "showMessage");
|
|
showMessage.messageActionItem = { additionalPropertiesSupport: true };
|
|
const showDocument = (0, features_1.ensure)(windowCapabilities, "showDocument");
|
|
showDocument.support = true;
|
|
const generalCapabilities = (0, features_1.ensure)(result, "general");
|
|
generalCapabilities.staleRequestSupport = {
|
|
cancel: true,
|
|
retryOnContentModified: Array.from(BaseLanguageClient.RequestsToCancelOnContentModified)
|
|
};
|
|
generalCapabilities.regularExpressions = { engine: "ECMAScript", version: "ES2020" };
|
|
generalCapabilities.markdown = {
|
|
parser: "marked",
|
|
version: "1.1.0"
|
|
};
|
|
generalCapabilities.positionEncodings = ["utf-16"];
|
|
if (this._clientOptions.markdown.supportHtml) {
|
|
generalCapabilities.markdown.allowedTags = ["ul", "li", "p", "code", "blockquote", "ol", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "em", "pre", "table", "thead", "tbody", "tr", "th", "td", "div", "del", "a", "strong", "br", "img", "span"];
|
|
}
|
|
for (const feature of this._features) {
|
|
feature.fillClientCapabilities(result);
|
|
}
|
|
return result;
|
|
}
|
|
initializeFeatures(_connection) {
|
|
const documentSelector = this._clientOptions.documentSelector;
|
|
for (const feature of this._features) {
|
|
if (Is.func(feature.preInitialize)) {
|
|
feature.preInitialize(this._capabilities, documentSelector);
|
|
}
|
|
}
|
|
for (const feature of this._features) {
|
|
feature.initialize(this._capabilities, documentSelector);
|
|
}
|
|
}
|
|
async handleRegistrationRequest(params) {
|
|
const middleware = this.clientOptions.middleware?.handleRegisterCapability;
|
|
if (middleware) {
|
|
return middleware(params, (nextParams) => this.doRegisterCapability(nextParams));
|
|
} else {
|
|
return this.doRegisterCapability(params);
|
|
}
|
|
}
|
|
async doRegisterCapability(params) {
|
|
if (!this.isRunning()) {
|
|
for (const registration of params.registrations) {
|
|
this._ignoredRegistrations.add(registration.id);
|
|
}
|
|
return;
|
|
}
|
|
for (const registration of params.registrations) {
|
|
const feature = this._dynamicFeatures.get(registration.method);
|
|
if (feature === undefined) {
|
|
return Promise.reject(new Error(`No feature implementation for ${registration.method} found. Registration failed.`));
|
|
}
|
|
const options = registration.registerOptions ?? {};
|
|
options.documentSelector = options.documentSelector ?? this._clientOptions.documentSelector;
|
|
const data = {
|
|
id: registration.id,
|
|
registerOptions: options
|
|
};
|
|
try {
|
|
feature.register(data);
|
|
} catch (err) {
|
|
return Promise.reject(err);
|
|
}
|
|
}
|
|
}
|
|
async handleUnregistrationRequest(params) {
|
|
const middleware = this.clientOptions.middleware?.handleUnregisterCapability;
|
|
if (middleware) {
|
|
return middleware(params, (nextParams) => this.doUnregisterCapability(nextParams));
|
|
} else {
|
|
return this.doUnregisterCapability(params);
|
|
}
|
|
}
|
|
async doUnregisterCapability(params) {
|
|
for (const unregistration of params.unregisterations) {
|
|
if (this._ignoredRegistrations.has(unregistration.id)) {
|
|
continue;
|
|
}
|
|
const feature = this._dynamicFeatures.get(unregistration.method);
|
|
if (!feature) {
|
|
return Promise.reject(new Error(`No feature implementation for ${unregistration.method} found. Unregistration failed.`));
|
|
}
|
|
feature.unregister(unregistration.id);
|
|
}
|
|
}
|
|
async handleApplyWorkspaceEdit(params) {
|
|
const middleware = this.clientOptions.middleware?.workspace?.handleApplyEdit;
|
|
if (middleware) {
|
|
const resultOrError = await middleware(params, (nextParams) => this.doHandleApplyWorkspaceEdit(nextParams));
|
|
if (resultOrError instanceof vscode_languageserver_protocol_1.ResponseError) {
|
|
return Promise.reject(resultOrError);
|
|
}
|
|
return resultOrError;
|
|
} else {
|
|
return this.doHandleApplyWorkspaceEdit(params);
|
|
}
|
|
}
|
|
workspaceEditLock = new async_1.Semaphore(1);
|
|
async doHandleApplyWorkspaceEdit(params) {
|
|
const workspaceEdit = params.edit;
|
|
const converted = await this.workspaceEditLock.lock(() => {
|
|
return this._p2c.asWorkspaceEdit(workspaceEdit);
|
|
});
|
|
const valid = this.validateWorkspaceEdit(workspaceEdit);
|
|
if (!valid) {
|
|
return Promise.resolve({ applied: false });
|
|
}
|
|
return Is.asPromise(vscode_1.workspace.applyEdit(converted, { isRefactoring: params.metadata?.isRefactoring }).then((value) => {
|
|
return { applied: value };
|
|
}));
|
|
}
|
|
validateWorkspaceEdit(workspaceEdit) {
|
|
const openTextDocuments = new Map;
|
|
vscode_1.workspace.textDocuments.forEach((document) => openTextDocuments.set(document.uri.toString(), document));
|
|
if (workspaceEdit.documentChanges) {
|
|
for (const change of workspaceEdit.documentChanges) {
|
|
if (vscode_languageserver_protocol_1.TextDocumentEdit.is(change) && change.textDocument.version !== null && change.textDocument.version >= 0) {
|
|
const changeUri = this._p2c.asUri(change.textDocument.uri).toString();
|
|
const textDocument = openTextDocuments.get(changeUri);
|
|
if (textDocument && textDocument.version !== change.textDocument.version) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
static RequestsToCancelOnContentModified = new Set([
|
|
vscode_languageserver_protocol_1.SemanticTokensRequest.method,
|
|
vscode_languageserver_protocol_1.SemanticTokensRangeRequest.method,
|
|
vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.method
|
|
]);
|
|
static CancellableResolveCalls = new Set([
|
|
vscode_languageserver_protocol_1.CompletionResolveRequest.method,
|
|
vscode_languageserver_protocol_1.CodeLensResolveRequest.method,
|
|
vscode_languageserver_protocol_1.CodeActionResolveRequest.method,
|
|
vscode_languageserver_protocol_1.InlayHintResolveRequest.method,
|
|
vscode_languageserver_protocol_1.DocumentLinkResolveRequest.method,
|
|
vscode_languageserver_protocol_1.WorkspaceSymbolResolveRequest.method
|
|
]);
|
|
handleFailedRequest(type, token, error, defaultValue, showNotification = true, throwOnCancel = false) {
|
|
if (error instanceof vscode_languageserver_protocol_1.ResponseError) {
|
|
if (error.code === vscode_languageserver_protocol_1.ErrorCodes.PendingResponseRejected || error.code === vscode_languageserver_protocol_1.ErrorCodes.ConnectionInactive) {
|
|
return defaultValue;
|
|
}
|
|
if (error.code === vscode_languageserver_protocol_1.LSPErrorCodes.RequestCancelled || error.code === vscode_languageserver_protocol_1.LSPErrorCodes.ServerCancelled) {
|
|
if (token !== undefined && token.isCancellationRequested && !throwOnCancel) {
|
|
return defaultValue;
|
|
} else {
|
|
if (error.data !== undefined) {
|
|
throw new features_1.LSPCancellationError(error.data);
|
|
} else {
|
|
throw new vscode_1.CancellationError;
|
|
}
|
|
}
|
|
} else if (error.code === vscode_languageserver_protocol_1.LSPErrorCodes.ContentModified) {
|
|
if (BaseLanguageClient.RequestsToCancelOnContentModified.has(type.method) || BaseLanguageClient.CancellableResolveCalls.has(type.method)) {
|
|
throw new vscode_1.CancellationError;
|
|
} else {
|
|
return defaultValue;
|
|
}
|
|
}
|
|
}
|
|
this.error(`Request ${type.method} failed.`, error, showNotification);
|
|
throw error;
|
|
}
|
|
}
|
|
exports2.BaseLanguageClient = BaseLanguageClient;
|
|
|
|
class LanguageClient extends BaseLanguageClient {
|
|
serverOptions;
|
|
constructor(id, name, serverOptions, clientOptions) {
|
|
super(id, name, clientOptions);
|
|
this.serverOptions = serverOptions;
|
|
}
|
|
async createMessageTransports(_encoding) {
|
|
return this.serverOptions();
|
|
}
|
|
}
|
|
exports2.LanguageClient = LanguageClient;
|
|
|
|
class ConsoleLogger {
|
|
error(message) {
|
|
(0, vscode_languageserver_protocol_1.RAL)().console.error(message);
|
|
}
|
|
warn(message) {
|
|
(0, vscode_languageserver_protocol_1.RAL)().console.warn(message);
|
|
}
|
|
info(message) {
|
|
(0, vscode_languageserver_protocol_1.RAL)().console.info(message);
|
|
}
|
|
log(message) {
|
|
(0, vscode_languageserver_protocol_1.RAL)().console.log(message);
|
|
}
|
|
}
|
|
function createConnection(input, output, errorHandler, closeHandler, options) {
|
|
const logger = new ConsoleLogger;
|
|
const connection = (0, vscode_languageserver_protocol_1.createProtocolConnection)(input, output, logger, options);
|
|
connection.onError((data) => {
|
|
errorHandler(data[0], data[1], data[2]);
|
|
});
|
|
connection.onClose(closeHandler);
|
|
const result = {
|
|
listen: () => connection.listen(),
|
|
sendRequest: connection.sendRequest,
|
|
onRequest: connection.onRequest,
|
|
hasPendingResponse: connection.hasPendingResponse,
|
|
sendNotification: connection.sendNotification,
|
|
onNotification: connection.onNotification,
|
|
onProgress: connection.onProgress,
|
|
sendProgress: connection.sendProgress,
|
|
trace: (value, tracer, sendNotificationOrTraceOptions) => {
|
|
const defaultTraceOptions = {
|
|
sendNotification: false,
|
|
traceFormat: vscode_languageserver_protocol_1.TraceFormat.Text
|
|
};
|
|
if (sendNotificationOrTraceOptions === undefined) {
|
|
return connection.trace(value, tracer, defaultTraceOptions);
|
|
} else if (Is.boolean(sendNotificationOrTraceOptions)) {
|
|
return connection.trace(value, tracer, sendNotificationOrTraceOptions);
|
|
} else {
|
|
return connection.trace(value, tracer, sendNotificationOrTraceOptions);
|
|
}
|
|
},
|
|
initialize: (params) => {
|
|
return connection.sendRequest(vscode_languageserver_protocol_1.InitializeRequest.type, params);
|
|
},
|
|
shutdown: () => {
|
|
return connection.sendRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, undefined);
|
|
},
|
|
exit: () => {
|
|
return connection.sendNotification(vscode_languageserver_protocol_1.ExitNotification.type);
|
|
},
|
|
end: () => connection.end(),
|
|
dispose: () => connection.dispose()
|
|
};
|
|
return result;
|
|
}
|
|
var ProposedFeatures;
|
|
(function(ProposedFeatures2) {
|
|
function createAll(_client) {
|
|
const result = [];
|
|
return result;
|
|
}
|
|
ProposedFeatures2.createAll = createAll;
|
|
})(ProposedFeatures || (exports2.ProposedFeatures = ProposedFeatures = {}));
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/node/processes.js
|
|
var require_processes = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.terminate = terminate;
|
|
var cp = __importStar(require("child_process"));
|
|
var isWindows = process.platform === "win32";
|
|
var isMacintosh = process.platform === "darwin";
|
|
var isLinux = process.platform === "linux";
|
|
function terminate(process2, cwd) {
|
|
if (isWindows) {
|
|
try {
|
|
const options = {
|
|
stdio: ["pipe", "pipe", "ignore"]
|
|
};
|
|
if (cwd) {
|
|
options.cwd = cwd;
|
|
}
|
|
cp.execFileSync("taskkill", ["/T", "/F", "/PID", process2.pid.toString()], options);
|
|
return true;
|
|
} catch (err) {
|
|
return false;
|
|
}
|
|
} else if (isLinux || isMacintosh) {
|
|
try {
|
|
const pid = process2.pid.toString();
|
|
if (!/^\d+$/.test(pid)) {
|
|
return false;
|
|
}
|
|
const script = `
|
|
terminateTree() {
|
|
for cpid in $(pgrep -P "$1"); do
|
|
terminateTree "$cpid"
|
|
done
|
|
kill -9 "$1" > /dev/null 2>&1
|
|
}
|
|
|
|
terminateTree "${pid}"
|
|
`;
|
|
const result = cp.spawnSync("/bin/sh", [], {
|
|
input: script,
|
|
stdio: ["pipe", "inherit", "inherit"]
|
|
});
|
|
return result.error ? false : true;
|
|
} catch (err) {
|
|
return false;
|
|
}
|
|
} else {
|
|
process2.kill("SIGKILL");
|
|
return true;
|
|
}
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/node/ril.js
|
|
var require_ril = __commonJS((exports2) => {
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
var util_1 = require("util");
|
|
var api_1 = require_api();
|
|
|
|
class MessageBuffer extends api_1.AbstractMessageBuffer {
|
|
static emptyBuffer = Buffer.allocUnsafe(0);
|
|
constructor(encoding = "utf-8") {
|
|
super(encoding);
|
|
}
|
|
emptyBuffer() {
|
|
return MessageBuffer.emptyBuffer;
|
|
}
|
|
fromString(value, encoding) {
|
|
return Buffer.from(value, encoding);
|
|
}
|
|
toString(value, encoding) {
|
|
if (value instanceof Buffer) {
|
|
return value.toString(encoding);
|
|
} else {
|
|
return new util_1.TextDecoder(encoding).decode(value);
|
|
}
|
|
}
|
|
asNative(buffer, length) {
|
|
if (length === undefined) {
|
|
return buffer instanceof Buffer ? buffer : Buffer.from(buffer);
|
|
} else {
|
|
return buffer instanceof Buffer ? buffer.slice(0, length) : Buffer.from(buffer, 0, length);
|
|
}
|
|
}
|
|
allocNative(length) {
|
|
return Buffer.allocUnsafe(length);
|
|
}
|
|
}
|
|
|
|
class ReadableStreamWrapper {
|
|
stream;
|
|
constructor(stream) {
|
|
this.stream = stream;
|
|
}
|
|
onClose(listener) {
|
|
this.stream.on("close", listener);
|
|
return api_1.Disposable.create(() => this.stream.off("close", listener));
|
|
}
|
|
onError(listener) {
|
|
this.stream.on("error", listener);
|
|
return api_1.Disposable.create(() => this.stream.off("error", listener));
|
|
}
|
|
onEnd(listener) {
|
|
this.stream.on("end", listener);
|
|
return api_1.Disposable.create(() => this.stream.off("end", listener));
|
|
}
|
|
onData(listener) {
|
|
this.stream.on("data", listener);
|
|
return api_1.Disposable.create(() => this.stream.off("data", listener));
|
|
}
|
|
}
|
|
|
|
class WritableStreamWrapper {
|
|
stream;
|
|
constructor(stream) {
|
|
this.stream = stream;
|
|
}
|
|
onClose(listener) {
|
|
this.stream.on("close", listener);
|
|
return api_1.Disposable.create(() => this.stream.off("close", listener));
|
|
}
|
|
onError(listener) {
|
|
this.stream.on("error", listener);
|
|
return api_1.Disposable.create(() => this.stream.off("error", listener));
|
|
}
|
|
onEnd(listener) {
|
|
this.stream.on("end", listener);
|
|
return api_1.Disposable.create(() => this.stream.off("end", listener));
|
|
}
|
|
write(data, encoding) {
|
|
return new Promise((resolve, reject) => {
|
|
const callback = (error) => {
|
|
if (error === undefined || error === null) {
|
|
resolve();
|
|
} else {
|
|
reject(error);
|
|
}
|
|
};
|
|
if (typeof data === "string") {
|
|
this.stream.write(data, encoding, callback);
|
|
} else {
|
|
this.stream.write(data, callback);
|
|
}
|
|
});
|
|
}
|
|
end() {
|
|
this.stream.end();
|
|
}
|
|
}
|
|
var _ril = Object.freeze({
|
|
messageBuffer: Object.freeze({
|
|
create: (encoding) => new MessageBuffer(encoding)
|
|
}),
|
|
applicationJson: Object.freeze({
|
|
encoder: Object.freeze({
|
|
name: "application/json",
|
|
encode: (msg, options) => {
|
|
try {
|
|
return Promise.resolve(Buffer.from(JSON.stringify(msg, undefined, 0), options.charset));
|
|
} catch (err) {
|
|
return Promise.reject(err);
|
|
}
|
|
}
|
|
}),
|
|
decoder: Object.freeze({
|
|
name: "application/json",
|
|
decode: (buffer, options) => {
|
|
try {
|
|
if (buffer instanceof Buffer) {
|
|
return Promise.resolve(JSON.parse(buffer.toString(options.charset)));
|
|
} else {
|
|
return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer)));
|
|
}
|
|
} catch (err) {
|
|
return Promise.reject(err);
|
|
}
|
|
}
|
|
})
|
|
}),
|
|
stream: Object.freeze({
|
|
asReadableStream: (stream) => new ReadableStreamWrapper(stream),
|
|
asWritableStream: (stream) => new WritableStreamWrapper(stream)
|
|
}),
|
|
console,
|
|
timer: Object.freeze({
|
|
setTimeout(callback, ms, ...args) {
|
|
const handle = setTimeout(callback, ms, ...args);
|
|
return { dispose: () => clearTimeout(handle) };
|
|
},
|
|
setImmediate(callback, ...args) {
|
|
const handle = setImmediate(callback, ...args);
|
|
return { dispose: () => clearImmediate(handle) };
|
|
},
|
|
setInterval(callback, ms, ...args) {
|
|
const handle = setInterval(callback, ms, ...args);
|
|
return { dispose: () => clearInterval(handle) };
|
|
}
|
|
})
|
|
});
|
|
function RIL() {
|
|
return _ril;
|
|
}
|
|
(function(RIL2) {
|
|
function install() {
|
|
api_1.RAL.install(_ril);
|
|
}
|
|
RIL2.install = install;
|
|
})(RIL || (RIL = {}));
|
|
exports2.default = RIL;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-jsonrpc/lib/node/main.js
|
|
var require_main3 = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
|
|
for (var p in m)
|
|
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p))
|
|
__createBinding(exports3, m, p);
|
|
};
|
|
var __importDefault = exports2 && exports2.__importDefault || function(mod) {
|
|
return mod && mod.__esModule ? mod : { default: mod };
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.StreamMessageWriter = exports2.StreamMessageReader = exports2.SocketMessageWriter = exports2.SocketMessageReader = exports2.PortMessageWriter = exports2.PortMessageReader = exports2.IPCMessageWriter = exports2.IPCMessageReader = undefined;
|
|
exports2.generateRandomPipeName = generateRandomPipeName;
|
|
exports2.createClientPipeTransport = createClientPipeTransport;
|
|
exports2.createServerPipeTransport = createServerPipeTransport;
|
|
exports2.createClientSocketTransport = createClientSocketTransport;
|
|
exports2.createServerSocketTransport = createServerSocketTransport;
|
|
exports2.createMessageConnection = createMessageConnection;
|
|
var ril_1 = __importDefault(require_ril());
|
|
ril_1.default.install();
|
|
var path = __importStar(require("path"));
|
|
var os = __importStar(require("os"));
|
|
var fs = __importStar(require("fs"));
|
|
var crypto_1 = require("crypto");
|
|
var net_1 = require("net");
|
|
var api_1 = require_api();
|
|
__exportStar(require_api(), exports2);
|
|
|
|
class IPCMessageReader extends api_1.AbstractMessageReader {
|
|
process;
|
|
constructor(process2) {
|
|
super();
|
|
this.process = process2;
|
|
const eventEmitter = this.process;
|
|
eventEmitter.on("error", (error) => this.fireError(error));
|
|
eventEmitter.on("close", () => this.fireClose());
|
|
}
|
|
listen(callback) {
|
|
this.process.on("message", callback);
|
|
return api_1.Disposable.create(() => this.process.off("message", callback));
|
|
}
|
|
}
|
|
exports2.IPCMessageReader = IPCMessageReader;
|
|
|
|
class IPCMessageWriter extends api_1.AbstractMessageWriter {
|
|
process;
|
|
errorCount;
|
|
constructor(process2) {
|
|
super();
|
|
this.process = process2;
|
|
this.errorCount = 0;
|
|
const eventEmitter = this.process;
|
|
eventEmitter.on("error", (error) => this.fireError(error));
|
|
eventEmitter.on("close", () => this.fireClose);
|
|
}
|
|
write(msg) {
|
|
try {
|
|
if (typeof this.process.send === "function") {
|
|
this.process.send(msg, undefined, undefined, (error) => {
|
|
if (error) {
|
|
this.errorCount++;
|
|
this.handleError(error, msg);
|
|
} else {
|
|
this.errorCount = 0;
|
|
}
|
|
});
|
|
}
|
|
return Promise.resolve();
|
|
} catch (error) {
|
|
this.handleError(error, msg);
|
|
return Promise.reject(error);
|
|
}
|
|
}
|
|
handleError(error, msg) {
|
|
this.errorCount++;
|
|
this.fireError(error, msg, this.errorCount);
|
|
}
|
|
end() {}
|
|
}
|
|
exports2.IPCMessageWriter = IPCMessageWriter;
|
|
|
|
class PortMessageReader extends api_1.AbstractMessageReader {
|
|
onData;
|
|
constructor(port) {
|
|
super();
|
|
this.onData = new api_1.Emitter;
|
|
port.on("close", () => this.fireClose);
|
|
port.on("error", (error) => this.fireError(error));
|
|
port.on("message", (message) => {
|
|
this.onData.fire(message);
|
|
});
|
|
}
|
|
listen(callback) {
|
|
return this.onData.event(callback);
|
|
}
|
|
}
|
|
exports2.PortMessageReader = PortMessageReader;
|
|
|
|
class PortMessageWriter extends api_1.AbstractMessageWriter {
|
|
port;
|
|
errorCount;
|
|
constructor(port) {
|
|
super();
|
|
this.port = port;
|
|
this.errorCount = 0;
|
|
port.on("close", () => this.fireClose());
|
|
port.on("error", (error) => this.fireError(error));
|
|
}
|
|
write(msg) {
|
|
try {
|
|
this.port.postMessage(msg);
|
|
return Promise.resolve();
|
|
} catch (error) {
|
|
this.handleError(error, msg);
|
|
return Promise.reject(error);
|
|
}
|
|
}
|
|
handleError(error, msg) {
|
|
this.errorCount++;
|
|
this.fireError(error, msg, this.errorCount);
|
|
}
|
|
end() {}
|
|
}
|
|
exports2.PortMessageWriter = PortMessageWriter;
|
|
|
|
class SocketMessageReader extends api_1.ReadableStreamMessageReader {
|
|
constructor(socket, encoding = "utf-8") {
|
|
super((0, ril_1.default)().stream.asReadableStream(socket), encoding);
|
|
}
|
|
}
|
|
exports2.SocketMessageReader = SocketMessageReader;
|
|
|
|
class SocketMessageWriter extends api_1.WriteableStreamMessageWriter {
|
|
socket;
|
|
constructor(socket, options) {
|
|
super((0, ril_1.default)().stream.asWritableStream(socket), options);
|
|
this.socket = socket;
|
|
}
|
|
dispose() {
|
|
super.dispose();
|
|
this.socket.destroy();
|
|
}
|
|
}
|
|
exports2.SocketMessageWriter = SocketMessageWriter;
|
|
|
|
class StreamMessageReader extends api_1.ReadableStreamMessageReader {
|
|
constructor(readable, encoding) {
|
|
super((0, ril_1.default)().stream.asReadableStream(readable), encoding);
|
|
}
|
|
}
|
|
exports2.StreamMessageReader = StreamMessageReader;
|
|
|
|
class StreamMessageWriter extends api_1.WriteableStreamMessageWriter {
|
|
constructor(writable, options) {
|
|
super((0, ril_1.default)().stream.asWritableStream(writable), options);
|
|
}
|
|
}
|
|
exports2.StreamMessageWriter = StreamMessageWriter;
|
|
var XDG_RUNTIME_DIR = process.env["XDG_RUNTIME_DIR"];
|
|
var safeIpcPathLengths = new Map([
|
|
["linux", 107],
|
|
["darwin", 102]
|
|
]);
|
|
function generateRandomPipeName() {
|
|
if (process.platform === "win32") {
|
|
return `\\\\.\\pipe\\lsp-${(0, crypto_1.randomBytes)(16).toString("hex")}-sock`;
|
|
}
|
|
let randomLength = 32;
|
|
const fixedLength = "/lsp-.sock".length;
|
|
const tmpDir = fs.realpathSync(XDG_RUNTIME_DIR ?? os.tmpdir());
|
|
const limit = safeIpcPathLengths.get(process.platform);
|
|
if (limit !== undefined) {
|
|
randomLength = Math.min(limit - tmpDir.length - fixedLength, randomLength);
|
|
}
|
|
if (randomLength < 16) {
|
|
throw new Error(`Unable to generate a random pipe name with ${randomLength} characters.`);
|
|
}
|
|
const randomSuffix = (0, crypto_1.randomBytes)(Math.floor(randomLength / 2)).toString("hex");
|
|
return path.join(tmpDir, `lsp-${randomSuffix}.sock`);
|
|
}
|
|
function createClientPipeTransport(pipeName, encoding = "utf-8") {
|
|
let connectResolve;
|
|
const connected = new Promise((resolve, _reject) => {
|
|
connectResolve = resolve;
|
|
});
|
|
return new Promise((resolve, reject) => {
|
|
const server = (0, net_1.createServer)((socket) => {
|
|
server.close();
|
|
connectResolve([
|
|
new SocketMessageReader(socket, encoding),
|
|
new SocketMessageWriter(socket, encoding)
|
|
]);
|
|
});
|
|
server.on("error", reject);
|
|
server.listen(pipeName, () => {
|
|
server.removeListener("error", reject);
|
|
resolve({
|
|
onConnected: () => {
|
|
return connected;
|
|
}
|
|
});
|
|
});
|
|
});
|
|
}
|
|
function createServerPipeTransport(pipeName, encoding = "utf-8") {
|
|
const socket = (0, net_1.createConnection)(pipeName);
|
|
return [
|
|
new SocketMessageReader(socket, encoding),
|
|
new SocketMessageWriter(socket, encoding)
|
|
];
|
|
}
|
|
function createClientSocketTransport(port, encoding = "utf-8") {
|
|
let connectResolve;
|
|
const connected = new Promise((resolve, _reject) => {
|
|
connectResolve = resolve;
|
|
});
|
|
return new Promise((resolve, reject) => {
|
|
const server = (0, net_1.createServer)((socket) => {
|
|
server.close();
|
|
connectResolve([
|
|
new SocketMessageReader(socket, encoding),
|
|
new SocketMessageWriter(socket, encoding)
|
|
]);
|
|
});
|
|
server.on("error", reject);
|
|
server.listen(port, "127.0.0.1", () => {
|
|
server.removeListener("error", reject);
|
|
resolve({
|
|
onConnected: () => {
|
|
return connected;
|
|
}
|
|
});
|
|
});
|
|
});
|
|
}
|
|
function createServerSocketTransport(port, encoding = "utf-8") {
|
|
const socket = (0, net_1.createConnection)(port, "127.0.0.1");
|
|
return [
|
|
new SocketMessageReader(socket, encoding),
|
|
new SocketMessageWriter(socket, encoding)
|
|
];
|
|
}
|
|
function isReadableStream(value) {
|
|
const candidate = value;
|
|
return candidate.read !== undefined && candidate.addListener !== undefined;
|
|
}
|
|
function isWritableStream(value) {
|
|
const candidate = value;
|
|
return candidate.write !== undefined && candidate.addListener !== undefined;
|
|
}
|
|
function createMessageConnection(input, output, logger, options) {
|
|
if (!logger) {
|
|
logger = api_1.NullLogger;
|
|
}
|
|
const reader = isReadableStream(input) ? new StreamMessageReader(input) : input;
|
|
const writer = isWritableStream(output) ? new StreamMessageWriter(output) : output;
|
|
if (api_1.ConnectionStrategy.is(options)) {
|
|
options = { connectionStrategy: options };
|
|
}
|
|
return (0, api_1.createMessageConnection)(reader, writer, logger, options);
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageserver-protocol/lib/node/main.js
|
|
var require_main4 = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
|
|
for (var p in m)
|
|
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p))
|
|
__createBinding(exports3, m, p);
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.createProtocolConnection = createProtocolConnection;
|
|
var node_1 = require_main3();
|
|
__exportStar(require_main3(), exports2);
|
|
__exportStar(require_api2(), exports2);
|
|
function createProtocolConnection(input, output, logger, options) {
|
|
return (0, node_1.createMessageConnection)(input, output, logger, options);
|
|
}
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/internal/debug.js
|
|
var require_debug = __commonJS((exports2, module2) => {
|
|
var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {};
|
|
module2.exports = debug;
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/internal/constants.js
|
|
var require_constants = __commonJS((exports2, module2) => {
|
|
var SEMVER_SPEC_VERSION = "2.0.0";
|
|
var MAX_LENGTH = 256;
|
|
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
|
|
var MAX_SAFE_COMPONENT_LENGTH = 16;
|
|
var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
|
|
var RELEASE_TYPES = [
|
|
"major",
|
|
"premajor",
|
|
"minor",
|
|
"preminor",
|
|
"patch",
|
|
"prepatch",
|
|
"prerelease"
|
|
];
|
|
module2.exports = {
|
|
MAX_LENGTH,
|
|
MAX_SAFE_COMPONENT_LENGTH,
|
|
MAX_SAFE_BUILD_LENGTH,
|
|
MAX_SAFE_INTEGER,
|
|
RELEASE_TYPES,
|
|
SEMVER_SPEC_VERSION,
|
|
FLAG_INCLUDE_PRERELEASE: 1,
|
|
FLAG_LOOSE: 2
|
|
};
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/internal/re.js
|
|
var require_re = __commonJS((exports2, module2) => {
|
|
var {
|
|
MAX_SAFE_COMPONENT_LENGTH,
|
|
MAX_SAFE_BUILD_LENGTH,
|
|
MAX_LENGTH
|
|
} = require_constants();
|
|
var debug = require_debug();
|
|
exports2 = module2.exports = {};
|
|
var re = exports2.re = [];
|
|
var safeRe = exports2.safeRe = [];
|
|
var src = exports2.src = [];
|
|
var safeSrc = exports2.safeSrc = [];
|
|
var t = exports2.t = {};
|
|
var R = 0;
|
|
var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
|
|
var safeRegexReplacements = [
|
|
["\\s", 1],
|
|
["\\d", MAX_LENGTH],
|
|
[LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
|
|
];
|
|
var makeSafeRegex = (value) => {
|
|
for (const [token, max] of safeRegexReplacements) {
|
|
value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
|
|
}
|
|
return value;
|
|
};
|
|
var createToken = (name, value, isGlobal) => {
|
|
const safe = makeSafeRegex(value);
|
|
const index = R++;
|
|
debug(name, index, value);
|
|
t[name] = index;
|
|
src[index] = value;
|
|
safeSrc[index] = safe;
|
|
re[index] = new RegExp(value, isGlobal ? "g" : undefined);
|
|
safeRe[index] = new RegExp(safe, isGlobal ? "g" : undefined);
|
|
};
|
|
createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
|
|
createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
|
|
createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
|
|
createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`);
|
|
createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`);
|
|
createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);
|
|
createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);
|
|
createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
|
|
createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
|
|
createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
|
|
createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
|
|
createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
|
|
createToken("FULL", `^${src[t.FULLPLAIN]}$`);
|
|
createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
|
|
createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`);
|
|
createToken("GTLT", "((?:<|>)?=?)");
|
|
createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
|
|
createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
|
|
createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?` + `)?)?`);
|
|
createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?` + `)?)?`);
|
|
createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
|
|
createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
|
|
createToken("COERCEPLAIN", `${"(^|[^\\d])" + "(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
|
|
createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);
|
|
createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?` + `(?:${src[t.BUILD]})?` + `(?:$|[^\\d])`);
|
|
createToken("COERCERTL", src[t.COERCE], true);
|
|
createToken("COERCERTLFULL", src[t.COERCEFULL], true);
|
|
createToken("LONETILDE", "(?:~>?)");
|
|
createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true);
|
|
exports2.tildeTrimReplace = "$1~";
|
|
createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
|
|
createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
|
|
createToken("LONECARET", "(?:\\^)");
|
|
createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true);
|
|
exports2.caretTrimReplace = "$1^";
|
|
createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
|
|
createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
|
|
createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
|
|
createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
|
|
createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
|
|
exports2.comparatorTrimReplace = "$1$2$3";
|
|
createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`);
|
|
createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`);
|
|
createToken("STAR", "(<|>)?=?\\s*\\*");
|
|
createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
|
|
createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/internal/parse-options.js
|
|
var require_parse_options = __commonJS((exports2, module2) => {
|
|
var looseOption = Object.freeze({ loose: true });
|
|
var emptyOpts = Object.freeze({});
|
|
var parseOptions = (options) => {
|
|
if (!options) {
|
|
return emptyOpts;
|
|
}
|
|
if (typeof options !== "object") {
|
|
return looseOption;
|
|
}
|
|
return options;
|
|
};
|
|
module2.exports = parseOptions;
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/internal/identifiers.js
|
|
var require_identifiers = __commonJS((exports2, module2) => {
|
|
var numeric = /^[0-9]+$/;
|
|
var compareIdentifiers = (a, b) => {
|
|
if (typeof a === "number" && typeof b === "number") {
|
|
return a === b ? 0 : a < b ? -1 : 1;
|
|
}
|
|
const anum = numeric.test(a);
|
|
const bnum = numeric.test(b);
|
|
if (anum && bnum) {
|
|
a = +a;
|
|
b = +b;
|
|
}
|
|
return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
|
|
};
|
|
var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
|
|
module2.exports = {
|
|
compareIdentifiers,
|
|
rcompareIdentifiers
|
|
};
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/classes/semver.js
|
|
var require_semver = __commonJS((exports2, module2) => {
|
|
var debug = require_debug();
|
|
var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();
|
|
var { safeRe: re, t } = require_re();
|
|
var parseOptions = require_parse_options();
|
|
var { compareIdentifiers } = require_identifiers();
|
|
var isPrereleaseIdentifier = (prerelease, identifier) => {
|
|
const identifiers = identifier.split(".");
|
|
if (identifiers.length > prerelease.length) {
|
|
return false;
|
|
}
|
|
for (let i = 0;i < identifiers.length; i++) {
|
|
if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
};
|
|
|
|
class SemVer {
|
|
constructor(version, options) {
|
|
options = parseOptions(options);
|
|
if (version instanceof SemVer) {
|
|
if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
|
|
return version;
|
|
} else {
|
|
version = version.version;
|
|
}
|
|
} else if (typeof version !== "string") {
|
|
throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`);
|
|
}
|
|
if (version.length > MAX_LENGTH) {
|
|
throw new TypeError(`version is longer than ${MAX_LENGTH} characters`);
|
|
}
|
|
debug("SemVer", version, options);
|
|
this.options = options;
|
|
this.loose = !!options.loose;
|
|
this.includePrerelease = !!options.includePrerelease;
|
|
const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
|
|
if (!m) {
|
|
throw new TypeError(`Invalid Version: ${version}`);
|
|
}
|
|
this.raw = version;
|
|
this.major = +m[1];
|
|
this.minor = +m[2];
|
|
this.patch = +m[3];
|
|
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
|
|
throw new TypeError("Invalid major version");
|
|
}
|
|
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
|
|
throw new TypeError("Invalid minor version");
|
|
}
|
|
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
|
|
throw new TypeError("Invalid patch version");
|
|
}
|
|
if (!m[4]) {
|
|
this.prerelease = [];
|
|
} else {
|
|
this.prerelease = m[4].split(".").map((id) => {
|
|
if (/^[0-9]+$/.test(id)) {
|
|
const num = +id;
|
|
if (num >= 0 && num < MAX_SAFE_INTEGER) {
|
|
return num;
|
|
}
|
|
}
|
|
return id;
|
|
});
|
|
}
|
|
this.build = m[5] ? m[5].split(".") : [];
|
|
this.format();
|
|
}
|
|
format() {
|
|
this.version = `${this.major}.${this.minor}.${this.patch}`;
|
|
if (this.prerelease.length) {
|
|
this.version += `-${this.prerelease.join(".")}`;
|
|
}
|
|
return this.version;
|
|
}
|
|
toString() {
|
|
return this.version;
|
|
}
|
|
compare(other) {
|
|
debug("SemVer.compare", this.version, this.options, other);
|
|
if (!(other instanceof SemVer)) {
|
|
if (typeof other === "string" && other === this.version) {
|
|
return 0;
|
|
}
|
|
other = new SemVer(other, this.options);
|
|
}
|
|
if (other.version === this.version) {
|
|
return 0;
|
|
}
|
|
return this.compareMain(other) || this.comparePre(other);
|
|
}
|
|
compareMain(other) {
|
|
if (!(other instanceof SemVer)) {
|
|
other = new SemVer(other, this.options);
|
|
}
|
|
if (this.major < other.major) {
|
|
return -1;
|
|
}
|
|
if (this.major > other.major) {
|
|
return 1;
|
|
}
|
|
if (this.minor < other.minor) {
|
|
return -1;
|
|
}
|
|
if (this.minor > other.minor) {
|
|
return 1;
|
|
}
|
|
if (this.patch < other.patch) {
|
|
return -1;
|
|
}
|
|
if (this.patch > other.patch) {
|
|
return 1;
|
|
}
|
|
return 0;
|
|
}
|
|
comparePre(other) {
|
|
if (!(other instanceof SemVer)) {
|
|
other = new SemVer(other, this.options);
|
|
}
|
|
if (this.prerelease.length && !other.prerelease.length) {
|
|
return -1;
|
|
} else if (!this.prerelease.length && other.prerelease.length) {
|
|
return 1;
|
|
} else if (!this.prerelease.length && !other.prerelease.length) {
|
|
return 0;
|
|
}
|
|
let i = 0;
|
|
do {
|
|
const a = this.prerelease[i];
|
|
const b = other.prerelease[i];
|
|
debug("prerelease compare", i, a, b);
|
|
if (a === undefined && b === undefined) {
|
|
return 0;
|
|
} else if (b === undefined) {
|
|
return 1;
|
|
} else if (a === undefined) {
|
|
return -1;
|
|
} else if (a === b) {
|
|
continue;
|
|
} else {
|
|
return compareIdentifiers(a, b);
|
|
}
|
|
} while (++i);
|
|
}
|
|
compareBuild(other) {
|
|
if (!(other instanceof SemVer)) {
|
|
other = new SemVer(other, this.options);
|
|
}
|
|
let i = 0;
|
|
do {
|
|
const a = this.build[i];
|
|
const b = other.build[i];
|
|
debug("build compare", i, a, b);
|
|
if (a === undefined && b === undefined) {
|
|
return 0;
|
|
} else if (b === undefined) {
|
|
return 1;
|
|
} else if (a === undefined) {
|
|
return -1;
|
|
} else if (a === b) {
|
|
continue;
|
|
} else {
|
|
return compareIdentifiers(a, b);
|
|
}
|
|
} while (++i);
|
|
}
|
|
inc(release, identifier, identifierBase) {
|
|
if (release.startsWith("pre")) {
|
|
if (!identifier && identifierBase === false) {
|
|
throw new Error("invalid increment argument: identifier is empty");
|
|
}
|
|
if (identifier) {
|
|
const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);
|
|
if (!match || match[1] !== identifier) {
|
|
throw new Error(`invalid identifier: ${identifier}`);
|
|
}
|
|
}
|
|
}
|
|
switch (release) {
|
|
case "premajor":
|
|
this.prerelease.length = 0;
|
|
this.patch = 0;
|
|
this.minor = 0;
|
|
this.major++;
|
|
this.inc("pre", identifier, identifierBase);
|
|
break;
|
|
case "preminor":
|
|
this.prerelease.length = 0;
|
|
this.patch = 0;
|
|
this.minor++;
|
|
this.inc("pre", identifier, identifierBase);
|
|
break;
|
|
case "prepatch":
|
|
this.prerelease.length = 0;
|
|
this.inc("patch", identifier, identifierBase);
|
|
this.inc("pre", identifier, identifierBase);
|
|
break;
|
|
case "prerelease":
|
|
if (this.prerelease.length === 0) {
|
|
this.inc("patch", identifier, identifierBase);
|
|
}
|
|
this.inc("pre", identifier, identifierBase);
|
|
break;
|
|
case "release":
|
|
if (this.prerelease.length === 0) {
|
|
throw new Error(`version ${this.raw} is not a prerelease`);
|
|
}
|
|
this.prerelease.length = 0;
|
|
break;
|
|
case "major":
|
|
if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
|
|
this.major++;
|
|
}
|
|
this.minor = 0;
|
|
this.patch = 0;
|
|
this.prerelease = [];
|
|
break;
|
|
case "minor":
|
|
if (this.patch !== 0 || this.prerelease.length === 0) {
|
|
this.minor++;
|
|
}
|
|
this.patch = 0;
|
|
this.prerelease = [];
|
|
break;
|
|
case "patch":
|
|
if (this.prerelease.length === 0) {
|
|
this.patch++;
|
|
}
|
|
this.prerelease = [];
|
|
break;
|
|
case "pre": {
|
|
const base = Number(identifierBase) ? 1 : 0;
|
|
if (this.prerelease.length === 0) {
|
|
this.prerelease = [base];
|
|
} else {
|
|
let i = this.prerelease.length;
|
|
while (--i >= 0) {
|
|
if (typeof this.prerelease[i] === "number") {
|
|
this.prerelease[i]++;
|
|
i = -2;
|
|
}
|
|
}
|
|
if (i === -1) {
|
|
if (identifier === this.prerelease.join(".") && identifierBase === false) {
|
|
throw new Error("invalid increment argument: identifier already exists");
|
|
}
|
|
this.prerelease.push(base);
|
|
}
|
|
}
|
|
if (identifier) {
|
|
let prerelease = [identifier, base];
|
|
if (identifierBase === false) {
|
|
prerelease = [identifier];
|
|
}
|
|
if (isPrereleaseIdentifier(this.prerelease, identifier)) {
|
|
const prereleaseBase = this.prerelease[identifier.split(".").length];
|
|
if (isNaN(prereleaseBase)) {
|
|
this.prerelease = prerelease;
|
|
}
|
|
} else {
|
|
this.prerelease = prerelease;
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
default:
|
|
throw new Error(`invalid increment argument: ${release}`);
|
|
}
|
|
this.raw = this.format();
|
|
if (this.build.length) {
|
|
this.raw += `+${this.build.join(".")}`;
|
|
}
|
|
return this;
|
|
}
|
|
}
|
|
module2.exports = SemVer;
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/functions/parse.js
|
|
var require_parse = __commonJS((exports2, module2) => {
|
|
var SemVer = require_semver();
|
|
var parse = (version, options, throwErrors = false) => {
|
|
if (version instanceof SemVer) {
|
|
return version;
|
|
}
|
|
try {
|
|
return new SemVer(version, options);
|
|
} catch (er) {
|
|
if (!throwErrors) {
|
|
return null;
|
|
}
|
|
throw er;
|
|
}
|
|
};
|
|
module2.exports = parse;
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/internal/lrucache.js
|
|
var require_lrucache = __commonJS((exports2, module2) => {
|
|
class LRUCache {
|
|
constructor() {
|
|
this.max = 1000;
|
|
this.map = new Map;
|
|
}
|
|
get(key) {
|
|
const value = this.map.get(key);
|
|
if (value === undefined) {
|
|
return;
|
|
} else {
|
|
this.map.delete(key);
|
|
this.map.set(key, value);
|
|
return value;
|
|
}
|
|
}
|
|
delete(key) {
|
|
return this.map.delete(key);
|
|
}
|
|
set(key, value) {
|
|
const deleted = this.delete(key);
|
|
if (!deleted && value !== undefined) {
|
|
if (this.map.size >= this.max) {
|
|
const firstKey = this.map.keys().next().value;
|
|
this.delete(firstKey);
|
|
}
|
|
this.map.set(key, value);
|
|
}
|
|
return this;
|
|
}
|
|
}
|
|
module2.exports = LRUCache;
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/functions/compare.js
|
|
var require_compare = __commonJS((exports2, module2) => {
|
|
var SemVer = require_semver();
|
|
var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose));
|
|
module2.exports = compare;
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/functions/eq.js
|
|
var require_eq = __commonJS((exports2, module2) => {
|
|
var compare = require_compare();
|
|
var eq = (a, b, loose) => compare(a, b, loose) === 0;
|
|
module2.exports = eq;
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/functions/neq.js
|
|
var require_neq = __commonJS((exports2, module2) => {
|
|
var compare = require_compare();
|
|
var neq = (a, b, loose) => compare(a, b, loose) !== 0;
|
|
module2.exports = neq;
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/functions/gt.js
|
|
var require_gt = __commonJS((exports2, module2) => {
|
|
var compare = require_compare();
|
|
var gt = (a, b, loose) => compare(a, b, loose) > 0;
|
|
module2.exports = gt;
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/functions/gte.js
|
|
var require_gte = __commonJS((exports2, module2) => {
|
|
var compare = require_compare();
|
|
var gte = (a, b, loose) => compare(a, b, loose) >= 0;
|
|
module2.exports = gte;
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/functions/lt.js
|
|
var require_lt = __commonJS((exports2, module2) => {
|
|
var compare = require_compare();
|
|
var lt = (a, b, loose) => compare(a, b, loose) < 0;
|
|
module2.exports = lt;
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/functions/lte.js
|
|
var require_lte = __commonJS((exports2, module2) => {
|
|
var compare = require_compare();
|
|
var lte = (a, b, loose) => compare(a, b, loose) <= 0;
|
|
module2.exports = lte;
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/functions/cmp.js
|
|
var require_cmp = __commonJS((exports2, module2) => {
|
|
var eq = require_eq();
|
|
var neq = require_neq();
|
|
var gt = require_gt();
|
|
var gte = require_gte();
|
|
var lt = require_lt();
|
|
var lte = require_lte();
|
|
var cmp = (a, op, b, loose) => {
|
|
switch (op) {
|
|
case "===":
|
|
if (typeof a === "object") {
|
|
a = a.version;
|
|
}
|
|
if (typeof b === "object") {
|
|
b = b.version;
|
|
}
|
|
return a === b;
|
|
case "!==":
|
|
if (typeof a === "object") {
|
|
a = a.version;
|
|
}
|
|
if (typeof b === "object") {
|
|
b = b.version;
|
|
}
|
|
return a !== b;
|
|
case "":
|
|
case "=":
|
|
case "==":
|
|
return eq(a, b, loose);
|
|
case "!=":
|
|
return neq(a, b, loose);
|
|
case ">":
|
|
return gt(a, b, loose);
|
|
case ">=":
|
|
return gte(a, b, loose);
|
|
case "<":
|
|
return lt(a, b, loose);
|
|
case "<=":
|
|
return lte(a, b, loose);
|
|
default:
|
|
throw new TypeError(`Invalid operator: ${op}`);
|
|
}
|
|
};
|
|
module2.exports = cmp;
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/classes/comparator.js
|
|
var require_comparator = __commonJS((exports2, module2) => {
|
|
var ANY = Symbol("SemVer ANY");
|
|
|
|
class Comparator {
|
|
static get ANY() {
|
|
return ANY;
|
|
}
|
|
constructor(comp, options) {
|
|
options = parseOptions(options);
|
|
if (comp instanceof Comparator) {
|
|
if (comp.loose === !!options.loose) {
|
|
return comp;
|
|
} else {
|
|
comp = comp.value;
|
|
}
|
|
}
|
|
comp = comp.trim().split(/\s+/).join(" ");
|
|
debug("comparator", comp, options);
|
|
this.options = options;
|
|
this.loose = !!options.loose;
|
|
this.parse(comp);
|
|
if (this.semver === ANY) {
|
|
this.value = "";
|
|
} else {
|
|
this.value = this.operator + this.semver.version;
|
|
}
|
|
debug("comp", this);
|
|
}
|
|
parse(comp) {
|
|
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
|
|
const m = comp.match(r);
|
|
if (!m) {
|
|
throw new TypeError(`Invalid comparator: ${comp}`);
|
|
}
|
|
this.operator = m[1] !== undefined ? m[1] : "";
|
|
if (this.operator === "=") {
|
|
this.operator = "";
|
|
}
|
|
if (!m[2]) {
|
|
this.semver = ANY;
|
|
} else {
|
|
this.semver = new SemVer(m[2], this.options.loose);
|
|
}
|
|
}
|
|
toString() {
|
|
return this.value;
|
|
}
|
|
test(version) {
|
|
debug("Comparator.test", version, this.options.loose);
|
|
if (this.semver === ANY || version === ANY) {
|
|
return true;
|
|
}
|
|
if (typeof version === "string") {
|
|
try {
|
|
version = new SemVer(version, this.options);
|
|
} catch (er) {
|
|
return false;
|
|
}
|
|
}
|
|
return cmp(version, this.operator, this.semver, this.options);
|
|
}
|
|
intersects(comp, options) {
|
|
if (!(comp instanceof Comparator)) {
|
|
throw new TypeError("a Comparator is required");
|
|
}
|
|
if (this.operator === "") {
|
|
if (this.value === "") {
|
|
return true;
|
|
}
|
|
return new Range(comp.value, options).test(this.value);
|
|
} else if (comp.operator === "") {
|
|
if (comp.value === "") {
|
|
return true;
|
|
}
|
|
return new Range(this.value, options).test(comp.semver);
|
|
}
|
|
options = parseOptions(options);
|
|
if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
|
|
return false;
|
|
}
|
|
if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
|
|
return false;
|
|
}
|
|
if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
|
|
return true;
|
|
}
|
|
if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
|
|
return true;
|
|
}
|
|
if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
|
|
return true;
|
|
}
|
|
if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
|
|
return true;
|
|
}
|
|
if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
module2.exports = Comparator;
|
|
var parseOptions = require_parse_options();
|
|
var { safeRe: re, t } = require_re();
|
|
var cmp = require_cmp();
|
|
var debug = require_debug();
|
|
var SemVer = require_semver();
|
|
var Range = require_range();
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/classes/range.js
|
|
var require_range = __commonJS((exports2, module2) => {
|
|
var SPACE_CHARACTERS = /\s+/g;
|
|
|
|
class Range {
|
|
constructor(range, options) {
|
|
options = parseOptions(options);
|
|
if (range instanceof Range) {
|
|
if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
|
|
return range;
|
|
} else {
|
|
return new Range(range.raw, options);
|
|
}
|
|
}
|
|
if (range instanceof Comparator) {
|
|
this.raw = range.value;
|
|
this.set = [[range]];
|
|
this.formatted = undefined;
|
|
return this;
|
|
}
|
|
this.options = options;
|
|
this.loose = !!options.loose;
|
|
this.includePrerelease = !!options.includePrerelease;
|
|
this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
|
|
this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length);
|
|
if (!this.set.length) {
|
|
throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
|
|
}
|
|
if (this.set.length > 1) {
|
|
const first = this.set[0];
|
|
this.set = this.set.filter((c) => !isNullSet(c[0]));
|
|
if (this.set.length === 0) {
|
|
this.set = [first];
|
|
} else if (this.set.length > 1) {
|
|
for (const c of this.set) {
|
|
if (c.length === 1 && isAny(c[0])) {
|
|
this.set = [c];
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
this.formatted = undefined;
|
|
}
|
|
get range() {
|
|
if (this.formatted === undefined) {
|
|
this.formatted = "";
|
|
for (let i = 0;i < this.set.length; i++) {
|
|
if (i > 0) {
|
|
this.formatted += "||";
|
|
}
|
|
const comps = this.set[i];
|
|
for (let k = 0;k < comps.length; k++) {
|
|
if (k > 0) {
|
|
this.formatted += " ";
|
|
}
|
|
this.formatted += comps[k].toString().trim();
|
|
}
|
|
}
|
|
}
|
|
return this.formatted;
|
|
}
|
|
format() {
|
|
return this.range;
|
|
}
|
|
toString() {
|
|
return this.range;
|
|
}
|
|
parseRange(range) {
|
|
range = range.replace(BUILDSTRIPRE, "");
|
|
const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
|
|
const memoKey = memoOpts + ":" + range;
|
|
const cached = cache.get(memoKey);
|
|
if (cached) {
|
|
return cached;
|
|
}
|
|
const loose = this.options.loose;
|
|
const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
|
|
range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
|
|
debug("hyphen replace", range);
|
|
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
|
|
debug("comparator trim", range);
|
|
range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
|
|
debug("tilde trim", range);
|
|
range = range.replace(re[t.CARETTRIM], caretTrimReplace);
|
|
debug("caret trim", range);
|
|
let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
|
|
if (loose) {
|
|
rangeList = rangeList.filter((comp) => {
|
|
debug("loose invalid filter", comp, this.options);
|
|
return !!comp.match(re[t.COMPARATORLOOSE]);
|
|
});
|
|
}
|
|
debug("range list", rangeList);
|
|
const rangeMap = new Map;
|
|
const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
|
|
for (const comp of comparators) {
|
|
if (isNullSet(comp)) {
|
|
return [comp];
|
|
}
|
|
rangeMap.set(comp.value, comp);
|
|
}
|
|
if (rangeMap.size > 1 && rangeMap.has("")) {
|
|
rangeMap.delete("");
|
|
}
|
|
const result = [...rangeMap.values()];
|
|
cache.set(memoKey, result);
|
|
return result;
|
|
}
|
|
intersects(range, options) {
|
|
if (!(range instanceof Range)) {
|
|
throw new TypeError("a Range is required");
|
|
}
|
|
return this.set.some((thisComparators) => {
|
|
return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
|
|
return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
|
|
return rangeComparators.every((rangeComparator) => {
|
|
return thisComparator.intersects(rangeComparator, options);
|
|
});
|
|
});
|
|
});
|
|
});
|
|
}
|
|
test(version) {
|
|
if (!version) {
|
|
return false;
|
|
}
|
|
if (typeof version === "string") {
|
|
try {
|
|
version = new SemVer(version, this.options);
|
|
} catch (er) {
|
|
return false;
|
|
}
|
|
}
|
|
for (let i = 0;i < this.set.length; i++) {
|
|
if (testSet(this.set[i], version, this.options)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
module2.exports = Range;
|
|
var LRU = require_lrucache();
|
|
var cache = new LRU;
|
|
var parseOptions = require_parse_options();
|
|
var Comparator = require_comparator();
|
|
var debug = require_debug();
|
|
var SemVer = require_semver();
|
|
var {
|
|
safeRe: re,
|
|
src,
|
|
t,
|
|
comparatorTrimReplace,
|
|
tildeTrimReplace,
|
|
caretTrimReplace
|
|
} = require_re();
|
|
var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants();
|
|
var BUILDSTRIPRE = new RegExp(src[t.BUILD], "g");
|
|
var isNullSet = (c) => c.value === "<0.0.0-0";
|
|
var isAny = (c) => c.value === "";
|
|
var isSatisfiable = (comparators, options) => {
|
|
let result = true;
|
|
const remainingComparators = comparators.slice();
|
|
let testComparator = remainingComparators.pop();
|
|
while (result && remainingComparators.length) {
|
|
result = remainingComparators.every((otherComparator) => {
|
|
return testComparator.intersects(otherComparator, options);
|
|
});
|
|
testComparator = remainingComparators.pop();
|
|
}
|
|
return result;
|
|
};
|
|
var parseComparator = (comp, options) => {
|
|
comp = comp.replace(re[t.BUILD], "");
|
|
debug("comp", comp, options);
|
|
comp = replaceCarets(comp, options);
|
|
debug("caret", comp);
|
|
comp = replaceTildes(comp, options);
|
|
debug("tildes", comp);
|
|
comp = replaceXRanges(comp, options);
|
|
debug("xrange", comp);
|
|
comp = replaceStars(comp, options);
|
|
debug("stars", comp);
|
|
return comp;
|
|
};
|
|
var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
|
|
var invalidXRangeOrder = (M, m, p) => isX(M) && !isX(m) || isX(m) && p && !isX(p);
|
|
var replaceTildes = (comp, options) => {
|
|
return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" ");
|
|
};
|
|
var replaceTilde = (comp, options) => {
|
|
const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
|
|
const z = options.includePrerelease ? "-0" : "";
|
|
return comp.replace(r, (_, M, m, p, pr) => {
|
|
debug("tilde", comp, _, M, m, p, pr);
|
|
let ret;
|
|
if (isX(M)) {
|
|
ret = "";
|
|
} else if (isX(m)) {
|
|
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
|
|
} else if (isX(p)) {
|
|
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
|
|
} else if (pr) {
|
|
debug("replaceTilde pr", pr);
|
|
ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
|
|
} else {
|
|
ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
|
|
}
|
|
debug("tilde return", ret);
|
|
return ret;
|
|
});
|
|
};
|
|
var replaceCarets = (comp, options) => {
|
|
return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" ");
|
|
};
|
|
var replaceCaret = (comp, options) => {
|
|
debug("caret", comp, options);
|
|
const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
|
|
const z = options.includePrerelease ? "-0" : "";
|
|
return comp.replace(r, (_, M, m, p, pr) => {
|
|
debug("caret", comp, _, M, m, p, pr);
|
|
let ret;
|
|
if (isX(M)) {
|
|
ret = "";
|
|
} else if (isX(m)) {
|
|
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
|
|
} else if (isX(p)) {
|
|
if (M === "0") {
|
|
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
|
|
} else {
|
|
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
|
|
}
|
|
} else if (pr) {
|
|
debug("replaceCaret pr", pr);
|
|
if (M === "0") {
|
|
if (m === "0") {
|
|
ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
|
|
} else {
|
|
ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
|
|
}
|
|
} else {
|
|
ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
|
|
}
|
|
} else {
|
|
debug("no pr");
|
|
if (M === "0") {
|
|
if (m === "0") {
|
|
ret = `>=${M}.${m}.${p} <${M}.${m}.${+p + 1}-0`;
|
|
} else {
|
|
ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
|
|
}
|
|
} else {
|
|
ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
|
|
}
|
|
}
|
|
debug("caret return", ret);
|
|
return ret;
|
|
});
|
|
};
|
|
var replaceXRanges = (comp, options) => {
|
|
debug("replaceXRanges", comp, options);
|
|
return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" ");
|
|
};
|
|
var replaceXRange = (comp, options) => {
|
|
comp = comp.trim();
|
|
const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
|
|
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
|
|
debug("xRange", comp, ret, gtlt, M, m, p, pr);
|
|
if (invalidXRangeOrder(M, m, p)) {
|
|
return comp;
|
|
}
|
|
const xM = isX(M);
|
|
const xm = xM || isX(m);
|
|
const xp = xm || isX(p);
|
|
const anyX = xp;
|
|
if (gtlt === "=" && anyX) {
|
|
gtlt = "";
|
|
}
|
|
pr = options.includePrerelease ? "-0" : "";
|
|
if (xM) {
|
|
if (gtlt === ">" || gtlt === "<") {
|
|
ret = "<0.0.0-0";
|
|
} else {
|
|
ret = "*";
|
|
}
|
|
} else if (gtlt && anyX) {
|
|
if (xm) {
|
|
m = 0;
|
|
}
|
|
p = 0;
|
|
if (gtlt === ">") {
|
|
gtlt = ">=";
|
|
if (xm) {
|
|
M = +M + 1;
|
|
m = 0;
|
|
p = 0;
|
|
} else {
|
|
m = +m + 1;
|
|
p = 0;
|
|
}
|
|
} else if (gtlt === "<=") {
|
|
gtlt = "<";
|
|
if (xm) {
|
|
M = +M + 1;
|
|
} else {
|
|
m = +m + 1;
|
|
}
|
|
}
|
|
if (gtlt === "<") {
|
|
pr = "-0";
|
|
}
|
|
ret = `${gtlt + M}.${m}.${p}${pr}`;
|
|
} else if (xm) {
|
|
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
|
|
} else if (xp) {
|
|
ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
|
|
}
|
|
debug("xRange return", ret);
|
|
return ret;
|
|
});
|
|
};
|
|
var replaceStars = (comp, options) => {
|
|
debug("replaceStars", comp, options);
|
|
return comp.trim().replace(re[t.STAR], "");
|
|
};
|
|
var replaceGTE0 = (comp, options) => {
|
|
debug("replaceGTE0", comp, options);
|
|
return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");
|
|
};
|
|
var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
|
|
if (isX(fM)) {
|
|
from = "";
|
|
} else if (isX(fm)) {
|
|
from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
|
|
} else if (isX(fp)) {
|
|
from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
|
|
} else if (fpr) {
|
|
from = `>=${from}`;
|
|
} else {
|
|
from = `>=${from}${incPr ? "-0" : ""}`;
|
|
}
|
|
if (isX(tM)) {
|
|
to = "";
|
|
} else if (isX(tm)) {
|
|
to = `<${+tM + 1}.0.0-0`;
|
|
} else if (isX(tp)) {
|
|
to = `<${tM}.${+tm + 1}.0-0`;
|
|
} else if (tpr) {
|
|
to = `<=${tM}.${tm}.${tp}-${tpr}`;
|
|
} else if (incPr) {
|
|
to = `<${tM}.${tm}.${+tp + 1}-0`;
|
|
} else {
|
|
to = `<=${to}`;
|
|
}
|
|
return `${from} ${to}`.trim();
|
|
};
|
|
var testSet = (set, version, options) => {
|
|
for (let i = 0;i < set.length; i++) {
|
|
if (!set[i].test(version)) {
|
|
return false;
|
|
}
|
|
}
|
|
if (version.prerelease.length && !options.includePrerelease) {
|
|
for (let i = 0;i < set.length; i++) {
|
|
debug(set[i].semver);
|
|
if (set[i].semver === Comparator.ANY) {
|
|
continue;
|
|
}
|
|
if (set[i].semver.prerelease.length > 0) {
|
|
const allowed = set[i].semver;
|
|
if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
return true;
|
|
};
|
|
});
|
|
|
|
// editors/vscode/node_modules/semver/functions/satisfies.js
|
|
var require_satisfies = __commonJS((exports2, module2) => {
|
|
var Range = require_range();
|
|
var satisfies = (version, range, options) => {
|
|
try {
|
|
range = new Range(range, options);
|
|
} catch (er) {
|
|
return false;
|
|
}
|
|
return range.test(version);
|
|
};
|
|
module2.exports = satisfies;
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/common/api.js
|
|
var require_api3 = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
|
|
for (var p in m)
|
|
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p))
|
|
__createBinding(exports3, m, p);
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.DiagnosticPullMode = exports2.vsdiag = undefined;
|
|
__exportStar(require_api2(), exports2);
|
|
__exportStar(require_features(), exports2);
|
|
var diagnostic_1 = require_diagnostic();
|
|
Object.defineProperty(exports2, "vsdiag", { enumerable: true, get: function() {
|
|
return diagnostic_1.vsdiag;
|
|
} });
|
|
Object.defineProperty(exports2, "DiagnosticPullMode", { enumerable: true, get: function() {
|
|
return diagnostic_1.DiagnosticPullMode;
|
|
} });
|
|
__exportStar(require_client(), exports2);
|
|
});
|
|
|
|
// editors/vscode/node_modules/vscode-languageclient/lib/node/main.js
|
|
var require_main5 = __commonJS((exports2) => {
|
|
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
} : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = exports2 && exports2.__importStar || function() {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
var ar = [];
|
|
for (var k in o2)
|
|
if (Object.prototype.hasOwnProperty.call(o2, k))
|
|
ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function(mod) {
|
|
if (mod && mod.__esModule)
|
|
return mod;
|
|
var result = {};
|
|
if (mod != null) {
|
|
for (var k = ownKeys(mod), i = 0;i < k.length; i++)
|
|
if (k[i] !== "default")
|
|
__createBinding(result, mod, k[i]);
|
|
}
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
}();
|
|
var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
|
|
for (var p in m)
|
|
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p))
|
|
__createBinding(exports3, m, p);
|
|
};
|
|
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
exports2.SettingMonitor = exports2.LanguageClient = exports2.TransportKind = undefined;
|
|
var cp = __importStar(require("child_process"));
|
|
var fs = __importStar(require("fs"));
|
|
var path = __importStar(require("path"));
|
|
var readline = __importStar(require("readline"));
|
|
var vscode_1 = require("vscode");
|
|
var Is = __importStar(require_is());
|
|
var client_1 = require_client();
|
|
var processes_1 = require_processes();
|
|
var node_1 = require_main4();
|
|
var semverParse = require_parse();
|
|
var semverSatisfies = require_satisfies();
|
|
__exportStar(require_main4(), exports2);
|
|
__exportStar(require_api3(), exports2);
|
|
var REQUIRED_VSCODE_VERSION = "^1.91.0";
|
|
var TransportKind;
|
|
(function(TransportKind2) {
|
|
TransportKind2[TransportKind2["stdio"] = 0] = "stdio";
|
|
TransportKind2[TransportKind2["ipc"] = 1] = "ipc";
|
|
TransportKind2[TransportKind2["pipe"] = 2] = "pipe";
|
|
TransportKind2[TransportKind2["socket"] = 3] = "socket";
|
|
})(TransportKind || (exports2.TransportKind = TransportKind = {}));
|
|
var Transport;
|
|
(function(Transport2) {
|
|
function isSocket(value) {
|
|
const candidate = value;
|
|
return candidate && candidate.kind === TransportKind.socket && Is.number(candidate.port);
|
|
}
|
|
Transport2.isSocket = isSocket;
|
|
})(Transport || (Transport = {}));
|
|
var Executable;
|
|
(function(Executable2) {
|
|
function is(value) {
|
|
return Is.string(value.command);
|
|
}
|
|
Executable2.is = is;
|
|
})(Executable || (Executable = {}));
|
|
var NodeModule;
|
|
(function(NodeModule2) {
|
|
function is(value) {
|
|
return Is.string(value.module);
|
|
}
|
|
NodeModule2.is = is;
|
|
})(NodeModule || (NodeModule = {}));
|
|
var StreamInfo;
|
|
(function(StreamInfo2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && candidate.writer !== undefined && candidate.reader !== undefined;
|
|
}
|
|
StreamInfo2.is = is;
|
|
})(StreamInfo || (StreamInfo = {}));
|
|
var ChildProcessInfo;
|
|
(function(ChildProcessInfo2) {
|
|
function is(value) {
|
|
const candidate = value;
|
|
return candidate && candidate.process !== undefined && typeof candidate.detached === "boolean";
|
|
}
|
|
ChildProcessInfo2.is = is;
|
|
})(ChildProcessInfo || (ChildProcessInfo = {}));
|
|
|
|
class LanguageClient extends client_1.BaseLanguageClient {
|
|
_serverOptions;
|
|
_forceDebug;
|
|
_serverProcess;
|
|
_isDetached;
|
|
_isInDebugMode;
|
|
constructor(arg1, arg2, arg3, arg4, arg5) {
|
|
let id;
|
|
let name;
|
|
let serverOptions;
|
|
let clientOptions;
|
|
let forceDebug;
|
|
if (Is.string(arg2)) {
|
|
id = arg1;
|
|
name = arg2;
|
|
serverOptions = arg3;
|
|
clientOptions = arg4;
|
|
forceDebug = !!arg5;
|
|
} else {
|
|
id = arg1.toLowerCase();
|
|
name = arg1;
|
|
serverOptions = arg2;
|
|
clientOptions = arg3;
|
|
forceDebug = arg4;
|
|
}
|
|
if (forceDebug === undefined) {
|
|
forceDebug = false;
|
|
}
|
|
super(id, name, clientOptions);
|
|
this._serverOptions = serverOptions;
|
|
this._forceDebug = forceDebug;
|
|
this._isInDebugMode = forceDebug;
|
|
try {
|
|
this.checkVersion();
|
|
} catch (error) {
|
|
if (Is.string(error.message)) {
|
|
this.outputChannel.appendLine(error.message);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
checkVersion() {
|
|
const codeVersion = semverParse(vscode_1.version);
|
|
if (!codeVersion) {
|
|
throw new Error(`No valid VS Code version detected. Version string is: ${vscode_1.version}`);
|
|
}
|
|
if (codeVersion.prerelease && codeVersion.prerelease.length > 0) {
|
|
codeVersion.prerelease = [];
|
|
}
|
|
if (!semverSatisfies(codeVersion, REQUIRED_VSCODE_VERSION)) {
|
|
throw new Error(`The language client requires VS Code version ${REQUIRED_VSCODE_VERSION} but received version ${vscode_1.version}`);
|
|
}
|
|
}
|
|
get isInDebugMode() {
|
|
return this._isInDebugMode;
|
|
}
|
|
get serverProcess() {
|
|
return this._serverProcess;
|
|
}
|
|
async restart() {
|
|
await this.stop();
|
|
if (this.isInDebugMode) {
|
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
await this.start();
|
|
} else {
|
|
await this.start();
|
|
}
|
|
}
|
|
shutdown(mode, timeout = 2000) {
|
|
return super.shutdown(mode, timeout).finally(() => {
|
|
if (this._serverProcess) {
|
|
const toCheck = this._serverProcess;
|
|
this._serverProcess = undefined;
|
|
if (this._isDetached === undefined || !this._isDetached) {
|
|
this.checkProcessDied(toCheck);
|
|
}
|
|
this._isDetached = undefined;
|
|
}
|
|
});
|
|
}
|
|
checkProcessDied(childProcess) {
|
|
if (!childProcess || childProcess.pid === undefined) {
|
|
return;
|
|
}
|
|
setTimeout(() => {
|
|
try {
|
|
if (childProcess.pid !== undefined) {
|
|
process.kill(childProcess.pid, 0);
|
|
(0, processes_1.terminate)(childProcess);
|
|
}
|
|
} catch (error) {}
|
|
}, 2000);
|
|
}
|
|
handleConnectionClosed() {
|
|
this._serverProcess = undefined;
|
|
return super.handleConnectionClosed();
|
|
}
|
|
fillInitializeParams(params) {
|
|
super.fillInitializeParams(params);
|
|
if (params.processId === null) {
|
|
params.processId = process.pid;
|
|
}
|
|
}
|
|
createMessageTransports(_encoding) {
|
|
function getEnvironment(env, fork) {
|
|
if (!env && !fork) {
|
|
return;
|
|
}
|
|
const result = Object.create(null);
|
|
Object.keys(process.env).forEach((key) => result[key] = process.env[key]);
|
|
if (fork) {
|
|
result["ELECTRON_RUN_AS_NODE"] = "1";
|
|
result["ELECTRON_NO_ASAR"] = "1";
|
|
}
|
|
if (env) {
|
|
Object.keys(env).forEach((key) => result[key] = env[key]);
|
|
}
|
|
return result;
|
|
}
|
|
const debugStartWith = ["--debug=", "--debug-brk=", "--inspect=", "--inspect-brk="];
|
|
const debugEquals = ["--debug", "--debug-brk", "--inspect", "--inspect-brk"];
|
|
function startedInDebugMode() {
|
|
const args = process.execArgv;
|
|
if (args) {
|
|
return args.some((arg) => {
|
|
return debugStartWith.some((value) => arg.startsWith(value)) || debugEquals.some((value) => arg === value);
|
|
});
|
|
}
|
|
return false;
|
|
}
|
|
function assertStdio(process2) {
|
|
if (process2.stdin === null || process2.stdout === null || process2.stderr === null) {
|
|
throw new Error("Process created without stdio streams");
|
|
}
|
|
}
|
|
function pipeStdoutToLogOutputChannel(input, outputChannel) {
|
|
readline.createInterface({
|
|
input,
|
|
crlfDelay: Infinity,
|
|
terminal: false,
|
|
historySize: 0
|
|
}).on("line", (data) => outputChannel.info(data));
|
|
}
|
|
function pipeStderrToLogOutputChannel(input, outputChannel) {
|
|
readline.createInterface({
|
|
input,
|
|
crlfDelay: Infinity,
|
|
terminal: false,
|
|
historySize: 0
|
|
}).on("line", (data) => outputChannel.error(data));
|
|
}
|
|
const server = this._serverOptions;
|
|
if (Is.func(server)) {
|
|
return server().then((result) => {
|
|
if (client_1.MessageTransports.is(result)) {
|
|
this._isDetached = !!result.detached;
|
|
return result;
|
|
} else if (StreamInfo.is(result)) {
|
|
this._isDetached = !!result.detached;
|
|
return { reader: new node_1.StreamMessageReader(result.reader), writer: new node_1.StreamMessageWriter(result.writer) };
|
|
} else {
|
|
let cp2;
|
|
if (ChildProcessInfo.is(result)) {
|
|
cp2 = result.process;
|
|
this._isDetached = result.detached;
|
|
} else {
|
|
cp2 = result;
|
|
this._isDetached = false;
|
|
}
|
|
pipeStderrToLogOutputChannel(cp2.stderr, this.outputChannel);
|
|
return { reader: new node_1.StreamMessageReader(cp2.stdout), writer: new node_1.StreamMessageWriter(cp2.stdin) };
|
|
}
|
|
});
|
|
}
|
|
let json;
|
|
const runDebug = server;
|
|
if (runDebug.run || runDebug.debug) {
|
|
if (this._forceDebug || startedInDebugMode()) {
|
|
json = runDebug.debug;
|
|
this._isInDebugMode = true;
|
|
} else {
|
|
json = runDebug.run;
|
|
this._isInDebugMode = false;
|
|
}
|
|
} else {
|
|
json = server;
|
|
}
|
|
return this._getServerWorkingDir(json.options).then((serverWorkingDir) => {
|
|
if (NodeModule.is(json) && json.module) {
|
|
const node = json;
|
|
const transport = node.transport || TransportKind.stdio;
|
|
if (node.runtime) {
|
|
const args = [];
|
|
const options = node.options ?? Object.create(null);
|
|
if (options.execArgv) {
|
|
options.execArgv.forEach((element) => args.push(element));
|
|
}
|
|
args.push(node.module);
|
|
if (node.args) {
|
|
node.args.forEach((element) => args.push(element));
|
|
}
|
|
const execOptions = Object.create(null);
|
|
execOptions.cwd = serverWorkingDir;
|
|
execOptions.env = getEnvironment(options.env, false);
|
|
const runtime = this._getRuntimePath(node.runtime, serverWorkingDir);
|
|
let pipeName = undefined;
|
|
if (transport === TransportKind.ipc) {
|
|
execOptions.stdio = [null, null, null, "ipc"];
|
|
args.push("--node-ipc");
|
|
} else if (transport === TransportKind.stdio) {
|
|
args.push("--stdio");
|
|
} else if (transport === TransportKind.pipe) {
|
|
pipeName = (0, node_1.generateRandomPipeName)();
|
|
args.push(`--pipe=${pipeName}`);
|
|
} else if (Transport.isSocket(transport)) {
|
|
args.push(`--socket=${transport.port}`);
|
|
}
|
|
args.push(`--clientProcessId=${process.pid.toString()}`);
|
|
if (transport === TransportKind.ipc || transport === TransportKind.stdio) {
|
|
const serverProcess = cp.spawn(runtime, args, execOptions);
|
|
if (!serverProcess || !serverProcess.pid) {
|
|
return handleChildProcessStartError(serverProcess, `Launching server using runtime ${runtime} failed.`);
|
|
}
|
|
this._serverProcess = serverProcess;
|
|
pipeStderrToLogOutputChannel(serverProcess.stderr, this.outputChannel);
|
|
if (transport === TransportKind.ipc) {
|
|
pipeStdoutToLogOutputChannel(serverProcess.stdout, this.outputChannel);
|
|
return Promise.resolve({ reader: new node_1.IPCMessageReader(serverProcess), writer: new node_1.IPCMessageWriter(serverProcess) });
|
|
} else {
|
|
return Promise.resolve({ reader: new node_1.StreamMessageReader(serverProcess.stdout), writer: new node_1.StreamMessageWriter(serverProcess.stdin) });
|
|
}
|
|
} else if (transport === TransportKind.pipe) {
|
|
return (0, node_1.createClientPipeTransport)(pipeName).then((transport2) => {
|
|
const process2 = cp.spawn(runtime, args, execOptions);
|
|
if (!process2 || !process2.pid) {
|
|
return handleChildProcessStartError(process2, `Launching server using runtime ${runtime} failed.`);
|
|
}
|
|
this._serverProcess = process2;
|
|
pipeStderrToLogOutputChannel(process2.stderr, this.outputChannel);
|
|
pipeStdoutToLogOutputChannel(process2.stdout, this.outputChannel);
|
|
return transport2.onConnected().then((protocol) => {
|
|
return { reader: protocol[0], writer: protocol[1] };
|
|
});
|
|
});
|
|
} else if (Transport.isSocket(transport)) {
|
|
return (0, node_1.createClientSocketTransport)(transport.port).then((transport2) => {
|
|
const process2 = cp.spawn(runtime, args, execOptions);
|
|
if (!process2 || !process2.pid) {
|
|
return handleChildProcessStartError(process2, `Launching server using runtime ${runtime} failed.`);
|
|
}
|
|
this._serverProcess = process2;
|
|
pipeStderrToLogOutputChannel(process2.stderr, this.outputChannel);
|
|
pipeStdoutToLogOutputChannel(process2.stdout, this.outputChannel);
|
|
return transport2.onConnected().then((protocol) => {
|
|
return { reader: protocol[0], writer: protocol[1] };
|
|
});
|
|
});
|
|
}
|
|
} else {
|
|
let pipeName = undefined;
|
|
return new Promise((resolve, reject) => {
|
|
const args = (node.args && node.args.slice()) ?? [];
|
|
if (transport === TransportKind.ipc) {
|
|
args.push("--node-ipc");
|
|
} else if (transport === TransportKind.stdio) {
|
|
args.push("--stdio");
|
|
} else if (transport === TransportKind.pipe) {
|
|
pipeName = (0, node_1.generateRandomPipeName)();
|
|
args.push(`--pipe=${pipeName}`);
|
|
} else if (Transport.isSocket(transport)) {
|
|
args.push(`--socket=${transport.port}`);
|
|
}
|
|
args.push(`--clientProcessId=${process.pid.toString()}`);
|
|
const options = node.options ? { ...node.options } : Object.create(null);
|
|
options.env = getEnvironment(options.env, true);
|
|
options.execArgv = options.execArgv || [];
|
|
options.cwd = serverWorkingDir;
|
|
options.silent = true;
|
|
if (transport === TransportKind.ipc || transport === TransportKind.stdio) {
|
|
const sp = cp.fork(node.module, args || [], options);
|
|
assertStdio(sp);
|
|
this._serverProcess = sp;
|
|
pipeStderrToLogOutputChannel(sp.stderr, this.outputChannel);
|
|
if (transport === TransportKind.ipc) {
|
|
pipeStdoutToLogOutputChannel(sp.stdout, this.outputChannel);
|
|
resolve({ reader: new node_1.IPCMessageReader(this._serverProcess), writer: new node_1.IPCMessageWriter(this._serverProcess) });
|
|
} else {
|
|
resolve({ reader: new node_1.StreamMessageReader(sp.stdout), writer: new node_1.StreamMessageWriter(sp.stdin) });
|
|
}
|
|
} else if (transport === TransportKind.pipe) {
|
|
(0, node_1.createClientPipeTransport)(pipeName).then((transport2) => {
|
|
const sp = cp.fork(node.module, args || [], options);
|
|
assertStdio(sp);
|
|
this._serverProcess = sp;
|
|
pipeStderrToLogOutputChannel(sp.stderr, this.outputChannel);
|
|
pipeStdoutToLogOutputChannel(sp.stdout, this.outputChannel);
|
|
transport2.onConnected().then((protocol) => {
|
|
resolve({ reader: protocol[0], writer: protocol[1] });
|
|
}, reject);
|
|
}, reject);
|
|
} else if (Transport.isSocket(transport)) {
|
|
(0, node_1.createClientSocketTransport)(transport.port).then((transport2) => {
|
|
const sp = cp.fork(node.module, args || [], options);
|
|
assertStdio(sp);
|
|
this._serverProcess = sp;
|
|
pipeStderrToLogOutputChannel(sp.stderr, this.outputChannel);
|
|
pipeStdoutToLogOutputChannel(sp.stdout, this.outputChannel);
|
|
transport2.onConnected().then((protocol) => {
|
|
resolve({ reader: protocol[0], writer: protocol[1] });
|
|
}, reject);
|
|
}, reject);
|
|
}
|
|
});
|
|
}
|
|
} else if (Executable.is(json) && json.command) {
|
|
const command = json;
|
|
const args = json.args !== undefined ? json.args.slice(0) : [];
|
|
let pipeName = undefined;
|
|
const transport = json.transport;
|
|
if (transport === TransportKind.stdio) {
|
|
args.push("--stdio");
|
|
} else if (transport === TransportKind.pipe) {
|
|
pipeName = (0, node_1.generateRandomPipeName)();
|
|
args.push(`--pipe=${pipeName}`);
|
|
} else if (Transport.isSocket(transport)) {
|
|
args.push(`--socket=${transport.port}`);
|
|
} else if (transport === TransportKind.ipc) {
|
|
throw new Error(`Transport kind ipc is not support for command executable`);
|
|
}
|
|
const options = Object.assign({}, command.options);
|
|
options.cwd = options.cwd || serverWorkingDir;
|
|
if (transport === undefined || transport === TransportKind.stdio) {
|
|
const serverProcess = cp.spawn(command.command, args, options);
|
|
if (!serverProcess || !serverProcess.pid) {
|
|
return handleChildProcessStartError(serverProcess, `Launching server using command ${command.command} failed.`);
|
|
}
|
|
pipeStderrToLogOutputChannel(serverProcess.stderr, this.outputChannel);
|
|
this._serverProcess = serverProcess;
|
|
this._isDetached = !!options.detached;
|
|
return Promise.resolve({ reader: new node_1.StreamMessageReader(serverProcess.stdout), writer: new node_1.StreamMessageWriter(serverProcess.stdin) });
|
|
} else if (transport === TransportKind.pipe) {
|
|
return (0, node_1.createClientPipeTransport)(pipeName).then((transport2) => {
|
|
const serverProcess = cp.spawn(command.command, args, options);
|
|
if (!serverProcess || !serverProcess.pid) {
|
|
return handleChildProcessStartError(serverProcess, `Launching server using command ${command.command} failed.`);
|
|
}
|
|
this._serverProcess = serverProcess;
|
|
this._isDetached = !!options.detached;
|
|
pipeStderrToLogOutputChannel(serverProcess.stderr, this.outputChannel);
|
|
pipeStdoutToLogOutputChannel(serverProcess.stdout, this.outputChannel);
|
|
return transport2.onConnected().then((protocol) => {
|
|
return { reader: protocol[0], writer: protocol[1] };
|
|
});
|
|
});
|
|
} else if (Transport.isSocket(transport)) {
|
|
return (0, node_1.createClientSocketTransport)(transport.port).then((transport2) => {
|
|
const serverProcess = cp.spawn(command.command, args, options);
|
|
if (!serverProcess || !serverProcess.pid) {
|
|
return handleChildProcessStartError(serverProcess, `Launching server using command ${command.command} failed.`);
|
|
}
|
|
this._serverProcess = serverProcess;
|
|
this._isDetached = !!options.detached;
|
|
pipeStderrToLogOutputChannel(serverProcess.stderr, this.outputChannel);
|
|
pipeStdoutToLogOutputChannel(serverProcess.stdout, this.outputChannel);
|
|
return transport2.onConnected().then((protocol) => {
|
|
return { reader: protocol[0], writer: protocol[1] };
|
|
});
|
|
});
|
|
}
|
|
}
|
|
return Promise.reject(new Error(`Unsupported server configuration ` + JSON.stringify(server, null, 4)));
|
|
}).finally(() => {
|
|
if (this._serverProcess !== undefined) {
|
|
this._serverProcess.on("exit", (code, signal) => {
|
|
if (code === 0) {
|
|
this.info("Server process exited successfully", undefined, false);
|
|
} else if (code !== null) {
|
|
this.error(`Server process exited with code ${code}.`, undefined, false);
|
|
}
|
|
if (signal !== null) {
|
|
this.error(`Server process exited with signal ${signal}.`, undefined, false);
|
|
}
|
|
});
|
|
}
|
|
});
|
|
}
|
|
_getRuntimePath(runtime, serverWorkingDirectory) {
|
|
if (path.isAbsolute(runtime)) {
|
|
return runtime;
|
|
}
|
|
const mainRootPath = this._mainGetRootPath();
|
|
if (mainRootPath !== undefined) {
|
|
const result = path.join(mainRootPath, runtime);
|
|
if (fs.existsSync(result)) {
|
|
return result;
|
|
}
|
|
}
|
|
if (serverWorkingDirectory !== undefined) {
|
|
const result = path.join(serverWorkingDirectory, runtime);
|
|
if (fs.existsSync(result)) {
|
|
return result;
|
|
}
|
|
}
|
|
return runtime;
|
|
}
|
|
_mainGetRootPath() {
|
|
const folders = vscode_1.workspace.workspaceFolders;
|
|
if (!folders || folders.length === 0) {
|
|
return;
|
|
}
|
|
const folder = folders[0];
|
|
if (folder.uri.scheme === "file") {
|
|
return folder.uri.fsPath;
|
|
}
|
|
return;
|
|
}
|
|
_getServerWorkingDir(options) {
|
|
let cwd = options && options.cwd;
|
|
if (!cwd) {
|
|
cwd = this.clientOptions.workspaceFolder ? this.clientOptions.workspaceFolder.uri.fsPath : this._mainGetRootPath();
|
|
}
|
|
if (cwd) {
|
|
return new Promise((s) => {
|
|
fs.lstat(cwd, (err, stats) => {
|
|
s(!err && stats.isDirectory() ? cwd : undefined);
|
|
});
|
|
});
|
|
}
|
|
return Promise.resolve(undefined);
|
|
}
|
|
}
|
|
exports2.LanguageClient = LanguageClient;
|
|
|
|
class SettingMonitor {
|
|
_client;
|
|
_setting;
|
|
_listeners;
|
|
constructor(_client, _setting) {
|
|
this._client = _client;
|
|
this._setting = _setting;
|
|
this._listeners = [];
|
|
}
|
|
start() {
|
|
vscode_1.workspace.onDidChangeConfiguration(this.onDidChangeConfiguration, this, this._listeners);
|
|
this.onDidChangeConfiguration();
|
|
return new vscode_1.Disposable(() => {
|
|
if (this._client.needsStop()) {
|
|
this._client.stop();
|
|
}
|
|
});
|
|
}
|
|
onDidChangeConfiguration() {
|
|
const index = this._setting.indexOf(".");
|
|
const primary = index >= 0 ? this._setting.substr(0, index) : this._setting;
|
|
const rest = index >= 0 ? this._setting.substr(index + 1) : undefined;
|
|
const enabled = rest ? vscode_1.workspace.getConfiguration(primary).get(rest, false) : vscode_1.workspace.getConfiguration(primary);
|
|
if (enabled && this._client.needsStart()) {
|
|
this._client.start().catch((error) => this._client.error("Start failed after configuration change", error, "force"));
|
|
} else if (!enabled && this._client.needsStop()) {
|
|
this._client.stop().catch((error) => this._client.error("Stop failed after configuration change", error, "force"));
|
|
}
|
|
}
|
|
}
|
|
exports2.SettingMonitor = SettingMonitor;
|
|
function handleChildProcessStartError(process2, message) {
|
|
if (process2 === null) {
|
|
return Promise.reject(message);
|
|
}
|
|
return new Promise((_, reject) => {
|
|
process2.on("error", (err) => {
|
|
reject(`${message} ${err}`);
|
|
});
|
|
setImmediate(() => reject(message));
|
|
});
|
|
}
|
|
});
|
|
|
|
// editors/vscode/src/compiler.cjs
|
|
var require_compiler = __commonJS((exports2, module2) => {
|
|
var __nodeRequire = require;
|
|
var __path = __nodeRequire("node:path");
|
|
var __modules = {
|
|
"packages/compiler/src/analysis.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.optimizeAst = optimizeAst;
|
|
exports3.analyzeOptimizations = analyzeOptimizations;
|
|
exports3.analyzeRuntimeRequirements = analyzeRuntimeRequirements;
|
|
function identifiers(value) {
|
|
return new Set(value.match(/[A-Za-z_$][\w$]*/g) ?? []);
|
|
}
|
|
function literalBoolean(expression) {
|
|
if (expression === null)
|
|
return true;
|
|
const value = expression.trim();
|
|
if (value === "true")
|
|
return true;
|
|
if (value === "false" || value === "null" || value === "undefined" || value === "0" || value === "''" || value === '""')
|
|
return false;
|
|
if (/^-?(?:[1-9]\d*|0?\.\d+)$/.test(value) || /^(['"]).+\1$/.test(value))
|
|
return true;
|
|
return;
|
|
}
|
|
function optimizeNodes(nodes, report) {
|
|
const output = [];
|
|
for (const node of nodes) {
|
|
if (node.type === "element")
|
|
output.push({
|
|
...node,
|
|
attrs: node.attrs.map((attribute) => ({ ...attribute })),
|
|
children: optimizeNodes(node.children, report)
|
|
});
|
|
else if (node.type === "each")
|
|
output.push({
|
|
...node,
|
|
body: optimizeNodes(node.body, report),
|
|
empty: optimizeNodes(node.empty, report)
|
|
});
|
|
else if (node.type === "if") {
|
|
let selected;
|
|
let dynamic = false;
|
|
for (const branch of node.branches) {
|
|
const value = literalBoolean(branch.cond);
|
|
if (value === undefined) {
|
|
dynamic = true;
|
|
break;
|
|
}
|
|
report.eliminated++;
|
|
if (value) {
|
|
selected = branch.body;
|
|
break;
|
|
}
|
|
}
|
|
if (dynamic)
|
|
output.push({
|
|
...node,
|
|
branches: node.branches.map((branch) => ({
|
|
...branch,
|
|
body: optimizeNodes(branch.body, report)
|
|
}))
|
|
});
|
|
else if (selected)
|
|
output.push(...optimizeNodes(selected, report));
|
|
} else
|
|
output.push({ ...node });
|
|
}
|
|
return output;
|
|
}
|
|
function optimizeAst(ast) {
|
|
const report = { eliminated: 0 };
|
|
return {
|
|
ast: { ...ast, view: optimizeNodes(ast.view, report) },
|
|
eliminatedBranches: report.eliminated
|
|
};
|
|
}
|
|
function analyzeOptimizations(ast) {
|
|
const used = new Set;
|
|
let staticNodes = 0;
|
|
let reactiveRegions = 0;
|
|
const componentNames = new Set;
|
|
const staticClasses = new Set;
|
|
const visit = (nodes) => {
|
|
for (const node of nodes) {
|
|
if (node.type === "text") {
|
|
const refs = identifiers(node.value);
|
|
refs.forEach((name) => used.add(name));
|
|
if (node.value.includes("{"))
|
|
reactiveRegions++;
|
|
else
|
|
staticNodes++;
|
|
} else if (node.type === "element") {
|
|
if (/^[A-Z]/.test(node.tag))
|
|
componentNames.add(node.tag);
|
|
let reactive = false;
|
|
for (const attribute of node.attrs) {
|
|
identifiers(attribute.value).forEach((name) => used.add(name));
|
|
reactive ||= attribute.event || attribute.value.includes("{");
|
|
if (attribute.name === "class" && !attribute.value.includes("{")) {
|
|
for (const name of attribute.value.split(/\s+/))
|
|
if (name)
|
|
staticClasses.add(name);
|
|
}
|
|
}
|
|
if (reactive)
|
|
reactiveRegions++;
|
|
else
|
|
staticNodes++;
|
|
visit(node.children);
|
|
} else if (node.type === "each") {
|
|
identifiers(`${node.list} ${node.key ?? ""}`).forEach((name) => used.add(name));
|
|
reactiveRegions++;
|
|
visit(node.body);
|
|
visit(node.empty);
|
|
} else {
|
|
for (const branch of node.branches) {
|
|
identifiers(branch.cond ?? "").forEach((name) => used.add(name));
|
|
visit(branch.body);
|
|
}
|
|
reactiveRegions++;
|
|
}
|
|
}
|
|
};
|
|
visit(ast.view);
|
|
const handlerReferences = new Set(used);
|
|
const executable = [
|
|
...ast.runtimeFunctions.map((fn) => fn.body),
|
|
...ast.functions,
|
|
...ast.effects.map((effect) => effect.body),
|
|
...ast.watches.map((watch) => watch.body),
|
|
...ast.actions.map((action) => action.body)
|
|
].join(`
|
|
`);
|
|
identifiers(executable).forEach((name) => used.add(name));
|
|
const localCss = new Set(ast.styles.flatMap((style) => [...style.matchAll(/\.([_a-zA-Z][\w-]*)/g)].map((match) => match[1])));
|
|
const optimized = optimizeAst(ast);
|
|
const assignmentCounts = ast.runtimeFunctions.map((fn) => ast.states.filter((state) => new RegExp(`\\b${state.name}\\s*(?:[+*/-]?=|\\+\\+|--)`).test(fn.body)).length);
|
|
return {
|
|
staticNodes,
|
|
reactiveRegions,
|
|
eliminatedBranches: optimized.eliminatedBranches,
|
|
unusedState: ast.states.filter((state) => !used.has(state.name)).map((state) => state.name),
|
|
unusedHandlers: ast.runtimeFunctions.filter((fn) => fn.runtime !== "server" && !handlerReferences.has(fn.name)).map((fn) => fn.name),
|
|
constantProps: ast.props.filter((prop) => /^(?:-?\d+(?:\.\d+)?|true|false|null|(['"]).*\1)$/.test(prop.default.trim())).map((prop) => prop.name),
|
|
unusedLocalCssClasses: [...localCss].filter((name) => !staticClasses.has(name)).sort(),
|
|
batchableStateUpdates: assignmentCounts.filter((count) => count > 1).reduce((sum, count) => sum + count - 1, 0),
|
|
memoizableComponents: [...componentNames].sort(),
|
|
preloadDependencies: ast.structuredImports.filter((entry) => !entry.typeOnly && !entry.source.startsWith("node:")).map((entry) => entry.source),
|
|
serverOnlyModules: ast.structuredImports.filter((entry) => entry.source.startsWith("node:") || ast.runtime === "server").map((entry) => entry.source)
|
|
};
|
|
}
|
|
function hasEvent(nodes) {
|
|
for (const node of nodes) {
|
|
if (node.type === "element") {
|
|
if (node.attrs.some((attribute) => attribute.event))
|
|
return true;
|
|
if (hasEvent(node.children))
|
|
return true;
|
|
} else if (node.type === "each") {
|
|
if (hasEvent(node.body) || hasEvent(node.empty))
|
|
return true;
|
|
} else if (node.type === "if") {
|
|
if (node.branches.some((branch) => hasEvent(branch.body)))
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
function analyzeRuntimeRequirements(ast) {
|
|
const reasons = [];
|
|
const clientFunctions = ast.runtimeFunctions.some((fn) => fn.runtime !== "server");
|
|
const clientState = ast.states.some((state) => state.runtime !== "server");
|
|
const interactive = clientFunctions || clientState || ast.effects.length > 0 || ast.watches.length > 0 || hasEvent(ast.view);
|
|
if (interactive)
|
|
reasons.push("client interactivity");
|
|
const requestData = ast.loads.length > 0 || ast.actions.length > 0 || ast.dataApis.length > 0 || ast.apis.length > 0 || ast.realtimes.length > 0 || ast.runtimeFunctions.some((fn) => fn.runtime === "server") || ast.states.some((state) => state.runtime === "server");
|
|
if (requestData)
|
|
reasons.push("server/request data");
|
|
const authenticated = /^(?:required|true)$/i.test(ast.security.auth ?? "");
|
|
if (authenticated)
|
|
reasons.push("authentication required");
|
|
const streaming = /^(?:true|required)$/i.test(ast.security.streaming ?? "");
|
|
if (streaming)
|
|
reasons.push("streaming enabled");
|
|
let kind;
|
|
if (streaming)
|
|
kind = "streaming-ssr";
|
|
else if (authenticated)
|
|
kind = "authenticated-ssr";
|
|
else if (requestData && interactive)
|
|
kind = "dynamic";
|
|
else if (requestData)
|
|
kind = "request-ssr";
|
|
else if (interactive)
|
|
kind = "static-interactive";
|
|
else
|
|
kind = "static";
|
|
if (ast.renderMode === "static") {
|
|
kind = "static";
|
|
reasons.push("explicit static rendering");
|
|
} else if (ast.renderMode === "server") {
|
|
kind = requestData ? "request-ssr" : "static";
|
|
reasons.push("explicit server rendering");
|
|
} else if (ast.renderMode === "client") {
|
|
kind = "static-interactive";
|
|
reasons.push("explicit client rendering");
|
|
} else if (ast.renderMode === "partial-static") {
|
|
kind = "streaming-ssr";
|
|
reasons.push("partial-static shell with streamed dynamic regions");
|
|
}
|
|
const clientDisabled = ast.renderMode === "static" || ast.renderMode === "server";
|
|
const serverDisabled = ast.renderMode === "client";
|
|
return {
|
|
kind,
|
|
canPrerender: kind === "static" || kind === "static-interactive",
|
|
needsClientRuntime: !clientDisabled && (interactive || ast.renderMode === "client") && ast.hydrate !== "none" && ast.runtime !== "server",
|
|
needsServerRuntime: !serverDisabled && (requestData || authenticated || streaming || ast.renderMode === "server" || ["server", "edge", "worker", "service-worker"].includes(ast.runtime ?? "")),
|
|
hydrationStrategy: clientDisabled ? null : interactive ? ast.hydrate ?? "load" : null,
|
|
reasons,
|
|
optimization: analyzeOptimizations(ast),
|
|
cachePolicy: { ...ast.cache ?? {} },
|
|
requiredPermission: ast.security.permission ?? null
|
|
};
|
|
}
|
|
},
|
|
"packages/compiler/src/cache.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.DependencyGraph = undefined;
|
|
exports3.compilationKey = compilationKey;
|
|
exports3.createCompilationCache = createCompilationCache;
|
|
const node_crypto_1 = require2("node:crypto");
|
|
const syntax_1 = require2("@wrnexus/syntax");
|
|
const codegen_ts_1 = require2("./codegen.js");
|
|
function compileSource(source, filePath) {
|
|
const richDiagnostics = (0, syntax_1.diagnose)(source, { file: filePath, accessibility: true });
|
|
const errors = richDiagnostics.filter((diagnostic) => diagnostic.severity === "error");
|
|
if (errors.length > 0) {
|
|
throw new syntax_1.ParseError(errors.map((diagnostic) => diagnostic.message).join(`
|
|
`), errors[0].code);
|
|
}
|
|
const ast = (0, syntax_1.parse)(source);
|
|
return {
|
|
code: `// compiled from .wrn
|
|
${(0, codegen_ts_1.generate)(ast)}`,
|
|
ast,
|
|
diagnostics: richDiagnostics.map((diagnostic) => `${diagnostic.code}: ${diagnostic.message}`),
|
|
richDiagnostics
|
|
};
|
|
}
|
|
function compilationKey(source, file = "<inline .wrn>", salt = "") {
|
|
return (0, node_crypto_1.createHash)("sha256").update(file).update("\x00").update(salt).update("\x00").update(source).digest("hex");
|
|
}
|
|
function createCompilationCache(options = {}) {
|
|
const maxEntries = options.maxEntries ?? 500;
|
|
if (!Number.isInteger(maxEntries) || maxEntries < 1)
|
|
throw new RangeError("maxEntries must be positive");
|
|
const now = options.now ?? Date.now;
|
|
const entries = new Map;
|
|
let hits = 0;
|
|
let misses = 0;
|
|
function touch(key, value) {
|
|
entries.delete(key);
|
|
entries.set(key, value);
|
|
while (entries.size > maxEntries)
|
|
entries.delete(entries.keys().next().value);
|
|
}
|
|
return {
|
|
compile(source, file = "<inline .wrn>", salt = "") {
|
|
const key = compilationKey(source, file, salt);
|
|
const existing = entries.get(key);
|
|
if (existing) {
|
|
hits++;
|
|
touch(key, existing);
|
|
return existing;
|
|
}
|
|
misses++;
|
|
const result = compileSource(source, file);
|
|
const entry = {
|
|
...result,
|
|
key,
|
|
file,
|
|
sourceHash: (0, node_crypto_1.createHash)("sha256").update(source).digest("hex"),
|
|
createdAt: now()
|
|
};
|
|
touch(key, entry);
|
|
return entry;
|
|
},
|
|
get(key) {
|
|
const entry = entries.get(key);
|
|
if (entry)
|
|
touch(key, entry);
|
|
return entry;
|
|
},
|
|
invalidate(file) {
|
|
let removed = 0;
|
|
for (const [key, entry] of entries) {
|
|
if (!file || entry.file === file) {
|
|
entries.delete(key);
|
|
removed++;
|
|
}
|
|
}
|
|
return removed;
|
|
},
|
|
clear() {
|
|
entries.clear();
|
|
},
|
|
size: () => entries.size,
|
|
stats: () => ({ hits, misses, entries: entries.size })
|
|
};
|
|
}
|
|
|
|
class DependencyGraph {
|
|
#dependencies = new Map;
|
|
#dependents = new Map;
|
|
set(file, dependencies) {
|
|
this.remove(file);
|
|
const values = new Set(dependencies);
|
|
this.#dependencies.set(file, values);
|
|
for (const dependency of values) {
|
|
const set = this.#dependents.get(dependency) ?? new Set;
|
|
set.add(file);
|
|
this.#dependents.set(dependency, set);
|
|
}
|
|
}
|
|
remove(file) {
|
|
for (const dependency of this.#dependencies.get(file) ?? []) {
|
|
const set = this.#dependents.get(dependency);
|
|
set?.delete(file);
|
|
if (set?.size === 0)
|
|
this.#dependents.delete(dependency);
|
|
}
|
|
this.#dependencies.delete(file);
|
|
}
|
|
dependencies(file) {
|
|
return [...this.#dependencies.get(file) ?? []].sort();
|
|
}
|
|
dependents(file) {
|
|
return [...this.#dependents.get(file) ?? []].sort();
|
|
}
|
|
affected(file) {
|
|
const found = new Set;
|
|
const queue = [file];
|
|
while (queue.length) {
|
|
const current = queue.shift();
|
|
for (const dependent of this.#dependents.get(current) ?? []) {
|
|
if (found.has(dependent))
|
|
continue;
|
|
found.add(dependent);
|
|
queue.push(dependent);
|
|
}
|
|
}
|
|
return [...found].sort();
|
|
}
|
|
}
|
|
exports3.DependencyGraph = DependencyGraph;
|
|
},
|
|
"packages/compiler/src/client-codegen.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.browserModuleRequired = browserModuleRequired;
|
|
exports3.generateBrowserModule = generateBrowserModule;
|
|
const syntax_1 = require2("@wrnexus/syntax");
|
|
const RESERVED_BINDINGS = new Set([
|
|
"await",
|
|
"break",
|
|
"case",
|
|
"catch",
|
|
"class",
|
|
"const",
|
|
"continue",
|
|
"debugger",
|
|
"default",
|
|
"delete",
|
|
"do",
|
|
"else",
|
|
"enum",
|
|
"export",
|
|
"extends",
|
|
"false",
|
|
"finally",
|
|
"for",
|
|
"function",
|
|
"if",
|
|
"implements",
|
|
"import",
|
|
"in",
|
|
"instanceof",
|
|
"interface",
|
|
"let",
|
|
"new",
|
|
"null",
|
|
"package",
|
|
"private",
|
|
"protected",
|
|
"public",
|
|
"return",
|
|
"static",
|
|
"super",
|
|
"switch",
|
|
"this",
|
|
"throw",
|
|
"true",
|
|
"try",
|
|
"typeof",
|
|
"var",
|
|
"void",
|
|
"while",
|
|
"with",
|
|
"yield"
|
|
]);
|
|
const RUNTIME_BINDINGS = new Set([
|
|
"context",
|
|
"state",
|
|
"output",
|
|
"server",
|
|
"props",
|
|
"refs",
|
|
"event",
|
|
"payload"
|
|
]);
|
|
function safeIdentifier(name) {
|
|
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) && !RESERVED_BINDINGS.has(name);
|
|
}
|
|
function identifierReferenced(source, name) {
|
|
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
return new RegExp(`(?:^|[^A-Za-z0-9_$])${escaped}(?![A-Za-z0-9_$])`).test(source);
|
|
}
|
|
function viewReferenceSource(nodes) {
|
|
return nodes.flatMap((node) => {
|
|
if (node.type === "text")
|
|
return [node.value];
|
|
if (node.type === "each") {
|
|
return [
|
|
node.list,
|
|
node.key ?? "",
|
|
...viewReferenceSource(node.body),
|
|
...viewReferenceSource(node.empty)
|
|
];
|
|
}
|
|
if (node.type === "if") {
|
|
return node.branches.flatMap((branch) => [
|
|
branch.cond ?? "",
|
|
...viewReferenceSource(branch.body)
|
|
]);
|
|
}
|
|
return [...node.attrs.map((attr) => attr.value), ...viewReferenceSource(node.children)];
|
|
});
|
|
}
|
|
function browserReferenceSource(ast, functions) {
|
|
return [
|
|
...functions.flatMap((fn) => [fn.source, fn.body]),
|
|
...ast.computed.map((entry) => entry.expr),
|
|
...ast.effects,
|
|
ast.lifecycle.mount ?? "",
|
|
ast.lifecycle.update ?? "",
|
|
ast.lifecycle.unmount ?? "",
|
|
...viewReferenceSource(ast.view)
|
|
].join(`
|
|
`);
|
|
}
|
|
function renderSelectedImport(entry, source) {
|
|
if (entry.typeOnly)
|
|
return null;
|
|
const isStore = entry.source.endsWith(".wrn") && /(?:^|\/)stores?\//.test(entry.source);
|
|
if (entry.source.endsWith(".wrn") && !isStore)
|
|
return null;
|
|
const defaultImport = entry.defaultImport && (isStore || identifierReferenced(source, entry.defaultImport)) ? entry.defaultImport : undefined;
|
|
const namespaceImport = entry.namespaceImport && (isStore || identifierReferenced(source, entry.namespaceImport)) ? entry.namespaceImport : undefined;
|
|
const namedImports = entry.namedImports.filter((item) => !item.typeOnly && (isStore || identifierReferenced(source, item.local)));
|
|
const bindings = [
|
|
...defaultImport ? [defaultImport] : [],
|
|
...namespaceImport ? [namespaceImport] : [],
|
|
...namedImports.map((item) => item.local)
|
|
].filter(safeIdentifier);
|
|
const hasBindings = Boolean(defaultImport || namespaceImport || namedImports.length);
|
|
const sideEffectOnly = !entry.defaultImport && !entry.namespaceImport && entry.namedImports.length === 0;
|
|
if (!hasBindings && !sideEffectOnly)
|
|
return null;
|
|
if (sideEffectOnly)
|
|
return { code: entry.raw, bindings: [] };
|
|
const clauses = [];
|
|
if (defaultImport)
|
|
clauses.push(defaultImport);
|
|
if (namespaceImport)
|
|
clauses.push(`* as ${namespaceImport}`);
|
|
if (namedImports.length) {
|
|
clauses.push(`{ ${namedImports.map((item) => item.imported === item.local ? item.imported : `${item.imported} as ${item.local}`).join(", ")} }`);
|
|
}
|
|
return {
|
|
code: `import ${clauses.join(", ")} from ${JSON.stringify(entry.source)};`,
|
|
bindings
|
|
};
|
|
}
|
|
function selectedBrowserImports(ast, functions) {
|
|
const referenceSource = browserReferenceSource(ast, functions);
|
|
return ast.structuredImports.map((entry) => renderSelectedImport(entry, referenceSource)).filter((entry) => entry !== null);
|
|
}
|
|
function browserModuleRequired(ast) {
|
|
const functions = ast.runtimeFunctions.filter((fn) => ["legacy", "client", "shared"].includes(fn.runtime));
|
|
return functions.length > 0 || selectedBrowserImports(ast, functions).length > 0;
|
|
}
|
|
function functionEntry(ast, fn, availableFunctions) {
|
|
const parameterNames = new Set(fn.parameters.map((parameter) => parameter.name));
|
|
const declaredLocals = new Set;
|
|
for (const match of fn.body.matchAll(/\b(?:var|let|const)\s+([A-Za-z_$][\w$]*)|\bfunction\s+([A-Za-z_$][\w$]*)/g)) {
|
|
const name = match[1] ?? match[2];
|
|
if (name)
|
|
declaredLocals.add(name);
|
|
}
|
|
const stateNames = ast.states.filter((state) => state.runtime !== "server" && safeIdentifier(state.name) && !RUNTIME_BINDINGS.has(state.name) && !parameterNames.has(state.name) && !declaredLocals.has(state.name)).map((state) => state.name);
|
|
const stateSet = new Set(stateNames);
|
|
const propNames = ast.props.filter((prop) => safeIdentifier(prop.name) && !RUNTIME_BINDINGS.has(prop.name) && !parameterNames.has(prop.name) && !stateSet.has(prop.name) && !declaredLocals.has(prop.name)).map((prop) => prop.name);
|
|
const functionAliases = availableFunctions.filter((name) => safeIdentifier(name) && !RUNTIME_BINDINGS.has(name) && !parameterNames.has(name) && !stateSet.has(name) && !propNames.includes(name) && !declaredLocals.has(name));
|
|
const parameters = fn.parameters.map((parameter) => parameter.name).join(", ");
|
|
const initialStateSnapshot = stateNames.length ? `const __wrnexusInitialState = { ${stateNames.map((name) => `${JSON.stringify(name)}: context.state.${name}`).join(", ")} };` : "";
|
|
const stateAliases = stateNames.length ? `let { ${stateNames.join(", ")} } = context.state;` : "";
|
|
const propAliases = propNames.length ? `const { ${propNames.join(", ")} } = context.props;` : "";
|
|
const syncStateToContext = stateNames.map((name) => `context.state.${name} = ${name};`).join(" ");
|
|
const syncStateFromContext = stateNames.map((name) => `${name} = context.state.${name};`).join(" ");
|
|
const peerAliases = functionAliases.map((name) => {
|
|
const call = `context.functions[${JSON.stringify(name)}](...__wrnexusPeerArgs)`;
|
|
if (!stateNames.length) {
|
|
return `const ${name} = (...__wrnexusPeerArgs) => ${call};`;
|
|
}
|
|
return `const ${name} = (...__wrnexusPeerArgs) => {
|
|
${syncStateToContext}
|
|
let __wrnexusPeerResult;
|
|
try {
|
|
__wrnexusPeerResult = ${call};
|
|
} catch (__wrnexusPeerError) {
|
|
${syncStateFromContext}
|
|
throw __wrnexusPeerError;
|
|
}
|
|
if (__wrnexusPeerResult && typeof __wrnexusPeerResult.then === "function") {
|
|
return Promise.resolve(__wrnexusPeerResult).finally(() => { ${syncStateFromContext} });
|
|
}
|
|
${syncStateFromContext}
|
|
return __wrnexusPeerResult;
|
|
};`;
|
|
}).join(`
|
|
`);
|
|
const copyBack = stateNames.map((name) => `if (!Object.is(${name}, __wrnexusInitialState[${JSON.stringify(name)}])) context.state.${name} = ${name};`).join(`
|
|
`);
|
|
const body = (0, syntax_1.eraseFunctionTypes)(fn.body);
|
|
const runtimeBindings = [
|
|
!parameterNames.has("output") ? "const output = context.output;" : "",
|
|
!parameterNames.has("server") ? "const server = context.server;" : "",
|
|
!parameterNames.has("props") ? "const props = context.props;" : "",
|
|
!parameterNames.has("refs") ? "const refs = context.refs;" : ""
|
|
].filter(Boolean).join(`
|
|
`);
|
|
return `${JSON.stringify(fn.name)}: ${fn.async ? "async " : ""}function(context${parameters ? `, ${parameters}` : ""}) {
|
|
${initialStateSnapshot}
|
|
${stateAliases}
|
|
${propAliases}
|
|
${peerAliases}
|
|
${runtimeBindings}
|
|
try {
|
|
${body}
|
|
} finally {
|
|
${copyBack}
|
|
}
|
|
}`;
|
|
}
|
|
function generateBrowserModule(ast) {
|
|
const functions = ast.runtimeFunctions.filter((fn) => ["legacy", "client", "shared"].includes(fn.runtime));
|
|
const functionNames = functions.map((fn) => fn.name);
|
|
const state = ast.states.filter((entry) => entry.runtime !== "server").map((entry) => entry.name);
|
|
const selectedImports = selectedBrowserImports(ast, functions);
|
|
const imports = selectedImports.map((entry) => entry.code).join(`
|
|
`);
|
|
const importedBindings = [...new Set(selectedImports.flatMap((entry) => entry.bindings))];
|
|
return `// generated WRNexusJS browser module for ${ast.name}
|
|
${imports}
|
|
export const __wrnexusClientFunctions = {
|
|
${functions.map((fn) => ` ${functionEntry(ast, fn, functionNames)}`).join(`,
|
|
`)}
|
|
};
|
|
export const __wrnexusClientState = ${JSON.stringify(state)};
|
|
export const __wrnexusOutputs = ${JSON.stringify(ast.outputs)};
|
|
export const __wrnexusImportedBindings = { ${importedBindings.join(", ")} };
|
|
export function bindClientScope(context) {
|
|
const functions = {};
|
|
const scopedContext = { ...context, functions };
|
|
for (const [name, handler] of Object.entries(__wrnexusClientFunctions)) {
|
|
functions[name] = (...args) => handler(scopedContext, ...args);
|
|
}
|
|
return functions;
|
|
}
|
|
`;
|
|
}
|
|
},
|
|
"packages/compiler/src/codegen.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.generate = generate;
|
|
exports3.parseForExpr = parseForExpr;
|
|
const node_buffer_1 = require2("node:buffer");
|
|
const parser_ts_1 = require2("./parser.js");
|
|
const types_ts_1 = require2("./types.js");
|
|
const syntax_1 = require2("@wrnexus/syntax");
|
|
const store_codegen_ts_1 = require2("./store-codegen.js");
|
|
const analysis_ts_1 = require2("./analysis.js");
|
|
const client_codegen_ts_1 = require2("./client-codegen.js");
|
|
function isComponentTag(tag) {
|
|
return /^[A-Z][A-Za-z0-9_$]*$/.test(tag);
|
|
}
|
|
const HTML_BOOLEAN_ATTRIBUTES = new Set([
|
|
"allowfullscreen",
|
|
"async",
|
|
"autofocus",
|
|
"autoplay",
|
|
"checked",
|
|
"controls",
|
|
"default",
|
|
"defer",
|
|
"disabled",
|
|
"formnovalidate",
|
|
"hidden",
|
|
"inert",
|
|
"ismap",
|
|
"itemscope",
|
|
"loop",
|
|
"multiple",
|
|
"muted",
|
|
"nomodule",
|
|
"novalidate",
|
|
"open",
|
|
"playsinline",
|
|
"readonly",
|
|
"required",
|
|
"reversed",
|
|
"selected"
|
|
]);
|
|
function isHtmlBooleanAttribute(name) {
|
|
return HTML_BOOLEAN_ATTRIBUTES.has(name.toLowerCase());
|
|
}
|
|
const URL_ATTRIBUTES = new Set([
|
|
"href",
|
|
"src",
|
|
"action",
|
|
"formaction",
|
|
"poster",
|
|
"cite",
|
|
"background",
|
|
"xlink:href"
|
|
]);
|
|
function stripAsciiControlAndSpace(value) {
|
|
let result = "";
|
|
for (const character of value) {
|
|
if (character.charCodeAt(0) > 32)
|
|
result += character;
|
|
}
|
|
return result;
|
|
}
|
|
function sanitizeUrlAttribute(value) {
|
|
const compact = stripAsciiControlAndSpace(value.trim());
|
|
const lower = compact.toLowerCase();
|
|
if (/^(?:javascript|vbscript|file):/.test(lower))
|
|
return "about:blank";
|
|
if (/^data:(?!image\/(?:png|gif|jpeg|webp|avif);)/.test(lower))
|
|
return "about:blank";
|
|
return value;
|
|
}
|
|
function safeAttributeValue(name, value) {
|
|
if (!URL_ATTRIBUTES.has(name.toLowerCase()) || value.includes("{"))
|
|
return value;
|
|
return sanitizeUrlAttribute(value);
|
|
}
|
|
function attrEscape(value) {
|
|
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
}
|
|
function templateEscape(html) {
|
|
return html.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
|
|
}
|
|
function styleEscape(css) {
|
|
return css.replace(/<\/style/gi, "<\\/style");
|
|
}
|
|
function attrValue(attrs, name) {
|
|
return attrs.find((attr) => !attr.event && attr.name === name)?.value;
|
|
}
|
|
function renderAttr(attr) {
|
|
if (attr.event)
|
|
return ` ${eventAttribute(attr.name)}="${attrEscape(attr.value)}"`;
|
|
switch (attr.name) {
|
|
case "api":
|
|
case "ssrGet":
|
|
case "ssrText":
|
|
case "csrGet":
|
|
case "csrText":
|
|
return "";
|
|
default:
|
|
return attr.boolean ? ` ${attr.name}` : ` ${attr.name}="${attrEscape(safeAttributeValue(attr.name, attr.value))}"`;
|
|
}
|
|
}
|
|
function eventAttribute(name) {
|
|
if (name.startsWith("window:")) {
|
|
return `data-on-window-${name.slice("window:".length)}`;
|
|
}
|
|
if (name.startsWith("document:")) {
|
|
return `data-on-document-${name.slice("document:".length)}`;
|
|
}
|
|
if (name.startsWith("browser-")) {
|
|
return `data-on-wrnexus-browser-${name.slice(8)}`;
|
|
}
|
|
if (name.startsWith("mobile-")) {
|
|
return `data-on-wrnexus-mobile-${name.slice(7)}`;
|
|
}
|
|
return `data-on-${name}`;
|
|
}
|
|
function componentEventAttribute(name) {
|
|
if (name.startsWith("window:") || name.startsWith("document:") || name.startsWith("browser-") || name.startsWith("mobile-")) {
|
|
return eventAttribute(name);
|
|
}
|
|
return `data-wrn-out-${name}`;
|
|
}
|
|
function reactiveAttrValue(raw, reactive) {
|
|
let found = false;
|
|
const value = raw.replace(/\{([^{}]+)\}/g, (whole, inner) => {
|
|
const expr = inner.trim();
|
|
if (!exprRefsState(expr, reactive.stateNames))
|
|
return whole;
|
|
found = true;
|
|
try {
|
|
const result = new Function("with(this){return (" + expr + ");}").call(reactive.scope);
|
|
return result == null ? "" : String(result);
|
|
} catch {
|
|
return whole;
|
|
}
|
|
});
|
|
return found ? value : null;
|
|
}
|
|
function renderAttrs(attrs, csrId, reactive = null, dynamicExpressions) {
|
|
let bindIndex = 0;
|
|
const rendered = attrs.map((attr) => {
|
|
const base = renderAttr(attr);
|
|
if (!reactive || attr.event || attr.boolean || !base || !attr.value.includes("{"))
|
|
return base;
|
|
const expression = wholeAttributeExpression(attr.value);
|
|
if (expression && exprRefsState(expression, reactive.runtimeStateNames) && dynamicExpressions) {
|
|
dynamicExpressions.push(`\${__wrnexusPropAttr(${expression})}`);
|
|
const sentinel = `\x00WRNEACH${dynamicExpressions.length - 1}\x00`;
|
|
const marker2 = JSON.stringify([attr.name, attr.value]);
|
|
return ` ${attr.name}="${sentinel}" data-wrn-bind-${bindIndex++}="${attrEscape(marker2)}"`;
|
|
}
|
|
const initial = reactiveAttrValue(attr.value, reactive);
|
|
if (initial === null)
|
|
return base;
|
|
const marker = JSON.stringify([attr.name, attr.value]);
|
|
return ` ${attr.name}="${attrEscape(URL_ATTRIBUTES.has(attr.name.toLowerCase()) ? sanitizeUrlAttribute(initial) : initial)}" data-wrn-bind-${bindIndex++}="${attrEscape(marker)}"`;
|
|
}).join("");
|
|
return csrId ? `${rendered} data-wrnexus-csr="${attrEscape(csrId)}"` : rendered;
|
|
}
|
|
function substituteTMarkers(text) {
|
|
return text.replace(/\{t:([^{}]+)\}/g, (_m, key) => `<span data-t="${attrEscape(key.trim())}"></span>`);
|
|
}
|
|
function htmlTextEscape(value) {
|
|
return value.replace(/[&<>]/g, (c) => c === "&" ? "&" : c === "<" ? "<" : ">");
|
|
}
|
|
function evalStateSeeds(states) {
|
|
const scope = {};
|
|
for (const s of states) {
|
|
try {
|
|
scope[s.name] = new Function("with(this){return (" + s.expr + ");}").call(scope);
|
|
} catch {
|
|
scope[s.name] = undefined;
|
|
}
|
|
}
|
|
return scope;
|
|
}
|
|
function substituteReactiveText(raw, reactive, dynamicExpressions) {
|
|
const text = substituteTMarkers(raw);
|
|
if (!reactive || reactive.stateNames.size === 0)
|
|
return text;
|
|
return text.replace(/\{([^{}]+)\}/g, (whole, inner) => {
|
|
const expr = inner.trim();
|
|
if (expr.startsWith("t:") || !exprRefsState(expr, reactive.stateNames))
|
|
return whole;
|
|
if (exprRefsState(expr, reactive.runtimeStateNames) && dynamicExpressions) {
|
|
dynamicExpressions.push(`\${__wrnexusEscapeHtml(${expr})}`);
|
|
const sentinel = `\x00WRNEACH${dynamicExpressions.length - 1}\x00`;
|
|
return `<span data-text="${attrEscape(expr)}">${sentinel}</span>`;
|
|
}
|
|
let value;
|
|
try {
|
|
value = new Function("with(this){return (" + expr + ");}").call(reactive.scope);
|
|
} catch {
|
|
return whole;
|
|
}
|
|
const baked = htmlTextEscape(value == null ? "" : String(value));
|
|
return `<span data-text="${attrEscape(expr)}">${baked}</span>`;
|
|
});
|
|
}
|
|
function bakeLoopText(raw) {
|
|
let out = "";
|
|
let last = 0;
|
|
let m;
|
|
const re = /\{([^{}]+)\}/g;
|
|
while (m = re.exec(raw)) {
|
|
out += escLit(raw.slice(last, m.index));
|
|
const expr = m[1].trim();
|
|
if (expr.startsWith("t:")) {
|
|
out += escLit(`<span data-t="${attrEscape(expr.slice(2).trim())}"></span>`);
|
|
} else {
|
|
out += "${__wrnexusEscapeHtml(" + expr + ")}";
|
|
}
|
|
last = m.index + m[0].length;
|
|
}
|
|
return out + escLit(raw.slice(last));
|
|
}
|
|
function bakeLoopAttr(raw, typed = false) {
|
|
const wholeExpression = wholeAttributeExpression(raw);
|
|
if (typed && wholeExpression)
|
|
return "${__wrnexusPropAttr(" + wholeExpression + ")}";
|
|
if (!raw.includes("{"))
|
|
return escLit(attrEscape(raw));
|
|
let out = "";
|
|
let last = 0;
|
|
let m;
|
|
const re = /\{([^{}]+)\}/g;
|
|
while (m = re.exec(raw)) {
|
|
out += escLit(attrEscape(raw.slice(last, m.index)));
|
|
out += "${__wrnexusEscapeHtml(" + m[1].trim() + ")}";
|
|
last = m.index + m[0].length;
|
|
}
|
|
return out + escLit(attrEscape(raw.slice(last)));
|
|
}
|
|
function renderLoopBody(node) {
|
|
if (node.type === "text") {
|
|
return bakeLoopText(node.value);
|
|
}
|
|
if (node.type === "each") {
|
|
return compileEachExpr(node);
|
|
}
|
|
if (node.type === "if") {
|
|
return compileIfExpr(node);
|
|
}
|
|
const componentTag = isComponentTag(node.tag);
|
|
const attrs = node.attrs.filter((attr) => attr.name !== "data-component").map((attr) => {
|
|
const name = attr.event ? componentTag ? componentEventAttribute(attr.name) : eventAttribute(attr.name) : attr.name;
|
|
if (attr.boolean) {
|
|
return escLit(` ${name}`);
|
|
}
|
|
return escLit(` ${name}="`) + bakeLoopAttr(attr.value, componentTag) + escLit(`"`);
|
|
}).join("");
|
|
const inner = node.children.map(renderLoopBody).join("");
|
|
if (node.tag === "Static")
|
|
return inner;
|
|
if (node.tag === "Dynamic")
|
|
return escLit('<wrn-dynamic-region data-wrn-dynamic="true">') + inner + escLit("</wrn-dynamic-region>");
|
|
if (node.tag === "KeepAlive") {
|
|
const key = node.attrs.find((attribute) => attribute.name === "key")?.value ?? "default";
|
|
return escLit('<div data-wrn-keepalive="') + bakeLoopAttr(key) + escLit(`">`) + inner + escLit("</div>");
|
|
}
|
|
if (node.tag === "Portal") {
|
|
const target = node.attrs.find((attribute) => attribute.name === "to")?.value ?? "body";
|
|
return escLit('<div data-wrn-portal="') + bakeLoopAttr(target) + escLit('">') + inner + escLit("</div>");
|
|
}
|
|
if (node.tag === "Transition") {
|
|
const name = node.attrs.find((attribute) => attribute.name === "name")?.value ?? "wrn-transition";
|
|
return escLit('<div data-wrn-transition="') + bakeLoopAttr(name) + escLit('">') + inner + escLit("</div>");
|
|
}
|
|
if (node.tag === "Component") {
|
|
const selected = node.attrs.find((attribute) => attribute.name === "is")?.value ?? "";
|
|
return escLit('<div data-wrn-dynamic-component="') + bakeLoopAttr(selected) + escLit('">') + inner + escLit("</div>");
|
|
}
|
|
if (componentTag) {
|
|
return escLit(`<div data-component="${attrEscape(node.tag)}"`) + attrs + escLit(">") + inner + escLit("</div>");
|
|
}
|
|
if (parser_ts_1.VOID_ELEMENTS.has(node.tag.toLowerCase())) {
|
|
return escLit(`<${node.tag}`) + attrs + escLit(">");
|
|
}
|
|
return escLit(`<${node.tag}`) + attrs + escLit(">") + inner + escLit(`</${node.tag}>`);
|
|
}
|
|
function compileEachExpr(node) {
|
|
const item = node.item;
|
|
const index = node.index ?? "__wi";
|
|
const body = node.body.map(renderLoopBody).join("");
|
|
const empty = node.empty.map(renderLoopBody).join("");
|
|
return "${(() => { const __wl = Array.isArray(" + node.list + ") ? (" + node.list + ") : []; return __wl.length ? __wl.map((" + item + ", " + index + ") => `" + body + '`).join("") : `' + empty + "`; })()}";
|
|
}
|
|
function compileIfExpr(node) {
|
|
let expr = "``";
|
|
for (let k = node.branches.length - 1;k >= 0; k--) {
|
|
const b = node.branches[k];
|
|
const bodySrc = "`" + b.body.map(renderLoopBody).join("") + "`";
|
|
expr = b.cond === null ? bodySrc : "(" + b.cond + ") ? " + bodySrc + " : " + expr;
|
|
}
|
|
return "${" + expr + "}";
|
|
}
|
|
function collectControlExprs(nodes, out = []) {
|
|
for (const node of nodes) {
|
|
if (node.type === "text")
|
|
continue;
|
|
if (node.type === "each") {
|
|
out.push(node.list);
|
|
collectControlExprs(node.body, out);
|
|
collectControlExprs(node.empty, out);
|
|
} else if (node.type === "if") {
|
|
for (const b of node.branches) {
|
|
if (b.cond)
|
|
out.push(b.cond);
|
|
collectControlExprs(b.body, out);
|
|
}
|
|
} else if (node.type === "element") {
|
|
collectControlExprs(node.children, out);
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
function renderNode(node, ssrBindings, csrBindings, apiBindings, loops, reactive = null) {
|
|
if (node.type === "text")
|
|
return substituteReactiveText(node.value, reactive, loops);
|
|
if (node.type === "each" || node.type === "if") {
|
|
loops.push(node.type === "each" ? compileEachExpr(node) : compileIfExpr(node));
|
|
return `\x00WRNEACH${loops.length - 1}\x00`;
|
|
}
|
|
if (node.tag === "Static" || node.tag === "Dynamic") {
|
|
const inner2 = node.children.map((child) => renderNode(child, ssrBindings, csrBindings, apiBindings, loops, reactive)).join("");
|
|
return node.tag === "Static" ? inner2 : `<wrn-dynamic-region data-wrn-dynamic="true">${inner2}</wrn-dynamic-region>`;
|
|
}
|
|
if (node.tag === "Portal" || node.tag === "Transition" || node.tag === "Component") {
|
|
const inner2 = node.children.map((child) => renderNode(child, ssrBindings, csrBindings, apiBindings, loops, reactive)).join("");
|
|
const attribute = node.tag === "Portal" ? "data-wrn-portal" : node.tag === "Transition" ? "data-wrn-transition" : "data-wrn-dynamic-component";
|
|
const source = node.tag === "Portal" ? "to" : node.tag === "Transition" ? "name" : "is";
|
|
const fallback = node.tag === "Portal" ? "body" : node.tag === "Transition" ? "wrn-transition" : "";
|
|
const original = node.attrs.find((item) => item.name === source);
|
|
const rendered = original ? renderAttrs([{ ...original, name: attribute }], undefined, reactive, loops) : ` ${attribute}="${attrEscape(fallback)}"`;
|
|
return `<div${rendered}>${inner2}</div>`;
|
|
}
|
|
if (node.tag === "Async") {
|
|
const source = attrValue(node.attrs, "source") ?? "data";
|
|
const retries = attrValue(node.attrs, "retries") ?? "2";
|
|
const tags = attrValue(node.attrs, "tags") ?? source;
|
|
const serverResolved = attrValue(node.attrs, "data-wrn-async-server") === "true";
|
|
const branchElement = (name) => node.children.find((child) => child.type === "element" && child.tag === name);
|
|
const branch = (name) => {
|
|
const element = branchElement(name);
|
|
return (element?.children ?? []).map((child) => renderNode(child, ssrBindings, csrBindings, apiBindings, loops, reactive)).join("");
|
|
};
|
|
const loading = branch("Loading");
|
|
const success = branch("Success");
|
|
const error = branch("Error");
|
|
const successElement = branchElement("Success");
|
|
const errorElement = branchElement("Error");
|
|
const identifier = (value, fallback) => value && isSafeGeneratedIdentifier(value) ? value : fallback;
|
|
const successAlias = identifier(successElement ? attrValue(successElement.attrs, "data") : undefined, identifier(source, "data"));
|
|
const errorAlias = identifier(errorElement ? attrValue(errorElement.attrs, "error") : undefined, "error");
|
|
const nested = (value) => value.replace(/\\/g, "\\\\").replace(/`/g, "\\`");
|
|
const scoped = (value, alias, expression) => {
|
|
const index = loops.push(`\${(() => { const ${alias} = ${expression}; return \`${nested(value)}\`; })()}`) - 1;
|
|
return `\x00WRNEACH${index}\x00`;
|
|
};
|
|
const successTemplate = scoped(success, successAlias, `(ctx[${JSON.stringify(source)}] ?? {})`);
|
|
const errorTemplate = scoped(error, errorAlias, `{ message: "" }`);
|
|
let initial = loading;
|
|
if (serverResolved) {
|
|
const sourcePattern = successAlias.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
const serverSuccess = success.replace(new RegExp(`\\{\\s*(${sourcePattern}(?:\\.[A-Za-z_$][\\w$]*)*)\\s*\\}`, "g"), (_whole, expression) => `\${__wrnexusEscapeHtml(${expression})}`);
|
|
const index = loops.push(`\${ctx[${JSON.stringify(source)}] !== undefined ? (() => { const ${successAlias} = ctx[${JSON.stringify(source)}]; return \`${nested(serverSuccess)}\`; })() : \`${nested(loading)}\`}`) - 1;
|
|
initial = `\x00WRNEACH${index}\x00`;
|
|
}
|
|
return `<section data-wrn-async="${attrEscape(source)}" data-wrn-async-tags="${attrEscape(tags)}" data-wrn-async-retries="${attrEscape(retries)}"${serverResolved ? ' data-wrn-async-resolved="true"' : ""} aria-busy="${serverResolved ? "false" : "true"}"><div data-wrn-async-content>${initial}</div><template data-wrn-async-loading>${loading}</template><template data-wrn-async-success data-wrn-async-alias="${attrEscape(successAlias)}">${successTemplate}</template><template data-wrn-async-error data-wrn-async-alias="${attrEscape(errorAlias)}">${errorTemplate}</template></section>`;
|
|
}
|
|
if (node.tag === "KeepAlive") {
|
|
const key = attrValue(node.attrs, "key") ?? "default";
|
|
const inner2 = node.children.map((child) => renderNode(child, ssrBindings, csrBindings, apiBindings, loops, reactive)).join("");
|
|
return `<div data-wrn-keepalive="${attrEscape(key)}">${inner2}</div>`;
|
|
}
|
|
if (isComponentTag(node.tag)) {
|
|
return renderPageComponentInvocation(node, ssrBindings, csrBindings, apiBindings, loops, reactive);
|
|
}
|
|
const apiName = attrValue(node.attrs, "api");
|
|
const apiBinding = apiName ? apiBindings.get(apiName) : undefined;
|
|
if (apiName && !apiBinding) {
|
|
throw new Error(`Unknown .wrn api binding "${apiName}"`);
|
|
}
|
|
const ssrGet = attrValue(node.attrs, "ssrGet");
|
|
const ssrText = attrValue(node.attrs, "ssrText");
|
|
const csrGet = attrValue(node.attrs, "csrGet");
|
|
const csrText = attrValue(node.attrs, "csrText");
|
|
const csrId = apiBinding?.mode === "client" ? csrMarker(csrBindings, renderBinding(apiBinding)) : csrGet && csrText ? csrMarker(csrBindings, {
|
|
method: "GET",
|
|
path: apiRoutePath(csrGet),
|
|
body: expressionBody(csrText),
|
|
helpers: ""
|
|
}) : undefined;
|
|
if (parser_ts_1.VOID_ELEMENTS.has(node.tag.toLowerCase())) {
|
|
return `<${node.tag}${renderAttrs(node.attrs, csrId, reactive, loops)}>`;
|
|
}
|
|
const inner = apiBinding?.mode === "ssr" ? ssrMarker(ssrBindings, renderBinding(apiBinding)) : ssrGet && ssrText ? ssrMarker(ssrBindings, {
|
|
method: "GET",
|
|
path: apiRoutePath(ssrGet),
|
|
body: expressionBody(ssrText),
|
|
helpers: ""
|
|
}) : node.children.map((child) => renderNode(child, ssrBindings, csrBindings, apiBindings, loops, reactive)).join("");
|
|
return `<${node.tag}${renderAttrs(node.attrs, csrId, reactive, loops)}>${inner}</${node.tag}>`;
|
|
}
|
|
function renderPageComponentInvocation(node, ssrBindings, csrBindings, apiBindings, loops, reactive) {
|
|
const attrs = node.attrs.filter((attr) => attr.name !== "data-component").map((attr) => renderPageComponentAttr(attr, loops)).join("");
|
|
const inner = node.children.map((child) => renderNode(child, ssrBindings, csrBindings, apiBindings, loops, reactive)).join("");
|
|
return `<div data-component="${attrEscape(node.tag)}"` + `${attrs}>${inner}</div>`;
|
|
}
|
|
function renderNestedComponentInvocation(node, ctx) {
|
|
let bindIndex = 0;
|
|
const attrs = node.attrs.filter((attr) => attr.name !== "data-component").map((attr) => {
|
|
const spread = /^\{\.\.\.([A-Za-z_$][\w$]*)\}$/.exec(attr.name);
|
|
if (spread) {
|
|
return `\${__wireSpreadAttrs(${ctx.resolveExpr(spread[1])})}`;
|
|
}
|
|
if (attr.event) {
|
|
return escLit(` ${componentEventAttribute(attr.name)}="`) + escLit(attrEscape(attr.value)) + escLit(`"`);
|
|
}
|
|
if (attr.boolean) {
|
|
return ` ${attr.name}`;
|
|
}
|
|
const wholeExpression = wholeAttributeExpression(attr.value);
|
|
const compiledValue = wholeExpression ? `\${__wireProp(${ctx.resolveExpr(wholeExpression)})}` : compileAttrValue(attr.value, ctx);
|
|
const rendered = ` ${attr.name}="${compiledValue}"`;
|
|
if (wholeExpression || !attr.value.includes("{") || !exprRefsState(attr.value, ctx.stateNames)) {
|
|
return rendered;
|
|
}
|
|
const marker = attrEscape(JSON.stringify([attr.name, attr.value]));
|
|
return rendered + ` data-wrn-bind-${bindIndex++}="${escLit(marker)}"`;
|
|
}).join("");
|
|
const loops = loopVarsOf(node);
|
|
const childCtx = loops.length > 0 ? {
|
|
...ctx,
|
|
forwardRestAttrs: false,
|
|
loopVars: new Set([...ctx.loopVars ?? [], ...loops])
|
|
} : { ...ctx, forwardRestAttrs: false };
|
|
const inner = node.children.map((child) => renderComponentNode(child, childCtx)).join("");
|
|
return `<div data-component="${attrEscape(node.tag)}"` + `${ctx.forwardRestAttrs ? "${__wireSpreadAttrs(__attrs)}" : ""}` + `${attrs}>${inner}</div>`;
|
|
}
|
|
function ssrMarker(bindings, binding) {
|
|
const marker = `<!--wrnexus-ssr:${bindings.length}-->`;
|
|
bindings.push({ marker, ...binding });
|
|
return marker;
|
|
}
|
|
function csrMarker(bindings, binding) {
|
|
const id = String(bindings.length);
|
|
bindings.push({ id, ...binding });
|
|
return id;
|
|
}
|
|
function renderBinding(binding) {
|
|
return {
|
|
method: binding.method,
|
|
path: binding.path,
|
|
body: binding.body,
|
|
helpers: binding.helpers
|
|
};
|
|
}
|
|
function hasClientBehavior(nodes) {
|
|
return nodes.some((node) => {
|
|
if (node.type === "text")
|
|
return /\{(?!t:)[^{}]+\}/.test(node.value);
|
|
if (node.type === "each") {
|
|
return hasClientBehavior(node.body) || hasClientBehavior(node.empty);
|
|
}
|
|
if (node.type === "if") {
|
|
return node.branches.some((branch) => hasClientBehavior(branch.body));
|
|
}
|
|
return node.attrs.some((attr) => attr.event || attr.name === "csrGet" || attr.name === "csrText") || hasClientBehavior(node.children);
|
|
});
|
|
}
|
|
function apiRoutePath(path) {
|
|
const trimmed = path.trim();
|
|
if (!trimmed.startsWith("/")) {
|
|
throw new Error(`.wrn API paths must start with "/": ${path}`);
|
|
}
|
|
if (trimmed.includes("\x00") || trimmed.includes("\\") || /(^|\/)\.\.(\/|$)/.test(trimmed)) {
|
|
throw new Error(`Unsafe .wrn API path: ${path}`);
|
|
}
|
|
if (trimmed === "/api" || trimmed.startsWith("/api/"))
|
|
return trimmed;
|
|
return `/api${trimmed}`;
|
|
}
|
|
function expressionBody(expr) {
|
|
return `return (${expr});`;
|
|
}
|
|
function dataBody(source) {
|
|
const trimmed = source.trim();
|
|
if (!trimmed)
|
|
return "return undefined;";
|
|
return /\breturn\b/.test(trimmed) ? trimmed : expressionBody(trimmed);
|
|
}
|
|
function modeHelpers(ast, mode, sharedHelpers) {
|
|
return [
|
|
sharedHelpers,
|
|
...ast.modeFunctions.filter((block) => block.mode === mode).map((block) => block.body.trim()).filter(Boolean)
|
|
].filter(Boolean).join(`
|
|
|
|
`);
|
|
}
|
|
function apiBindingMap(ast, sharedHelpers) {
|
|
const bindings = new Map;
|
|
for (const block of ast.dataApis) {
|
|
if (bindings.has(block.name)) {
|
|
throw new Error(`Duplicate .wrn api binding "${block.name}"`);
|
|
}
|
|
bindings.set(block.name, {
|
|
mode: block.mode,
|
|
method: block.method,
|
|
path: apiRoutePath(block.path),
|
|
body: dataBody(block.body),
|
|
helpers: modeHelpers(ast, block.mode, sharedHelpers)
|
|
});
|
|
}
|
|
return bindings;
|
|
}
|
|
function ssrRuntimeSource() {
|
|
return `const __wrnexusHtmlEscapes = { "&": "&", "<": "<", ">": ">", "\\"": """, "'": "'" };
|
|
function __wrnexusEscapeHtml(value: unknown): string {
|
|
return String(value).replace(/[&<>"']/g, (ch) => __wrnexusHtmlEscapes[ch] ?? ch);
|
|
}
|
|
|
|
function __wrnexusEvalData(data: unknown, body: string, helpers = "", ctx: any): unknown {
|
|
const adapters = {
|
|
cookies: ctx.cookies,
|
|
session: ctx.session,
|
|
localStorage: ctx.localStorage,
|
|
};
|
|
return new Function("$data", "$adapters", "const cookies = $adapters.cookies;\\nconst session = $adapters.session;\\nconst localStorage = $adapters.localStorage;\\nwith ($data ?? {}) {\\n" + helpers + "\\n" + body + "\\n}")(data, adapters);
|
|
}
|
|
|
|
function __wrnexusPropAttr(
|
|
value: unknown,
|
|
): string {
|
|
const serialized =
|
|
value !== null &&
|
|
typeof value === "object"
|
|
? JSON.stringify(value)
|
|
: String(value == null ? "" : value);
|
|
|
|
return serialized.replace(
|
|
/[&<>"]/g,
|
|
(character) =>
|
|
character === "&"
|
|
? "&"
|
|
: character === "<"
|
|
? "<"
|
|
: character === ">"
|
|
? ">"
|
|
: """,
|
|
);
|
|
}
|
|
|
|
async function __wrnexusCallApi(path: string, method: string, ctx: any): Promise<unknown> {
|
|
if (typeof ctx.__wrnexusCallApi === "function") {
|
|
return await ctx.__wrnexusCallApi(path, method);
|
|
}
|
|
|
|
const url = new URL(path, ctx.req.url);
|
|
const res = await fetch(new Request(url, { method, headers: ctx.req.headers }));
|
|
if (!res.ok) {
|
|
throw new Error(".wrn data API request failed with status " + res.status);
|
|
}
|
|
|
|
const type = res.headers.get("content-type") || "";
|
|
return type.includes("application/json") ? await res.json() : await res.text();
|
|
}
|
|
|
|
async function __wrnexusRenderSsrBindings(html: string, ctx: any): Promise<string> {
|
|
for (const binding of __wrnexusSsrBindings) {
|
|
const data = await __wrnexusCallApi(binding.path, binding.method, ctx);
|
|
const value = __wrnexusEvalData(data, binding.body, binding.helpers, ctx);
|
|
html = html.replace(binding.marker, __wrnexusEscapeHtml(value));
|
|
}
|
|
return html;
|
|
}`;
|
|
}
|
|
function stableHash(value) {
|
|
let hash = 2166136261;
|
|
for (let index = 0;index < value.length; index++) {
|
|
hash ^= value.charCodeAt(index);
|
|
hash = Math.imul(hash, 16777619);
|
|
}
|
|
return (hash >>> 0).toString(36);
|
|
}
|
|
function hydrationId(ast) {
|
|
const shape = JSON.stringify({
|
|
kind: ast.kind,
|
|
name: ast.name,
|
|
props: ast.props.map((entry) => entry.name),
|
|
events: ast.events.map((entry) => entry.name),
|
|
states: ast.states.map((entry) => entry.name),
|
|
computed: ast.computed.map((entry) => entry.name),
|
|
view: ast.view
|
|
});
|
|
return `${ast.name}:${stableHash(shape)}`;
|
|
}
|
|
function localStyleId(ast) {
|
|
return `wrn-${ast.kind}-${stableHash(`${ast.kind}:${ast.name}`)}`;
|
|
}
|
|
function localStyleTag(ast, styles) {
|
|
if (!styles.length)
|
|
return "";
|
|
const id = localStyleId(ast);
|
|
const css = styles.map(styleEscape).join(`
|
|
`);
|
|
return `<style data-wrnexus-style="${attrEscape(ast.name)}" data-wrnexus-style-id="${attrEscape(id)}" data-wrnexus-style-owner="${attrEscape(ast.name)}" data-wrnexus-style-kind="${attrEscape(ast.kind)}">
|
|
${css}
|
|
</style>`;
|
|
}
|
|
function localStyleExport(ast, styles) {
|
|
if (!styles.length)
|
|
return null;
|
|
return `export const __wrnexusStyles = ${JSON.stringify([
|
|
{
|
|
id: localStyleId(ast),
|
|
owner: ast.name,
|
|
kind: ast.kind,
|
|
css: styles.join(`
|
|
`)
|
|
}
|
|
], null, 2)};`;
|
|
}
|
|
function isStoreImportSource(source) {
|
|
return /(?:^|\/)stores?\//.test(source) || source.startsWith("@wrnexus/store");
|
|
}
|
|
function importedStoreBindings(ast) {
|
|
return ast.structuredImports.filter((entry) => entry.defaultImport && entry.source.endsWith(".wrn") && isStoreImportSource(entry.source)).map((entry) => ({
|
|
local: entry.defaultImport,
|
|
internal: `__wrnexusStoreDefinition_${entry.defaultImport}`
|
|
}));
|
|
}
|
|
function generatedImports(ast) {
|
|
const stores = new Map(importedStoreBindings(ast).map((entry) => [entry.local, entry.internal]));
|
|
return ast.structuredImports.map((entry) => {
|
|
if (!entry.defaultImport)
|
|
return entry.raw;
|
|
const internal = stores.get(entry.defaultImport);
|
|
return internal ? entry.raw.replace(new RegExp(`^(\\s*import\\s+(?:type\\s+)?)(?:${entry.defaultImport.replace(/[.*+?^${}()|[\\]\\]/g, "\\$&")})(\\s+from\\s+)`), `$1${internal}$2`) : entry.raw;
|
|
});
|
|
}
|
|
function isSafeGeneratedIdentifier(name) {
|
|
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
|
|
}
|
|
function generateSsrStateAliases(stateNames) {
|
|
const names = [...new Set(stateNames)].filter(isSafeGeneratedIdentifier);
|
|
if (!names.length) {
|
|
return "";
|
|
}
|
|
return `const { ${names.join(", ")} } = __state;
|
|
`;
|
|
}
|
|
function orderPageStates(entries) {
|
|
if (entries.length < 2)
|
|
return entries;
|
|
const byName = new Map(entries.map((entry) => [entry.name, entry]));
|
|
const visiting = new Set;
|
|
const visited = new Set;
|
|
const ordered = [];
|
|
const visit = (name) => {
|
|
if (visited.has(name))
|
|
return;
|
|
if (visiting.has(name)) {
|
|
throw new Error(`WRN-STATE-CYCLE: state value '${name}' has a dependency cycle.`);
|
|
}
|
|
const entry = byName.get(name);
|
|
if (!entry)
|
|
return;
|
|
visiting.add(name);
|
|
for (const dependency of byName.keys()) {
|
|
if (dependency !== name && new RegExp(`\\b${dependency.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).test(entry.expr)) {
|
|
visit(dependency);
|
|
}
|
|
}
|
|
visiting.delete(name);
|
|
visited.add(name);
|
|
ordered.push(entry);
|
|
};
|
|
for (const entry of entries)
|
|
visit(entry.name);
|
|
return ordered;
|
|
}
|
|
function generateSsrStateInitializer(entries) {
|
|
const ordered = orderPageStates(entries);
|
|
const declarations = ordered.filter((entry) => isSafeGeneratedIdentifier(entry.name)).map((entry) => `const ${entry.name} = (() => { try { return (${entry.expr}); } catch { return undefined; } })();`).join(" ");
|
|
const values = entries.map((entry) => {
|
|
if (isSafeGeneratedIdentifier(entry.name)) {
|
|
return `${JSON.stringify(entry.name)}: ${entry.name}`;
|
|
}
|
|
return `${JSON.stringify(entry.name)}: (() => { try { return (${entry.expr}); } catch { return undefined; } })()`;
|
|
}).join(", ");
|
|
return `(() => { ${declarations} return { ${values} }; })()`;
|
|
}
|
|
function orderPageComputed(entries) {
|
|
if (entries.length < 2)
|
|
return entries;
|
|
const byName = new Map(entries.map((entry) => [entry.name, entry]));
|
|
const visiting = new Set;
|
|
const visited = new Set;
|
|
const ordered = [];
|
|
const visit = (name) => {
|
|
if (visited.has(name))
|
|
return;
|
|
if (visiting.has(name)) {
|
|
throw new Error(`WRN-COMPUTED-CYCLE: computed value '${name}' has a dependency cycle.`);
|
|
}
|
|
const entry = byName.get(name);
|
|
if (!entry)
|
|
return;
|
|
visiting.add(name);
|
|
for (const dependency of byName.keys()) {
|
|
if (dependency !== name && new RegExp(`\\b${dependency.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).test(entry.expr)) {
|
|
visit(dependency);
|
|
}
|
|
}
|
|
visiting.delete(name);
|
|
visited.add(name);
|
|
ordered.push(entry);
|
|
};
|
|
for (const entry of entries)
|
|
visit(entry.name);
|
|
return ordered;
|
|
}
|
|
function generateSsrComputedAliases(entries) {
|
|
return orderPageComputed(entries).filter((entry) => isSafeGeneratedIdentifier(entry.name)).map((entry) => `const ${entry.name} = (() => { try { return (${entry.expr}); } catch { return undefined; } })();`).join(`
|
|
`);
|
|
}
|
|
function runtimeComputedNames(states, computed, runtimeRoots = []) {
|
|
const entries = [...states, ...computed];
|
|
const runtime = new Set([
|
|
...runtimeRoots,
|
|
...entries.filter((entry) => /\bctx\b/.test(entry.expr)).map((entry) => entry.name)
|
|
]);
|
|
let changed = true;
|
|
while (changed) {
|
|
changed = false;
|
|
for (const entry of entries) {
|
|
if (runtime.has(entry.name))
|
|
continue;
|
|
if ([...runtime].some((name) => new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).test(entry.expr))) {
|
|
runtime.add(entry.name);
|
|
changed = true;
|
|
}
|
|
}
|
|
}
|
|
return runtime;
|
|
}
|
|
function hydrationAttribute(ast) {
|
|
const strategy = ["static", "server"].includes(ast.renderMode ?? "") ? "none" : ast.hydrate ?? "load";
|
|
const hasBrowserModule = (0, client_codegen_ts_1.browserModuleRequired)(ast);
|
|
const moduleAttribute = hasBrowserModule ? ' data-wrn-client-module="__WRNEXUS_CLIENT_MODULE__"' : "";
|
|
return ` data-wrn-hydration="${attrEscape(hydrationId(ast))}" data-wrn-hydrate="${attrEscape(strategy)}" data-wrn-runtime="${attrEscape(ast.runtime ?? "universal")}"${moduleAttribute}`;
|
|
}
|
|
function targetFunctions(ast, target) {
|
|
const runtimes = target === "browser" ? ["legacy", "client", "shared"] : ["legacy", "server", "shared"];
|
|
return ast.functions.map((body) => (0, syntax_1.stripRuntimeFunctionModifiers)(body, [...runtimes])).map((body) => body.trim()).filter(Boolean).join(`
|
|
|
|
`);
|
|
}
|
|
function publicOutputNames(ast) {
|
|
return [
|
|
...new Set([
|
|
...ast.outputs.map((output) => output.name),
|
|
...ast.events.map((event) => event.name)
|
|
])
|
|
];
|
|
}
|
|
function prepareActionForms(nodes, actions) {
|
|
for (const node of nodes) {
|
|
if (node.type === "text")
|
|
continue;
|
|
if (node.type === "each") {
|
|
prepareActionForms(node.body, actions);
|
|
prepareActionForms(node.empty, actions);
|
|
continue;
|
|
}
|
|
if (node.type === "if") {
|
|
node.branches.forEach((branch) => prepareActionForms(branch.body, actions));
|
|
continue;
|
|
}
|
|
prepareActionForms(node.children, actions);
|
|
if (node.tag.toLowerCase() !== "form")
|
|
continue;
|
|
const submit = node.attrs.find((attr) => attr.event && attr.name === "submit");
|
|
if (!submit || !actions.has(submit.value.trim()))
|
|
continue;
|
|
const name = submit.value.trim();
|
|
node.attrs = node.attrs.filter((attr) => attr !== submit);
|
|
if (!node.attrs.some((attr) => !attr.event && attr.name === "method")) {
|
|
node.attrs.push({ name: "method", value: "post", event: false });
|
|
}
|
|
node.attrs.push({ name: "data-wrn-action", value: name, event: false });
|
|
node.children.unshift({
|
|
type: "element",
|
|
tag: "input",
|
|
attrs: [
|
|
{ name: "type", value: "hidden", event: false },
|
|
{ name: "name", value: "_wrnexus_action", event: false },
|
|
{ name: "value", value: name, event: false }
|
|
],
|
|
children: []
|
|
});
|
|
}
|
|
}
|
|
function markServerAsyncBoundaries(nodes, serverLoads) {
|
|
for (const node of nodes) {
|
|
if (node.type === "text")
|
|
continue;
|
|
if (node.type === "each") {
|
|
markServerAsyncBoundaries(node.body, serverLoads);
|
|
markServerAsyncBoundaries(node.empty, serverLoads);
|
|
continue;
|
|
}
|
|
if (node.type === "if") {
|
|
node.branches.forEach((branch) => markServerAsyncBoundaries(branch.body, serverLoads));
|
|
continue;
|
|
}
|
|
if (node.tag === "Async") {
|
|
const source = attrValue(node.attrs, "source") ?? "data";
|
|
if (serverLoads.has(source) && !node.attrs.some((attribute) => attribute.name === "data-wrn-async-server")) {
|
|
node.attrs.push({ name: "data-wrn-async-server", value: "true", event: false });
|
|
}
|
|
}
|
|
markServerAsyncBoundaries(node.children, serverLoads);
|
|
}
|
|
}
|
|
function generate(ast) {
|
|
ast = (0, analysis_ts_1.optimizeAst)(ast).ast;
|
|
if (ast.kind === "global-store" || ast.kind === "page-store")
|
|
return (0, store_codegen_ts_1.generateStoreModule)(ast);
|
|
if (ast.kind === "component" || ast.kind === "layout") {
|
|
return generateComponent(ast);
|
|
}
|
|
const out = [];
|
|
prepareActionForms(ast.view, new Set(ast.actions.map((action) => action.name)));
|
|
markServerAsyncBoundaries(ast.view, new Set(ast.loads.filter((load) => load.mode === "server" && !load.deferred && load.name).map((load) => load.name)));
|
|
if (ast.actions.length > 0) {
|
|
out.push(`import { createActionClient } from "@wrnexus/csr";
|
|
import type { InferSchema } from "@wrnexus/validation";`);
|
|
}
|
|
if (ast.imports.length > 0)
|
|
out.push(generatedImports(ast).join(`
|
|
`));
|
|
const ssrBindings = [];
|
|
const csrBindings = [];
|
|
const helpers = targetFunctions(ast, "server");
|
|
const apiBindings = apiBindingMap(ast, helpers);
|
|
const typeSource = ast.types.map((body2) => body2.trim()).filter(Boolean).join(`
|
|
|
|
`);
|
|
if (typeSource)
|
|
out.push(typeSource);
|
|
if (helpers) {
|
|
out.push(`// --- .wrn functions ---
|
|
${helpers}`);
|
|
}
|
|
out.push(`export const meta = ${JSON.stringify({ title: ast.name, ...ast.seo }, null, 2)};`);
|
|
if (ast.layout)
|
|
out.push(`export const layout = ${ast.layoutIsSymbol ? ast.layout : JSON.stringify(ast.layout)};`);
|
|
out.push(`export const __wrnexusRuntime = ${JSON.stringify(ast.runtime ?? "universal")};`);
|
|
out.push(`export const __wrnexusRender = ${JSON.stringify(ast.renderMode ?? "hybrid")};`);
|
|
out.push(`export const __wrnexusHydrate = ${JSON.stringify(["static", "server"].includes(ast.renderMode ?? "") ? "none" : ast.hydrate ?? "load")};`);
|
|
out.push(`export const __wrnexusHydrationId = ${JSON.stringify(hydrationId(ast))};`);
|
|
if (Object.keys(ast.cache ?? {}).length > 0)
|
|
out.push(`export const __wrnexusCache = ${JSON.stringify(ast.cache, null, 2)};`);
|
|
if (Object.keys(ast.security).length > 0) {
|
|
out.push(`export const __wrnexusSecurity = ${JSON.stringify(ast.security, null, 2)};`);
|
|
}
|
|
if (Object.keys(ast.navigation).length > 0) {
|
|
out.push(`export const __wrnexusNavigation = ${JSON.stringify(ast.navigation, null, 2)};`);
|
|
}
|
|
const orderedStates = orderPageStates(ast.states);
|
|
const browserStates = ast.states.filter((state) => state.runtime !== "server");
|
|
const seedScope = evalStateSeeds(orderedStates);
|
|
const orderedComputed = orderPageComputed(ast.computed);
|
|
for (const entry of orderedComputed) {
|
|
try {
|
|
seedScope[entry.name] = new Function("with(this){return (" + entry.expr + ");}").call(seedScope);
|
|
} catch {
|
|
seedScope[entry.name] = undefined;
|
|
}
|
|
}
|
|
const reactiveNames = [
|
|
...browserStates.map((entry) => entry.name),
|
|
...ast.computed.map((entry) => entry.name)
|
|
];
|
|
const storeBindings = importedStoreBindings(ast);
|
|
const runtimeRoots = [
|
|
...storeBindings.map((entry) => entry.local),
|
|
...ast.loads.filter((load) => load.mode === "server" && !load.deferred && load.name).map((load) => load.name)
|
|
];
|
|
const runtimeStateNames = runtimeComputedNames(orderedStates, orderedComputed, runtimeRoots);
|
|
const reactive = reactiveNames.length > 0 ? { stateNames: new Set(reactiveNames), runtimeStateNames, scope: seedScope } : null;
|
|
const loops = [];
|
|
let html = ast.view.map((node) => renderNode(node, ssrBindings, csrBindings, apiBindings, loops, reactive)).join("");
|
|
const styles = ast.styles.map((body2) => body2.trim()).filter(Boolean);
|
|
const pageBehavior = ast.runtime === "server" ? null : componentBehavior(ast);
|
|
const needsClientRuntime = ast.runtime !== "server" && (browserStates.length > 0 || ast.computed.length > 0 || hasClientBehavior(ast.view) || pageBehavior !== null);
|
|
if (needsClientRuntime) {
|
|
const scopePlaceholder = "__WRNEXUS_DYNAMIC_SCOPE__";
|
|
html = `<div data-scope="${scopePlaceholder}"${behaviorAttribute(pageBehavior)}${hydrationAttribute(ast)}>${html}</div>`;
|
|
}
|
|
const pageStyleTag = localStyleTag(ast, styles);
|
|
if (pageStyleTag) {
|
|
html = `${pageStyleTag}${html}`;
|
|
}
|
|
if (ast.renderMode === "client") {
|
|
const clientRoot = hydrationId(ast);
|
|
html = `<div data-wrn-client-root="${clientRoot}" aria-busy="true"></div><template data-wrn-client-template="${clientRoot}">${html}</template>`;
|
|
}
|
|
const pageStyleExport = localStyleExport(ast, styles);
|
|
if (pageStyleExport)
|
|
out.push(pageStyleExport);
|
|
if (csrBindings.length > 0) {
|
|
out.push(`export const __wrnexusCsr = ${JSON.stringify(csrBindings, null, 2)};`);
|
|
}
|
|
if (pageBehavior) {
|
|
out.push(`export const __wrnexusBehavior = ${JSON.stringify(pageBehavior, null, 2)};`);
|
|
}
|
|
let body = templateEscape(html);
|
|
let staticShellBody;
|
|
if (ast.renderMode === "partial-static") {
|
|
const shellHtml = html.replace(/<wrn-dynamic-region\b[^>]*>[\s\S]*?<\/wrn-dynamic-region>/gi, '<wrn-dynamic-region data-wrn-dynamic="true"></wrn-dynamic-region>');
|
|
staticShellBody = templateEscape(shellHtml);
|
|
}
|
|
const dynamicStateInitializer = generateSsrStateInitializer(orderedStates);
|
|
const stateType = ast.states.length > 0 ? `{ ${ast.states.map((state) => `${JSON.stringify(state.name)}: ${state.valueType ?? "unknown"}`).join("; ")} }` : "Record<string, never>";
|
|
const hydrationStateNames = JSON.stringify(browserStates.map((state) => state.name));
|
|
const ssrStateAliases = generateSsrStateAliases(ast.states.map((state) => state.name));
|
|
const ssrComputedAliases = generateSsrComputedAliases(orderedComputed);
|
|
const storeDeclarations = storeBindings.map((entry) => ` const ${entry.local} = await ctx.__wrnexusUseStore(${entry.internal});`).join(`
|
|
`);
|
|
const serverLoadAliases = ast.loads.filter((load) => load.mode === "server" && !load.deferred && load.name).map((load) => ` const ${load.name} = ctx[${JSON.stringify(load.name)}];`).join(`
|
|
`);
|
|
for (let idx = loops.length - 1;idx >= 0; idx--) {
|
|
const code = loops[idx];
|
|
body = body.replaceAll(`\x00WRNEACH${idx}\x00`, code);
|
|
if (staticShellBody?.includes(`\x00WRNEACH${idx}\x00`)) {
|
|
staticShellBody = staticShellBody.replaceAll(`\x00WRNEACH${idx}\x00`, code);
|
|
}
|
|
}
|
|
const loopConsts = [];
|
|
if (loops.length > 0) {
|
|
const lists = collectControlExprs(ast.view);
|
|
for (const [name, binding] of apiBindings) {
|
|
if (binding.mode !== "ssr")
|
|
continue;
|
|
if (!lists.some((expr) => new RegExp(`\\b${name}\\b`).test(expr)))
|
|
continue;
|
|
loopConsts.push(` const ${name} = __wrnexusEvalData(await __wrnexusCallApi(${JSON.stringify(binding.path)}, ${JSON.stringify(binding.method)}, ctx), ${JSON.stringify(binding.body)}, ${JSON.stringify(binding.helpers)}, ctx);`);
|
|
}
|
|
}
|
|
const needsSsrRuntime = ssrBindings.length > 0 || loops.length > 0 || runtimeStateNames.size > 0;
|
|
if (needsSsrRuntime) {
|
|
out.push(ssrRuntimeSource());
|
|
out.push(`const __wrnexusSsrBindings = ${JSON.stringify(ssrBindings, null, 2)};`);
|
|
const decls = loopConsts.length > 0 ? loopConsts.join(`
|
|
`) + `
|
|
` : "";
|
|
out.push(`export default async function ${ast.name}(ctx: any) {
|
|
${storeDeclarations}
|
|
${serverLoadAliases}
|
|
${decls}
|
|
const __state: ${stateType} = ${dynamicStateInitializer};
|
|
${ssrStateAliases}
|
|
${ssrComputedAliases}
|
|
const __hydrationState = Object.fromEntries(${hydrationStateNames}.map((key) => [key, (__state as any)[key]]));
|
|
const __scopeValue = Object.entries(__hydrationState)
|
|
.map(([key, value]) => {
|
|
let encoded: string;
|
|
try {
|
|
encoded = value === undefined ? "undefined" : JSON.stringify(value);
|
|
} catch {
|
|
encoded = JSON.stringify(String(value));
|
|
}
|
|
return key + ": " + encoded;
|
|
})
|
|
.join(", ")
|
|
.replace(/&/g, "&")
|
|
.replace(/"/g, """)
|
|
.replace(/</g, "<")
|
|
.replace(/>/g, ">");
|
|
|
|
const html = \`${body}\`.replace(
|
|
"__WRNEXUS_DYNAMIC_SCOPE__",
|
|
__scopeValue,
|
|
);
|
|
|
|
return await __wrnexusRenderSsrBindings(html, ctx);
|
|
}`);
|
|
} else {
|
|
out.push(`export default ${storeBindings.length > 0 ? "async " : ""}function ${ast.name}(ctx: any) {
|
|
${storeDeclarations}
|
|
${serverLoadAliases}
|
|
const __state: ${stateType} = ${dynamicStateInitializer};
|
|
${ssrStateAliases}
|
|
${ssrComputedAliases}
|
|
const __hydrationState = Object.fromEntries(${hydrationStateNames}.map((key) => [key, (__state as any)[key]]));
|
|
const __scopeValue = Object.entries(__hydrationState)
|
|
.map(([key, value]) => {
|
|
let encoded: string;
|
|
try {
|
|
encoded = value === undefined ? "undefined" : JSON.stringify(value);
|
|
} catch {
|
|
encoded = JSON.stringify(String(value));
|
|
}
|
|
return key + ": " + encoded;
|
|
})
|
|
.join(", ")
|
|
.replace(/&/g, "&")
|
|
.replace(/"/g, """)
|
|
.replace(/</g, "<")
|
|
.replace(/>/g, ">");
|
|
|
|
return \`${body}\`.replace(
|
|
"__WRNEXUS_DYNAMIC_SCOPE__",
|
|
__scopeValue,
|
|
);
|
|
}`);
|
|
}
|
|
if (staticShellBody !== undefined) {
|
|
out.push(`export async function __wrnexusBuildStaticShell(ctx: any = {}) {
|
|
${storeDeclarations}
|
|
${serverLoadAliases}
|
|
${loopConsts.length > 0 ? loopConsts.join(`
|
|
`) : ""}
|
|
const __state: ${stateType} = ${dynamicStateInitializer};
|
|
${ssrStateAliases}
|
|
${ssrComputedAliases}
|
|
const __hydrationState = Object.fromEntries(${hydrationStateNames}.map((key) => [key, (__state as any)[key]]));
|
|
const __scopeValue = Object.entries(__hydrationState)
|
|
.map(([key, value]) => {
|
|
let encoded: string;
|
|
try {
|
|
encoded = value === undefined ? "undefined" : JSON.stringify(value);
|
|
} catch {
|
|
encoded = JSON.stringify(String(value));
|
|
}
|
|
return key + ": " + encoded;
|
|
})
|
|
.join(", ")
|
|
.replace(/&/g, "&")
|
|
.replace(/"/g, """)
|
|
.replace(/</g, "<")
|
|
.replace(/>/g, ">");
|
|
return \`${staticShellBody}\`.replace("__WRNEXUS_DYNAMIC_SCOPE__", __scopeValue);
|
|
}`);
|
|
}
|
|
if (ast.loads.length > 0) {
|
|
const serverLoads = ast.loads.filter((entry) => entry.mode === "server" && !entry.deferred);
|
|
const publicClientLoads = ast.loads.filter((entry) => entry.mode === "client" || entry.deferred);
|
|
const namedByName = new Map(ast.loads.filter((entry) => entry.name).map((entry) => [entry.name, entry]));
|
|
const clientNames = new Set(publicClientLoads.flatMap((entry) => entry.name ? [entry.name] : []));
|
|
const includeDependencies = (name) => {
|
|
for (const dependency of namedByName.get(name)?.dependsOn ?? []) {
|
|
if (clientNames.has(dependency))
|
|
continue;
|
|
clientNames.add(dependency);
|
|
includeDependencies(dependency);
|
|
}
|
|
};
|
|
for (const name of [...clientNames])
|
|
includeDependencies(name);
|
|
const clientLoads = ast.loads.filter((entry) => !entry.name || clientNames.has(entry.name));
|
|
const renderLoads = (exportName, execution, exposed) => {
|
|
const declarations = execution.filter((entry) => entry.name).map((entry) => {
|
|
const dependencies = (entry.dependsOn ?? []).map((dependency) => `const ${dependency} = await __load_${dependency}();`).join(`
|
|
`);
|
|
return ` let __promise_${entry.name}: Promise<unknown> | undefined;
|
|
const __load_${entry.name} = () => (__promise_${entry.name} ??= (async () => {
|
|
${dependencies}
|
|
${entry.body}
|
|
})());`;
|
|
}).join(`
|
|
`);
|
|
const visible = exposed.filter((entry) => entry.name);
|
|
return `export async function ${exportName}(ctx: any) {
|
|
${exposed.filter((entry) => !entry.name).map((entry) => entry.body).join(`
|
|
`)}
|
|
${declarations}
|
|
${visible.length ? ` const __values = await Promise.all([${visible.map((entry) => `__load_${entry.name}()`).join(", ")}]);
|
|
return { ${visible.map((entry, index) => `${JSON.stringify(entry.name)}: __values[${index}]`).join(", ")} };` : ""}
|
|
}`;
|
|
};
|
|
if (serverLoads.length > 0)
|
|
out.push(renderLoads("__wrnexusLoad", serverLoads, serverLoads));
|
|
if (publicClientLoads.length > 0)
|
|
out.push(renderLoads("__wrnexusClientLoad", clientLoads, publicClientLoads));
|
|
}
|
|
if (ast.actions.length > 0) {
|
|
for (const action of ast.actions) {
|
|
if (!action.schema) {
|
|
out.push(`export async function ${action.name}(${action.args.join(", ")}) {${action.body}}`);
|
|
continue;
|
|
}
|
|
out.push(`export async function ${action.name}(input: any, ctx: any) {
|
|
const invalidate = (...tags: string[]) => {
|
|
const bucket = (ctx.locals.__wrnexusInvalidatedTags ??= []);
|
|
bucket.push(...tags.flat());
|
|
};
|
|
${action.body}
|
|
}`);
|
|
}
|
|
out.push(`export const __wrnexusActions = { ${ast.actions.map((action) => `${action.name}: { run: ${action.name}, schema: ${action.schema ?? "undefined"} }`).join(", ")} };`);
|
|
out.push(`export const __wrnexusActionClients = {
|
|
${ast.actions.map((action) => ` ${action.name}: createActionClient<${action.schema ? `InferSchema<typeof ${action.schema}>` : "Record<string, unknown>"}, Awaited<ReturnType<typeof ${action.name}>>>("", ${JSON.stringify(action.name)}),`).join(`
|
|
`)}
|
|
};`);
|
|
}
|
|
if (ast.apis.length > 0) {
|
|
ast.apis.forEach((api, index) => {
|
|
const name = `__wrnexusApi_${api.method}_${index}`;
|
|
out.push(`// ${api.method} ${apiRoutePath(api.path)}
|
|
const ${name} = async (ctx: any) => {${api.body}};`);
|
|
});
|
|
const entries = ast.apis.map((api, index) => ` ${JSON.stringify(`${api.method} ${apiRoutePath(api.path)}`)}: __wrnexusApi_${api.method}_${index},`);
|
|
out.push(`export const __wrnexusApi = {
|
|
${entries.join(`
|
|
`)}
|
|
};`);
|
|
const exported = new Set;
|
|
ast.apis.forEach((api, index) => {
|
|
if (exported.has(api.method))
|
|
return;
|
|
exported.add(api.method);
|
|
out.push(`export const ${api.method} = __wrnexusApi_${api.method}_${index};`);
|
|
});
|
|
}
|
|
if (ast.realtimes.length > 0) {
|
|
const handlers = ast.realtimes.flatMap((rt) => rt.handlers.map((h) => {
|
|
const params = ["ws", ...h.args].join(", ");
|
|
return ` ${h.event}(${params}: any) {${h.body}},`;
|
|
}));
|
|
out.push(`export const websocket = {
|
|
${handlers.join(`
|
|
`)}
|
|
};`);
|
|
}
|
|
return out.join(`
|
|
|
|
`) + `
|
|
`;
|
|
}
|
|
function parseForExpr(value) {
|
|
const m = /^\s*([A-Za-z_$][\w$]*)\s*(?:,\s*([A-Za-z_$][\w$]*)\s*)?\s+in\s+([\s\S]+?)(?:\s+key\s+([\s\S]+?))?\s*$/.exec(value);
|
|
if (!m)
|
|
return null;
|
|
return { item: m[1], index: m[2], list: m[3].trim(), key: m[4]?.trim() };
|
|
}
|
|
function loopVarsOf(node) {
|
|
if (node.type !== "element")
|
|
return [];
|
|
const attr = node.attrs.find((a) => !a.event && a.name === "data-for");
|
|
if (!attr)
|
|
return [];
|
|
const parsed = parseForExpr(attr.value);
|
|
return parsed ? [parsed.item, ...parsed.index ? [parsed.index] : []] : [];
|
|
}
|
|
const JS_RESERVED = new Set([
|
|
"class",
|
|
"for",
|
|
"default",
|
|
"function",
|
|
"return",
|
|
"if",
|
|
"else",
|
|
"new",
|
|
"delete",
|
|
"typeof",
|
|
"in",
|
|
"instanceof",
|
|
"void",
|
|
"do",
|
|
"while",
|
|
"switch",
|
|
"case",
|
|
"break",
|
|
"continue",
|
|
"this",
|
|
"super",
|
|
"import",
|
|
"export",
|
|
"extends",
|
|
"var",
|
|
"let",
|
|
"const",
|
|
"null",
|
|
"true",
|
|
"false",
|
|
"try",
|
|
"catch",
|
|
"finally",
|
|
"throw",
|
|
"yield",
|
|
"await",
|
|
"enum",
|
|
"with",
|
|
"debugger",
|
|
"implements",
|
|
"interface",
|
|
"package",
|
|
"private",
|
|
"protected",
|
|
"public",
|
|
"static"
|
|
]);
|
|
function safeRef(name) {
|
|
return JS_RESERVED.has(name) ? `__p_${name}` : name;
|
|
}
|
|
function escLit(s) {
|
|
return s.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
|
|
}
|
|
function componentBehavior(ast) {
|
|
const functions = (0, types_ts_1.eraseFunctionTypes)(targetFunctions(ast, "browser"));
|
|
const computed = ast.computed.map((entry) => ({ name: entry.name, expr: entry.expr.trim() }));
|
|
const effects = ast.effects.map((entry) => entry.body.trim()).filter(Boolean);
|
|
const lifecycle = {
|
|
...ast.lifecycle.mount?.trim() ? { mount: ast.lifecycle.mount.trim() } : {},
|
|
...ast.lifecycle.update?.trim() ? { update: ast.lifecycle.update.trim() } : {},
|
|
...ast.lifecycle.unmount?.trim() ? { unmount: ast.lifecycle.unmount.trim() } : {}
|
|
};
|
|
const watches = ast.watches.map((watch) => ({
|
|
state: watch.state,
|
|
body: watch.body.trim()
|
|
}));
|
|
if (!functions && ast.outputs.length === 0 && computed.length === 0 && effects.length === 0 && Object.keys(lifecycle).length === 0 && watches.length === 0) {
|
|
return null;
|
|
}
|
|
return {
|
|
functions,
|
|
outputs: ast.outputs,
|
|
computed,
|
|
effects,
|
|
lifecycle,
|
|
watches
|
|
};
|
|
}
|
|
function behaviorAttribute(behavior) {
|
|
if (!behavior) {
|
|
return "";
|
|
}
|
|
const encoded = node_buffer_1.Buffer.from(JSON.stringify(behavior), "utf8").toString("base64");
|
|
return ` data-wrn-behavior="${encoded}"`;
|
|
}
|
|
const INTERP_RE = /\{([^{}]+)\}/g;
|
|
function exprRefsState(expr, stateNames) {
|
|
for (const name of stateNames) {
|
|
if (new RegExp(`\\b${name}\\b`).test(expr))
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
function exprRefsComponentReactiveValue(expr, ctx) {
|
|
return exprRefsState(expr, ctx.stateNames) || exprRefsState(expr, ctx.functionNames);
|
|
}
|
|
function viewHasEvents(nodes) {
|
|
return nodes.some((node) => {
|
|
if (node.type === "text")
|
|
return false;
|
|
if (node.type === "each") {
|
|
return viewHasEvents(node.body) || viewHasEvents(node.empty);
|
|
}
|
|
if (node.type === "if") {
|
|
return node.branches.some((branch) => viewHasEvents(branch.body));
|
|
}
|
|
return node.attrs.some((attr) => attr.event) || viewHasEvents(node.children);
|
|
});
|
|
}
|
|
function viewHasServerEach(nodes) {
|
|
return nodes.some((node) => {
|
|
if (node.type === "text")
|
|
return false;
|
|
if (node.type === "each")
|
|
return true;
|
|
if (node.type === "if") {
|
|
return node.branches.some((branch) => viewHasServerEach(branch.body));
|
|
}
|
|
return viewHasServerEach(node.children);
|
|
});
|
|
}
|
|
function viewHasRestAttributeSpread(nodes) {
|
|
return nodes.some((node) => {
|
|
if (node.type === "text")
|
|
return false;
|
|
if (node.type === "each") {
|
|
return viewHasRestAttributeSpread(node.body) || viewHasRestAttributeSpread(node.empty);
|
|
}
|
|
if (node.type === "if") {
|
|
return node.branches.some((branch) => viewHasRestAttributeSpread(branch.body));
|
|
}
|
|
return node.attrs.some((attr) => /^\{\.\.\.([A-Za-z_$][\w$]*)\}$/.test(attr.name)) || viewHasRestAttributeSpread(node.children);
|
|
});
|
|
}
|
|
function compileText(raw, ctx) {
|
|
let out = "";
|
|
let last = 0;
|
|
let m;
|
|
INTERP_RE.lastIndex = 0;
|
|
while (m = INTERP_RE.exec(raw)) {
|
|
out += escLit(raw.slice(last, m.index));
|
|
const expr = m[1].trim();
|
|
if (expr.startsWith("t:")) {
|
|
out += escLit(`<span data-t="${attrEscape(expr.slice(2).trim())}"></span>`);
|
|
} else if (ctx.loopVars && exprRefsState(expr, ctx.loopVars)) {
|
|
out += escLit(`{${expr}}`);
|
|
} else if (exprRefsComponentReactiveValue(expr, ctx)) {
|
|
out += escLit(`<span data-text="${attrEscape(expr)}">`) + `\${__wireHtml(${ctx.resolveExpr(expr)})}` + escLit(`</span>`);
|
|
} else if (expr === "content") {
|
|
out += `\${__wireRaw(${ctx.resolveExpr(expr)})}`;
|
|
} else {
|
|
out += `\${__wireHtml(${ctx.resolveExpr(expr)})}`;
|
|
}
|
|
last = m.index + m[0].length;
|
|
}
|
|
return out + escLit(raw.slice(last));
|
|
}
|
|
function compileAttrValue(raw, ctx) {
|
|
if (!raw.includes("{"))
|
|
return escLit(attrEscape(raw));
|
|
let out = "";
|
|
let last = 0;
|
|
let m;
|
|
INTERP_RE.lastIndex = 0;
|
|
while (m = INTERP_RE.exec(raw)) {
|
|
out += escLit(attrEscape(raw.slice(last, m.index)));
|
|
const expr = m[1].trim();
|
|
if (ctx.loopVars && exprRefsState(expr, ctx.loopVars)) {
|
|
out += escLit(`{${expr}}`);
|
|
} else {
|
|
out += `\${__wireAttr(${ctx.resolveExpr(expr)})}`;
|
|
}
|
|
last = m.index + m[0].length;
|
|
}
|
|
return out + escLit(attrEscape(raw.slice(last)));
|
|
}
|
|
function renderComponentIfNode(node, ctx) {
|
|
let expression = "``";
|
|
for (let index = node.branches.length - 1;index >= 0; index--) {
|
|
const branch = node.branches[index];
|
|
const body = branch.body.map((child) => renderComponentNode(child, ctx)).join("");
|
|
const bodyExpression = "`" + body + "`";
|
|
expression = branch.cond === null ? bodyExpression : `(${ctx.resolveExpr(branch.cond)}) ? ${bodyExpression} : ${expression}`;
|
|
}
|
|
return "${" + expression + "}";
|
|
}
|
|
function renderComponentEachNode(node, ctx) {
|
|
const item = node.item;
|
|
const index = node.index ?? "__wi";
|
|
const list = ctx.resolveExpr(node.list);
|
|
const childCtx = {
|
|
...ctx,
|
|
serverLocals: new Set([...ctx.serverLocals ?? [], item, index])
|
|
};
|
|
const body = node.body.map((child) => renderComponentNode(child, childCtx)).join("");
|
|
const empty = node.empty.map((child) => renderComponentNode(child, ctx)).join("");
|
|
return "${(() => { const __wl = Array.isArray(" + list + ") ? (" + list + ") : []; return __wl.length ? __wl.map((" + item + ", " + index + ") => `" + body + '`).join("") : `' + empty + "`; })()}";
|
|
}
|
|
function serverLoopLocalsAttribute(ctx) {
|
|
const locals = [...ctx.serverLocals ?? []];
|
|
if (locals.length === 0) {
|
|
return "";
|
|
}
|
|
const entries = locals.map((name) => `${JSON.stringify(name)}: ${name}`).join(", ");
|
|
return ` data-wrn-loop-locals="\${__wrnexusEncodeLoopLocals({ ${entries} })}"`;
|
|
}
|
|
function unwrapDirectiveExpression(raw) {
|
|
const value = raw.trim();
|
|
if (!value.startsWith("{") || !value.endsWith("}")) {
|
|
return value;
|
|
}
|
|
let depth = 0;
|
|
let quote = null;
|
|
let escaped = false;
|
|
for (let index = 0;index < value.length; index++) {
|
|
const char = value[index];
|
|
if (escaped) {
|
|
escaped = false;
|
|
continue;
|
|
}
|
|
if (quote) {
|
|
if (char === "\\") {
|
|
escaped = true;
|
|
} else if (char === quote) {
|
|
quote = null;
|
|
}
|
|
continue;
|
|
}
|
|
if (char === '"' || char === "'" || char === "`") {
|
|
quote = char;
|
|
continue;
|
|
}
|
|
if (char === "{")
|
|
depth++;
|
|
if (char === "}")
|
|
depth--;
|
|
if (depth === 0 && index < value.length - 1) {
|
|
return value;
|
|
}
|
|
}
|
|
return depth === 0 ? value.slice(1, -1).trim() : value;
|
|
}
|
|
function renderComponentNode(node, ctx) {
|
|
if (node.type === "text")
|
|
return compileText(node.value, ctx);
|
|
if (node.type === "each") {
|
|
return renderComponentEachNode(node, ctx);
|
|
}
|
|
if (node.type === "if") {
|
|
return renderComponentIfNode(node, ctx);
|
|
}
|
|
if (node.tag === "Static" || node.tag === "Dynamic") {
|
|
const inner2 = node.children.map((child) => renderComponentNode(child, ctx)).join("");
|
|
return node.tag === "Static" ? inner2 : `<wrn-dynamic-region data-wrn-dynamic="true">${inner2}</wrn-dynamic-region>`;
|
|
}
|
|
if (node.tag === "KeepAlive") {
|
|
const key = node.attrs.find((attribute) => attribute.name === "key")?.value ?? "default";
|
|
const inner2 = node.children.map((child) => renderComponentNode(child, ctx)).join("");
|
|
return `<div data-wrn-keepalive="${compileAttrValue(key, ctx)}">${inner2}</div>`;
|
|
}
|
|
if (node.tag === "Portal" || node.tag === "Transition" || node.tag === "Component") {
|
|
const inner2 = node.children.map((child) => renderComponentNode(child, ctx)).join("");
|
|
const attribute = node.tag === "Portal" ? "data-wrn-portal" : node.tag === "Transition" ? "data-wrn-transition" : "data-wrn-dynamic-component";
|
|
const source = node.tag === "Portal" ? "to" : node.tag === "Transition" ? "name" : "is";
|
|
const fallback = node.tag === "Portal" ? "body" : node.tag === "Transition" ? "wrn-transition" : "";
|
|
const raw = node.attrs.find((item) => item.name === source)?.value ?? fallback;
|
|
return `<div ${attribute}="${compileAttrValue(raw, ctx)}">${inner2}</div>`;
|
|
}
|
|
if (isComponentTag(node.tag)) {
|
|
return renderNestedComponentInvocation(node, ctx);
|
|
}
|
|
const loopVariables = loopVarsOf(node);
|
|
const elementContext = {
|
|
...ctx,
|
|
forwardRestAttrs: false,
|
|
...loopVariables.length > 0 ? { loopVars: new Set([...ctx.loopVars ?? [], ...loopVariables]) } : {}
|
|
};
|
|
let bindIndex = 0;
|
|
const staticClasses = [];
|
|
const conditionalClasses = [];
|
|
for (const attr of node.attrs) {
|
|
if (!attr.event && attr.name === "class") {
|
|
staticClasses.push(attr.value);
|
|
}
|
|
if (!attr.event && attr.name.startsWith("class:")) {
|
|
conditionalClasses.push({
|
|
className: attr.name.slice("class:".length),
|
|
expression: unwrapDirectiveExpression(attr.value)
|
|
});
|
|
}
|
|
}
|
|
const isExplicitComponentMount = node.attrs.some((attribute) => attribute.name === "data-component");
|
|
const attrs = node.attrs.filter((a) => a.name !== "class" && !a.name.startsWith("class:")).map((a) => {
|
|
const spread = /^\{\.\.\.([A-Za-z_$][\w$]*)\}$/.exec(a.name);
|
|
if (spread) {
|
|
return `\${__wireSpreadAttrs(${elementContext.resolveExpr(spread[1])})}`;
|
|
}
|
|
if (a.event) {
|
|
return ` ${eventAttribute(a.name)}="${escLit(attrEscape(a.value))}"`;
|
|
}
|
|
if (a.boolean) {
|
|
return ` ${a.name}`;
|
|
}
|
|
if (isHtmlBooleanAttribute(a.name)) {
|
|
const expression = wholeAttributeExpression(a.value);
|
|
if (expression) {
|
|
const referencesState2 = exprRefsComponentReactiveValue(a.value, ctx);
|
|
const referencesLoopVariable2 = elementContext.loopVars ? exprRefsState(a.value, elementContext.loopVars) : false;
|
|
const referencesServerLocal2 = ctx.serverLocals ? exprRefsState(a.value, ctx.serverLocals) : false;
|
|
const marker2 = referencesState2 || referencesLoopVariable2 || referencesServerLocal2 ? ` data-wrn-bind-${bindIndex++}="${escLit(attrEscape(JSON.stringify([a.name, a.value])))}"` : "";
|
|
if (referencesLoopVariable2) {
|
|
return ` data-wrn-bind-${bindIndex++}="${escLit(attrEscape(JSON.stringify([a.name, a.value])))}"`;
|
|
}
|
|
return `\${__wireBooleanAttr(${JSON.stringify(a.name)}, ${elementContext.resolveExpr(expression)})}${marker2}`;
|
|
}
|
|
if (a.value === "false")
|
|
return "";
|
|
if (a.value === "true" || a.value === "")
|
|
return ` ${a.name}`;
|
|
}
|
|
const wholeExpression = wholeAttributeExpression(a.value);
|
|
if (a.name === "data-show" && wholeExpression) {
|
|
return ` data-show="${escLit(attrEscape(wholeExpression))}"`;
|
|
}
|
|
const compiledValue = isExplicitComponentMount && wholeExpression ? `\${__wireProp(${elementContext.resolveExpr(wholeExpression)})}` : compileAttrValue(a.value, elementContext);
|
|
const rendered = ` ${a.name}="${compiledValue}"`;
|
|
const referencesState = exprRefsComponentReactiveValue(a.value, ctx);
|
|
const referencesLoopVariable = elementContext.loopVars ? exprRefsState(a.value, elementContext.loopVars) : false;
|
|
const referencesServerLocal = ctx.serverLocals ? exprRefsState(a.value, ctx.serverLocals) : false;
|
|
if (!a.value.includes("{") || !referencesState && !referencesLoopVariable && !referencesServerLocal) {
|
|
return rendered;
|
|
}
|
|
const marker = attrEscape(JSON.stringify([a.name, a.value]));
|
|
return `${rendered} data-wrn-bind-${bindIndex++}="${escLit(marker)}"`;
|
|
}).join("");
|
|
const initialConditionalClasses = conditionalClasses.map(({ className, expression }) => {
|
|
const referencesLoopVariable = elementContext.loopVars ? exprRefsState(expression, elementContext.loopVars) : false;
|
|
if (referencesLoopVariable) {
|
|
return "";
|
|
}
|
|
return `\${(${ctx.resolveExpr(expression)}) ? ${JSON.stringify(` ${className}`)} : ""}`;
|
|
}).join("");
|
|
const staticClassValue = staticClasses.join(" ");
|
|
const classReferencesState = exprRefsComponentReactiveValue(staticClassValue, ctx);
|
|
const classReferencesLoopVariable = elementContext.loopVars ? exprRefsState(staticClassValue, elementContext.loopVars) : false;
|
|
const classReferencesServerLocal = ctx.serverLocals ? exprRefsState(staticClassValue, ctx.serverLocals) : false;
|
|
const classHasReactiveExpression = staticClassValue.includes("{") && (classReferencesState || classReferencesLoopVariable || classReferencesServerLocal);
|
|
const classAttribute = staticClasses.length > 0 || conditionalClasses.length > 0 ? ` class="${compileAttrValue(staticClassValue, elementContext)}${initialConditionalClasses}"` : "";
|
|
const classReactiveBinding = classHasReactiveExpression ? ` data-wrn-bind-class="${escLit(attrEscape(JSON.stringify(["class", staticClassValue])))}"` : "";
|
|
const classBindings = conditionalClasses.map(({ className, expression }, index) => {
|
|
const marker = attrEscape(JSON.stringify([className, expression]));
|
|
return ` data-wrn-class-${index}="${escLit(marker)}"`;
|
|
}).join("");
|
|
const loopLocalsAttribute = serverLoopLocalsAttribute(ctx);
|
|
const allAttrs = `${loopLocalsAttribute}` + `${ctx.forwardRestAttrs ? "${__wireSpreadAttrs(__attrs)}" : ""}` + `${ctx.eventNames?.length ? ` data-wrn-events="${attrEscape(ctx.eventNames.join(","))}"` : ""}` + `${classAttribute}` + `${classReactiveBinding}` + `${classBindings}` + `${attrs}`;
|
|
if (parser_ts_1.VOID_ELEMENTS.has(node.tag.toLowerCase())) {
|
|
return `<${node.tag}${allAttrs}>`;
|
|
}
|
|
const inner = node.children.map((child) => renderComponentNode(child, elementContext)).join("");
|
|
return `<${node.tag}${allAttrs}>${inner}</${node.tag}>`;
|
|
}
|
|
function generateComponent(ast) {
|
|
const out = [];
|
|
if (ast.imports.length > 0)
|
|
out.push(generatedImports(ast).join(`
|
|
`));
|
|
const hasServerEach = viewHasServerEach(ast.view);
|
|
const effectiveProps = ast.kind === "layout" && !ast.props.some((prop) => prop.name === "content") ? [
|
|
{
|
|
name: "content",
|
|
default: '""',
|
|
valueType: "string",
|
|
required: false
|
|
},
|
|
...ast.props
|
|
] : ast.props;
|
|
const browserStates = ast.states.filter((state) => state.runtime !== "server");
|
|
const stateNames = new Set([
|
|
...browserStates.map((entry) => entry.name),
|
|
...ast.computed.map((entry) => entry.name)
|
|
]);
|
|
const nameRefs = new Map;
|
|
for (const p of effectiveProps) {
|
|
nameRefs.set(p.name, safeRef(p.name));
|
|
}
|
|
if (!nameRefs.has("attrs")) {
|
|
nameRefs.set("attrs", "__attrs");
|
|
}
|
|
for (const s of ast.states)
|
|
nameRefs.set(s.name, safeRef(s.name));
|
|
for (const entry of ast.computed)
|
|
nameRefs.set(entry.name, safeRef(entry.name));
|
|
const resolveExpr = (expr) => {
|
|
let result = expr;
|
|
for (const [name, ref] of nameRefs) {
|
|
if (name !== ref)
|
|
result = result.replace(new RegExp(`\\b${name}\\b`, "g"), ref);
|
|
}
|
|
return result;
|
|
};
|
|
const ctx = {
|
|
stateNames,
|
|
functionNames: new Set(ast.runtimeFunctions.filter((fn) => fn.runtime !== "server").map((fn) => fn.name)),
|
|
resolveExpr,
|
|
eventNames: publicOutputNames(ast)
|
|
};
|
|
const serverFunctions = targetFunctions(ast, "server");
|
|
const hasExplicitRestSpread = viewHasRestAttributeSpread(ast.view);
|
|
const rootElementIndex = ast.view.findIndex((node) => node.type === "element");
|
|
const automaticallyForwardRootAttrs = !hasExplicitRestSpread && !effectiveProps.some((prop) => prop.name === "attrs") && rootElementIndex >= 0;
|
|
const viewCode = ast.view.map((node, index) => renderComponentNode(node, automaticallyForwardRootAttrs && index === rootElementIndex ? { ...ctx, forwardRestAttrs: true } : ctx)).join("");
|
|
const styles = ast.styles.map((body) => body.trim()).filter(Boolean);
|
|
const styleTag = escLit(localStyleTag(ast, styles));
|
|
const behavior = componentBehavior(ast);
|
|
const needsScope = ast.runtime !== "server" && (browserStates.length > 0 || ast.computed.length > 0 || viewHasEvents(ast.view) || behavior !== null);
|
|
if (hasServerEach || needsScope) {
|
|
out.push(`import { Buffer as __WrnexusBuffer } from "node:buffer";`);
|
|
}
|
|
const scopeKeys = [
|
|
...effectiveProps.map((prop) => prop.name),
|
|
...browserStates.map((state) => state.name)
|
|
];
|
|
const behaviorAttr = behaviorAttribute(behavior);
|
|
const decls = [];
|
|
for (const prop of effectiveProps) {
|
|
if (prop.required) {
|
|
decls.push(` if (__p[${JSON.stringify(prop.name)}] === undefined) throw new TypeError(${JSON.stringify(`${ast.name} requires prop '${prop.name}' (${prop.valueType ?? "unknown"})`)});`);
|
|
}
|
|
decls.push(` const ${nameRefs.get(prop.name)}: ${prop.valueType ?? "any"} = __coerce(__p[${JSON.stringify(prop.name)}], (${resolveExpr(prop.default)}), ${JSON.stringify((0, types_ts_1.runtimeTypeOf)(prop.valueType))});`);
|
|
}
|
|
if (!effectiveProps.some((prop) => prop.name === "attrs")) {
|
|
decls.push(` const __attrs = __restProps(__p, new Set(${JSON.stringify(effectiveProps.map((prop) => prop.name))}));`);
|
|
}
|
|
for (const state of ast.states) {
|
|
decls.push(` let ${nameRefs.get(state.name)}${state.valueType ? `: ${state.valueType}` : ""} = (${resolveExpr(state.expr)});`);
|
|
}
|
|
for (const entry of ast.computed) {
|
|
decls.push(` const ${nameRefs.get(entry.name)} = (${resolveExpr(entry.expr)});`);
|
|
}
|
|
const returnExpr = needsScope ? "`" + styleTag + `<div data-scope="\${__scope}" data-wrn-scope="\${__scopePayload}"${behaviorAttr}${hydrationAttribute(ast)}>` + viewCode + "</div>`" : "`" + styleTag + viewCode + "`";
|
|
const scopeLine = needsScope && scopeKeys.length > 0 ? ` const __scopeState = { ${scopeKeys.map((key) => `${JSON.stringify(key)}: ${nameRefs.get(key)}`).join(", ")} };
|
|
const __scope = __wrnexusScopeDecl(__scopeState);
|
|
const __scopePayload = __WrnexusBuffer.from(JSON.stringify(__scopeState), "utf8").toString("base64");
|
|
` : needsScope ? ` const __scopeState = {};
|
|
const __scope = "";
|
|
const __scopePayload = __WrnexusBuffer.from("{}", "utf8").toString("base64");
|
|
` : "";
|
|
if (ast.kind === "layout") {
|
|
out.push(`export const __wrnexusLayout = ${JSON.stringify(ast.name)};`);
|
|
} else {
|
|
out.push(`export const __wrnexusComponent = ${JSON.stringify(ast.name)};`);
|
|
}
|
|
out.push(`export const __wrnexusRuntime = ${JSON.stringify(ast.runtime ?? "universal")};`);
|
|
out.push(`export const __wrnexusRender = ${JSON.stringify(ast.renderMode ?? "hybrid")};`);
|
|
out.push(`export const __wrnexusHydrate = ${JSON.stringify(["static", "server"].includes(ast.renderMode ?? "") ? "none" : ast.hydrate ?? "load")};`);
|
|
out.push(`export const __wrnexusHydrationId = ${JSON.stringify(hydrationId(ast))};`);
|
|
if (Object.keys(ast.cache ?? {}).length > 0)
|
|
out.push(`export const __wrnexusCache = ${JSON.stringify(ast.cache, null, 2)};`);
|
|
if (Object.keys(ast.security).length > 0) {
|
|
out.push(`export const __wrnexusSecurity = ${JSON.stringify(ast.security, null, 2)};`);
|
|
}
|
|
if (Object.keys(ast.navigation).length > 0) {
|
|
out.push(`export const __wrnexusNavigation = ${JSON.stringify(ast.navigation, null, 2)};`);
|
|
}
|
|
const componentStyleExport = localStyleExport(ast, styles);
|
|
if (componentStyleExport)
|
|
out.push(componentStyleExport);
|
|
if (behavior) {
|
|
out.push(`export const __wrnexusBehavior = ${JSON.stringify(behavior, null, 2)};`);
|
|
}
|
|
const typeSource = ast.types.map((body) => body.trim()).filter(Boolean).join(`
|
|
|
|
`);
|
|
if (typeSource)
|
|
out.push(typeSource);
|
|
if (effectiveProps.length > 0) {
|
|
out.push(`export interface ${ast.name}Props {
|
|
[attribute: string]: unknown;
|
|
${effectiveProps.map((prop) => ` ${JSON.stringify(prop.name)}${prop.required ? "" : "?"}: ${prop.valueType ?? "unknown"};`).join(`
|
|
`)}
|
|
}`);
|
|
}
|
|
if (ast.outputs.length > 0) {
|
|
out.push(`export interface ${ast.name}Outputs {
|
|
${ast.outputs.map((output) => ` ${JSON.stringify(output.name)}(${output.payload ? `${output.payload.name}${output.payload.optional ? "?" : ""}: ${output.payload.valueType}` : ""}): void;`).join(`
|
|
`)}
|
|
}`);
|
|
}
|
|
out.push(`function __coerce(v: any, def: any, declared: string = "unknown"): any {
|
|
if (v === undefined || v === null) {
|
|
return def;
|
|
}
|
|
|
|
if (declared === "number" || typeof def === "number") {
|
|
const parsed = Number(v);
|
|
if (!Number.isFinite(parsed)) throw new TypeError("Expected a finite number prop");
|
|
return parsed;
|
|
}
|
|
|
|
if (declared === "boolean" || typeof def === "boolean") {
|
|
if (v === true || v === "" || v === "true" || v === 1 || v === "1") return true;
|
|
if (v === false || v === "false" || v === 0 || v === "0") return false;
|
|
throw new TypeError("Expected a boolean prop");
|
|
}
|
|
|
|
if (declared === "array" || Array.isArray(def)) {
|
|
if (Array.isArray(v)) {
|
|
return v;
|
|
}
|
|
|
|
if (typeof v === "string") {
|
|
try {
|
|
const parsed = JSON.parse(v);
|
|
return Array.isArray(parsed) ? parsed : def;
|
|
} catch {
|
|
if (declared === "array") throw new TypeError("Expected an array prop");
|
|
return def;
|
|
}
|
|
}
|
|
|
|
return def;
|
|
}
|
|
|
|
if (declared === "object" || (def !== null && typeof def === "object")) {
|
|
if (
|
|
v !== null &&
|
|
typeof v === "object" &&
|
|
!Array.isArray(v)
|
|
) {
|
|
return v;
|
|
}
|
|
|
|
if (typeof v === "string") {
|
|
try {
|
|
const parsed = JSON.parse(v);
|
|
|
|
return (
|
|
parsed !== null &&
|
|
typeof parsed === "object" &&
|
|
!Array.isArray(parsed)
|
|
)
|
|
? parsed
|
|
: def;
|
|
} catch {
|
|
if (declared === "object") throw new TypeError("Expected an object prop");
|
|
return def;
|
|
}
|
|
}
|
|
|
|
return def;
|
|
}
|
|
|
|
if (declared === "bigint") return BigInt(v);
|
|
if (declared === "function" && typeof v !== "function") {
|
|
throw new TypeError("Expected a function prop");
|
|
}
|
|
return declared === "unknown" && def === undefined ? v : String(v);
|
|
}
|
|
|
|
function __restProps(
|
|
props: Record<string, any>,
|
|
declared: Set<string>,
|
|
): Record<string, any> {
|
|
return Object.fromEntries(
|
|
Object.entries(props).filter(([name]) => !declared.has(name)),
|
|
);
|
|
}
|
|
|
|
function __wireHtml(v: any): string {
|
|
return String(v == null ? "" : v).replace(
|
|
/[&<>]/g,
|
|
(c) =>
|
|
c === "&"
|
|
? "&"
|
|
: c === "<"
|
|
? "<"
|
|
: ">",
|
|
);
|
|
}
|
|
|
|
function __wireAttr(v: any): string {
|
|
return String(v == null ? "" : v).replace(
|
|
/[&<>"]/g,
|
|
(c) =>
|
|
c === "&"
|
|
? "&"
|
|
: c === "<"
|
|
? "<"
|
|
: c === ">"
|
|
? ">"
|
|
: """,
|
|
);
|
|
}
|
|
|
|
function __wireBooleanAttr(name: string, value: any): string {
|
|
return value === true ||
|
|
value === "true" ||
|
|
value === "" ||
|
|
value === 1 ||
|
|
value === "1" ||
|
|
value === name
|
|
? " " + name
|
|
: "";
|
|
}
|
|
|
|
function __wireSpreadAttrs(value: any): string {
|
|
if (value === null || typeof value !== "object" || Array.isArray(value)) return "";
|
|
|
|
const booleanAttributes = new Set(${JSON.stringify([...HTML_BOOLEAN_ATTRIBUTES])});
|
|
const attributes: string[] = [];
|
|
|
|
for (const [name, raw] of Object.entries(value)) {
|
|
const lowerName = name.toLowerCase();
|
|
if (
|
|
!/^[A-Za-z_:][A-Za-z0-9_.:-]*$/.test(name) ||
|
|
lowerName.startsWith("on") ||
|
|
lowerName === "style" ||
|
|
lowerName === "slot" ||
|
|
lowerName === "data-component" ||
|
|
// Internal markers must not leak through a spread -- except the
|
|
// parent's output handlers, whose whole job is to ride from the mount
|
|
// onto the view root so the mounting scope can bind them there.
|
|
(lowerName.startsWith("data-wrn") && !lowerName.startsWith("data-wrn-out-"))
|
|
) {
|
|
continue;
|
|
}
|
|
|
|
if (booleanAttributes.has(lowerName)) {
|
|
attributes.push(__wireBooleanAttr(name, raw));
|
|
continue;
|
|
}
|
|
|
|
if (raw === false || raw === null || raw === undefined) continue;
|
|
attributes.push(" " + name + '="' + __wireAttr(raw) + '"');
|
|
}
|
|
|
|
return attributes.join("");
|
|
}
|
|
|
|
function __wireProp(v: any): string {
|
|
const value =
|
|
v !== null && typeof v === "object"
|
|
? JSON.stringify(v)
|
|
: String(v == null ? "" : v);
|
|
|
|
return __wireAttr(value);
|
|
}
|
|
|
|
function __wireRaw(v: any): string {
|
|
return String(v == null ? "" : v);
|
|
}`);
|
|
if (hasServerEach) {
|
|
out.push(`function __wrnexusEncodeLoopLocals(value: Record<string, any>): string {
|
|
return __WrnexusBuffer.from(JSON.stringify(value), "utf8").toString("base64");
|
|
}`);
|
|
}
|
|
if (needsScope) {
|
|
out.push(`function __wrnexusSerializeScopeValue(value: any): string {
|
|
if (value === undefined) {
|
|
return "undefined";
|
|
}
|
|
|
|
if (value === null) {
|
|
return "null";
|
|
}
|
|
|
|
if (typeof value === "number") {
|
|
return Number.isFinite(value)
|
|
? String(value)
|
|
: "null";
|
|
}
|
|
|
|
if (typeof value === "boolean") {
|
|
return value ? "true" : "false";
|
|
}
|
|
|
|
if (typeof value === "string") {
|
|
return JSON.stringify(value);
|
|
}
|
|
|
|
try {
|
|
const serialized = JSON.stringify(value);
|
|
|
|
return serialized === undefined
|
|
? "undefined"
|
|
: serialized;
|
|
} catch {
|
|
return "null";
|
|
}
|
|
}
|
|
|
|
function __wrnexusScopeDecl(obj: Record<string, any>): string {
|
|
return Object.keys(obj)
|
|
.map(
|
|
(key) =>
|
|
key +
|
|
": " +
|
|
__wrnexusSerializeScopeValue(
|
|
obj[key],
|
|
),
|
|
)
|
|
.join(", ")
|
|
.replace(/&/g, "&")
|
|
.replace(/"/g, """)
|
|
.replace(/</g, "<")
|
|
.replace(/>/g, ">");
|
|
}`);
|
|
}
|
|
const serverFunctionSource = serverFunctions ? `${serverFunctions}
|
|
` : "";
|
|
out.push(`export function render(props: ${effectiveProps.length > 0 ? `${ast.name}Props` : "Record<string, any>"} = {} as ${effectiveProps.length > 0 ? `${ast.name}Props` : "Record<string, any>"}): string {
|
|
` + ` const __p = props || {};
|
|
` + (decls.length > 0 ? decls.join(`
|
|
`) + `
|
|
` : "") + serverFunctionSource + scopeLine + ` return ${returnExpr};
|
|
` + `}`);
|
|
out.push(`export default { name: ${JSON.stringify(ast.name)}, kind: ${JSON.stringify(ast.kind)}, render };`);
|
|
return out.join(`
|
|
|
|
`) + `
|
|
`;
|
|
}
|
|
function __wireRaw(v) {
|
|
return String(v == null ? "" : v);
|
|
}
|
|
function wholeAttributeExpression(value) {
|
|
const match = /^\s*\{([\s\S]+)\}\s*$/.exec(value);
|
|
return match?.[1]?.trim() || null;
|
|
}
|
|
function __wireHtml(v) {
|
|
return String(v == null ? "" : v).replace(/[&<>]/g, (c) => c === "&" ? "&" : c === "<" ? "<" : ">");
|
|
}
|
|
function __wireAttr(v) {
|
|
return String(v == null ? "" : v).replace(/[&<>"]/g, (c) => c === "&" ? "&" : c === "<" ? "<" : c === ">" ? ">" : """);
|
|
}
|
|
function __wireProp(v) {
|
|
const value = v !== null && typeof v === "object" ? JSON.stringify(v) : String(v == null ? "" : v);
|
|
return __wireAttr(value);
|
|
}
|
|
function renderPageComponentAttr(attr, dynamicExpressions) {
|
|
if (attr.event) {
|
|
return ` ${componentEventAttribute(attr.name)}="${attrEscape(attr.value)}"`;
|
|
}
|
|
if (attr.boolean) {
|
|
return ` ${attr.name}`;
|
|
}
|
|
const expression = wholeAttributeExpression(attr.value);
|
|
if (!expression) {
|
|
return ` ${attr.name}="${attrEscape(safeAttributeValue(attr.name, attr.value))}"`;
|
|
}
|
|
dynamicExpressions.push(`\${__wrnexusPropAttr(${expression})}`);
|
|
const marker = `\x00WRNEACH${dynamicExpressions.length - 1}\x00`;
|
|
return ` ${attr.name}="${marker}"`;
|
|
}
|
|
},
|
|
"packages/compiler/src/component-contract.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.createComponentContract = createComponentContract;
|
|
function unionOptions(type) {
|
|
if (!type || !type.includes("|"))
|
|
return;
|
|
const values = type.split("|").map((part) => part.trim()).filter((part) => /^(?:"[^"]*"|'[^']*')$/.test(part)).map((part) => part.slice(1, -1));
|
|
return values.length ? values : undefined;
|
|
}
|
|
function createComponentContract(ast) {
|
|
return {
|
|
name: ast.name,
|
|
kind: ast.kind,
|
|
props: ast.props.map((prop) => ({
|
|
name: prop.name,
|
|
type: prop.valueType ?? "unknown",
|
|
required: prop.required,
|
|
...prop.default !== "undefined" ? { default: prop.default } : {},
|
|
...unionOptions(prop.valueType) ? { options: unionOptions(prop.valueType) } : {}
|
|
})),
|
|
outputs: ast.outputs.map((output) => ({
|
|
name: output.name,
|
|
...output.payload ? { payloadName: output.payload.name, payloadType: output.payload.valueType } : {}
|
|
})),
|
|
functions: ast.runtimeFunctions.map((fn) => ({
|
|
name: fn.name,
|
|
runtime: fn.runtime,
|
|
async: fn.async,
|
|
parameters: fn.parameters.map((param) => ({
|
|
name: param.name,
|
|
type: param.valueType ?? "unknown",
|
|
optional: param.optional
|
|
})),
|
|
returnType: fn.returnType ?? (fn.async ? "Promise<unknown>" : "unknown")
|
|
})),
|
|
states: ast.states.map((state) => ({
|
|
name: state.name,
|
|
runtime: state.runtime,
|
|
type: state.valueType ?? "unknown",
|
|
initializer: state.expr
|
|
})),
|
|
computed: ast.computed.map((entry) => ({
|
|
name: entry.name,
|
|
type: entry.valueType ?? "unknown",
|
|
expression: entry.expr
|
|
})),
|
|
imports: ast.structuredImports.map((entry) => ({
|
|
source: entry.source,
|
|
typeOnly: entry.typeOnly,
|
|
...entry.defaultImport ? { defaultImport: entry.defaultImport } : {},
|
|
namedImports: entry.namedImports.map((named) => named.local)
|
|
}))
|
|
};
|
|
}
|
|
},
|
|
"packages/compiler/src/import-resolver.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.resolveWrnImport = resolveWrnImport;
|
|
exports3.resolveWrnImports = resolveWrnImports;
|
|
const node_fs_1 = require2("node:fs");
|
|
const node_path_1 = require2("node:path");
|
|
function candidates(path) {
|
|
return (0, node_path_1.extname)(path) ? [path] : [
|
|
path,
|
|
`${path}.wrn`,
|
|
`${path}.ts`,
|
|
`${path}.d.ts`,
|
|
(0, node_path_1.join)(path, "index.wrn"),
|
|
(0, node_path_1.join)(path, "index.ts")
|
|
];
|
|
}
|
|
function resolveWrnImport(declaration, importer, options) {
|
|
const source = declaration.source;
|
|
const aliases = {
|
|
"@": "./app",
|
|
...options.aliases ?? {}
|
|
};
|
|
const alias = Object.keys(aliases).filter((key) => key.length > 0 && (source === key || source.startsWith(`${key}/`))).sort((left, right) => right.length - left.length)[0];
|
|
if (!source.startsWith(".") && !alias)
|
|
return { declaration, resolved: source };
|
|
const base = alias ? (0, node_path_1.resolve)(options.appRoot, aliases[alias], source === alias ? "" : source.slice(alias.length + 1)) : (0, node_path_1.resolve)((0, node_path_1.dirname)(importer), source);
|
|
const found = candidates(base).find((candidate) => {
|
|
if (!(0, node_fs_1.existsSync)(candidate))
|
|
return false;
|
|
try {
|
|
return (0, node_fs_1.statSync)(candidate).isFile();
|
|
} catch {
|
|
return false;
|
|
}
|
|
});
|
|
if (found)
|
|
return { declaration, resolved: (0, node_fs_1.realpathSync)(found) };
|
|
const severity = (options.mode ?? "compatible") === "explicit" ? "error" : "warning";
|
|
return {
|
|
declaration,
|
|
diagnostic: {
|
|
code: "WRN-IMPORT-NOT-FOUND",
|
|
message: `Cannot resolve import '${source}' from ${importer}`,
|
|
severity
|
|
}
|
|
};
|
|
}
|
|
function resolveWrnImports(declarations, importer, options) {
|
|
return declarations.map((declaration) => resolveWrnImport(declaration, importer, options));
|
|
}
|
|
},
|
|
"packages/compiler/src/index.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.DependencyGraph = exports3.createCompilationCache = exports3.compilationKey = exports3.runtimeTypeOf = exports3.inferredRuntimeType = exports3.eraseFunctionTypes = exports3.LexError = exports3.Lexer = exports3.NativeCompileError = exports3.generateNative = exports3.runtimeCapabilities = exports3.analyzeRuntimeImports = exports3.optimizeAst = exports3.analyzeRuntimeRequirements = exports3.analyzeOptimizations = exports3.createWrnSourceMap = exports3.resolveWrnImports = exports3.resolveWrnImport = exports3.createComponentContract = exports3.generateStoreModule = exports3.generateStoreBrowserModule = exports3.generateDeclarations = exports3.rpcManifest = exports3.generateServerFunctionsModule = exports3.generateBrowserModule = exports3.generateTargets = exports3.generate = exports3.ParseError = exports3.parse = exports3.formatDiagnostic = exports3.diagnosticFromError = exports3.diagnose = exports3.assertValidAst = exports3.formatWrn = undefined;
|
|
exports3.compileNativeWireFile = compileNativeWireFile;
|
|
exports3.compileWireFile = compileWireFile;
|
|
exports3.compile = compile;
|
|
const syntax_1 = require2("@wrnexus/syntax");
|
|
var syntax_2 = require2("@wrnexus/syntax");
|
|
Object.defineProperty(exports3, "formatWrn", { enumerable: true, get: function() {
|
|
return syntax_2.formatWrn;
|
|
} });
|
|
const codegen_ts_1 = require2("./codegen.js");
|
|
const native_codegen_ts_1 = require2("./native-codegen.js");
|
|
var syntax_3 = require2("@wrnexus/syntax");
|
|
Object.defineProperty(exports3, "assertValidAst", { enumerable: true, get: function() {
|
|
return syntax_3.assertValidAst;
|
|
} });
|
|
Object.defineProperty(exports3, "diagnose", { enumerable: true, get: function() {
|
|
return syntax_3.diagnose;
|
|
} });
|
|
Object.defineProperty(exports3, "diagnosticFromError", { enumerable: true, get: function() {
|
|
return syntax_3.diagnosticFromError;
|
|
} });
|
|
Object.defineProperty(exports3, "formatDiagnostic", { enumerable: true, get: function() {
|
|
return syntax_3.formatDiagnostic;
|
|
} });
|
|
Object.defineProperty(exports3, "parse", { enumerable: true, get: function() {
|
|
return syntax_3.parse;
|
|
} });
|
|
Object.defineProperty(exports3, "ParseError", { enumerable: true, get: function() {
|
|
return syntax_3.ParseError;
|
|
} });
|
|
var codegen_ts_2 = require2("./codegen.js");
|
|
Object.defineProperty(exports3, "generate", { enumerable: true, get: function() {
|
|
return codegen_ts_2.generate;
|
|
} });
|
|
var targets_ts_1 = require2("./targets.js");
|
|
Object.defineProperty(exports3, "generateTargets", { enumerable: true, get: function() {
|
|
return targets_ts_1.generateTargets;
|
|
} });
|
|
var client_codegen_ts_1 = require2("./client-codegen.js");
|
|
Object.defineProperty(exports3, "generateBrowserModule", { enumerable: true, get: function() {
|
|
return client_codegen_ts_1.generateBrowserModule;
|
|
} });
|
|
var server_codegen_ts_1 = require2("./server-codegen.js");
|
|
Object.defineProperty(exports3, "generateServerFunctionsModule", { enumerable: true, get: function() {
|
|
return server_codegen_ts_1.generateServerFunctionsModule;
|
|
} });
|
|
Object.defineProperty(exports3, "rpcManifest", { enumerable: true, get: function() {
|
|
return server_codegen_ts_1.rpcManifest;
|
|
} });
|
|
var type_codegen_ts_1 = require2("./type-codegen.js");
|
|
Object.defineProperty(exports3, "generateDeclarations", { enumerable: true, get: function() {
|
|
return type_codegen_ts_1.generateDeclarations;
|
|
} });
|
|
var store_codegen_ts_1 = require2("./store-codegen.js");
|
|
Object.defineProperty(exports3, "generateStoreBrowserModule", { enumerable: true, get: function() {
|
|
return store_codegen_ts_1.generateStoreBrowserModule;
|
|
} });
|
|
Object.defineProperty(exports3, "generateStoreModule", { enumerable: true, get: function() {
|
|
return store_codegen_ts_1.generateStoreModule;
|
|
} });
|
|
var component_contract_ts_1 = require2("./component-contract.js");
|
|
Object.defineProperty(exports3, "createComponentContract", { enumerable: true, get: function() {
|
|
return component_contract_ts_1.createComponentContract;
|
|
} });
|
|
var import_resolver_ts_1 = require2("./import-resolver.js");
|
|
Object.defineProperty(exports3, "resolveWrnImport", { enumerable: true, get: function() {
|
|
return import_resolver_ts_1.resolveWrnImport;
|
|
} });
|
|
Object.defineProperty(exports3, "resolveWrnImports", { enumerable: true, get: function() {
|
|
return import_resolver_ts_1.resolveWrnImports;
|
|
} });
|
|
var source_map_ts_1 = require2("./source-map.js");
|
|
Object.defineProperty(exports3, "createWrnSourceMap", { enumerable: true, get: function() {
|
|
return source_map_ts_1.createWrnSourceMap;
|
|
} });
|
|
var analysis_ts_1 = require2("./analysis.js");
|
|
Object.defineProperty(exports3, "analyzeOptimizations", { enumerable: true, get: function() {
|
|
return analysis_ts_1.analyzeOptimizations;
|
|
} });
|
|
Object.defineProperty(exports3, "analyzeRuntimeRequirements", { enumerable: true, get: function() {
|
|
return analysis_ts_1.analyzeRuntimeRequirements;
|
|
} });
|
|
Object.defineProperty(exports3, "optimizeAst", { enumerable: true, get: function() {
|
|
return analysis_ts_1.optimizeAst;
|
|
} });
|
|
var runtime_capabilities_ts_1 = require2("./runtime-capabilities.js");
|
|
Object.defineProperty(exports3, "analyzeRuntimeImports", { enumerable: true, get: function() {
|
|
return runtime_capabilities_ts_1.analyzeRuntimeImports;
|
|
} });
|
|
Object.defineProperty(exports3, "runtimeCapabilities", { enumerable: true, get: function() {
|
|
return runtime_capabilities_ts_1.runtimeCapabilities;
|
|
} });
|
|
var native_codegen_ts_2 = require2("./native-codegen.js");
|
|
Object.defineProperty(exports3, "generateNative", { enumerable: true, get: function() {
|
|
return native_codegen_ts_2.generateNative;
|
|
} });
|
|
Object.defineProperty(exports3, "NativeCompileError", { enumerable: true, get: function() {
|
|
return native_codegen_ts_2.NativeCompileError;
|
|
} });
|
|
var syntax_4 = require2("@wrnexus/syntax");
|
|
Object.defineProperty(exports3, "Lexer", { enumerable: true, get: function() {
|
|
return syntax_4.Lexer;
|
|
} });
|
|
Object.defineProperty(exports3, "LexError", { enumerable: true, get: function() {
|
|
return syntax_4.LexError;
|
|
} });
|
|
var syntax_5 = require2("@wrnexus/syntax");
|
|
Object.defineProperty(exports3, "eraseFunctionTypes", { enumerable: true, get: function() {
|
|
return syntax_5.eraseFunctionTypes;
|
|
} });
|
|
Object.defineProperty(exports3, "inferredRuntimeType", { enumerable: true, get: function() {
|
|
return syntax_5.inferredRuntimeType;
|
|
} });
|
|
Object.defineProperty(exports3, "runtimeTypeOf", { enumerable: true, get: function() {
|
|
return syntax_5.runtimeTypeOf;
|
|
} });
|
|
function compileNativeWireFile(source) {
|
|
const ast = (0, syntax_1.parse)(source);
|
|
(0, syntax_1.assertValidAst)(ast);
|
|
return (0, native_codegen_ts_1.generateNative)(ast);
|
|
}
|
|
function compileWireFile(source, filePath = "<inline .wrn>") {
|
|
try {
|
|
const ast = (0, syntax_1.parse)(source);
|
|
(0, syntax_1.assertValidAst)(ast, { file: filePath, accessibility: true });
|
|
return `// compiled from .wrn
|
|
${(0, codegen_ts_1.generate)(ast)}`;
|
|
} catch (error) {
|
|
const diagnostic = (0, syntax_1.diagnosticFromError)(source, error, { file: filePath });
|
|
throw new Error(`Failed to parse ${filePath}:
|
|
|
|
${(0, syntax_1.formatDiagnostic)(source, diagnostic)}`, {
|
|
cause: error
|
|
});
|
|
}
|
|
}
|
|
function compile(source, filePath = "<inline .wrn>") {
|
|
const richDiagnostics = (0, syntax_1.diagnose)(source, { file: filePath, accessibility: true });
|
|
const errors = richDiagnostics.filter((diagnostic) => diagnostic.severity === "error");
|
|
if (errors.length > 0) {
|
|
throw new syntax_1.ParseError(errors.map((diagnostic) => diagnostic.message).join(`
|
|
`), errors[0].code);
|
|
}
|
|
const ast = (0, syntax_1.parse)(source);
|
|
return {
|
|
code: `// compiled from .wrn
|
|
${(0, codegen_ts_1.generate)(ast)}`,
|
|
ast,
|
|
diagnostics: richDiagnostics.map((diagnostic) => `${diagnostic.code}: ${diagnostic.message}`),
|
|
richDiagnostics
|
|
};
|
|
}
|
|
var cache_ts_1 = require2("./cache.js");
|
|
Object.defineProperty(exports3, "compilationKey", { enumerable: true, get: function() {
|
|
return cache_ts_1.compilationKey;
|
|
} });
|
|
Object.defineProperty(exports3, "createCompilationCache", { enumerable: true, get: function() {
|
|
return cache_ts_1.createCompilationCache;
|
|
} });
|
|
Object.defineProperty(exports3, "DependencyGraph", { enumerable: true, get: function() {
|
|
return cache_ts_1.DependencyGraph;
|
|
} });
|
|
},
|
|
"packages/compiler/src/native-codegen.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.NativeCompileError = undefined;
|
|
exports3.generateNative = generateNative;
|
|
|
|
class NativeCompileError extends Error {
|
|
constructor(message) {
|
|
super(message);
|
|
this.name = "NativeCompileError";
|
|
}
|
|
}
|
|
exports3.NativeCompileError = NativeCompileError;
|
|
const tagMap = {
|
|
div: "View",
|
|
main: "View",
|
|
section: "View",
|
|
article: "View",
|
|
nav: "View",
|
|
header: "View",
|
|
footer: "View",
|
|
aside: "View",
|
|
form: "View",
|
|
ul: "View",
|
|
ol: "View",
|
|
li: "View",
|
|
p: "Text",
|
|
span: "Text",
|
|
strong: "Text",
|
|
em: "Text",
|
|
small: "Text",
|
|
label: "Text",
|
|
h1: "Text",
|
|
h2: "Text",
|
|
h3: "Text",
|
|
h4: "Text",
|
|
h5: "Text",
|
|
h6: "Text",
|
|
button: "Pressable",
|
|
a: "Pressable",
|
|
input: "TextInput",
|
|
textarea: "TextInput",
|
|
img: "Image",
|
|
view: "View",
|
|
text: "Text",
|
|
pressable: "Pressable",
|
|
textinput: "TextInput",
|
|
image: "Image",
|
|
scrollview: "ScrollView",
|
|
safeareaview: "SafeAreaView",
|
|
flatlist: "FlatList",
|
|
activityindicator: "ActivityIndicator"
|
|
};
|
|
const attrMap = {
|
|
class: "style",
|
|
className: "style",
|
|
src: "source",
|
|
alt: "accessibilityLabel",
|
|
placeholder: "placeholder",
|
|
disabled: "disabled",
|
|
value: "value",
|
|
href: "__href",
|
|
"aria-label": "accessibilityLabel"
|
|
};
|
|
function expression(value) {
|
|
const exact = /^\{([\s\S]+)\}$/.exec(value.trim());
|
|
return exact?.[1]?.trim() ?? null;
|
|
}
|
|
function textJsx(value) {
|
|
const pieces = [];
|
|
let last = 0;
|
|
for (const match of value.matchAll(/\{([^{}]+)\}/g)) {
|
|
if (match.index > last)
|
|
pieces.push(value.slice(last, match.index));
|
|
const expr = match[1].trim();
|
|
pieces.push(expr.startsWith("t:") ? `{${JSON.stringify(expr.slice(2).trim())}}` : `{${expr}}`);
|
|
last = match.index + match[0].length;
|
|
}
|
|
pieces.push(value.slice(last));
|
|
return pieces.join("").replace(/([<>])/g, (char) => char === "<" ? "<" : ">");
|
|
}
|
|
function eventBody(value, states) {
|
|
let body = expression(value) ?? value;
|
|
for (const state of states) {
|
|
const cap = state[0].toUpperCase() + state.slice(1);
|
|
body = body.replace(new RegExp(`\\b${state}\\+\\+`, "g"), `set${cap}(value => value + 1)`).replace(new RegExp(`\\b${state}--`, "g"), `set${cap}(value => value - 1)`).replace(new RegExp(`\\b${state}\\s*=\\s*([^;]+)`, "g"), `set${cap}($1)`);
|
|
}
|
|
return `() => { ${body} }`;
|
|
}
|
|
function renderAttrs(attrs, states) {
|
|
return attrs.map((attr) => {
|
|
if (attr.event) {
|
|
if (attr.name.startsWith("browser-"))
|
|
return "";
|
|
const eventName = attr.name.startsWith("mobile-") ? attr.name.slice(7) : attr.name;
|
|
const event = eventName === "click" || eventName === "press" ? "onPress" : eventName === "input" || eventName === "change" ? "onChangeText" : `on${eventName[0].toUpperCase()}${eventName.slice(1)}`;
|
|
return ` ${event}={${eventBody(attr.value, states)}}`;
|
|
}
|
|
if (attr.name === "data-native-browser" || attr.name.startsWith("data-native-on-browser-"))
|
|
return "";
|
|
if (attr.name === "data-native-options" || attr.name === "data-native-only" || attr.name === "data-native-requires" || attr.name === "data-native-unsupported")
|
|
return "";
|
|
if (attr.name === "data-native-mobile") {
|
|
throw new NativeCompileError(`Declarative native capability "${attr.value}" currently targets browser/Capacitor pages. In Expo output, call the installed Expo package from an @mobile-event handler.`);
|
|
}
|
|
const name = attrMap[attr.name] ?? attr.name;
|
|
if (name === "__href")
|
|
return ` onPress={() => router.push(${JSON.stringify(attr.value)})}`;
|
|
if (name === "source") {
|
|
const expr2 = expression(attr.value);
|
|
return ` source={${expr2 ? `{ uri: ${expr2} }` : `{ uri: ${JSON.stringify(attr.value)} }`}}`;
|
|
}
|
|
if (name === "style" && attr.name !== "style") {
|
|
return ` style={[${attr.value.split(/\s+/).filter(Boolean).map((value) => `styles[${JSON.stringify(value)}]`).join(", ")} ]}`;
|
|
}
|
|
if (name === "style") {
|
|
const inlineExpression = expression(attr.value);
|
|
if (inlineExpression)
|
|
return ` style={${inlineExpression}}`;
|
|
throw new NativeCompileError('Inline CSS strings are not portable to native; use class="name" and a page style block');
|
|
}
|
|
if (attr.boolean)
|
|
return ` ${name}`;
|
|
const expr = expression(attr.value);
|
|
return expr ? ` ${name}={${expr}}` : ` ${name}=${JSON.stringify(attr.value)}`;
|
|
}).join("");
|
|
}
|
|
function renderNode(node, states, key) {
|
|
if (node.type === "text")
|
|
return textJsx(node.value);
|
|
if (node.type === "each") {
|
|
const params = node.index ? `${node.item}, ${node.index}` : `${node.item}, __index`;
|
|
const body = node.body.map((child, index) => renderNode(child, states, index === 0 ? node.index ?? "__index" : undefined)).join("");
|
|
const empty = node.empty.map((child) => renderNode(child, states)).join("");
|
|
return `{(${node.list})?.length ? (${node.list}).map((${params}) => <>${body}</>) : <>${empty}</>}`;
|
|
}
|
|
if (node.type === "if") {
|
|
const result = node.branches.reduceRight((fallback, branch) => branch.cond === null ? `<>${branch.body.map((child) => renderNode(child, states)).join("")}</>` : `(${branch.cond}) ? <>${branch.body.map((child) => renderNode(child, states)).join("")}</> : ${fallback}`, "null");
|
|
return `{${result}}`;
|
|
}
|
|
const nativeOnly = node.attrs.find((attr) => !attr.event && attr.name === "data-native-only")?.value;
|
|
if (nativeOnly === "browser" || nativeOnly === "web")
|
|
return "";
|
|
const nativeTag = tagMap[node.tag.toLowerCase()] ?? (/^[A-Z]/.test(node.tag) ? node.tag : undefined);
|
|
if (!nativeTag)
|
|
throw new NativeCompileError(`HTML element <${node.tag}> has no native equivalent`);
|
|
const attrs = renderAttrs(node.attrs, states) + (key ? ` key={${key}}` : "");
|
|
if (nativeTag === "TextInput" || nativeTag === "Image" || nativeTag === "ActivityIndicator")
|
|
return `<${nativeTag}${attrs} />`;
|
|
const children = node.children.map((child) => {
|
|
if (child.type !== "text")
|
|
return renderNode(child, states);
|
|
if (!child.value.trim())
|
|
return "";
|
|
const text = textJsx(child.value);
|
|
return nativeTag === "Text" ? text : `<Text>${text}</Text>`;
|
|
}).join("");
|
|
return `<${nativeTag}${attrs}>${children}</${nativeTag}>`;
|
|
}
|
|
function nativeStyles(blocks) {
|
|
const entries = [];
|
|
for (const block of blocks) {
|
|
for (const match of block.matchAll(/\.([A-Za-z_][\w-]*)\s*\{([^}]*)\}/g)) {
|
|
const props = [];
|
|
for (const declaration of match[2].split(";")) {
|
|
const colon = declaration.indexOf(":");
|
|
if (colon < 0)
|
|
continue;
|
|
const name = declaration.slice(0, colon).trim().replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
let value = declaration.slice(colon + 1).trim();
|
|
if (/^-?\d+(?:\.\d+)?px$/.test(value))
|
|
value = Number(value.slice(0, -2));
|
|
props.push(`${JSON.stringify(name)}: ${typeof value === "number" ? value : JSON.stringify(value)}`);
|
|
}
|
|
entries.push(`${JSON.stringify(match[1])}: { ${props.join(", ")} }`);
|
|
}
|
|
}
|
|
return `const styles = StyleSheet.create({ ${entries.join(`,
|
|
`)} });`;
|
|
}
|
|
function generateNative(ast) {
|
|
if (ast.kind !== "page")
|
|
throw new NativeCompileError("Native route compilation currently accepts page files only");
|
|
if (ast.dataApis.length)
|
|
throw new NativeCompileError("Data API blocks are not yet portable to native screens; fetch through the generated native backend helper");
|
|
const states = new Set(ast.states.map((state) => state.name));
|
|
const hooks = ast.states.map((state) => {
|
|
const cap = state.name[0].toUpperCase() + state.name.slice(1);
|
|
return ` const [${state.name}, set${cap}] = useState${state.valueType ? `<${state.valueType}>` : ""}(${state.expr});`;
|
|
}).join(`
|
|
`);
|
|
const body = ast.view.map((node) => renderNode(node, states)).join("");
|
|
const typeSource = ast.types.map((block) => block.trim()).filter(Boolean).join(`
|
|
|
|
`);
|
|
return `// generated from .wrn for Expo/React Native
|
|
import React, { useState } from "react";
|
|
import { ActivityIndicator, FlatList, Image, Pressable, SafeAreaView, ScrollView, StyleSheet, Text, TextInput, View } from "react-native";
|
|
import { useRouter } from "expo-router";
|
|
${ast.imports.join(`
|
|
`)}
|
|
|
|
${typeSource}
|
|
|
|
export default function ${ast.name}() {
|
|
const router = useRouter();
|
|
${hooks}
|
|
return <>${body}</>;
|
|
}
|
|
|
|
${nativeStyles(ast.styles)}
|
|
`;
|
|
}
|
|
},
|
|
"packages/compiler/src/parser.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __exportStar = this && this.__exportStar || function(m, exports4) {
|
|
for (var p in m)
|
|
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports4, p))
|
|
__createBinding(exports4, m, p);
|
|
};
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
__exportStar(require2("@wrnexus/syntax/parser"), exports3);
|
|
},
|
|
"packages/compiler/src/runtime-capabilities.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.runtimeCapabilities = runtimeCapabilities;
|
|
exports3.analyzeRuntimeImports = analyzeRuntimeImports;
|
|
const CAPABILITIES = {
|
|
bun: new Set([
|
|
"filesystem",
|
|
"tcp",
|
|
"process",
|
|
"websocket",
|
|
"crypto",
|
|
"streams",
|
|
"background-tasks"
|
|
]),
|
|
node: new Set([
|
|
"filesystem",
|
|
"tcp",
|
|
"process",
|
|
"websocket",
|
|
"crypto",
|
|
"streams",
|
|
"background-tasks"
|
|
]),
|
|
edge: new Set(["websocket", "crypto", "streams", "background-tasks"]),
|
|
worker: new Set(["websocket", "crypto", "streams", "background-tasks"]),
|
|
"service-worker": new Set(["crypto", "streams", "background-tasks"]),
|
|
browser: new Set(["websocket", "crypto", "streams"])
|
|
};
|
|
const MODULE_CAPABILITIES = [
|
|
[/^(?:node:)?(?:fs|path|os)(?:\/|$)/, "filesystem"],
|
|
[/^(?:node:)?(?:net|tls|dgram|http2)(?:\/|$)/, "tcp"],
|
|
[/^(?:node:)?(?:child_process|cluster|worker_threads)(?:\/|$)/, "process"]
|
|
];
|
|
function runtimeCapabilities(runtime) {
|
|
return CAPABILITIES[runtime];
|
|
}
|
|
function analyzeRuntimeImports(source, runtime) {
|
|
const modules = [
|
|
...source.matchAll(/\b(?:import\s+(?:[\s\S]*?\s+from\s+)?|require\s*\()\s*["']([^"']+)["']/g)
|
|
].map((match) => match[1]);
|
|
const available = runtimeCapabilities(runtime);
|
|
return modules.flatMap((module4) => {
|
|
const requirement = MODULE_CAPABILITIES.find(([pattern]) => pattern.test(module4));
|
|
if (!requirement || available.has(requirement[1]))
|
|
return [];
|
|
return [
|
|
{
|
|
code: "WRN-RUNTIME-CAPABILITY",
|
|
runtime,
|
|
module: module4,
|
|
capability: requirement[1],
|
|
message: `Module '${module4}' requires ${requirement[1]}, which is unavailable in the ${runtime} runtime.`
|
|
}
|
|
];
|
|
});
|
|
}
|
|
},
|
|
"packages/compiler/src/server-codegen.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.remotelyReferencedServerFunctions = remotelyReferencedServerFunctions;
|
|
exports3.rpcManifest = rpcManifest;
|
|
exports3.generateServerFunctionsModule = generateServerFunctionsModule;
|
|
const syntax_1 = require2("@wrnexus/syntax");
|
|
function stableId(value) {
|
|
let hash = 2166136261;
|
|
for (let index = 0;index < value.length; index++) {
|
|
hash ^= value.charCodeAt(index);
|
|
hash = Math.imul(hash, 16777619);
|
|
}
|
|
return `wrn_${(hash >>> 0).toString(36)}`;
|
|
}
|
|
function remotelyReferencedServerFunctions(ast) {
|
|
const browserSources = ast.runtimeFunctions.filter((fn) => ["legacy", "client", "shared"].includes(fn.runtime)).map((fn) => fn.body);
|
|
for (const [hook, body] of Object.entries(ast.storeLifecycle)) {
|
|
if (hook !== "serverInit" && body)
|
|
browserSources.push(body);
|
|
}
|
|
const names = new Set;
|
|
const call = /\bserver\.([A-Za-z_$][\w$]*)\s*\(/g;
|
|
for (const source of browserSources) {
|
|
for (const match of source.matchAll(call))
|
|
names.add(match[1]);
|
|
}
|
|
return names;
|
|
}
|
|
function rpcManifest(ast) {
|
|
const exposed = remotelyReferencedServerFunctions(ast);
|
|
return ast.runtimeFunctions.filter((fn) => fn.runtime === "server" && exposed.has(fn.name)).map((fn) => ({
|
|
id: stableId(`${ast.name}:${fn.name}`),
|
|
component: ast.name,
|
|
function: fn.name,
|
|
parameters: fn.parameters.map((param) => ({
|
|
name: param.name,
|
|
type: param.valueType ?? "unknown",
|
|
optional: param.optional
|
|
})),
|
|
returnType: fn.returnType ?? (fn.async ? "Promise<unknown>" : "unknown")
|
|
}));
|
|
}
|
|
function generateServerFunctionsModule(ast) {
|
|
const source = ast.functions.map((body) => (0, syntax_1.stripRuntimeFunctionModifiers)(body, ["legacy", "server", "shared"])).filter(Boolean).join(`
|
|
|
|
`);
|
|
const names = ast.runtimeFunctions.filter((fn) => ["legacy", "server", "shared"].includes(fn.runtime)).map((fn) => fn.name);
|
|
const manifest = rpcManifest(ast);
|
|
return `// generated WRNexusJS server module for ${ast.name}
|
|
${source}
|
|
|
|
export const __wrnexusServerFunctions = { ${[...new Set(names)].join(", ")} };
|
|
export const __wrnexusRpcManifest = ${JSON.stringify(manifest, null, 2)};
|
|
`;
|
|
}
|
|
},
|
|
"packages/compiler/src/source-map.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.createWrnSourceMap = createWrnSourceMap;
|
|
function createWrnSourceMap(source, generated) {
|
|
const sourceLines = source.split(/\r?\n/).length;
|
|
const generatedLines = generated.split(/\r?\n/).length;
|
|
const mappings = Array.from({ length: Math.min(sourceLines, generatedLines) }, (_, index) => ({
|
|
generatedLine: index + 1,
|
|
sourceLine: index + 1,
|
|
sourceColumn: 1,
|
|
kind: "line"
|
|
}));
|
|
return { version: 1, source, generated, mappings };
|
|
}
|
|
},
|
|
"packages/compiler/src/store-codegen.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.generateStoreModule = generateStoreModule;
|
|
exports3.generateStoreBrowserModule = generateStoreBrowserModule;
|
|
const syntax_1 = require2("@wrnexus/syntax");
|
|
const type_codegen_ts_1 = require2("./type-codegen.js");
|
|
const server_codegen_ts_1 = require2("./server-codegen.js");
|
|
const RESERVED_BINDINGS = new Set([
|
|
"await",
|
|
"break",
|
|
"case",
|
|
"catch",
|
|
"class",
|
|
"const",
|
|
"continue",
|
|
"debugger",
|
|
"default",
|
|
"delete",
|
|
"do",
|
|
"else",
|
|
"enum",
|
|
"export",
|
|
"extends",
|
|
"false",
|
|
"finally",
|
|
"for",
|
|
"function",
|
|
"if",
|
|
"implements",
|
|
"import",
|
|
"in",
|
|
"instanceof",
|
|
"interface",
|
|
"let",
|
|
"new",
|
|
"null",
|
|
"package",
|
|
"private",
|
|
"protected",
|
|
"public",
|
|
"return",
|
|
"static",
|
|
"super",
|
|
"switch",
|
|
"this",
|
|
"throw",
|
|
"true",
|
|
"try",
|
|
"typeof",
|
|
"var",
|
|
"void",
|
|
"while",
|
|
"with",
|
|
"yield"
|
|
]);
|
|
function safeBinding(name) {
|
|
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) && !RESERVED_BINDINGS.has(name);
|
|
}
|
|
function stateObject(ast, runtime) {
|
|
const entries = ast.states.filter((state) => state.runtime === runtime).map((state) => `${JSON.stringify(state.name)}: (${state.expr})`);
|
|
return `{ ${entries.join(", ")} }`;
|
|
}
|
|
function actionSource(fn, stateNames, eraseTypes = false) {
|
|
const parameterNames = new Set(fn.parameters.map((param) => param.name));
|
|
const params = fn.parameters.map((param) => param.name).join(", ");
|
|
const aliases = stateNames.filter((name) => safeBinding(name) && !parameterNames.has(name));
|
|
const aliasSource = aliases.length ? `let { ${aliases.join(", ")} } = context.state;` : "";
|
|
const runtimeAliases = ["server"].filter((name) => !parameterNames.has(name)).map((name) => `const ${name} = context.${name};`).join(`
|
|
`);
|
|
const copyBack = aliases.map((name) => `context.state.${name} = ${name};`).join(`
|
|
`);
|
|
const body = eraseTypes ? (0, syntax_1.eraseFunctionTypes)(fn.body) : fn.body;
|
|
return `{ runtime: ${JSON.stringify(fn.runtime)}, handler: ${fn.async ? "async " : ""}function(context${params ? `, ${params}` : ""}) { ${runtimeAliases}
|
|
${aliasSource}
|
|
try { ${body} } finally { ${copyBack} } } }`;
|
|
}
|
|
function persistedCallback(source, functionName) {
|
|
if (!source?.trim())
|
|
return;
|
|
const body = (0, syntax_1.eraseFunctionTypes)(source);
|
|
if (functionName === "migrate") {
|
|
return `(value, fromVersion, toVersion) => {
|
|
${body}
|
|
if (typeof migrate === "function") return migrate(value, fromVersion, toVersion);
|
|
return value;
|
|
}`;
|
|
}
|
|
return `(value) => {
|
|
${body}
|
|
if (typeof validate === "function") return validate(value);
|
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
}`;
|
|
}
|
|
function persistenceSource(ast) {
|
|
if (!ast.persist)
|
|
return "undefined";
|
|
const migrate = persistedCallback(ast.persist.migrations, "migrate");
|
|
const validate = persistedCallback(ast.persist.validation, "validate");
|
|
return `{ storage: ${JSON.stringify(ast.persist.storage)}, include: ${JSON.stringify(ast.persist.include)}, version: ${ast.persist.version}${migrate ? `, migrate: ${migrate}` : ""}${validate ? `, validate: ${validate}` : ""} }`;
|
|
}
|
|
function lifecycleSource(ast, stateNames, browser) {
|
|
return Object.entries(ast.storeLifecycle).filter(([name]) => !browser || name !== "serverInit").map(([name, body]) => {
|
|
const aliases = stateNames.filter(safeBinding);
|
|
const aliasSource = aliases.length ? `let { ${aliases.join(", ")} } = context.state;` : "";
|
|
const runtimeAliases = browser ? "const server = context.server;" : "";
|
|
const copyBack = aliases.map((state) => `context.state.${state} = ${state};`).join(`
|
|
`);
|
|
const emittedBody = browser ? (0, syntax_1.eraseFunctionTypes)(body) : body;
|
|
return `${name}: async (context) => { ${runtimeAliases} ${aliasSource} try { ${emittedBody} } finally { ${copyBack} } }`;
|
|
}).join(`,
|
|
`);
|
|
}
|
|
function generateStoreModule(ast) {
|
|
if (ast.kind !== "global-store" && ast.kind !== "page-store") {
|
|
throw new Error("generateStoreModule requires a store AST");
|
|
}
|
|
const stateNames = ast.states.map((state) => state.name);
|
|
const safeStateNames = stateNames.filter(safeBinding);
|
|
const computed = ast.computed.map((entry) => `${JSON.stringify(entry.name)}: (state) => { ${safeStateNames.length ? `const { ${safeStateNames.join(", ")} } = state;` : ""} return (${entry.expr}); }`).join(`,
|
|
`);
|
|
const actionGroups = new Map;
|
|
for (const fn of ast.runtimeFunctions) {
|
|
const group = actionGroups.get(fn.name) ?? [];
|
|
group.push(fn);
|
|
actionGroups.set(fn.name, group);
|
|
}
|
|
const actions = Array.from(actionGroups, ([name, functions]) => `${JSON.stringify(name)}: [${functions.map((fn) => actionSource(fn, stateNames)).join(", ")}]`).join(`,
|
|
`);
|
|
const persistence = persistenceSource(ast);
|
|
const lifecycle = lifecycleSource(ast, stateNames, false);
|
|
const manifest = (0, server_codegen_ts_1.rpcManifest)(ast);
|
|
const remoteFunctions = manifest.map((entry) => entry.function);
|
|
const rpcWrappers = remoteFunctions.map((name) => `${JSON.stringify(name)}: async (...received) => {
|
|
const rpcContext = received.pop();
|
|
if (!rpcContext || !rpcContext.request) throw new Error("WRN-RPC-CONTEXT: request context is required");
|
|
let container = __wrnexusRpcContainers.get(rpcContext.request);
|
|
if (!container) {
|
|
const url = new URL(rpcContext.request.url);
|
|
container = createRequestStoreContainer(rpcContext.request, url.pathname + url.search);
|
|
__wrnexusRpcContainers.set(rpcContext.request, container);
|
|
}
|
|
const store = await container.use(${ast.name});
|
|
const action = store.actions[${JSON.stringify(name)}];
|
|
if (typeof action !== "function") throw new Error(${JSON.stringify(`WRN-RPC-FUNCTION: store action '${name}' is unavailable on the server`)});
|
|
return action(...received);
|
|
}`).join(`,
|
|
`);
|
|
return `${ast.imports.join(`
|
|
`)}
|
|
import { defineStore } from "@wrnexus/store";
|
|
import { createRequestStoreContainer } from "@wrnexus/store/server";
|
|
|
|
${ast.types.join(`
|
|
|
|
`)}
|
|
|
|
export const ${ast.name} = defineStore({
|
|
name: ${JSON.stringify(ast.name)},
|
|
kind: ${JSON.stringify(ast.storeKind)},
|
|
createSharedState: () => (${stateObject(ast, "shared")}),
|
|
createClientState: () => (${stateObject(ast, "client")}),
|
|
createServerState: () => (${stateObject(ast, "server")}),
|
|
computed: { ${computed} },
|
|
actions: { ${actions} },
|
|
persist: ${persistence},
|
|
lifecycle: { ${lifecycle} },
|
|
});
|
|
|
|
export default ${ast.name};
|
|
|
|
const __wrnexusRpcContainers = new WeakMap();
|
|
export const __wrnexusServerFunctions = {
|
|
${rpcWrappers}
|
|
};
|
|
export const __wrnexusRpcManifest = ${JSON.stringify(manifest, null, 2)};
|
|
|
|
${(0, type_codegen_ts_1.generateDeclarations)(ast)}
|
|
`;
|
|
}
|
|
function generateStoreBrowserModule(ast) {
|
|
if (ast.kind !== "global-store" && ast.kind !== "page-store") {
|
|
throw new Error("generateStoreBrowserModule requires a store AST");
|
|
}
|
|
const browserStates = ast.states.filter((state) => state.runtime !== "server");
|
|
const stateNames = browserStates.map((state) => state.name);
|
|
const safeStateNames = stateNames.filter(safeBinding);
|
|
const initialState = `{ ${browserStates.map((state) => `${JSON.stringify(state.name)}: (${state.expr})`).join(", ")} }`;
|
|
const computed = ast.computed.map((entry) => `${JSON.stringify(entry.name)}: (state) => { ${safeStateNames.length ? `const { ${safeStateNames.join(", ")} } = state;` : ""} return (${entry.expr}); }`).join(`,
|
|
`);
|
|
const groups = new Map;
|
|
for (const fn of ast.runtimeFunctions.filter((entry) => ["client", "shared", "legacy"].includes(entry.runtime))) {
|
|
const group = groups.get(fn.name) ?? [];
|
|
group.push(fn);
|
|
groups.set(fn.name, group);
|
|
}
|
|
const actions = Array.from(groups, ([name, functions]) => `${JSON.stringify(name)}: [${functions.map((fn) => actionSource(fn, stateNames, true)).join(", ")}]`).join(`,
|
|
`);
|
|
const persistence = persistenceSource(ast);
|
|
const lifecycleEntries = lifecycleSource(ast, stateNames, true);
|
|
return `// generated WRNexusJS browser store module for ${ast.name}
|
|
const __root = globalThis;
|
|
const __registry = __root.__wrnexusStoreRegistry || (__root.__wrnexusStoreRegistry = new Map());
|
|
const __hydrationNode = typeof document !== "undefined" ? document.querySelector("script[data-wrnexus-store-hydration]") : null;
|
|
let __hydration = {};
|
|
try { __hydration = __hydrationNode ? JSON.parse(__hydrationNode.textContent || "{}") : {}; } catch (_) {}
|
|
function __clone(value) { try { return structuredClone(value); } catch (_) { return JSON.parse(JSON.stringify(value)); } }
|
|
function __storage(kind) { if (typeof window === "undefined") return null; return kind === "local" ? window.localStorage : kind === "session" ? window.sessionStorage : null; }
|
|
function __diagnostic(code, message, details) {
|
|
const detail = { code, message, store: ${JSON.stringify(ast.name)}, details };
|
|
try { __root.dispatchEvent && __root.dispatchEvent(new CustomEvent("wrnexus:store-diagnostic", { detail })); } catch (_) {}
|
|
if (typeof console !== "undefined" && console.warn) console.warn("[wrnexus:store] " + code + ": " + message, details || "");
|
|
}
|
|
function __csrfToken() {
|
|
if (typeof document === "undefined") return undefined;
|
|
const match = /(?:^|;\\s*)wire-csrf=([^;]+)/.exec(document.cookie || "");
|
|
return match ? decodeURIComponent(match[1]) : undefined;
|
|
}
|
|
async function __callServerFunction(storeName, functionName, args, options) {
|
|
options = options || {};
|
|
const csrf = options.csrfToken || __csrfToken();
|
|
const traceId = options.traceId || (globalThis.crypto && crypto.randomUUID ? crypto.randomUUID() : String(Date.now()));
|
|
const response = await fetch(options.endpoint || "/__wrnexus/rpc", {
|
|
method: "POST",
|
|
credentials: "same-origin",
|
|
signal: options.signal,
|
|
headers: Object.assign({ "content-type": "application/json", "x-request-id": traceId }, csrf ? { "x-csrf-token": csrf } : {}, options.headers || {}),
|
|
body: JSON.stringify({ component: storeName, function: functionName, args: args }),
|
|
});
|
|
const payload = await response.json().catch(function () { return null; });
|
|
if (!response.ok || !payload || !payload.ok) {
|
|
const error = new Error(payload && payload.error && payload.error.message || "Server call failed (" + response.status + ")");
|
|
error.code = payload && payload.error && payload.error.code || "WRN-RPC-FAILED";
|
|
error.status = response.status;
|
|
error.details = payload && payload.error && payload.error.details;
|
|
error.traceId = payload && payload.error && payload.error.traceId || traceId;
|
|
throw error;
|
|
}
|
|
return payload.value;
|
|
}
|
|
function __compatible(expected, value) {
|
|
if (expected === null || value === null) return expected === value || expected === null;
|
|
if (Array.isArray(expected)) return Array.isArray(value);
|
|
return typeof expected === typeof value;
|
|
}
|
|
function __create(definition) {
|
|
const routeId = typeof location !== "undefined" ? location.pathname + location.search : "default";
|
|
const key = definition.kind === "page" ? definition.name + "@" + routeId : definition.name;
|
|
if (__registry.has(key)) return __registry.get(key);
|
|
let currentDefinition = definition;
|
|
const listeners = new Set();
|
|
const initial = currentDefinition.createState();
|
|
let restored = null;
|
|
if (currentDefinition.persist) {
|
|
try {
|
|
const storage = __storage(currentDefinition.persist.storage);
|
|
const rawValue = storage && storage.getItem("wrnexus:store:" + currentDefinition.name);
|
|
const parsed = rawValue ? JSON.parse(rawValue) : null;
|
|
if (parsed) {
|
|
let candidate = parsed.state;
|
|
const fromVersion = Number(parsed.version || 0);
|
|
if (fromVersion !== currentDefinition.persist.version) {
|
|
if (typeof currentDefinition.persist.migrate === "function") candidate = currentDefinition.persist.migrate(candidate, fromVersion, currentDefinition.persist.version);
|
|
else { __diagnostic("WRN-PERSIST-VERSION", "Persisted state version cannot be restored without a migration.", { fromVersion, toVersion: currentDefinition.persist.version }); candidate = null; }
|
|
}
|
|
if (candidate && typeof currentDefinition.persist.validate === "function") candidate = currentDefinition.persist.validate(candidate);
|
|
if (candidate && typeof candidate === "object" && !Array.isArray(candidate)) {
|
|
restored = {};
|
|
currentDefinition.persist.include.forEach(function (name) { if (Object.prototype.hasOwnProperty.call(candidate, name)) restored[name] = candidate[name]; });
|
|
} else if (candidate != null) {
|
|
__diagnostic("WRN-PERSIST-INVALID", "Persisted state failed validation and was reset.", candidate);
|
|
}
|
|
}
|
|
} catch (error) { __diagnostic("WRN-PERSIST-RESTORE", "Persisted state could not be restored and was reset.", error); }
|
|
}
|
|
const raw = Object.assign({}, initial, restored || {}, __hydration[currentDefinition.name] || {});
|
|
let mutable = false;
|
|
let actionName = "direct";
|
|
function persistState() {
|
|
if (!currentDefinition.persist) return;
|
|
try {
|
|
const picked = {};
|
|
currentDefinition.persist.include.forEach(function (name) { picked[name] = raw[name]; });
|
|
const storage = __storage(currentDefinition.persist.storage);
|
|
if (storage) storage.setItem("wrnexus:store:" + currentDefinition.name, JSON.stringify({ version: currentDefinition.persist.version, state: picked }));
|
|
} catch (error) { __diagnostic("WRN-PERSIST-WRITE", "Persisted state could not be written.", error); }
|
|
}
|
|
const state = new Proxy(raw, {
|
|
set(target, property, value) {
|
|
if (!mutable) throw new TypeError("WRN-STORE-READONLY: " + currentDefinition.name + "." + String(property) + " must be changed by a store action.");
|
|
if (Object.is(target[property], value)) return true;
|
|
target[property] = value;
|
|
persistState();
|
|
listeners.forEach(function (listener) { listener(instance.snapshot(), { store: currentDefinition.name, action: actionName, changed: [String(property)] }); });
|
|
return true;
|
|
},
|
|
deleteProperty(target, property) {
|
|
if (!mutable) throw new TypeError("WRN-STORE-READONLY: store state is readonly outside actions");
|
|
return Reflect.deleteProperty(target, property);
|
|
},
|
|
});
|
|
const actions = {};
|
|
const server = new Proxy({}, { get: function (_target, property) { return function () { return __callServerFunction(currentDefinition.name, String(property), Array.prototype.slice.call(arguments)); }; } });
|
|
function installActions() {
|
|
Object.keys(actions).forEach(function (name) { delete actions[name]; });
|
|
Object.entries(currentDefinition.actions || {}).forEach(function (pair) {
|
|
const name = pair[0], candidates = pair[1];
|
|
const selected = candidates.find(function (entry) { return entry.runtime === "client"; }) || candidates.find(function (entry) { return entry.runtime === "shared"; }) || candidates.find(function (entry) { return entry.runtime === "legacy"; });
|
|
if (!selected) return;
|
|
actions[name] = async function () {
|
|
const args = Array.prototype.slice.call(arguments);
|
|
const previousMutable = mutable, previousAction = actionName;
|
|
mutable = true; actionName = name;
|
|
try { return await selected.handler({ state, snapshot: function () { return __clone(state); }, reset: function () { return instance.reset(); }, runtime: "client", routeId, server }, ...args); }
|
|
finally { mutable = previousMutable; actionName = previousAction; }
|
|
};
|
|
});
|
|
}
|
|
installActions();
|
|
const core = {
|
|
name: currentDefinition.name,
|
|
kind: currentDefinition.kind,
|
|
state,
|
|
actions,
|
|
whenReady: Promise.resolve(),
|
|
reset() {
|
|
mutable = true; actionName = "$reset";
|
|
try {
|
|
const next = currentDefinition.createState();
|
|
Object.keys(raw).forEach(function (name) { if (!(name in next)) delete raw[name]; });
|
|
Object.assign(raw, next); persistState();
|
|
listeners.forEach(function (listener) { listener(instance.snapshot(), { store: currentDefinition.name, action: "$reset", changed: Object.keys(next) }); });
|
|
} finally { mutable = false; actionName = "direct"; }
|
|
},
|
|
snapshot() { return Object.freeze(__clone(raw)); },
|
|
subscribe(listener) { listeners.add(listener); return function () { listeners.delete(listener); }; },
|
|
async dispose() {
|
|
mutable = true; actionName = "$dispose";
|
|
try { await currentDefinition.lifecycle && currentDefinition.lifecycle.dispose && currentDefinition.lifecycle.dispose({ state, runtime: "client", routeId, server }); }
|
|
finally { mutable = false; actionName = "direct"; listeners.clear(); __registry.delete(key); }
|
|
},
|
|
async __hotUpdate(nextDefinition) {
|
|
const previous = __clone(raw);
|
|
const nextShape = nextDefinition.createState();
|
|
const preserved = [], reset = [], added = [], removed = [];
|
|
Object.keys(previous).forEach(function (name) {
|
|
if (!(name in nextShape)) { removed.push(name); return; }
|
|
if (__compatible(nextShape[name], previous[name])) { nextShape[name] = previous[name]; preserved.push(name); }
|
|
else reset.push(name);
|
|
});
|
|
Object.keys(nextShape).forEach(function (name) { if (!(name in previous)) added.push(name); });
|
|
currentDefinition = nextDefinition;
|
|
mutable = true; actionName = "$hmr";
|
|
try {
|
|
Object.keys(raw).forEach(function (name) { delete raw[name]; });
|
|
Object.assign(raw, nextShape);
|
|
installActions(); persistState();
|
|
} finally { mutable = false; actionName = "direct"; }
|
|
const result = { store: currentDefinition.name, preserved, reset, added, removed };
|
|
listeners.forEach(function (listener) { listener(instance.snapshot(), { store: currentDefinition.name, action: "$hmr", changed: added.concat(reset, removed) }); });
|
|
try { __root.dispatchEvent && __root.dispatchEvent(new CustomEvent("wrnexus:store-hmr", { detail: result })); } catch (_) {}
|
|
return result;
|
|
},
|
|
};
|
|
const instance = new Proxy(core, {
|
|
get(target, property, receiver) {
|
|
if (Reflect.has(target, property)) return Reflect.get(target, property, receiver);
|
|
if (property in actions) return actions[property];
|
|
if (property in (currentDefinition.computed || {})) return currentDefinition.computed[property](state);
|
|
return state[property];
|
|
},
|
|
set() { throw new TypeError("WRN-STORE-READONLY: store state is readonly outside actions"); },
|
|
});
|
|
__registry.set(key, instance);
|
|
const hydrationSource = __hydration[currentDefinition.name];
|
|
const init = async function () {
|
|
const run = async function (name, hook) {
|
|
if (!hook) return;
|
|
mutable = true; actionName = name;
|
|
try { await hook({ state, runtime: "client", routeId, server }); }
|
|
finally { mutable = false; actionName = "direct"; }
|
|
};
|
|
await run("$clientInit", currentDefinition.lifecycle && currentDefinition.lifecycle.clientInit);
|
|
if (hydrationSource) await run("$hydrate", currentDefinition.lifecycle && currentDefinition.lifecycle.hydrate);
|
|
};
|
|
core.whenReady = init();
|
|
return instance;
|
|
}
|
|
if (!__root.__wrnexusApplyStoreHotUpdate) {
|
|
__root.__wrnexusApplyStoreHotUpdate = async function (name, definition) {
|
|
const results = [];
|
|
for (const item of Array.from(__registry.values())) if (item.name === name && typeof item.__hotUpdate === "function") results.push(await item.__hotUpdate(definition));
|
|
return results;
|
|
};
|
|
}
|
|
if (!__root.__wrnexusStoreContainer) {
|
|
__root.__wrnexusStoreContainer = {
|
|
async disposePageStores() { for (const item of Array.from(__registry.values())) if (item.kind === "page") await item.dispose(); },
|
|
async hotUpdate(name, definition) { return __root.__wrnexusApplyStoreHotUpdate(name, definition); },
|
|
inspect() { return Array.from(__registry.values()).map(function (item) { return { name: item.name, kind: item.kind, state: item.snapshot() }; }); },
|
|
};
|
|
}
|
|
export const ${ast.name}Definition = {
|
|
name: ${JSON.stringify(ast.name)},
|
|
kind: ${JSON.stringify(ast.storeKind)},
|
|
createState: () => (${initialState}),
|
|
computed: { ${computed} },
|
|
actions: { ${actions} },
|
|
persist: ${persistence},
|
|
lifecycle: { ${lifecycleEntries} },
|
|
};
|
|
export const ${ast.name} = __create(${ast.name}Definition);
|
|
export default ${ast.name};
|
|
`;
|
|
}
|
|
},
|
|
"packages/compiler/src/targets.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.generateTargets = generateTargets;
|
|
const component_contract_ts_1 = require2("./component-contract.js");
|
|
const client_codegen_ts_1 = require2("./client-codegen.js");
|
|
const server_codegen_ts_1 = require2("./server-codegen.js");
|
|
const type_codegen_ts_1 = require2("./type-codegen.js");
|
|
const store_codegen_ts_1 = require2("./store-codegen.js");
|
|
function generateTargets(ast) {
|
|
return {
|
|
server: ast.kind === "global-store" || ast.kind === "page-store" ? (0, store_codegen_ts_1.generateStoreModule)(ast) : (0, server_codegen_ts_1.generateServerFunctionsModule)(ast),
|
|
browser: ast.kind === "global-store" || ast.kind === "page-store" ? (0, store_codegen_ts_1.generateStoreBrowserModule)(ast) : (0, client_codegen_ts_1.generateBrowserModule)(ast),
|
|
declarations: (0, type_codegen_ts_1.generateDeclarations)(ast),
|
|
contract: (0, component_contract_ts_1.createComponentContract)(ast),
|
|
rpc: (0, server_codegen_ts_1.rpcManifest)(ast)
|
|
};
|
|
}
|
|
},
|
|
"packages/compiler/src/tokenizer.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __exportStar = this && this.__exportStar || function(m, exports4) {
|
|
for (var p in m)
|
|
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports4, p))
|
|
__createBinding(exports4, m, p);
|
|
};
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
__exportStar(require2("@wrnexus/syntax/tokenizer"), exports3);
|
|
},
|
|
"packages/compiler/src/type-codegen.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.generateDeclarations = generateDeclarations;
|
|
function member(name) {
|
|
return /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
|
|
}
|
|
function params(astParams) {
|
|
return astParams.map((param) => `${member(param.name)}${param.optional ? "?" : ""}: ${param.valueType ?? "unknown"}`).join(", ");
|
|
}
|
|
function generateDeclarations(ast) {
|
|
const inline = ast.types.map((body) => body.trim()).filter(Boolean).join(`
|
|
|
|
`);
|
|
if (ast.kind === "global-store" || ast.kind === "page-store") {
|
|
const state = ast.states.filter((entry) => entry.runtime !== "server").map((entry) => ` readonly ${member(entry.name)}: ${entry.valueType ?? "unknown"};`).join(`
|
|
`);
|
|
const computed = ast.computed.map((entry) => ` readonly ${member(entry.name)}: ${entry.valueType ?? "unknown"};`).join(`
|
|
`);
|
|
const actions = ast.runtimeFunctions.filter((fn) => fn.runtime !== "server").map((fn) => ` ${member(fn.name)}(${params(fn.parameters)}): ${fn.returnType ?? (fn.async ? "Promise<unknown>" : "unknown")};`).join(`
|
|
`);
|
|
return `${inline ? `${inline}
|
|
|
|
` : ""}export interface ${ast.name}State {
|
|
${state}
|
|
}
|
|
|
|
export interface ${ast.name}Computed {
|
|
${computed}
|
|
}
|
|
|
|
export interface ${ast.name}Actions {
|
|
${actions}
|
|
}
|
|
|
|
export interface ${ast.name}Instance extends ${ast.name}State, ${ast.name}Computed, ${ast.name}Actions {
|
|
reset(): void;
|
|
snapshot(): Readonly<${ast.name}State>;
|
|
}
|
|
|
|
declare const store: ${ast.name}Instance;
|
|
export default store;
|
|
`;
|
|
}
|
|
const props = ast.props.map((prop) => ` readonly ${member(prop.name)}${prop.required ? "" : "?"}: ${prop.valueType ?? "unknown"};`).join(`
|
|
`);
|
|
const outputs = ast.outputs.map((output) => ` ${member(output.name)}(${output.payload ? `${member(output.payload.name)}${output.payload.optional ? "?" : ""}: ${output.payload.valueType}` : ""}): void;`).join(`
|
|
`);
|
|
const clientFunctions = ast.runtimeFunctions.filter((fn) => fn.runtime === "client" || fn.runtime === "shared" || fn.runtime === "legacy").map((fn) => ` ${member(fn.name)}(${params(fn.parameters)}): ${fn.returnType ?? (fn.async ? "Promise<unknown>" : "unknown")};`).join(`
|
|
`);
|
|
const serverFunctions = ast.runtimeFunctions.filter((fn) => fn.runtime === "server").map((fn) => ` ${member(fn.name)}(${params(fn.parameters)}): Promise<Awaited<${fn.returnType ?? "unknown"}>>;`).join(`
|
|
`);
|
|
return `${inline ? `${inline}
|
|
|
|
` : ""}export interface ${ast.name}Props {
|
|
${props}
|
|
}
|
|
|
|
export interface ${ast.name}Outputs {
|
|
${outputs}
|
|
}
|
|
|
|
export interface ${ast.name}ClientFunctions {
|
|
${clientFunctions}
|
|
}
|
|
|
|
export interface ${ast.name}ServerCalls {
|
|
${serverFunctions}
|
|
}
|
|
`;
|
|
}
|
|
},
|
|
"packages/compiler/src/types.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __exportStar = this && this.__exportStar || function(m, exports4) {
|
|
for (var p in m)
|
|
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports4, p))
|
|
__createBinding(exports4, m, p);
|
|
};
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
__exportStar(require2("@wrnexus/syntax/types"), exports3);
|
|
},
|
|
"packages/syntax/src/diagnostics.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.containsReadonlyPropMutation = containsReadonlyPropMutation;
|
|
exports3.positionAt = positionAt;
|
|
exports3.classifyParseError = classifyParseError;
|
|
exports3.diagnosticFromError = diagnosticFromError;
|
|
exports3.diagnose = diagnose;
|
|
exports3.assertValidAst = assertValidAst;
|
|
exports3.isHydrationStrategy = isHydrationStrategy;
|
|
exports3.isRuntimeTarget = isRuntimeTarget;
|
|
exports3.formatDiagnostic = formatDiagnostic;
|
|
const parser_ts_1 = require2("./parser.js");
|
|
const spec_ts_1 = require2("./spec.js");
|
|
function stripAsciiControlAndSpace(value) {
|
|
let result = "";
|
|
for (const character of value) {
|
|
if (character.charCodeAt(0) > 32)
|
|
result += character;
|
|
}
|
|
return result;
|
|
}
|
|
function maskJavaScriptTrivia(source) {
|
|
let result = "";
|
|
let index = 0;
|
|
let quote = null;
|
|
let lineComment = false;
|
|
let blockComment = false;
|
|
while (index < source.length) {
|
|
const char = source[index];
|
|
const next = source[index + 1];
|
|
if (lineComment) {
|
|
if (char === `
|
|
`) {
|
|
lineComment = false;
|
|
result += `
|
|
`;
|
|
} else
|
|
result += " ";
|
|
index++;
|
|
continue;
|
|
}
|
|
if (blockComment) {
|
|
if (char === "*" && next === "/") {
|
|
result += " ";
|
|
index += 2;
|
|
blockComment = false;
|
|
} else {
|
|
result += char === `
|
|
` ? `
|
|
` : " ";
|
|
index++;
|
|
}
|
|
continue;
|
|
}
|
|
if (quote) {
|
|
if (char === "\\") {
|
|
result += " ";
|
|
index += Math.min(2, source.length - index);
|
|
} else if (char === quote) {
|
|
result += " ";
|
|
index++;
|
|
quote = null;
|
|
} else {
|
|
result += char === `
|
|
` ? `
|
|
` : " ";
|
|
index++;
|
|
}
|
|
continue;
|
|
}
|
|
if (char === "/" && next === "/") {
|
|
result += " ";
|
|
index += 2;
|
|
lineComment = true;
|
|
continue;
|
|
}
|
|
if (char === "/" && next === "*") {
|
|
result += " ";
|
|
index += 2;
|
|
blockComment = true;
|
|
continue;
|
|
}
|
|
if (char === "'" || char === '"' || char === "`") {
|
|
quote = char;
|
|
result += " ";
|
|
index++;
|
|
continue;
|
|
}
|
|
result += char;
|
|
index++;
|
|
}
|
|
return result;
|
|
}
|
|
function containsReadonlyPropMutation(body, propName, parameterNames) {
|
|
const code = maskJavaScriptTrivia(body);
|
|
const escaped = propName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
const operator = String.raw`(?:\+\+|--|(?:\*\*|&&|\|\||\?\?|[+\-*/%&|^])?=(?!=|>))`;
|
|
if (new RegExp(String.raw`\bprops\.${escaped}\s*${operator}`).test(code))
|
|
return true;
|
|
if (parameterNames.has(propName))
|
|
return false;
|
|
if (new RegExp(String.raw`\b(?:const|let|var)\s+${escaped}\b`).test(code))
|
|
return false;
|
|
return new RegExp(String.raw`(?:^|[^\w$.])${escaped}\s*${operator}`, "m").test(code);
|
|
}
|
|
function positionAt(source, offset) {
|
|
const safe = Math.max(0, Math.min(offset, source.length));
|
|
const before = source.slice(0, safe);
|
|
const lines = before.split(/\r?\n/);
|
|
return { offset: safe, line: lines.length, column: (lines.at(-1)?.length ?? 0) + 1 };
|
|
}
|
|
function offsetFromMessage(message) {
|
|
const match = /offset\s+(\d+)/i.exec(message);
|
|
return match ? Number(match[1]) : undefined;
|
|
}
|
|
function classifyParseError(message) {
|
|
if (/Expected 'page', 'component', or 'layout'/.test(message))
|
|
return spec_ts_1.WRN_DIAGNOSTIC_CODES.root;
|
|
if (/Unknown (?:page|component|layout|ssr|client) member/.test(message)) {
|
|
return spec_ts_1.WRN_DIAGNOSTIC_CODES.member;
|
|
}
|
|
if (/prop initializer|Expected eq/.test(message))
|
|
return spec_ts_1.WRN_DIAGNOSTIC_CODES.propInitializer;
|
|
if (/State '.+' requires an initializer/.test(message)) {
|
|
return spec_ts_1.WRN_DIAGNOSTIC_CODES.stateInitializer;
|
|
}
|
|
if (/Cannot watch undeclared state/.test(message))
|
|
return spec_ts_1.WRN_DIAGNOSTIC_CODES.watchUndeclared;
|
|
return spec_ts_1.WRN_DIAGNOSTIC_CODES.parse;
|
|
}
|
|
function diagnosticFromError(source, error, options = {}) {
|
|
const message = error instanceof Error ? error.message : String(error);
|
|
const offset = error instanceof parser_ts_1.ParseError && error.offset !== undefined ? error.offset : offsetFromMessage(message);
|
|
return {
|
|
code: error instanceof parser_ts_1.ParseError ? error.code : classifyParseError(message),
|
|
severity: "error",
|
|
message,
|
|
file: options.file,
|
|
...offset === undefined ? {} : { position: positionAt(source, offset) }
|
|
};
|
|
}
|
|
function walk(nodes, visit) {
|
|
for (const node of nodes) {
|
|
visit(node);
|
|
if (node.type === "element")
|
|
walk(node.children, visit);
|
|
else if (node.type === "each") {
|
|
walk(node.body, visit);
|
|
walk(node.empty, visit);
|
|
} else if (node.type === "if") {
|
|
for (const branch of node.branches)
|
|
walk(branch.body, visit);
|
|
}
|
|
}
|
|
}
|
|
function astDiagnostics(ast, options) {
|
|
const diagnostics = [];
|
|
const seen = new Map;
|
|
for (const [kind, declarations] of [
|
|
["prop", ast.props],
|
|
["state", ast.states],
|
|
["computed", ast.computed]
|
|
]) {
|
|
for (const declaration of declarations) {
|
|
const previous = seen.get(declaration.name);
|
|
if (previous) {
|
|
diagnostics.push({
|
|
code: spec_ts_1.WRN_DIAGNOSTIC_CODES.duplicateSymbol,
|
|
severity: "error",
|
|
message: `Duplicate symbol '${declaration.name}' (${previous} and ${kind}).`,
|
|
hint: "Rename one declaration so every prop, state, and computed value is unique.",
|
|
file: options.file
|
|
});
|
|
} else {
|
|
seen.set(declaration.name, kind);
|
|
}
|
|
}
|
|
}
|
|
if (ast.hydrate && !isHydrationStrategy(ast.hydrate)) {
|
|
diagnostics.push({
|
|
code: spec_ts_1.WRN_DIAGNOSTIC_CODES.invalidHydration,
|
|
severity: "error",
|
|
message: `Unknown hydration strategy '${ast.hydrate}'.`,
|
|
hint: "Use load, idle, visible, interaction, none, or media:<query>.",
|
|
file: options.file
|
|
});
|
|
}
|
|
if (ast.runtime && !isRuntimeTarget(ast.runtime)) {
|
|
diagnostics.push({
|
|
code: spec_ts_1.WRN_DIAGNOSTIC_CODES.invalidRuntime,
|
|
severity: "error",
|
|
message: `Unknown runtime target '${ast.runtime}'.`,
|
|
hint: "Use server, client, or universal.",
|
|
file: options.file
|
|
});
|
|
}
|
|
let interactive = ast.states.length > 0 || ast.effects.length > 0 || ast.watches.length > 0;
|
|
const urlAttributes = new Set([
|
|
"href",
|
|
"src",
|
|
"action",
|
|
"formaction",
|
|
"poster",
|
|
"cite",
|
|
"background",
|
|
"xlink:href"
|
|
]);
|
|
walk(ast.view, (node) => {
|
|
if (node.type !== "element")
|
|
return;
|
|
if (node.attrs.some((attribute) => attribute.event))
|
|
interactive = true;
|
|
const tag = node.tag.toLowerCase();
|
|
for (const attribute of node.attrs) {
|
|
if (attribute.event || attribute.boolean || !urlAttributes.has(attribute.name.toLowerCase()))
|
|
continue;
|
|
if (attribute.value.includes("{"))
|
|
continue;
|
|
const value = stripAsciiControlAndSpace(attribute.value.trim()).toLowerCase();
|
|
if (/^(?:javascript|vbscript|file):/.test(value) || /^data:(?!image\/(?:png|gif|jpeg|webp|avif);)/.test(value)) {
|
|
diagnostics.push({
|
|
code: "WRN-SEC-UNSAFE-URL",
|
|
severity: "error",
|
|
message: `Unsafe URL protocol in ${attribute.name} on <${node.tag}>.`,
|
|
hint: "Use a relative URL, https:, mailto:, tel:, or a framework-validated URL helper.",
|
|
file: options.file
|
|
});
|
|
}
|
|
}
|
|
if (tag === "a") {
|
|
const target = node.attrs.find((attribute) => attribute.name === "target")?.value;
|
|
const rel = node.attrs.find((attribute) => attribute.name === "rel")?.value ?? "";
|
|
if (target === "_blank" && !/\bnoopener\b/i.test(rel)) {
|
|
diagnostics.push({
|
|
code: "WRN-SEC-BLANK-REL",
|
|
severity: "warning",
|
|
message: "A target=_blank link should include rel=noopener.",
|
|
hint: 'Add rel="noopener noreferrer".',
|
|
file: options.file
|
|
});
|
|
}
|
|
}
|
|
if (!options.accessibility)
|
|
return;
|
|
if (tag === "img") {
|
|
if (!node.attrs.some((attribute) => attribute.name === "alt")) {
|
|
diagnostics.push({
|
|
code: spec_ts_1.WRN_DIAGNOSTIC_CODES.accessibility,
|
|
severity: "warning",
|
|
message: "Image is missing an alt attribute.",
|
|
hint: 'Add alt text, or alt="" for a decorative image.',
|
|
file: options.file
|
|
});
|
|
}
|
|
const hasWidth = node.attrs.some((attribute) => attribute.name === "width");
|
|
const hasHeight = node.attrs.some((attribute) => attribute.name === "height");
|
|
if (!hasWidth || !hasHeight) {
|
|
diagnostics.push({
|
|
code: "WRN-PERF-IMAGE-DIMENSIONS",
|
|
severity: "warning",
|
|
message: "Image width and height are required to prevent layout shifts.",
|
|
hint: "Declare intrinsic width and height, or use @wrnexus/image.",
|
|
file: options.file
|
|
});
|
|
}
|
|
}
|
|
});
|
|
if (ast.runtime === "server" && interactive) {
|
|
diagnostics.push({
|
|
code: spec_ts_1.WRN_DIAGNOSTIC_CODES.serverInteractive,
|
|
severity: "error",
|
|
message: "A server-only WRN root cannot contain client state, effects, watches, or event handlers.",
|
|
hint: 'Use runtime = "universal" or remove interactive behavior.',
|
|
file: options.file
|
|
});
|
|
}
|
|
const outputs = new Set(ast.outputs.map((output) => output.name));
|
|
for (const fn of ast.runtimeFunctions) {
|
|
for (const call of fn.body.matchAll(/\boutput\.([A-Za-z_$][\w$]*)\s*\(/g)) {
|
|
const outputName = call[1];
|
|
if (fn.runtime === "server") {
|
|
diagnostics.push({
|
|
code: "WRN-OUTPUT-SERVER-CALL",
|
|
severity: "error",
|
|
message: `Server function '${fn.name}' cannot call output.${outputName}().`,
|
|
hint: "Return a typed value to the browser and call the output from a client function.",
|
|
file: options.file
|
|
});
|
|
} else if (!outputs.has(outputName)) {
|
|
diagnostics.push({
|
|
code: "WRN-OUTPUT-UNKNOWN",
|
|
severity: "error",
|
|
message: `Unknown output '${outputName}' called from '${fn.name}'.`,
|
|
hint: `Declare ${outputName}(payload) inside outputs { ... }.`,
|
|
file: options.file
|
|
});
|
|
}
|
|
}
|
|
if (fn.runtime === "client" && /\b(?:process|Bun|Deno|__dirname|require)\b/.test(fn.body)) {
|
|
diagnostics.push({
|
|
code: "WRN-CLIENT-SERVER-API",
|
|
severity: "error",
|
|
message: `Client function '${fn.name}' references a server-only API.`,
|
|
hint: "Move that operation into a server function and call it through server.name(...).",
|
|
file: options.file
|
|
});
|
|
}
|
|
if (fn.runtime === "server" && /\b(?:window|document|localStorage|sessionStorage|navigator)\b/.test(fn.body)) {
|
|
diagnostics.push({
|
|
code: "WRN-SERVER-BROWSER-API",
|
|
severity: "error",
|
|
message: `Server function '${fn.name}' references a browser-only API.`,
|
|
hint: "Move that code into a client function.",
|
|
file: options.file
|
|
});
|
|
}
|
|
if (fn.runtime !== "server" && /\b(?:eval\s*\(|new\s+Function\s*\(|document\.write\s*\(|\.innerHTML\s*=|\.outerHTML\s*=|insertAdjacentHTML\s*\()/.test(fn.body)) {
|
|
diagnostics.push({
|
|
code: "WRN-SEC-DOM-SINK",
|
|
severity: "error",
|
|
message: `Client function '${fn.name}' uses an unsafe dynamic-code or HTML sink.`,
|
|
hint: "Use compiled templates, textContent, typed outputs, or a reviewed TrustedHTML sanitizer.",
|
|
file: options.file
|
|
});
|
|
}
|
|
if (fn.runtime !== "server" && /\b(?:setTimeout|setInterval)\s*\(\s*["'`]/.test(fn.body)) {
|
|
diagnostics.push({
|
|
code: "WRN-SEC-STRING-TIMER",
|
|
severity: "error",
|
|
message: `Client function '${fn.name}' passes a string to a timer.`,
|
|
hint: "Pass a function instead of executable text.",
|
|
file: options.file
|
|
});
|
|
}
|
|
const parameterNames = new Set(fn.parameters.map((parameter) => parameter.name));
|
|
for (const prop of ast.props) {
|
|
if (containsReadonlyPropMutation(fn.body, prop.name, parameterNames)) {
|
|
diagnostics.push({
|
|
code: "WRN-PROP-READONLY",
|
|
severity: "error",
|
|
message: `Function '${fn.name}' attempts to mutate readonly prop '${prop.name}'.`,
|
|
hint: "Copy the prop into state before mutating it.",
|
|
file: options.file
|
|
});
|
|
}
|
|
}
|
|
}
|
|
for (const state of ast.states) {
|
|
if (state.runtime === "shared" && /^(?:new\s+(?:Map|Set|WeakMap|WeakSet)|(?:async\s+)?function\b|.*=>)/.test(state.expr.trim())) {
|
|
diagnostics.push({
|
|
code: "WRN-STATE-NON-SERIALIZABLE",
|
|
severity: "error",
|
|
message: `Shared state '${state.name}' is not safely serializable.`,
|
|
hint: "Use JSON-compatible data or move the value into client/server state.",
|
|
file: options.file
|
|
});
|
|
}
|
|
if (state.runtime !== "server" && /\b(?:process\.env|Bun\.env|Deno\.env|ctx\.env|import\.meta\.env)\b/.test(state.expr)) {
|
|
diagnostics.push({
|
|
code: "WRN-SEC-SERVER-SECRET-SOURCE",
|
|
severity: "error",
|
|
message: `Browser-visible state '${state.name}' reads from a server environment source.`,
|
|
hint: "Move environment-backed values into server state and return only an explicitly safe result.",
|
|
file: options.file
|
|
});
|
|
}
|
|
}
|
|
if (ast.persist) {
|
|
const stateNames = new Set(ast.states.filter((state) => state.runtime !== "server").map((state) => state.name));
|
|
for (const name of ast.persist.include)
|
|
if (!stateNames.has(name))
|
|
diagnostics.push({
|
|
code: "WRN-PERSIST-UNKNOWN-FIELD",
|
|
severity: "error",
|
|
message: `Persist include references unknown or server-only state '${name}'.`,
|
|
hint: "Persist only declared shared/client state fields.",
|
|
file: options.file
|
|
});
|
|
for (const name of ast.persist.include)
|
|
if (/token|password|secret|otp|api.?key/i.test(name))
|
|
diagnostics.push({
|
|
code: "WRN-PERSIST-SENSITIVE",
|
|
severity: "error",
|
|
message: `Sensitive field '${name}' cannot be persisted.`,
|
|
hint: "Remove secrets, tokens, passwords, OTPs, and API keys from persistence.",
|
|
file: options.file
|
|
});
|
|
}
|
|
return diagnostics;
|
|
}
|
|
function diagnose(source, options = {}) {
|
|
try {
|
|
return astDiagnostics((0, parser_ts_1.parse)(source), options);
|
|
} catch (error) {
|
|
return [diagnosticFromError(source, error, options)];
|
|
}
|
|
}
|
|
function assertValidAst(ast, options = {}) {
|
|
const errors = astDiagnostics(ast, options).filter((diagnostic) => diagnostic.severity === "error");
|
|
if (!errors.length)
|
|
return;
|
|
const first = errors[0];
|
|
throw new parser_ts_1.ParseError(first.message, first.code);
|
|
}
|
|
function isHydrationStrategy(value) {
|
|
return spec_ts_1.WRN_HYDRATION_STRATEGIES.includes(value) || value.startsWith("media:") && value.length > "media:".length;
|
|
}
|
|
function isRuntimeTarget(value) {
|
|
return spec_ts_1.WRN_RUNTIME_TARGETS.includes(value);
|
|
}
|
|
function formatDiagnostic(source, diagnostic) {
|
|
const location = diagnostic.position ? `${diagnostic.file ?? "<inline .wrn>"}:${diagnostic.position.line}:${diagnostic.position.column}` : diagnostic.file ?? "<inline .wrn>";
|
|
const lines = [
|
|
`${diagnostic.code} ${diagnostic.severity.toUpperCase()}`,
|
|
"",
|
|
diagnostic.message,
|
|
"",
|
|
location
|
|
];
|
|
if (diagnostic.position) {
|
|
const sourceLine = source.split(/\r?\n/)[diagnostic.position.line - 1] ?? "";
|
|
lines.push("", sourceLine, `${" ".repeat(Math.max(0, diagnostic.position.column - 1))}^`);
|
|
}
|
|
if (diagnostic.hint)
|
|
lines.push("", `Hint: ${diagnostic.hint}`);
|
|
return lines.join(`
|
|
`);
|
|
}
|
|
},
|
|
"packages/syntax/src/formatter.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.formatWrn = formatWrn;
|
|
const VOID_ELEMENTS = new Set([
|
|
"area",
|
|
"base",
|
|
"br",
|
|
"col",
|
|
"embed",
|
|
"hr",
|
|
"img",
|
|
"input",
|
|
"link",
|
|
"meta",
|
|
"param",
|
|
"source",
|
|
"track",
|
|
"wbr"
|
|
]);
|
|
function splitPropDeclarations(value) {
|
|
const declarations = [];
|
|
let start = 0;
|
|
let index = 0;
|
|
let quote = null;
|
|
let escaped = false;
|
|
let square = 0;
|
|
let brace = 0;
|
|
let paren = 0;
|
|
let segmentHasColon = false;
|
|
let segmentHasEquals = false;
|
|
const isIdentifierStart = (character) => /[A-Za-z_]/.test(character || "");
|
|
const isIdentifierPart = (character) => /[A-Za-z0-9_]/.test(character || "");
|
|
const beginsDeclaration = (position) => {
|
|
let cursor = position;
|
|
while (cursor < value.length && /[ \t]/.test(value[cursor]))
|
|
cursor += 1;
|
|
if (value.slice(cursor).startsWith("@event")) {
|
|
cursor += "@event".length;
|
|
if (!/\s/.test(value[cursor] || ""))
|
|
return false;
|
|
while (cursor < value.length && /\s/.test(value[cursor]))
|
|
cursor += 1;
|
|
if (!isIdentifierStart(value[cursor]))
|
|
return false;
|
|
cursor += 1;
|
|
while (cursor < value.length && isIdentifierPart(value[cursor]))
|
|
cursor += 1;
|
|
while (cursor < value.length && /[ \t]/.test(value[cursor]))
|
|
cursor += 1;
|
|
return value[cursor] === "=" ? "=" : null;
|
|
}
|
|
if (!isIdentifierStart(value[cursor]))
|
|
return false;
|
|
cursor += 1;
|
|
while (cursor < value.length && isIdentifierPart(value[cursor]))
|
|
cursor += 1;
|
|
if (value[cursor] === "?")
|
|
cursor += 1;
|
|
while (cursor < value.length && /[ \t]/.test(value[cursor]))
|
|
cursor += 1;
|
|
return value[cursor] === "=" || value[cursor] === ":" ? value[cursor] : null;
|
|
};
|
|
while (index < value.length) {
|
|
const character = value[index];
|
|
if (quote !== null) {
|
|
if (escaped)
|
|
escaped = false;
|
|
else if (character === "\\")
|
|
escaped = true;
|
|
else if (character === quote)
|
|
quote = null;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (character === '"' || character === "'" || character === "`") {
|
|
quote = character;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (character === "[")
|
|
square += 1;
|
|
else if (character === "]" && square > 0)
|
|
square -= 1;
|
|
else if (character === "{")
|
|
brace += 1;
|
|
else if (character === "}" && brace > 0)
|
|
brace -= 1;
|
|
else if (character === "(")
|
|
paren += 1;
|
|
else if (character === ")" && paren > 0)
|
|
paren -= 1;
|
|
const topLevel = square === 0 && brace === 0 && paren === 0;
|
|
if (topLevel && character === ":")
|
|
segmentHasColon = true;
|
|
if (topLevel && character === "=")
|
|
segmentHasEquals = true;
|
|
const candidateDelimiter = topLevel && /\s/.test(character) ? beginsDeclaration(index) : null;
|
|
const beginsNext = candidateDelimiter === ":" || candidateDelimiter === "=" && (segmentHasEquals || !segmentHasColon);
|
|
if (topLevel && /\s/.test(character) && value.slice(start, index).trim() !== "@event" && beginsNext) {
|
|
const declaration2 = value.slice(start, index).trim();
|
|
if (declaration2)
|
|
declarations.push(declaration2);
|
|
while (index < value.length && /\s/.test(value[index]))
|
|
index += 1;
|
|
start = index;
|
|
segmentHasColon = false;
|
|
segmentHasEquals = false;
|
|
continue;
|
|
}
|
|
index += 1;
|
|
}
|
|
const declaration = value.slice(start).trim();
|
|
if (declaration)
|
|
declarations.push(declaration);
|
|
return declarations;
|
|
}
|
|
function splitOutputDeclarations(value) {
|
|
const declarations = [];
|
|
let start = 0;
|
|
let paren = 0;
|
|
let angle = 0;
|
|
let square = 0;
|
|
let quote = null;
|
|
let escaped = false;
|
|
const startsOutput = (position) => {
|
|
let cursor = position;
|
|
while (cursor < value.length && /\s/.test(value[cursor]))
|
|
cursor += 1;
|
|
if (!/[A-Za-z_$]/.test(value[cursor] || ""))
|
|
return false;
|
|
cursor += 1;
|
|
while (cursor < value.length && /[A-Za-z0-9_$]/.test(value[cursor] || ""))
|
|
cursor += 1;
|
|
while (cursor < value.length && /\s/.test(value[cursor]))
|
|
cursor += 1;
|
|
return value[cursor] === "(";
|
|
};
|
|
for (let index = 0;index < value.length; index += 1) {
|
|
const character = value[index];
|
|
if (quote !== null) {
|
|
if (escaped)
|
|
escaped = false;
|
|
else if (character === "\\")
|
|
escaped = true;
|
|
else if (character === quote)
|
|
quote = null;
|
|
continue;
|
|
}
|
|
if (character === '"' || character === "'" || character === "`") {
|
|
quote = character;
|
|
continue;
|
|
}
|
|
if (character === "(")
|
|
paren += 1;
|
|
else if (character === ")" && paren > 0)
|
|
paren -= 1;
|
|
else if (character === "[")
|
|
square += 1;
|
|
else if (character === "]" && square > 0)
|
|
square -= 1;
|
|
else if (character === "<")
|
|
angle += 1;
|
|
else if (character === ">" && angle > 0)
|
|
angle -= 1;
|
|
if (paren === 0 && square === 0 && angle === 0 && /\s/.test(character) && startsOutput(index)) {
|
|
const declaration = value.slice(start, index).trim();
|
|
if (declaration)
|
|
declarations.push(declaration);
|
|
while (index < value.length && /\s/.test(value[index]))
|
|
index += 1;
|
|
start = index;
|
|
index -= 1;
|
|
}
|
|
}
|
|
const finalDeclaration = value.slice(start).trim();
|
|
if (finalDeclaration)
|
|
declarations.push(finalDeclaration);
|
|
return declarations;
|
|
}
|
|
function formatInlineDeclarationBlock(value, unit, depth) {
|
|
const match = /^(props|state|computed|outputs)\s*\{([\s\S]*)\}$/.exec(value.trim());
|
|
if (!match)
|
|
return null;
|
|
const declarations = match[1] === "outputs" ? splitOutputDeclarations(match[2].trim()) : splitPropDeclarations(match[2].trim());
|
|
return [
|
|
`${unit.repeat(depth)}${match[1]} {`,
|
|
...declarations.map((declaration) => `${unit.repeat(depth + 1)}${declaration}`),
|
|
`${unit.repeat(depth)}}`
|
|
];
|
|
}
|
|
function formatInlinePropsBlock(value, unit, depth) {
|
|
const match = /^props\s*\{([\s\S]*)\}$/.exec(value.trim());
|
|
if (!match)
|
|
return null;
|
|
const declarations = splitPropDeclarations(match[1].trim());
|
|
if (declarations.length === 0) {
|
|
return [`${unit.repeat(depth)}props {`, `${unit.repeat(depth)}}`];
|
|
}
|
|
return [
|
|
`${unit.repeat(depth)}props {`,
|
|
...declarations.map((declaration) => `${unit.repeat(depth + 1)}${declaration}`),
|
|
`${unit.repeat(depth)}}`
|
|
];
|
|
}
|
|
function findOpeningTagEnd(value) {
|
|
let quote = null;
|
|
let escaped = false;
|
|
for (let index = 0;index < value.length; index += 1) {
|
|
const character = value[index];
|
|
if (quote !== null) {
|
|
if (escaped) {
|
|
escaped = false;
|
|
continue;
|
|
}
|
|
if (character === "\\") {
|
|
escaped = true;
|
|
continue;
|
|
}
|
|
if (character === quote) {
|
|
quote = null;
|
|
}
|
|
continue;
|
|
}
|
|
if (character === '"' || character === "'") {
|
|
quote = character;
|
|
continue;
|
|
}
|
|
if (character === ">") {
|
|
return index;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
function parseAttributes(value) {
|
|
const attributes = [];
|
|
let index = 0;
|
|
while (index < value.length) {
|
|
while (index < value.length && /\s/.test(value[index]))
|
|
index += 1;
|
|
if (index >= value.length)
|
|
break;
|
|
const start = index;
|
|
while (index < value.length && !/[\s=]/.test(value[index]))
|
|
index += 1;
|
|
while (index < value.length && /\s/.test(value[index]))
|
|
index += 1;
|
|
if (value[index] === "=") {
|
|
index += 1;
|
|
while (index < value.length && /\s/.test(value[index]))
|
|
index += 1;
|
|
const quote = value[index];
|
|
if (quote === '"' || quote === "'") {
|
|
index += 1;
|
|
let escaped = false;
|
|
while (index < value.length) {
|
|
const character = value[index++];
|
|
if (escaped)
|
|
escaped = false;
|
|
else if (character === "\\")
|
|
escaped = true;
|
|
else if (character === quote)
|
|
break;
|
|
}
|
|
} else if (value[index] === "{") {
|
|
let depth = 0;
|
|
let expressionQuote = null;
|
|
let escaped = false;
|
|
while (index < value.length) {
|
|
const character = value[index++];
|
|
if (expressionQuote !== null) {
|
|
if (escaped)
|
|
escaped = false;
|
|
else if (character === "\\")
|
|
escaped = true;
|
|
else if (character === expressionQuote)
|
|
expressionQuote = null;
|
|
continue;
|
|
}
|
|
if (character === '"' || character === "'" || character === "`") {
|
|
expressionQuote = character;
|
|
} else if (character === "{") {
|
|
depth += 1;
|
|
} else if (character === "}" && --depth === 0) {
|
|
break;
|
|
}
|
|
}
|
|
} else {
|
|
while (index < value.length && !/\s/.test(value[index]))
|
|
index += 1;
|
|
}
|
|
}
|
|
const attribute = value.slice(start, index).trim();
|
|
if (attribute)
|
|
attributes.push(attribute);
|
|
}
|
|
return attributes;
|
|
}
|
|
function parseStructuredAttribute(attribute) {
|
|
const match = /^([^\s=]+)\s*=\s*\{([\s\S]*)\}$/.exec(attribute);
|
|
if (!match)
|
|
return null;
|
|
const expression = match[2].trim();
|
|
if (!expression.startsWith("[") && !expression.startsWith("{"))
|
|
return null;
|
|
try {
|
|
return {
|
|
name: match[1],
|
|
value: JSON.parse(expression)
|
|
};
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
function formatAttribute(attribute, indentation, unit) {
|
|
const structured = parseStructuredAttribute(attribute);
|
|
if (!structured)
|
|
return [`${indentation}${attribute}`];
|
|
const jsonLines = JSON.stringify(structured.value, null, unit).split(`
|
|
`);
|
|
if (jsonLines.length === 1) {
|
|
return [`${indentation}${structured.name}={${jsonLines[0]}}`];
|
|
}
|
|
return [
|
|
`${indentation}${structured.name}={${jsonLines[0]}`,
|
|
...jsonLines.slice(1, -1).map((line) => `${indentation}${line}`),
|
|
`${indentation}${jsonLines.at(-1)}}`
|
|
];
|
|
}
|
|
function escapeRegExp(value) {
|
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
}
|
|
function parseOpeningTag(value) {
|
|
const endIndex = findOpeningTagEnd(value);
|
|
if (endIndex === -1) {
|
|
return null;
|
|
}
|
|
const openingPart = value.slice(0, endIndex + 1);
|
|
const remainder = value.slice(endIndex + 1).trim();
|
|
const match = /^<([A-Za-z][\w$:.-]*)([\s\S]*?)(\/?)>$/.exec(openingPart);
|
|
if (!match) {
|
|
return null;
|
|
}
|
|
const tagName = match[1];
|
|
const attributes = parseAttributes(match[2].trim());
|
|
const selfClosing = match[3] === "/";
|
|
const escapedTagName = escapeRegExp(tagName);
|
|
const immediateClosing = new RegExp(`^<\\/${escapedTagName}\\s*>`, "i").test(remainder);
|
|
const trailingClosingMatch = new RegExp(`^([\\s\\S]*?)<\\/${escapedTagName}\\s*>$`, "i").exec(remainder);
|
|
const trailingClosing = trailingClosingMatch !== null;
|
|
const inlineContent = trailingClosing ? trailingClosingMatch[1].trim() : "";
|
|
const inlineClosing = trailingClosing && inlineContent.length === 0;
|
|
const closesInRemainder = immediateClosing || trailingClosing;
|
|
return {
|
|
tagName,
|
|
attributes,
|
|
selfClosing,
|
|
inlineClosing,
|
|
immediateClosing,
|
|
trailingClosing,
|
|
inlineContent,
|
|
closesInRemainder,
|
|
remainder
|
|
};
|
|
}
|
|
function formatOpeningTag(value, unit, depth, printWidth = 100, multilineAttributes = true) {
|
|
const parsed = parseOpeningTag(value);
|
|
if (!parsed) {
|
|
return {
|
|
lines: [`${unit.repeat(depth)}${value.trim()}`],
|
|
opensElement: false
|
|
};
|
|
}
|
|
const baseIndent = unit.repeat(depth);
|
|
const childIndent = unit.repeat(depth + 1);
|
|
const normalizedOpening = `<${parsed.tagName}` + `${parsed.attributes.length ? ` ${parsed.attributes.join(" ")}` : ""}` + `${parsed.selfClosing ? " /" : ""}>`;
|
|
const normalizedSingleLine = `${normalizedOpening}${parsed.remainder}`;
|
|
const shouldBreak = value.includes(`
|
|
`) || multilineAttributes && parsed.attributes.length > 0 || baseIndent.length + normalizedSingleLine.length > printWidth;
|
|
const opensElement = !parsed.selfClosing && !parsed.closesInRemainder && !VOID_ELEMENTS.has(parsed.tagName.toLowerCase());
|
|
if (!shouldBreak) {
|
|
return {
|
|
lines: [`${baseIndent}${normalizedSingleLine}`],
|
|
opensElement
|
|
};
|
|
}
|
|
if (parsed.attributes.length === 0 && !parsed.selfClosing) {
|
|
const lines2 = [`${baseIndent}<${parsed.tagName}>`];
|
|
if (parsed.trailingClosing) {
|
|
if (parsed.inlineContent)
|
|
lines2.push(`${childIndent}${parsed.inlineContent}`);
|
|
lines2.push(`${baseIndent}</${parsed.tagName}>`);
|
|
} else if (parsed.remainder) {
|
|
lines2.push(`${childIndent}${parsed.remainder}`);
|
|
}
|
|
return { lines: lines2, opensElement };
|
|
}
|
|
const lines = [
|
|
`${baseIndent}<${parsed.tagName}`,
|
|
...parsed.attributes.flatMap((attribute) => formatAttribute(attribute, childIndent, unit))
|
|
];
|
|
if (parsed.selfClosing) {
|
|
lines.push(`${baseIndent}/>`);
|
|
return {
|
|
lines,
|
|
opensElement
|
|
};
|
|
}
|
|
lines.push(`${baseIndent}>`);
|
|
if (parsed.trailingClosing) {
|
|
if (parsed.inlineContent) {
|
|
lines.push(`${childIndent}${parsed.inlineContent}`);
|
|
}
|
|
lines.push(`${baseIndent}</${parsed.tagName}>`);
|
|
} else if (parsed.remainder) {
|
|
lines.push(`${parsed.immediateClosing ? baseIndent : childIndent}${parsed.remainder}`);
|
|
}
|
|
return {
|
|
lines,
|
|
opensElement
|
|
};
|
|
}
|
|
function isMultilineOpeningTagStart(value) {
|
|
if (!value.startsWith("<")) {
|
|
return false;
|
|
}
|
|
if (value.startsWith("</") || value.startsWith("<!--") || value.startsWith("<!") || value.startsWith("<?")) {
|
|
return false;
|
|
}
|
|
return findOpeningTagEnd(value) === -1;
|
|
}
|
|
function isClosingTag(value) {
|
|
return /^<\/[A-Za-z][\w$:.-]*\s*>/.test(value);
|
|
}
|
|
function isBalancedInlineHtmlFragment(value) {
|
|
if (!value.startsWith("<") || value.startsWith("</") || value.startsWith("<!--")) {
|
|
return false;
|
|
}
|
|
const stack = [];
|
|
let tagCount = 0;
|
|
let rootCount = 0;
|
|
let hasNestedElement = false;
|
|
let hasOutsideText = false;
|
|
let index = 0;
|
|
while (index < value.length) {
|
|
const tagStart = value.indexOf("<", index);
|
|
if (tagStart === -1) {
|
|
if (stack.length === 0 && value.slice(index).trim())
|
|
hasOutsideText = true;
|
|
break;
|
|
}
|
|
if (stack.length === 0 && value.slice(index, tagStart).trim())
|
|
hasOutsideText = true;
|
|
if (value.startsWith("<!--", tagStart)) {
|
|
const commentEnd = value.indexOf("-->", tagStart + 4);
|
|
if (commentEnd === -1)
|
|
return false;
|
|
index = commentEnd + 3;
|
|
continue;
|
|
}
|
|
const relativeEnd = findOpeningTagEnd(value.slice(tagStart));
|
|
if (relativeEnd === -1)
|
|
return false;
|
|
const tag = value.slice(tagStart, tagStart + relativeEnd + 1);
|
|
const match = /^<\/?([A-Za-z][\w$:.-]*)[\s\S]*?>$/.exec(tag);
|
|
if (!match) {
|
|
index = tagStart + 1;
|
|
continue;
|
|
}
|
|
tagCount += 1;
|
|
const tagName = match[1];
|
|
const normalizedName = /^[a-z]/.test(tagName) ? tagName.toLowerCase() : tagName;
|
|
const closing = tag.startsWith("</");
|
|
const selfClosing = /\/\s*>$/.test(tag);
|
|
const voidElement = VOID_ELEMENTS.has(tagName.toLowerCase());
|
|
if (closing) {
|
|
if (stack.at(-1) !== normalizedName)
|
|
return false;
|
|
stack.pop();
|
|
} else {
|
|
if (stack.length === 0)
|
|
rootCount += 1;
|
|
else
|
|
hasNestedElement = true;
|
|
if (!selfClosing && !voidElement)
|
|
stack.push(normalizedName);
|
|
}
|
|
index = tagStart + relativeEnd + 1;
|
|
}
|
|
return tagCount >= 2 && stack.length === 0 && (rootCount > 1 || hasNestedElement || hasOutsideText);
|
|
}
|
|
function isControlBlockOpen(value) {
|
|
return /^\{#(?:if|each)\b[\s\S]*\}$/.test(value);
|
|
}
|
|
function isControlBlockMiddle(value) {
|
|
return /^\{:(?:else(?:\s+if\b[\s\S]*)?|empty)\}$/.test(value);
|
|
}
|
|
function isControlBlockClose(value) {
|
|
return /^\{\/(?:if|each)\}$/.test(value);
|
|
}
|
|
function countLeadingClosingBraces(value) {
|
|
let index = 0;
|
|
let count = 0;
|
|
while (index < value.length) {
|
|
while (index < value.length && /\s/.test(value[index])) {
|
|
index += 1;
|
|
}
|
|
if (value[index] !== "}" && value[index] !== "]") {
|
|
break;
|
|
}
|
|
count += 1;
|
|
index += 1;
|
|
}
|
|
return count;
|
|
}
|
|
function countStructuralBraces(value) {
|
|
let openings = 0;
|
|
let closings = 0;
|
|
let quote = null;
|
|
let escaped = false;
|
|
let htmlComment = false;
|
|
for (let index = 0;index < value.length; index += 1) {
|
|
if (!quote && !htmlComment && value.startsWith("<!--", index)) {
|
|
htmlComment = true;
|
|
index += 3;
|
|
continue;
|
|
}
|
|
if (htmlComment && value.startsWith("-->", index)) {
|
|
htmlComment = false;
|
|
index += 2;
|
|
continue;
|
|
}
|
|
if (htmlComment) {
|
|
continue;
|
|
}
|
|
const character = value[index];
|
|
if (quote !== null) {
|
|
if (escaped) {
|
|
escaped = false;
|
|
continue;
|
|
}
|
|
if (character === "\\") {
|
|
escaped = true;
|
|
continue;
|
|
}
|
|
if (character === quote) {
|
|
quote = null;
|
|
}
|
|
continue;
|
|
}
|
|
if (character === '"' || character === "'" || character === "`") {
|
|
quote = character;
|
|
continue;
|
|
}
|
|
if (character === "{") {
|
|
openings += 1;
|
|
} else if (character === "}") {
|
|
closings += 1;
|
|
} else if (character === "[") {
|
|
openings += 1;
|
|
} else if (character === "]") {
|
|
closings += 1;
|
|
}
|
|
}
|
|
return {
|
|
openings,
|
|
closings
|
|
};
|
|
}
|
|
function collectOpeningTag(inputLines, startIndex) {
|
|
const collected = [inputLines[startIndex].trim()];
|
|
let index = startIndex;
|
|
while (index + 1 < inputLines.length) {
|
|
const joined = collected.join(" ");
|
|
if (findOpeningTagEnd(joined) !== -1) {
|
|
break;
|
|
}
|
|
index += 1;
|
|
collected.push(inputLines[index].trim());
|
|
}
|
|
return {
|
|
value: collected.join(`
|
|
`),
|
|
endIndex: index
|
|
};
|
|
}
|
|
function isPreservedRawBlockStart(value) {
|
|
return /<pre(?:\s|>)/i.test(value) && !/<\/pre\s*>/i.test(value.slice(0, value.search(/<pre(?:\s|>)/i)));
|
|
}
|
|
function hasPreservedRawBlockEnd(value) {
|
|
return /<\/pre\s*>/i.test(value);
|
|
}
|
|
function transformOutsidePreservedRawBlocks(lines, transformLine) {
|
|
const output = [];
|
|
let preserving = false;
|
|
for (const line of lines) {
|
|
if (preserving) {
|
|
output.push(line);
|
|
if (hasPreservedRawBlockEnd(line))
|
|
preserving = false;
|
|
continue;
|
|
}
|
|
if (isPreservedRawBlockStart(line)) {
|
|
output.push(line);
|
|
preserving = !hasPreservedRawBlockEnd(line);
|
|
continue;
|
|
}
|
|
output.push(...transformLine(line));
|
|
}
|
|
return output;
|
|
}
|
|
function collectPreservedRawBlock(lines, startIndex) {
|
|
const collected = [lines[startIndex]];
|
|
let index = startIndex;
|
|
while (!hasPreservedRawBlockEnd(collected.at(-1) || "") && index + 1 < lines.length) {
|
|
index += 1;
|
|
collected.push(lines[index]);
|
|
}
|
|
return { lines: collected, endIndex: index };
|
|
}
|
|
function expandInlineControlBlocks(lines) {
|
|
const marker = /(\{#(?:if|each)\b[^}]*\}|\{:(?:else(?:\s+if\b[^}]*)?|empty)\}|\{\/(?:if|each)\})/g;
|
|
return transformOutsidePreservedRawBlocks(lines, (line) => {
|
|
if (!marker.test(line))
|
|
return [line];
|
|
marker.lastIndex = 0;
|
|
const indentation = line.match(/^\s*/)?.[0] ?? "";
|
|
const segments = line.split(marker).map((segment) => segment.trim()).filter(Boolean);
|
|
return segments.map((segment) => `${indentation}${segment}`);
|
|
});
|
|
}
|
|
function expandStructuredStateDeclarations(lines, unit) {
|
|
return transformOutsidePreservedRawBlocks(lines, (line) => {
|
|
const match = /^(\s*state\s+[A-Za-z_$][\w$]*\s*=\s*)([\\[{][\s\S]*)$/.exec(line);
|
|
if (!match)
|
|
return [line];
|
|
try {
|
|
const parsed = JSON.parse(match[2].trim());
|
|
const jsonLines = JSON.stringify(parsed, null, unit).split(`
|
|
`);
|
|
if (jsonLines.length === 1)
|
|
return [`${match[1]}${jsonLines[0]}`];
|
|
const leading = match[1].match(/^\s*/)?.[0] ?? "";
|
|
return [
|
|
`${match[1]}${jsonLines[0]}`,
|
|
...jsonLines.slice(1).map((jsonLine) => `${leading}${jsonLine}`)
|
|
];
|
|
} catch {
|
|
return [line];
|
|
}
|
|
});
|
|
}
|
|
function formatWrnPass(source, options = {}) {
|
|
const unit = options.insertSpaces === false ? "\t" : " ".repeat(options.tabSize ?? 4);
|
|
const printWidth = options.printWidth ?? 100;
|
|
const multilineAttributes = options.multilineAttributes !== false;
|
|
let codeDepth = 0;
|
|
let htmlDepth = 0;
|
|
let controlDepth = 0;
|
|
let index = 0;
|
|
const sourceLines = source.replace(/\r\n/g, `
|
|
`).split(`
|
|
`);
|
|
const inputLines = expandInlineControlBlocks(expandStructuredStateDeclarations(sourceLines, unit));
|
|
const output = [];
|
|
let previousWasBlank = false;
|
|
while (index < inputLines.length) {
|
|
const originalLine = inputLines[index];
|
|
let value = originalLine.trim();
|
|
if (value === "") {
|
|
if (!previousWasBlank && output.length > 0) {
|
|
output.push("");
|
|
}
|
|
previousWasBlank = true;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
previousWasBlank = false;
|
|
if (/^import\b/.test(value)) {
|
|
const importLines = [value];
|
|
while (!/(?:\bfrom\s+)?["'][^"']+["']\s*;?$/.test(importLines[importLines.length - 1]) && index + 1 < inputLines.length) {
|
|
index += 1;
|
|
importLines.push(inputLines[index].trim());
|
|
}
|
|
output.push(importLines[0], ...importLines.slice(1).map((line) => `${unit}${line}`));
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (isPreservedRawBlockStart(value)) {
|
|
const collected = collectPreservedRawBlock(inputLines, index);
|
|
const depth2 = codeDepth + htmlDepth + controlDepth;
|
|
output.push(`${unit.repeat(depth2)}${collected.lines[0].trimStart()}`);
|
|
output.push(...collected.lines.slice(1));
|
|
index = collected.endIndex + 1;
|
|
continue;
|
|
}
|
|
if (isMultilineOpeningTagStart(value)) {
|
|
const collected = collectOpeningTag(inputLines, index);
|
|
value = collected.value;
|
|
index = collected.endIndex;
|
|
}
|
|
const inlineDeclaration = formatInlineDeclarationBlock(value, unit, codeDepth + htmlDepth);
|
|
const inlineProps = inlineDeclaration ?? formatInlinePropsBlock(value, unit, codeDepth + htmlDepth);
|
|
if (inlineProps) {
|
|
output.push(...inlineProps);
|
|
index += 1;
|
|
continue;
|
|
}
|
|
const leadingClosingBraces = countLeadingClosingBraces(value);
|
|
const closesControlBlock = isControlBlockClose(value);
|
|
const continuesControlBlock = isControlBlockMiddle(value);
|
|
const lineControlDepth = closesControlBlock || continuesControlBlock ? Math.max(0, controlDepth - 1) : controlDepth;
|
|
const lineCodeDepth = Math.max(0, codeDepth - leadingClosingBraces);
|
|
let lineHtmlDepth = htmlDepth;
|
|
if (isClosingTag(value)) {
|
|
lineHtmlDepth = Math.max(0, htmlDepth - 1);
|
|
}
|
|
const depth = lineCodeDepth + lineHtmlDepth + lineControlDepth;
|
|
const inlineFragmentFits = unit.repeat(depth).length + value.length <= printWidth;
|
|
if (isBalancedInlineHtmlFragment(value) && inlineFragmentFits) {
|
|
output.push(`${unit.repeat(depth)}${value}`);
|
|
} else if (value.startsWith("<") && !value.startsWith("</") && !value.startsWith("<!--") && !value.startsWith("<!") && !value.startsWith("<?")) {
|
|
const formattedTag = formatOpeningTag(value, unit, depth, printWidth, multilineAttributes);
|
|
output.push(...formattedTag.lines);
|
|
if (formattedTag.opensElement) {
|
|
htmlDepth += 1;
|
|
}
|
|
} else {
|
|
output.push(`${unit.repeat(depth)}${value}`);
|
|
}
|
|
if (isClosingTag(value)) {
|
|
htmlDepth = lineHtmlDepth;
|
|
}
|
|
const braces = countStructuralBraces(value);
|
|
codeDepth = Math.max(0, lineCodeDepth + braces.openings - Math.max(0, braces.closings - leadingClosingBraces));
|
|
if (isControlBlockOpen(value) || continuesControlBlock) {
|
|
controlDepth = lineControlDepth + 1;
|
|
} else if (closesControlBlock) {
|
|
controlDepth = lineControlDepth;
|
|
}
|
|
index += 1;
|
|
}
|
|
while (output.length > 0 && output[output.length - 1] === "") {
|
|
output.pop();
|
|
}
|
|
return `${output.join(`
|
|
`)}
|
|
`;
|
|
}
|
|
function formatWrn(source, options = {}) {
|
|
let current = source;
|
|
const seen = new Set;
|
|
for (let pass = 0;pass < 8; pass++) {
|
|
const formatted = formatWrnPass(current, options);
|
|
if (formatted === current)
|
|
return formatted;
|
|
if (seen.has(formatted))
|
|
return [...seen, formatted].sort()[0];
|
|
seen.add(current);
|
|
current = formatted;
|
|
}
|
|
return current;
|
|
}
|
|
},
|
|
"packages/syntax/src/index.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
} : function(o, m, k, k2) {
|
|
if (k2 === undefined)
|
|
k2 = k;
|
|
o[k2] = m[k];
|
|
});
|
|
var __exportStar = this && this.__exportStar || function(m, exports4) {
|
|
for (var p in m)
|
|
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports4, p))
|
|
__createBinding(exports4, m, p);
|
|
};
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.stripRuntimeFunctionModifiers = exports3.parseStructuredImports = exports3.parseStoreLifecycle = exports3.parseStateDeclarations = exports3.parseRuntimeFunctions = exports3.parsePersist = exports3.parseOutputs = exports3.parseComputedDeclarations = exports3.supportsSyntaxFeature = exports3.diagnosticSummary = exports3.sliceSource = exports3.createSourceRange = exports3.WRN_SYNTAX_FEATURES = exports3.WRN_SYNTAX_VERSION = exports3.positionAt = exports3.isRuntimeTarget = exports3.isHydrationStrategy = exports3.formatDiagnostic = exports3.diagnosticFromError = exports3.diagnose = exports3.containsReadonlyPropMutation = exports3.classifyParseError = exports3.assertValidAst = exports3.validateTypedInitializer = exports3.runtimeTypeOf = exports3.inferredRuntimeType = exports3.eraseFunctionTypes = exports3.VOID_ELEMENTS = exports3.ParseError = exports3.parseHtmlView = exports3.parse = exports3.formatWrn = exports3.LexError = exports3.Lexer = undefined;
|
|
var tokenizer_ts_1 = require2("./tokenizer.js");
|
|
Object.defineProperty(exports3, "Lexer", { enumerable: true, get: function() {
|
|
return tokenizer_ts_1.Lexer;
|
|
} });
|
|
Object.defineProperty(exports3, "LexError", { enumerable: true, get: function() {
|
|
return tokenizer_ts_1.LexError;
|
|
} });
|
|
var formatter_ts_1 = require2("./formatter.js");
|
|
Object.defineProperty(exports3, "formatWrn", { enumerable: true, get: function() {
|
|
return formatter_ts_1.formatWrn;
|
|
} });
|
|
var parser_ts_1 = require2("./parser.js");
|
|
Object.defineProperty(exports3, "parse", { enumerable: true, get: function() {
|
|
return parser_ts_1.parse;
|
|
} });
|
|
Object.defineProperty(exports3, "parseHtmlView", { enumerable: true, get: function() {
|
|
return parser_ts_1.parseHtmlView;
|
|
} });
|
|
Object.defineProperty(exports3, "ParseError", { enumerable: true, get: function() {
|
|
return parser_ts_1.ParseError;
|
|
} });
|
|
Object.defineProperty(exports3, "VOID_ELEMENTS", { enumerable: true, get: function() {
|
|
return parser_ts_1.VOID_ELEMENTS;
|
|
} });
|
|
var types_ts_1 = require2("./types.js");
|
|
Object.defineProperty(exports3, "eraseFunctionTypes", { enumerable: true, get: function() {
|
|
return types_ts_1.eraseFunctionTypes;
|
|
} });
|
|
Object.defineProperty(exports3, "inferredRuntimeType", { enumerable: true, get: function() {
|
|
return types_ts_1.inferredRuntimeType;
|
|
} });
|
|
Object.defineProperty(exports3, "runtimeTypeOf", { enumerable: true, get: function() {
|
|
return types_ts_1.runtimeTypeOf;
|
|
} });
|
|
Object.defineProperty(exports3, "validateTypedInitializer", { enumerable: true, get: function() {
|
|
return types_ts_1.validateTypedInitializer;
|
|
} });
|
|
var diagnostics_ts_1 = require2("./diagnostics.js");
|
|
Object.defineProperty(exports3, "assertValidAst", { enumerable: true, get: function() {
|
|
return diagnostics_ts_1.assertValidAst;
|
|
} });
|
|
Object.defineProperty(exports3, "classifyParseError", { enumerable: true, get: function() {
|
|
return diagnostics_ts_1.classifyParseError;
|
|
} });
|
|
Object.defineProperty(exports3, "containsReadonlyPropMutation", { enumerable: true, get: function() {
|
|
return diagnostics_ts_1.containsReadonlyPropMutation;
|
|
} });
|
|
Object.defineProperty(exports3, "diagnose", { enumerable: true, get: function() {
|
|
return diagnostics_ts_1.diagnose;
|
|
} });
|
|
Object.defineProperty(exports3, "diagnosticFromError", { enumerable: true, get: function() {
|
|
return diagnostics_ts_1.diagnosticFromError;
|
|
} });
|
|
Object.defineProperty(exports3, "formatDiagnostic", { enumerable: true, get: function() {
|
|
return diagnostics_ts_1.formatDiagnostic;
|
|
} });
|
|
Object.defineProperty(exports3, "isHydrationStrategy", { enumerable: true, get: function() {
|
|
return diagnostics_ts_1.isHydrationStrategy;
|
|
} });
|
|
Object.defineProperty(exports3, "isRuntimeTarget", { enumerable: true, get: function() {
|
|
return diagnostics_ts_1.isRuntimeTarget;
|
|
} });
|
|
Object.defineProperty(exports3, "positionAt", { enumerable: true, get: function() {
|
|
return diagnostics_ts_1.positionAt;
|
|
} });
|
|
__exportStar(require2("./spec.js"), exports3);
|
|
var versioning_ts_1 = require2("./versioning.js");
|
|
Object.defineProperty(exports3, "WRN_SYNTAX_VERSION", { enumerable: true, get: function() {
|
|
return versioning_ts_1.WRN_SYNTAX_VERSION;
|
|
} });
|
|
Object.defineProperty(exports3, "WRN_SYNTAX_FEATURES", { enumerable: true, get: function() {
|
|
return versioning_ts_1.WRN_SYNTAX_FEATURES;
|
|
} });
|
|
Object.defineProperty(exports3, "createSourceRange", { enumerable: true, get: function() {
|
|
return versioning_ts_1.createSourceRange;
|
|
} });
|
|
Object.defineProperty(exports3, "sliceSource", { enumerable: true, get: function() {
|
|
return versioning_ts_1.sliceSource;
|
|
} });
|
|
Object.defineProperty(exports3, "diagnosticSummary", { enumerable: true, get: function() {
|
|
return versioning_ts_1.diagnosticSummary;
|
|
} });
|
|
Object.defineProperty(exports3, "supportsSyntaxFeature", { enumerable: true, get: function() {
|
|
return versioning_ts_1.supportsSyntaxFeature;
|
|
} });
|
|
var v060_ts_1 = require2("./v060.js");
|
|
Object.defineProperty(exports3, "parseComputedDeclarations", { enumerable: true, get: function() {
|
|
return v060_ts_1.parseComputedDeclarations;
|
|
} });
|
|
Object.defineProperty(exports3, "parseOutputs", { enumerable: true, get: function() {
|
|
return v060_ts_1.parseOutputs;
|
|
} });
|
|
Object.defineProperty(exports3, "parsePersist", { enumerable: true, get: function() {
|
|
return v060_ts_1.parsePersist;
|
|
} });
|
|
Object.defineProperty(exports3, "parseRuntimeFunctions", { enumerable: true, get: function() {
|
|
return v060_ts_1.parseRuntimeFunctions;
|
|
} });
|
|
Object.defineProperty(exports3, "parseStateDeclarations", { enumerable: true, get: function() {
|
|
return v060_ts_1.parseStateDeclarations;
|
|
} });
|
|
Object.defineProperty(exports3, "parseStoreLifecycle", { enumerable: true, get: function() {
|
|
return v060_ts_1.parseStoreLifecycle;
|
|
} });
|
|
Object.defineProperty(exports3, "parseStructuredImports", { enumerable: true, get: function() {
|
|
return v060_ts_1.parseStructuredImports;
|
|
} });
|
|
Object.defineProperty(exports3, "stripRuntimeFunctionModifiers", { enumerable: true, get: function() {
|
|
return v060_ts_1.stripRuntimeFunctionModifiers;
|
|
} });
|
|
},
|
|
"packages/syntax/src/parser.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.ParseError = exports3.VOID_ELEMENTS = undefined;
|
|
exports3.parse = parse;
|
|
exports3.parseHtmlView = parseHtmlView;
|
|
const spec_ts_1 = require2("./spec.js");
|
|
const tokenizer_ts_1 = require2("./tokenizer.js");
|
|
const types_ts_1 = require2("./types.js");
|
|
const v060_ts_1 = require2("./v060.js");
|
|
exports3.VOID_ELEMENTS = new Set([
|
|
"area",
|
|
"base",
|
|
"br",
|
|
"col",
|
|
"embed",
|
|
"hr",
|
|
"img",
|
|
"input",
|
|
"link",
|
|
"meta",
|
|
"param",
|
|
"source",
|
|
"track",
|
|
"wbr"
|
|
]);
|
|
|
|
class ParseError extends Error {
|
|
code;
|
|
offset;
|
|
constructor(message, code = "WRN-PARSE-001") {
|
|
super(message);
|
|
this.name = "ParseError";
|
|
this.code = code;
|
|
const match = /offset\s+(\d+)/i.exec(message);
|
|
this.offset = match ? Number(match[1]) : undefined;
|
|
}
|
|
}
|
|
exports3.ParseError = ParseError;
|
|
function parseSeoBlock(body) {
|
|
const out = {};
|
|
const pair = /([A-Za-z][A-Za-z0-9_-]*)\s*=\s*(?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'|([^\n;]+))/g;
|
|
for (const match of body.matchAll(pair)) {
|
|
const key = match[1];
|
|
const rawValue = match[2] ?? match[3] ?? match[4] ?? "";
|
|
out[key] = unescapeSeoValue(rawValue.trim());
|
|
}
|
|
return out;
|
|
}
|
|
function unescapeSeoValue(value) {
|
|
return value.replace(/\\(["'\\nrt])/g, (_match, ch) => {
|
|
if (ch === "n")
|
|
return `
|
|
`;
|
|
if (ch === "r")
|
|
return "\r";
|
|
if (ch === "t")
|
|
return "\t";
|
|
return ch;
|
|
});
|
|
}
|
|
function parse(source) {
|
|
const lx = new tokenizer_ts_1.Lexer(source);
|
|
const imports = [];
|
|
const importPattern = /import\s+(?:type\s+)?(?:[\s\S]*?\s+from\s+)?["'][^"'\r\n]+["']\s*;?/y;
|
|
while (true) {
|
|
while (/\s/u.test(source[lx.pos] ?? ""))
|
|
lx.pos++;
|
|
if (source.startsWith("//", lx.pos)) {
|
|
while (lx.pos < source.length && source[lx.pos] !== `
|
|
`)
|
|
lx.pos++;
|
|
continue;
|
|
}
|
|
importPattern.lastIndex = lx.pos;
|
|
const statement = importPattern.exec(source);
|
|
if (!statement)
|
|
break;
|
|
imports.push(statement[0].trim());
|
|
lx.pos = importPattern.lastIndex;
|
|
}
|
|
const expect = (type) => {
|
|
const t = lx.next();
|
|
if (t.type !== type) {
|
|
throw new ParseError(`Expected ${type} but got '${t.value || t.type}' at offset ${t.pos}`);
|
|
}
|
|
return t;
|
|
};
|
|
const expectKeyword = (kw) => {
|
|
const t = lx.next();
|
|
if (t.type !== "ident" || t.value !== kw) {
|
|
throw new ParseError(`Expected '${kw}' but got '${t.value || t.type}' at offset ${t.pos}`);
|
|
}
|
|
};
|
|
try {
|
|
const opener = lx.next();
|
|
if (opener.type !== "ident" || !["page", "component", "layout", "global"].includes(opener.value)) {
|
|
throw new ParseError(`Expected 'page', 'component', 'layout', 'global store', or 'page store' but got '${opener.value || opener.type}' at offset ${opener.pos}`);
|
|
}
|
|
let kind;
|
|
let storeKind;
|
|
let name;
|
|
if (opener.value === "global") {
|
|
expectKeyword("store");
|
|
kind = "global-store";
|
|
storeKind = "global";
|
|
name = expect("ident").value;
|
|
} else if (opener.value === "page" && lx.peek().type === "ident" && lx.peek().value === "store") {
|
|
lx.next();
|
|
kind = "page-store";
|
|
storeKind = "page";
|
|
name = expect("ident").value;
|
|
} else {
|
|
kind = opener.value;
|
|
name = expect("ident").value;
|
|
}
|
|
expect("lbrace");
|
|
let layout;
|
|
let layoutIsSymbol = false;
|
|
let runtime;
|
|
let renderMode;
|
|
let hydrate;
|
|
const props = [];
|
|
const events = [];
|
|
const outputs = [];
|
|
const types = [];
|
|
const states = [];
|
|
const computed = [];
|
|
const effects = [];
|
|
const loads = [];
|
|
const actions = [];
|
|
const security = {};
|
|
const cache = {};
|
|
const navigation = {};
|
|
const seo = {};
|
|
const view = [];
|
|
const styles = [];
|
|
const functions = [];
|
|
const runtimeFunctions = [];
|
|
const dataApis = [];
|
|
const modeFunctions = [];
|
|
const lifecycle = {};
|
|
let storeLifecycle = {};
|
|
let persist;
|
|
const watches = [];
|
|
const apis = [];
|
|
const realtimes = [];
|
|
while (lx.peek().type !== "rbrace") {
|
|
const kw = lx.peek();
|
|
if (kw.type === "eof")
|
|
throw new ParseError(`Unexpected end of input inside ${kind}`);
|
|
if (kw.type !== "ident") {
|
|
throw new ParseError(`Expected a ${kind} member keyword at offset ${kw.pos}`);
|
|
}
|
|
switch (kw.value) {
|
|
case "layout": {
|
|
lx.next();
|
|
expect("eq");
|
|
const layoutToken = lx.next();
|
|
if (layoutToken.type !== "string" && layoutToken.type !== "ident") {
|
|
throw new ParseError(`Expected a layout string or imported symbol at offset ${layoutToken.pos}`);
|
|
}
|
|
layout = layoutToken.value;
|
|
layoutIsSymbol = layoutToken.type === "ident";
|
|
break;
|
|
}
|
|
case "runtime": {
|
|
lx.next();
|
|
expect("eq");
|
|
const value = expect("string").value;
|
|
if (!spec_ts_1.WRN_RUNTIME_TARGETS.includes(value)) {
|
|
throw new ParseError(`Unknown runtime target '${value}' at offset ${kw.pos}`, "WRN-RUNTIME-TARGET");
|
|
}
|
|
runtime = value;
|
|
break;
|
|
}
|
|
case "render": {
|
|
lx.next();
|
|
expect("eq");
|
|
const value = expect("string").value;
|
|
if (!["static", "server", "hybrid", "client", "partial-static"].includes(value))
|
|
throw new ParseError(`Unknown render mode '${value}' at offset ${kw.pos}`, "WRN-RENDER-MODE");
|
|
renderMode = value;
|
|
break;
|
|
}
|
|
case "hydrate": {
|
|
lx.next();
|
|
expect("eq");
|
|
const value = expect("string").value;
|
|
hydrate = value === "never" ? "none" : value;
|
|
break;
|
|
}
|
|
case "props": {
|
|
lx.next();
|
|
expect("lbrace");
|
|
while (lx.peek().type !== "rbrace") {
|
|
const t = lx.peek();
|
|
if (t.type === "eof")
|
|
throw new ParseError("Unexpected end of input inside props");
|
|
if (t.type === "at") {
|
|
lx.next();
|
|
const declarationKind = expect("ident");
|
|
if (declarationKind.value !== "event") {
|
|
throw new ParseError(`Expected '@event' but got '@${declarationKind.value}' at offset ${declarationKind.pos}`);
|
|
}
|
|
const eventName = expect("ident").value;
|
|
expect("eq");
|
|
const marker = lx.readPropInitializer();
|
|
if (marker !== "function") {
|
|
throw new ParseError(`Event '${eventName}' must be declared as '@event ${eventName} = function'`);
|
|
}
|
|
events.push({ name: eventName });
|
|
continue;
|
|
}
|
|
if (t.type !== "ident") {
|
|
throw new ParseError(`Expected a prop name at offset ${t.pos}`);
|
|
}
|
|
const pName = expect("ident").value;
|
|
const optional = lx.peek().type === "question" ? (lx.next(), true) : false;
|
|
let valueType;
|
|
let hasDefault = false;
|
|
if (lx.peek().type === "colon") {
|
|
lx.next();
|
|
const annotation = lx.readTypeAnnotation();
|
|
valueType = annotation.type;
|
|
hasDefault = annotation.hasDefault;
|
|
} else {
|
|
expect("eq");
|
|
hasDefault = true;
|
|
}
|
|
const defaultValue = hasDefault ? lx.readPropInitializer() : "undefined";
|
|
props.push({
|
|
name: pName,
|
|
valueType,
|
|
required: !hasDefault && !optional,
|
|
default: defaultValue
|
|
});
|
|
}
|
|
expect("rbrace");
|
|
break;
|
|
}
|
|
case "state": {
|
|
lx.next();
|
|
if (lx.peek().type === "lbrace") {
|
|
const grouped = (0, v060_ts_1.parseStateDeclarations)(lx.readBalancedBraces(), "shared");
|
|
states.push(...grouped);
|
|
break;
|
|
}
|
|
const sName = expect("ident").value;
|
|
let valueType;
|
|
if (lx.peek().type === "colon") {
|
|
lx.next();
|
|
const annotation = lx.readTypeAnnotation();
|
|
valueType = annotation.type;
|
|
if (!annotation.hasDefault)
|
|
throw new ParseError(`State '${sName}' requires an initializer`);
|
|
} else {
|
|
expect("eq");
|
|
}
|
|
states.push({
|
|
name: sName,
|
|
valueType,
|
|
expr: lx.readPropInitializer(),
|
|
runtime: "shared"
|
|
});
|
|
break;
|
|
}
|
|
case "computed": {
|
|
lx.next();
|
|
if (lx.peek().type === "lbrace") {
|
|
computed.push(...(0, v060_ts_1.parseComputedDeclarations)(lx.readBalancedBraces()));
|
|
} else {
|
|
const cName = expect("ident").value;
|
|
let valueType;
|
|
if (lx.peek().type === "colon") {
|
|
lx.next();
|
|
const annotation = lx.readTypeAnnotation();
|
|
valueType = annotation.type;
|
|
if (!annotation.hasDefault)
|
|
throw new ParseError(`Computed '${cName}' requires an expression`);
|
|
} else
|
|
expect("eq");
|
|
computed.push({ name: cName, valueType, expr: lx.readPropInitializer() });
|
|
}
|
|
break;
|
|
}
|
|
case "outputs": {
|
|
lx.next();
|
|
try {
|
|
outputs.push(...(0, v060_ts_1.parseOutputs)(lx.readBalancedBraces()));
|
|
} catch (error) {
|
|
throw new ParseError(error instanceof Error ? error.message : String(error), "WRN-OUTPUT-DECLARATION");
|
|
}
|
|
break;
|
|
}
|
|
case "effect": {
|
|
lx.next();
|
|
effects.push({ body: lx.readBalancedBraces() });
|
|
break;
|
|
}
|
|
case "types": {
|
|
lx.next();
|
|
types.push(lx.readBalancedBraces());
|
|
break;
|
|
}
|
|
case "view": {
|
|
lx.next();
|
|
expect("lbrace");
|
|
const { nodes, endPos } = parseHtmlView(lx.src, lx.pos);
|
|
view.push(...nodes);
|
|
lx.pos = endPos;
|
|
expect("rbrace");
|
|
break;
|
|
}
|
|
case "seo": {
|
|
lx.next();
|
|
Object.assign(seo, parseSeoBlock(lx.readBalancedBraces()));
|
|
break;
|
|
}
|
|
case "security": {
|
|
lx.next();
|
|
Object.assign(security, parseSeoBlock(lx.readBalancedBraces()));
|
|
break;
|
|
}
|
|
case "navigation": {
|
|
lx.next();
|
|
Object.assign(navigation, parseSeoBlock(lx.readBalancedBraces()));
|
|
break;
|
|
}
|
|
case "cache": {
|
|
lx.next();
|
|
Object.assign(cache, parseSeoBlock(lx.readBalancedBraces()));
|
|
break;
|
|
}
|
|
case "load": {
|
|
lx.next();
|
|
const first = expect("ident");
|
|
const mode = first.value === "client" ? "client" : "server";
|
|
const name2 = first.value === "server" || first.value === "client" ? lx.peek().type === "ident" ? expect("ident").value : undefined : first.value;
|
|
const dependsOn = [];
|
|
let deferred = false;
|
|
while (lx.peek().type === "ident") {
|
|
if (lx.peek().value === "defer") {
|
|
lx.next();
|
|
deferred = true;
|
|
continue;
|
|
}
|
|
if (lx.peek().value !== "after")
|
|
break;
|
|
lx.next();
|
|
dependsOn.push(expect("ident").value);
|
|
while (lx.peek().type === "comma") {
|
|
lx.next();
|
|
dependsOn.push(expect("ident").value);
|
|
}
|
|
}
|
|
loads.push({
|
|
mode,
|
|
name: name2,
|
|
...dependsOn.length ? { dependsOn } : {},
|
|
...deferred ? { deferred: true } : {},
|
|
body: lx.readBalancedBraces()
|
|
});
|
|
break;
|
|
}
|
|
case "action": {
|
|
lx.next();
|
|
const actionName = expect("ident").value;
|
|
const args = [];
|
|
if (lx.peek().type === "lparen") {
|
|
lx.next();
|
|
while (lx.peek().type !== "rparen") {
|
|
args.push(expect("ident").value);
|
|
if (lx.peek().type === "comma")
|
|
lx.next();
|
|
}
|
|
expect("rparen");
|
|
}
|
|
let schema;
|
|
if (lx.peek().type === "ident" && lx.peek().value === "using") {
|
|
lx.next();
|
|
schema = expect("ident").value;
|
|
}
|
|
actions.push({ name: actionName, args, schema, body: lx.readBalancedBraces() });
|
|
break;
|
|
}
|
|
case "api": {
|
|
lx.next();
|
|
const method = expect("ident").value.toUpperCase();
|
|
const path = lx.readPath();
|
|
const body = lx.readBalancedBraces();
|
|
apis.push({ method, path, body });
|
|
break;
|
|
}
|
|
case "ssr":
|
|
case "client":
|
|
case "server": {
|
|
const rawMode = kw.value;
|
|
const mode = rawMode === "client" ? "client" : "ssr";
|
|
lx.next();
|
|
if ((rawMode === "client" || rawMode === "server") && lx.peek().type === "ident" && lx.peek().value === "state") {
|
|
lx.next();
|
|
if (lx.peek().type !== "lbrace")
|
|
throw new ParseError(`Expected a grouped ${rawMode} state block`);
|
|
states.push(...(0, v060_ts_1.parseStateDeclarations)(lx.readBalancedBraces(), rawMode));
|
|
break;
|
|
}
|
|
if (mode === "client" && lx.peek().type === "eq") {
|
|
lx.next();
|
|
hydrate = expect("string").value;
|
|
break;
|
|
}
|
|
expect("lbrace");
|
|
while (lx.peek().type !== "rbrace") {
|
|
const member = lx.peek();
|
|
if (member.type === "eof") {
|
|
throw new ParseError(`Unexpected end of input inside ${mode} block`);
|
|
}
|
|
if (member.type !== "ident") {
|
|
throw new ParseError(`Expected a ${mode} member keyword at offset ${member.pos}`);
|
|
}
|
|
switch (member.value) {
|
|
case "api": {
|
|
lx.next();
|
|
const name2 = expect("ident").value;
|
|
const method = expect("ident").value.toUpperCase();
|
|
const path = lx.readPath();
|
|
const body = lx.readBalancedBraces();
|
|
dataApis.push({ mode, name: name2, method, path, body });
|
|
break;
|
|
}
|
|
case "functions": {
|
|
lx.next();
|
|
modeFunctions.push({ mode, body: lx.readBalancedBraces() });
|
|
break;
|
|
}
|
|
default:
|
|
throw new ParseError(`Unknown ${mode} member '${member.value}' at offset ${member.pos}`);
|
|
}
|
|
}
|
|
expect("rbrace");
|
|
break;
|
|
}
|
|
case "shared": {
|
|
lx.next();
|
|
const member = expect("ident");
|
|
if (member.value !== "state")
|
|
throw new ParseError(`Expected 'state' after shared at offset ${member.pos}`);
|
|
states.push(...(0, v060_ts_1.parseStateDeclarations)(lx.readBalancedBraces(), "shared"));
|
|
break;
|
|
}
|
|
case "realtime": {
|
|
lx.next();
|
|
const rName = expect("ident").value;
|
|
expect("lbrace");
|
|
const handlers = [];
|
|
while (lx.peek().type !== "rbrace") {
|
|
expectKeyword("on");
|
|
const event = expect("ident").value;
|
|
expect("lparen");
|
|
const args = [];
|
|
while (lx.peek().type !== "rparen") {
|
|
args.push(expect("ident").value);
|
|
if (lx.peek().type === "comma")
|
|
lx.next();
|
|
}
|
|
expect("rparen");
|
|
handlers.push({ event, args, body: lx.readBalancedBraces() });
|
|
}
|
|
expect("rbrace");
|
|
realtimes.push({ name: rName, handlers });
|
|
break;
|
|
}
|
|
case "style": {
|
|
lx.next();
|
|
styles.push(lx.readBalancedBraces());
|
|
break;
|
|
}
|
|
case "lifecycle": {
|
|
lx.next();
|
|
const body = lx.readBalancedBraces();
|
|
if (kind === "global-store" || kind === "page-store") {
|
|
storeLifecycle = (0, v060_ts_1.parseStoreLifecycle)(body);
|
|
const allowedStoreHooks = new Set(["serverInit", "clientInit", "hydrate", "dispose"]);
|
|
const hookLexer = new tokenizer_ts_1.Lexer(body);
|
|
while (hookLexer.peek().type !== "eof") {
|
|
const token = hookLexer.next();
|
|
if (token.type !== "ident") {
|
|
throw new ParseError(`Expected a lifecycle hook at offset ${token.pos}`);
|
|
}
|
|
if (!allowedStoreHooks.has(token.value)) {
|
|
throw new ParseError(`Unknown store lifecycle hook '${token.value}'`);
|
|
}
|
|
hookLexer.readBalancedBraces();
|
|
}
|
|
} else {
|
|
const allowedComponentHooks = new Set([
|
|
"mount",
|
|
"update",
|
|
"unmount",
|
|
"clientInit",
|
|
"dispose"
|
|
]);
|
|
const hookLexer = new tokenizer_ts_1.Lexer(body);
|
|
while (hookLexer.peek().type !== "eof") {
|
|
const token = hookLexer.next();
|
|
if (token.type !== "ident") {
|
|
throw new ParseError(`Expected a lifecycle hook at offset ${token.pos}`);
|
|
}
|
|
if (!allowedComponentHooks.has(token.value)) {
|
|
throw new ParseError(`Unknown lifecycle hook '${token.value}'`);
|
|
}
|
|
const hookBody = hookLexer.readBalancedBraces();
|
|
const hook = token.value === "clientInit" ? "mount" : token.value === "dispose" ? "unmount" : token.value;
|
|
if (lifecycle[hook] !== undefined) {
|
|
throw new ParseError(`Duplicate lifecycle hook '${hook}'`);
|
|
}
|
|
lifecycle[hook] = hookBody;
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case "watch": {
|
|
lx.next();
|
|
const stateName = expect("ident").value;
|
|
const body = lx.readBalancedBraces();
|
|
watches.push({
|
|
state: stateName,
|
|
body
|
|
});
|
|
break;
|
|
}
|
|
case "functions": {
|
|
lx.next();
|
|
const body = lx.readBalancedBraces();
|
|
functions.push(body);
|
|
try {
|
|
runtimeFunctions.push(...(0, v060_ts_1.parseRuntimeFunctions)(body));
|
|
} catch (error) {
|
|
throw new ParseError(error instanceof Error ? error.message : String(error), "WRN-FUNCTION-DECLARATION");
|
|
}
|
|
break;
|
|
}
|
|
case "persist": {
|
|
lx.next();
|
|
persist = (0, v060_ts_1.parsePersist)(lx.readBalancedBraces());
|
|
break;
|
|
}
|
|
default:
|
|
throw new ParseError(`Unknown page member '${kw.value}' at offset ${kw.pos}`);
|
|
}
|
|
}
|
|
expect("rbrace");
|
|
const declaredStates = new Set(states.map((state) => state.name));
|
|
for (const watcher of watches) {
|
|
if (!declaredStates.has(watcher.state)) {
|
|
throw new ParseError(`Cannot watch undeclared state '${watcher.state}'`);
|
|
}
|
|
}
|
|
for (const prop of props) {
|
|
const problem = (0, types_ts_1.validateTypedInitializer)(`Prop '${prop.name}'`, prop.valueType, prop.default);
|
|
if (problem)
|
|
throw new ParseError(problem);
|
|
}
|
|
for (const state of states) {
|
|
const problem = (0, types_ts_1.validateTypedInitializer)(`State '${state.name}'`, state.valueType, state.expr);
|
|
if (problem)
|
|
throw new ParseError(problem);
|
|
}
|
|
const symbols = new Set;
|
|
for (const declaration of [...props, ...states, ...computed]) {
|
|
if (symbols.has(declaration.name)) {
|
|
throw new ParseError(`Duplicate symbol '${declaration.name}'`, "WRN-SYMBOL-DUPLICATE");
|
|
}
|
|
symbols.add(declaration.name);
|
|
}
|
|
const outputNames = new Set;
|
|
for (const output of outputs) {
|
|
if (outputNames.has(output.name))
|
|
throw new ParseError(`Duplicate output '${output.name}'`, "WRN-OUTPUT-DUPLICATE");
|
|
outputNames.add(output.name);
|
|
}
|
|
const functionKeys = new Set;
|
|
for (const fn of runtimeFunctions) {
|
|
const key = `${fn.runtime}:${fn.name}`;
|
|
if (functionKeys.has(key))
|
|
throw new ParseError(`Duplicate ${fn.runtime} function '${fn.name}'`, "WRN-FUNCTION-DUPLICATE");
|
|
functionKeys.add(key);
|
|
}
|
|
const namedLoads = new Map(loads.filter((load) => load.name).map((load) => [load.name, load]));
|
|
for (const load of namedLoads.values()) {
|
|
for (const dependency of load.dependsOn ?? []) {
|
|
const dependencyLoad = namedLoads.get(dependency);
|
|
if (!dependencyLoad)
|
|
throw new ParseError(`Load '${load.name}' depends on unknown load '${dependency}'`, "WRN-LOAD-DEPENDENCY");
|
|
if (load.mode === "server" && !load.deferred && (dependencyLoad.mode !== "server" || dependencyLoad.deferred))
|
|
throw new ParseError(`Server load '${load.name}' cannot depend on deferred/client load '${dependency}'`, "WRN-LOAD-PHASE");
|
|
}
|
|
}
|
|
const visiting = new Set;
|
|
const visited = new Set;
|
|
const visitLoad = (name2) => {
|
|
if (visiting.has(name2))
|
|
throw new ParseError(`Load dependency cycle includes '${name2}'`, "WRN-LOAD-CYCLE");
|
|
if (visited.has(name2))
|
|
return;
|
|
visiting.add(name2);
|
|
for (const dependency of namedLoads.get(name2)?.dependsOn ?? [])
|
|
visitLoad(dependency);
|
|
visiting.delete(name2);
|
|
visited.add(name2);
|
|
};
|
|
for (const name2 of namedLoads.keys())
|
|
visitLoad(name2);
|
|
return {
|
|
type: "page",
|
|
imports,
|
|
structuredImports: (0, v060_ts_1.parseStructuredImports)(imports),
|
|
kind,
|
|
storeKind,
|
|
name,
|
|
layout,
|
|
layoutIsSymbol,
|
|
runtime,
|
|
renderMode,
|
|
hydrate,
|
|
cache,
|
|
props,
|
|
events,
|
|
outputs,
|
|
types,
|
|
states,
|
|
computed,
|
|
effects,
|
|
loads,
|
|
actions,
|
|
security,
|
|
navigation,
|
|
seo,
|
|
view,
|
|
styles,
|
|
functions,
|
|
runtimeFunctions,
|
|
dataApis,
|
|
modeFunctions,
|
|
lifecycle,
|
|
storeLifecycle,
|
|
persist,
|
|
watches,
|
|
apis,
|
|
realtimes
|
|
};
|
|
} catch (err) {
|
|
if (err instanceof tokenizer_ts_1.LexError)
|
|
throw new ParseError(err.message);
|
|
throw err;
|
|
}
|
|
}
|
|
function parseHtmlView(src, pos) {
|
|
let i = pos;
|
|
const isNameStart = (c) => /[A-Za-z_]/.test(c);
|
|
const isTagNamePart = (c) => /[A-Za-z0-9_$:.-]/.test(c);
|
|
const isWs = (c) => c === " " || c === "\t" || c === `
|
|
` || c === "\r";
|
|
const fail = (msg) => {
|
|
throw new ParseError(`${msg} at offset ${i}`);
|
|
};
|
|
const skipWs = () => {
|
|
while (i < src.length && isWs(src[i]))
|
|
i++;
|
|
};
|
|
const readInterpolation = () => {
|
|
const start = i;
|
|
let depth = 0;
|
|
let quote = null;
|
|
for (;i < src.length; i++) {
|
|
const char = src[i];
|
|
if (quote) {
|
|
if (char === "\\" && i + 1 < src.length) {
|
|
i++;
|
|
continue;
|
|
}
|
|
if (char === quote)
|
|
quote = null;
|
|
continue;
|
|
}
|
|
if (char === '"' || char === "'" || char === "`") {
|
|
quote = char;
|
|
continue;
|
|
}
|
|
if (char === "{")
|
|
depth++;
|
|
else if (char === "}" && --depth === 0) {
|
|
i++;
|
|
return src.slice(start, i);
|
|
}
|
|
}
|
|
return fail("Unterminated `{` interpolation in view");
|
|
};
|
|
const readQuoted = () => {
|
|
const quote = src[i];
|
|
if (quote !== '"' && quote !== "'")
|
|
return fail("Expected a quoted attribute value");
|
|
i++;
|
|
const start = i;
|
|
while (i < src.length && src[i] !== quote)
|
|
i++;
|
|
if (i >= src.length)
|
|
return fail("Unterminated attribute value");
|
|
const value = src.slice(start, i);
|
|
i++;
|
|
return value;
|
|
};
|
|
const readTagName = () => {
|
|
if (i >= src.length || !isNameStart(src[i])) {
|
|
return fail("Expected a tag name");
|
|
}
|
|
const start = i++;
|
|
while (i < src.length && isTagNamePart(src[i])) {
|
|
i++;
|
|
}
|
|
return src.slice(start, i);
|
|
};
|
|
const readAttributeName = () => {
|
|
if (i >= src.length) {
|
|
return fail("Expected an attribute name");
|
|
}
|
|
const start = i;
|
|
while (i < src.length) {
|
|
const char = src[i];
|
|
const next = src[i + 1];
|
|
if (char === "=" || char === ">" || char === '"' || char === "'" || char === " " || char === "\t" || char === `
|
|
` || char === "\r" || char === "/" && next === ">") {
|
|
break;
|
|
}
|
|
i++;
|
|
}
|
|
if (i === start) {
|
|
return fail("Expected an attribute name");
|
|
}
|
|
return src.slice(start, i);
|
|
};
|
|
const parseTag = () => {
|
|
i++;
|
|
const tag = readTagName();
|
|
const attrs = [];
|
|
for (;; ) {
|
|
skipWs();
|
|
const c = src[i];
|
|
if (c === undefined)
|
|
return fail(`Unterminated <${tag}> tag`);
|
|
if (c === ">") {
|
|
i++;
|
|
break;
|
|
}
|
|
if (c === "/" && src[i + 1] === ">") {
|
|
i += 2;
|
|
return { type: "element", tag, attrs, children: [] };
|
|
}
|
|
if (c === "@") {
|
|
i++;
|
|
const name2 = readAttributeName();
|
|
skipWs();
|
|
if (src[i] !== "=")
|
|
return fail(`Expected '=' after @${name2}`);
|
|
i++;
|
|
skipWs();
|
|
attrs.push({ name: name2, value: readQuoted(), event: true });
|
|
continue;
|
|
}
|
|
const name = readAttributeName();
|
|
skipWs();
|
|
if (src[i] === "=") {
|
|
i++;
|
|
skipWs();
|
|
const value = src[i] === '"' || src[i] === "'" ? readQuoted() : src[i] === "{" ? readInterpolation() : fail(`Expected a quoted value or {...} expression after '${name}='`);
|
|
attrs.push({ name, value, event: false });
|
|
} else {
|
|
attrs.push({ name, value: "", event: false, boolean: true });
|
|
}
|
|
}
|
|
if (exports3.VOID_ELEMENTS.has(tag.toLowerCase())) {
|
|
return { type: "element", tag, attrs, children: [] };
|
|
}
|
|
const children = parseNodeList("element");
|
|
if (src[i] !== "<" || src[i + 1] !== "/")
|
|
return fail(`Expected </${tag}>`);
|
|
i += 2;
|
|
skipWs();
|
|
const close = readTagName();
|
|
if (close !== tag)
|
|
return fail(`Mismatched </${close}>, expected </${tag}>`);
|
|
skipWs();
|
|
if (src[i] !== ">")
|
|
return fail(`Expected '>' to close </${tag}>`);
|
|
i++;
|
|
return { type: "element", tag, attrs, children };
|
|
};
|
|
const EACH_HEADER = /^\{#each\s+([\s\S]+?)\s+as\s+([A-Za-z_$][\w$]*)\s*(?:,\s*([A-Za-z_$][\w$]*))?(?:\s+key\s+([\s\S]+?))?\s*\}$/;
|
|
function parseEach() {
|
|
const header = readInterpolation();
|
|
const m = EACH_HEADER.exec(header);
|
|
if (!m)
|
|
return fail(`Invalid {#each …} header: ${header}`);
|
|
const list = m[1].trim();
|
|
const item = m[2];
|
|
const index = m[3];
|
|
const key = m[4]?.trim();
|
|
const body = parseNodeList("each");
|
|
let empty = [];
|
|
if (src.startsWith("{:empty}", i)) {
|
|
i += "{:empty}".length;
|
|
empty = parseNodeList("each");
|
|
}
|
|
if (!src.startsWith("{/each}", i))
|
|
return fail("Expected `{/each}` to close `{#each}`");
|
|
i += "{/each}".length;
|
|
return { type: "each", list, item, index, key, body, empty };
|
|
}
|
|
function parseIf() {
|
|
const header = readInterpolation();
|
|
const m = /^\{#if\s+([\s\S]+?)\s*\}$/.exec(header);
|
|
if (!m)
|
|
return fail(`Invalid {#if …} header: ${header}`);
|
|
const branches = [
|
|
{ cond: m[1].trim(), body: parseNodeList("if") }
|
|
];
|
|
for (;; ) {
|
|
if (src.startsWith("{:else if", i)) {
|
|
const h = readInterpolation();
|
|
const mm = /^\{:else if\s+([\s\S]+?)\s*\}$/.exec(h);
|
|
if (!mm)
|
|
return fail(`Invalid {:else if …}: ${h}`);
|
|
branches.push({ cond: mm[1].trim(), body: parseNodeList("if") });
|
|
continue;
|
|
}
|
|
if (src.startsWith("{:else}", i)) {
|
|
i += "{:else}".length;
|
|
branches.push({ cond: null, body: parseNodeList("if") });
|
|
continue;
|
|
}
|
|
break;
|
|
}
|
|
if (!src.startsWith("{/if}", i))
|
|
return fail("Expected `{/if}` to close `{#if}`");
|
|
i += "{/if}".length;
|
|
return { type: "if", branches };
|
|
}
|
|
function parseNodeList(mode) {
|
|
const nodes2 = [];
|
|
let text = "";
|
|
const flush = () => {
|
|
if (text.length > 0) {
|
|
nodes2.push({ type: "text", value: text });
|
|
text = "";
|
|
}
|
|
};
|
|
for (;; ) {
|
|
if (i >= src.length) {
|
|
return mode === "root" ? fail("Unexpected end of view (missing `}`)") : fail("Unclosed block");
|
|
}
|
|
const c = src[i];
|
|
if (c === "<") {
|
|
const next = src[i + 1];
|
|
if (next === "/") {
|
|
flush();
|
|
break;
|
|
}
|
|
if (src.startsWith("<!--", i)) {
|
|
const end = src.indexOf("-->", i + 4);
|
|
i = end === -1 ? src.length : end + 3;
|
|
continue;
|
|
}
|
|
if (next !== undefined && (isNameStart(next) || next === "!")) {
|
|
flush();
|
|
nodes2.push(parseTag());
|
|
continue;
|
|
}
|
|
text += c;
|
|
i++;
|
|
continue;
|
|
}
|
|
if (c === "{") {
|
|
if (src.startsWith("{#each", i)) {
|
|
flush();
|
|
nodes2.push(parseEach());
|
|
continue;
|
|
}
|
|
if (src.startsWith("{#if", i)) {
|
|
flush();
|
|
nodes2.push(parseIf());
|
|
continue;
|
|
}
|
|
if (mode === "each" && (src.startsWith("{:empty}", i) || src.startsWith("{/each}", i))) {
|
|
flush();
|
|
break;
|
|
}
|
|
if (mode === "if" && (src.startsWith("{:else", i) || src.startsWith("{/if}", i))) {
|
|
flush();
|
|
break;
|
|
}
|
|
text += readInterpolation();
|
|
continue;
|
|
}
|
|
if (c === "}" && mode === "root") {
|
|
flush();
|
|
break;
|
|
}
|
|
text += c;
|
|
i++;
|
|
}
|
|
return nodes2;
|
|
}
|
|
const nodes = parseNodeList("root");
|
|
return { nodes, endPos: i };
|
|
}
|
|
},
|
|
"packages/syntax/src/spec.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.WRN_DIAGNOSTIC_CODES = exports3.WRN_RUNTIME_TARGETS = exports3.WRN_HYDRATION_STRATEGIES = exports3.WRN_ROOT_MEMBERS = exports3.WRN_ROOT_KINDS = exports3.WRN_LANGUAGE_VERSION = undefined;
|
|
exports3.WRN_LANGUAGE_VERSION = "0.6";
|
|
exports3.WRN_ROOT_KINDS = [
|
|
"page",
|
|
"component",
|
|
"layout",
|
|
"global-store",
|
|
"page-store"
|
|
];
|
|
exports3.WRN_ROOT_MEMBERS = [
|
|
"layout",
|
|
"runtime",
|
|
"hydrate",
|
|
"client",
|
|
"types",
|
|
"props",
|
|
"outputs",
|
|
"state",
|
|
"shared",
|
|
"server",
|
|
"computed",
|
|
"effect",
|
|
"watch",
|
|
"lifecycle",
|
|
"view",
|
|
"seo",
|
|
"security",
|
|
"load",
|
|
"action",
|
|
"api",
|
|
"ssr",
|
|
"realtime",
|
|
"style",
|
|
"functions",
|
|
"persist"
|
|
];
|
|
exports3.WRN_HYDRATION_STRATEGIES = ["load", "idle", "visible", "interaction", "none"];
|
|
exports3.WRN_RUNTIME_TARGETS = [
|
|
"server",
|
|
"client",
|
|
"universal",
|
|
"edge",
|
|
"worker",
|
|
"service-worker"
|
|
];
|
|
exports3.WRN_DIAGNOSTIC_CODES = {
|
|
parse: "WRN-PARSE-001",
|
|
root: "WRN-PARSE-ROOT",
|
|
member: "WRN-PARSE-MEMBER",
|
|
propInitializer: "WRN-PROP-INITIALIZER",
|
|
stateInitializer: "WRN-STATE-INITIALIZER",
|
|
watchUndeclared: "WRN-WATCH-UNDECLARED",
|
|
duplicateSymbol: "WRN-SYMBOL-DUPLICATE",
|
|
invalidHydration: "WRN-HYDRATE-STRATEGY",
|
|
invalidRuntime: "WRN-RUNTIME-TARGET",
|
|
serverInteractive: "WRN-RUNTIME-SERVER-INTERACTIVE",
|
|
accessibility: "WRN-A11Y-001",
|
|
import: "WRN-IMPORT-001",
|
|
function: "WRN-FUNCTION-001",
|
|
client: "WRN-CLIENT-001",
|
|
server: "WRN-SERVER-001",
|
|
output: "WRN-OUTPUT-001",
|
|
type: "WRN-TYPE-001",
|
|
state: "WRN-STATE-001",
|
|
component: "WRN-COMPONENT-001",
|
|
template: "WRN-TEMPLATE-001",
|
|
store: "WRN-STORE-001",
|
|
persist: "WRN-PERSIST-001",
|
|
rpc: "WRN-RPC-001",
|
|
hydration: "WRN-HYDRATION-001",
|
|
migration: "WRN-MIGRATION-001"
|
|
};
|
|
},
|
|
"packages/syntax/src/tokenizer.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.Lexer = exports3.LexError = undefined;
|
|
|
|
class LexError extends Error {
|
|
}
|
|
exports3.LexError = LexError;
|
|
const isWs = (c) => c === " " || c === "\t" || c === `
|
|
` || c === "\r";
|
|
const isIdentStart = (c) => /[A-Za-z_]/.test(c);
|
|
const isIdentPart = (c) => /[A-Za-z0-9_]/.test(c);
|
|
|
|
class Lexer {
|
|
src;
|
|
pos = 0;
|
|
constructor(src) {
|
|
this.src = src;
|
|
}
|
|
skipTrivia() {
|
|
const { src } = this;
|
|
while (this.pos < src.length) {
|
|
const c = src[this.pos];
|
|
if (isWs(c)) {
|
|
this.pos++;
|
|
continue;
|
|
}
|
|
if (c === "/" && src[this.pos + 1] === "/") {
|
|
while (this.pos < src.length && src[this.pos] !== `
|
|
`)
|
|
this.pos++;
|
|
continue;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
next() {
|
|
this.skipTrivia();
|
|
const { src } = this;
|
|
const pos = this.pos;
|
|
if (pos >= src.length)
|
|
return { type: "eof", value: "", pos };
|
|
const c = src[pos];
|
|
switch (c) {
|
|
case "{":
|
|
this.pos++;
|
|
return { type: "lbrace", value: c, pos };
|
|
case "}":
|
|
this.pos++;
|
|
return { type: "rbrace", value: c, pos };
|
|
case "(":
|
|
this.pos++;
|
|
return { type: "lparen", value: c, pos };
|
|
case ")":
|
|
this.pos++;
|
|
return { type: "rparen", value: c, pos };
|
|
case "@":
|
|
this.pos++;
|
|
return { type: "at", value: c, pos };
|
|
case "=":
|
|
this.pos++;
|
|
return { type: "eq", value: c, pos };
|
|
case ":":
|
|
this.pos++;
|
|
return { type: "colon", value: c, pos };
|
|
case ",":
|
|
this.pos++;
|
|
return { type: "comma", value: c, pos };
|
|
case "?":
|
|
this.pos++;
|
|
return { type: "question", value: c, pos };
|
|
case '"':
|
|
case "'":
|
|
return this.readString(c, pos);
|
|
}
|
|
if (isIdentStart(c)) {
|
|
let v = "";
|
|
while (this.pos < src.length && isIdentPart(src[this.pos]))
|
|
v += src[this.pos++];
|
|
return { type: "ident", value: v, pos };
|
|
}
|
|
throw new LexError(`Unexpected character '${c}' at offset ${pos} (line ${this.lineAt(pos)})`);
|
|
}
|
|
peek() {
|
|
const save = this.pos;
|
|
const t = this.next();
|
|
this.pos = save;
|
|
return t;
|
|
}
|
|
readString(quote, pos) {
|
|
const { src } = this;
|
|
let v = "";
|
|
this.pos++;
|
|
while (this.pos < src.length) {
|
|
const c = src[this.pos++];
|
|
if (c === "\\") {
|
|
const n = src[this.pos++];
|
|
v += n === "n" ? `
|
|
` : n === "t" ? "\t" : n;
|
|
continue;
|
|
}
|
|
if (c === quote)
|
|
return { type: "string", value: v, pos };
|
|
v += c;
|
|
}
|
|
throw new LexError(`Unterminated string at offset ${pos}`);
|
|
}
|
|
readPath() {
|
|
this.skipTrivia();
|
|
const { src } = this;
|
|
let v = "";
|
|
while (this.pos < src.length && !isWs(src[this.pos]) && src[this.pos] !== "{") {
|
|
v += src[this.pos++];
|
|
}
|
|
if (!v)
|
|
throw new LexError(`Expected a path at offset ${this.pos}`);
|
|
return v;
|
|
}
|
|
readPropInitializer() {
|
|
const { src } = this;
|
|
while (this.pos < src.length && (src[this.pos] === " " || src[this.pos] === "\t")) {
|
|
this.pos++;
|
|
}
|
|
const start = this.pos;
|
|
let square = 0;
|
|
let brace = 0;
|
|
let paren = 0;
|
|
let angle = 0;
|
|
let quote = null;
|
|
const atTopLevel = () => square === 0 && brace === 0 && paren === 0 && angle === 0;
|
|
while (this.pos < src.length) {
|
|
const c = src[this.pos];
|
|
if (quote) {
|
|
this.pos++;
|
|
if (c === "\\" && this.pos < src.length) {
|
|
this.pos++;
|
|
} else if (c === quote) {
|
|
quote = null;
|
|
}
|
|
continue;
|
|
}
|
|
if (c === '"' || c === "'" || c === "`") {
|
|
quote = c;
|
|
this.pos++;
|
|
continue;
|
|
}
|
|
if (atTopLevel()) {
|
|
if (c === `
|
|
` || c === "\r" || c === "}")
|
|
break;
|
|
if (c === " " || c === "\t") {
|
|
let look = this.pos;
|
|
while (look < src.length && (src[look] === " " || src[look] === "\t"))
|
|
look++;
|
|
const rest = src.slice(look);
|
|
if (/^[A-Za-z_][A-Za-z0-9_]*(?:\s*:[^=\r\n{}]+)?\s*=/.test(rest))
|
|
break;
|
|
}
|
|
}
|
|
if (c === "[")
|
|
square++;
|
|
else if (c === "]" && square > 0)
|
|
square--;
|
|
else if (c === "{")
|
|
brace++;
|
|
else if (c === "}" && brace > 0)
|
|
brace--;
|
|
else if (c === "(")
|
|
paren++;
|
|
else if (c === ")" && paren > 0)
|
|
paren--;
|
|
else if (c === "<")
|
|
angle++;
|
|
else if (c === ">" && angle > 0)
|
|
angle--;
|
|
this.pos++;
|
|
}
|
|
const value = src.slice(start, this.pos).trim();
|
|
if (!value)
|
|
throw new LexError(`Expected a prop initializer at offset ${start}`);
|
|
return value;
|
|
}
|
|
readToLineEnd() {
|
|
const { src } = this;
|
|
let v = "";
|
|
while (this.pos < src.length && src[this.pos] !== `
|
|
`)
|
|
v += src[this.pos++];
|
|
return v.trim();
|
|
}
|
|
readTypeAnnotation() {
|
|
const { src } = this;
|
|
let value = "";
|
|
let angle = 0;
|
|
let square = 0;
|
|
let brace = 0;
|
|
let paren = 0;
|
|
let quote = null;
|
|
while (this.pos < src.length) {
|
|
const c = src[this.pos];
|
|
if (quote) {
|
|
value += c;
|
|
this.pos++;
|
|
if (c === "\\" && this.pos < src.length)
|
|
value += src[this.pos++];
|
|
else if (c === quote)
|
|
quote = null;
|
|
continue;
|
|
}
|
|
if (c === '"' || c === "'" || c === "`") {
|
|
quote = c;
|
|
value += c;
|
|
this.pos++;
|
|
continue;
|
|
}
|
|
if (c === "}" && angle === 0 && square === 0 && brace === 0 && paren === 0)
|
|
break;
|
|
if (c === "<")
|
|
angle++;
|
|
else if (c === ">" && angle > 0)
|
|
angle--;
|
|
else if (c === "[")
|
|
square++;
|
|
else if (c === "]" && square > 0)
|
|
square--;
|
|
else if (c === "{")
|
|
brace++;
|
|
else if (c === "}" && brace > 0)
|
|
brace--;
|
|
else if (c === "(")
|
|
paren++;
|
|
else if (c === ")" && paren > 0)
|
|
paren--;
|
|
if (angle === 0 && square === 0 && brace === 0 && paren === 0) {
|
|
if (c === " " || c === "\t") {
|
|
let look = this.pos;
|
|
while (look < src.length && (src[look] === " " || src[look] === "\t"))
|
|
look++;
|
|
if (/^[A-Za-z_][A-Za-z0-9_]*\??\s*:/.test(src.slice(look)))
|
|
break;
|
|
}
|
|
if (c === "=") {
|
|
this.pos++;
|
|
const type2 = value.trim();
|
|
if (!type2)
|
|
throw new LexError(`Expected a type annotation at offset ${this.pos}`);
|
|
return { type: type2, hasDefault: true };
|
|
}
|
|
if (c === `
|
|
` || c === "\r")
|
|
break;
|
|
}
|
|
value += c;
|
|
this.pos++;
|
|
}
|
|
const type = value.trim();
|
|
if (!type)
|
|
throw new LexError(`Expected a type annotation at offset ${this.pos}`);
|
|
return { type, hasDefault: false };
|
|
}
|
|
readBalancedBraces() {
|
|
this.skipTrivia();
|
|
const { src } = this;
|
|
if (src[this.pos] !== "{") {
|
|
throw new LexError(`Expected '{' at offset ${this.pos}`);
|
|
}
|
|
const start = this.pos + 1;
|
|
let depth = 0;
|
|
let i = this.pos;
|
|
let str = null;
|
|
let atLineStart = false;
|
|
for (;i < src.length; i++) {
|
|
const c = src[i];
|
|
if (str) {
|
|
if (c === "\\") {
|
|
i++;
|
|
continue;
|
|
}
|
|
if (c === str)
|
|
str = null;
|
|
continue;
|
|
}
|
|
if (c === `
|
|
`) {
|
|
atLineStart = true;
|
|
continue;
|
|
}
|
|
if (c === "/" && src[i + 1] === "*") {
|
|
const close = src.indexOf("*/", i + 2);
|
|
if (close === -1)
|
|
break;
|
|
i = close + 1;
|
|
atLineStart = false;
|
|
continue;
|
|
}
|
|
if (atLineStart && c === "/" && src[i + 1] === "/") {
|
|
const newline = src.indexOf(`
|
|
`, i + 2);
|
|
if (newline === -1)
|
|
break;
|
|
i = newline - 1;
|
|
continue;
|
|
}
|
|
if (c !== " " && c !== "\t" && c !== "\r")
|
|
atLineStart = false;
|
|
if (c === '"' || c === "'" || c === "`") {
|
|
str = c;
|
|
continue;
|
|
}
|
|
if (c === "{")
|
|
depth++;
|
|
else if (c === "}") {
|
|
depth--;
|
|
if (depth === 0) {
|
|
this.pos = i + 1;
|
|
return src.slice(start, i);
|
|
}
|
|
}
|
|
}
|
|
throw new LexError(`Unbalanced braces starting at offset ${this.pos}`);
|
|
}
|
|
lineAt(pos) {
|
|
let line = 1;
|
|
for (let i = 0;i < pos && i < this.src.length; i++) {
|
|
if (this.src[i] === `
|
|
`)
|
|
line++;
|
|
}
|
|
return line;
|
|
}
|
|
}
|
|
exports3.Lexer = Lexer;
|
|
},
|
|
"packages/syntax/src/types.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.runtimeTypeOf = runtimeTypeOf;
|
|
exports3.inferredRuntimeType = inferredRuntimeType;
|
|
exports3.validateTypedInitializer = validateTypedInitializer;
|
|
exports3.eraseFunctionTypes = eraseFunctionTypes;
|
|
function runtimeTypeOf(annotation) {
|
|
if (!annotation)
|
|
return "unknown";
|
|
const type = annotation.trim().replace(/^readonly\s+/, "");
|
|
const unionParts = type.split("|").map((part) => part.trim());
|
|
const concreteParts = unionParts.filter((part) => !/^(?:null|undefined)$/.test(part));
|
|
if (/^(?:string|String)(?:\s*\|\s*(?:null|undefined))*$/.test(type) || concreteParts.length > 0 && concreteParts.every((part) => /^(?:"[^"]*"|'[^']*')$/.test(part)))
|
|
return "string";
|
|
if (/^(?:number|Number)(?:\s*\|\s*(?:null|undefined))*$/.test(type) || concreteParts.length > 0 && concreteParts.every((part) => /^-?(?:\d+\.?\d*|\.\d+)$/.test(part)))
|
|
return "number";
|
|
if (/^(?:boolean|Boolean)(?:\s*\|\s*(?:null|undefined))*$/.test(type) || concreteParts.length > 0 && concreteParts.every((part) => /^(?:true|false)$/.test(part)))
|
|
return "boolean";
|
|
if (/^bigint(?:\s*\|\s*(?:null|undefined))*$/.test(type))
|
|
return "bigint";
|
|
if (/^(?:Array\s*<|ReadonlyArray\s*<|.+\[\])/.test(type) || /^\[/.test(type))
|
|
return "array";
|
|
if (/^(?:Record\s*<|object\b|\{)/.test(type))
|
|
return "object";
|
|
if (/=>|^(?:Function|\([^)]*\)\s*=>)/.test(type))
|
|
return "function";
|
|
return "unknown";
|
|
}
|
|
function inferredRuntimeType(expression) {
|
|
const value = expression.trim();
|
|
if (/^["'`]/.test(value))
|
|
return "string";
|
|
if (/^-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(value))
|
|
return "number";
|
|
if (/^(?:true|false)$/.test(value))
|
|
return "boolean";
|
|
if (/^-?\d+n$/.test(value))
|
|
return "bigint";
|
|
if (value.startsWith("["))
|
|
return "array";
|
|
if (value.startsWith("{") || /^new\s+(?:Map|Set|Date)\b/.test(value))
|
|
return "object";
|
|
if (/^(?:async\s+)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/.test(value)) {
|
|
return "function";
|
|
}
|
|
return "unknown";
|
|
}
|
|
function validateTypedInitializer(name, annotation, expression) {
|
|
if (!annotation || expression.trim() === "undefined" || expression.trim() === "null")
|
|
return null;
|
|
const expected = runtimeTypeOf(annotation);
|
|
const actual = inferredRuntimeType(expression);
|
|
if (expected === "unknown" || actual === "unknown" || expected === actual)
|
|
return null;
|
|
return `${name} is declared as ${annotation}, but its initializer is ${actual}`;
|
|
}
|
|
function eraseFunctionTypes(source) {
|
|
return source.replace(/(\b(?:async\s+)?function\s+[A-Za-z_$][\w$]*\s*\()([^)]*)(\)\s*)(?::\s*([^{}=>]+)\s*)?(\{)/g, (_whole, open, params, close, _returnType, brace) => {
|
|
const plainParams = params.split(",").map((param) => param.replace(/([A-Za-z_$][\w$]*)(\?)?\s*:\s*([^=]+?)(?=\s*=|$)/, "$1").trim()).join(", ");
|
|
return `${open}${plainParams}${close}${brace}`;
|
|
});
|
|
}
|
|
},
|
|
"packages/syntax/src/v060.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.parseRuntimeFunctions = parseRuntimeFunctions;
|
|
exports3.stripRuntimeFunctionModifiers = stripRuntimeFunctionModifiers;
|
|
exports3.parseOutputs = parseOutputs;
|
|
exports3.parseStructuredImports = parseStructuredImports;
|
|
exports3.parseStateDeclarations = parseStateDeclarations;
|
|
exports3.parseComputedDeclarations = parseComputedDeclarations;
|
|
exports3.parsePersist = parsePersist;
|
|
exports3.parseStoreLifecycle = parseStoreLifecycle;
|
|
const tokenizer_ts_1 = require2("./tokenizer.js");
|
|
function splitTopLevel(input, separator = ",") {
|
|
const parts = [];
|
|
let start = 0;
|
|
let quote = null;
|
|
let angle = 0;
|
|
let square = 0;
|
|
let brace = 0;
|
|
let paren = 0;
|
|
for (let i = 0;i < input.length; i++) {
|
|
const c = input[i];
|
|
if (quote) {
|
|
if (c === "\\")
|
|
i++;
|
|
else if (c === quote)
|
|
quote = null;
|
|
continue;
|
|
}
|
|
if (c === '"' || c === "'" || c === "`") {
|
|
quote = c;
|
|
continue;
|
|
}
|
|
if (c === "<")
|
|
angle++;
|
|
else if (c === ">" && angle > 0)
|
|
angle--;
|
|
else if (c === "[")
|
|
square++;
|
|
else if (c === "]" && square > 0)
|
|
square--;
|
|
else if (c === "{")
|
|
brace++;
|
|
else if (c === "}" && brace > 0)
|
|
brace--;
|
|
else if (c === "(")
|
|
paren++;
|
|
else if (c === ")" && paren > 0)
|
|
paren--;
|
|
else if (c === separator && angle === 0 && square === 0 && brace === 0 && paren === 0) {
|
|
parts.push(input.slice(start, i).trim());
|
|
start = i + 1;
|
|
}
|
|
}
|
|
const tail = input.slice(start).trim();
|
|
if (tail)
|
|
parts.push(tail);
|
|
return parts;
|
|
}
|
|
function findTopLevelChar(input, wanted) {
|
|
let quote = null;
|
|
let angle = 0;
|
|
let square = 0;
|
|
let brace = 0;
|
|
let paren = 0;
|
|
for (let i = 0;i < input.length; i++) {
|
|
const c = input[i];
|
|
if (quote) {
|
|
if (c === "\\")
|
|
i++;
|
|
else if (c === quote)
|
|
quote = null;
|
|
continue;
|
|
}
|
|
if (c === '"' || c === "'" || c === "`") {
|
|
quote = c;
|
|
continue;
|
|
}
|
|
if (c === "<")
|
|
angle++;
|
|
else if (c === ">" && angle > 0)
|
|
angle--;
|
|
else if (c === "[")
|
|
square++;
|
|
else if (c === "]" && square > 0)
|
|
square--;
|
|
else if (c === "{")
|
|
brace++;
|
|
else if (c === "}" && brace > 0)
|
|
brace--;
|
|
else if (c === "(")
|
|
paren++;
|
|
else if (c === ")" && paren > 0)
|
|
paren--;
|
|
if (c === wanted && angle === 0 && square === 0 && brace === 0 && paren === 0)
|
|
return i;
|
|
}
|
|
return -1;
|
|
}
|
|
function parseParameters(source) {
|
|
return splitTopLevel(source).filter(Boolean).map((entry) => {
|
|
const eq = findTopLevelChar(entry, "=");
|
|
const declaration = (eq >= 0 ? entry.slice(0, eq) : entry).trim();
|
|
const defaultValue = eq >= 0 ? entry.slice(eq + 1).trim() : undefined;
|
|
const colon = findTopLevelChar(declaration, ":");
|
|
const rawName = (colon >= 0 ? declaration.slice(0, colon) : declaration).trim();
|
|
const optional = rawName.endsWith("?");
|
|
const name = optional ? rawName.slice(0, -1).trim() : rawName;
|
|
const valueType = colon >= 0 ? declaration.slice(colon + 1).trim() : undefined;
|
|
return {
|
|
name,
|
|
optional,
|
|
...valueType ? { valueType } : {},
|
|
...defaultValue ? { default: defaultValue } : {}
|
|
};
|
|
});
|
|
}
|
|
function skipTrivia(source, start) {
|
|
let i = start;
|
|
while (i < source.length) {
|
|
if (/\s/.test(source[i])) {
|
|
i++;
|
|
continue;
|
|
}
|
|
if (source.startsWith("//", i)) {
|
|
const end = source.indexOf(`
|
|
`, i + 2);
|
|
i = end < 0 ? source.length : end + 1;
|
|
continue;
|
|
}
|
|
if (source.startsWith("/*", i)) {
|
|
const end = source.indexOf("*/", i + 2);
|
|
i = end < 0 ? source.length : end + 2;
|
|
continue;
|
|
}
|
|
break;
|
|
}
|
|
return i;
|
|
}
|
|
function readWord(source, start) {
|
|
const match = /^[A-Za-z_$][\w$]*/.exec(source.slice(start));
|
|
return match ? { word: match[0], end: start + match[0].length } : null;
|
|
}
|
|
function readBalanced(source, start, open, close) {
|
|
if (source[start] !== open)
|
|
throw new Error(`Expected '${open}' at offset ${start}`);
|
|
let depth = 0;
|
|
let quote = null;
|
|
for (let i = start;i < source.length; i++) {
|
|
const c = source[i];
|
|
if (quote) {
|
|
if (c === "\\")
|
|
i++;
|
|
else if (c === quote)
|
|
quote = null;
|
|
continue;
|
|
}
|
|
if (c === '"' || c === "'" || c === "`") {
|
|
quote = c;
|
|
continue;
|
|
}
|
|
if (c === open)
|
|
depth++;
|
|
else if (c === close && --depth === 0)
|
|
return { inner: source.slice(start + 1, i), end: i + 1 };
|
|
}
|
|
throw new Error(`Unbalanced '${open}${close}' starting at offset ${start}`);
|
|
}
|
|
function parseRuntimeFunctions(source) {
|
|
const declarations = [];
|
|
let i = 0;
|
|
while (i < source.length) {
|
|
i = skipTrivia(source, i);
|
|
const start = i;
|
|
let token = readWord(source, i);
|
|
if (!token) {
|
|
i++;
|
|
continue;
|
|
}
|
|
let runtime = "legacy";
|
|
if (["client", "server", "shared"].includes(token.word)) {
|
|
runtime = token.word;
|
|
i = skipTrivia(source, token.end);
|
|
token = readWord(source, i);
|
|
if (!token)
|
|
continue;
|
|
}
|
|
let isAsync = false;
|
|
if (token.word === "async") {
|
|
isAsync = true;
|
|
i = skipTrivia(source, token.end);
|
|
token = readWord(source, i);
|
|
if (!token)
|
|
continue;
|
|
}
|
|
if (token.word !== "function") {
|
|
i = token.end;
|
|
continue;
|
|
}
|
|
i = skipTrivia(source, token.end);
|
|
const nameToken = readWord(source, i);
|
|
if (!nameToken)
|
|
throw new Error(`Expected function name at offset ${i}`);
|
|
const name = nameToken.word;
|
|
i = skipTrivia(source, nameToken.end);
|
|
const params = readBalanced(source, i, "(", ")");
|
|
i = skipTrivia(source, params.end);
|
|
let returnType;
|
|
if (source[i] === ":") {
|
|
i++;
|
|
const typeStart = i;
|
|
let quote = null;
|
|
let angle = 0;
|
|
let square = 0;
|
|
let paren = 0;
|
|
while (i < source.length) {
|
|
const c = source[i];
|
|
if (quote) {
|
|
if (c === "\\")
|
|
i++;
|
|
else if (c === quote)
|
|
quote = null;
|
|
i++;
|
|
continue;
|
|
}
|
|
if (c === '"' || c === "'" || c === "`")
|
|
quote = c;
|
|
else if (c === "<")
|
|
angle++;
|
|
else if (c === ">" && angle > 0)
|
|
angle--;
|
|
else if (c === "[")
|
|
square++;
|
|
else if (c === "]" && square > 0)
|
|
square--;
|
|
else if (c === "(")
|
|
paren++;
|
|
else if (c === ")" && paren > 0)
|
|
paren--;
|
|
else if (c === "{" && angle === 0 && square === 0 && paren === 0)
|
|
break;
|
|
i++;
|
|
}
|
|
returnType = source.slice(typeStart, i).trim();
|
|
}
|
|
i = skipTrivia(source, i);
|
|
const body = readBalanced(source, i, "{", "}");
|
|
i = body.end;
|
|
declarations.push({
|
|
name,
|
|
runtime,
|
|
async: isAsync,
|
|
parameters: parseParameters(params.inner),
|
|
...returnType ? { returnType } : {},
|
|
body: body.inner,
|
|
source: source.slice(start, body.end).trim()
|
|
});
|
|
}
|
|
return declarations;
|
|
}
|
|
function stripRuntimeFunctionModifiers(source, include) {
|
|
const allowed = new Set(include);
|
|
return parseRuntimeFunctions(source).filter((entry) => allowed.has(entry.runtime)).map((entry) => {
|
|
const params = entry.parameters.map((param) => `${param.name}${param.optional ? "?" : ""}${param.valueType ? `: ${param.valueType}` : ""}${param.default ? ` = ${param.default}` : ""}`).join(", ");
|
|
return `${entry.async ? "async " : ""}function ${entry.name}(${params})${entry.returnType ? `: ${entry.returnType}` : ""} {${entry.body}}`;
|
|
}).join(`
|
|
|
|
`);
|
|
}
|
|
function parseOutputs(source) {
|
|
const out = [];
|
|
let i = 0;
|
|
while (i < source.length) {
|
|
i = skipTrivia(source, i);
|
|
if (i >= source.length)
|
|
break;
|
|
const nameToken = readWord(source, i);
|
|
if (!nameToken)
|
|
throw new Error(`Expected output name at offset ${i}`);
|
|
i = skipTrivia(source, nameToken.end);
|
|
const args = readBalanced(source, i, "(", ")");
|
|
i = args.end;
|
|
const parameters = parseParameters(args.inner);
|
|
if (parameters.length > 1)
|
|
throw new Error(`Output '${nameToken.word}' accepts zero or one payload`);
|
|
const payload = parameters[0];
|
|
if (payload && !payload.valueType)
|
|
throw new Error(`Output '${nameToken.word}' payload requires a type`);
|
|
out.push({
|
|
name: nameToken.word,
|
|
...payload ? {
|
|
payload: {
|
|
name: payload.name,
|
|
valueType: payload.valueType,
|
|
optional: payload.optional
|
|
}
|
|
} : {}
|
|
});
|
|
}
|
|
return out;
|
|
}
|
|
function parseStructuredImports(imports) {
|
|
return imports.map((raw) => {
|
|
const sourceMatch = /\sfrom\s+["']([^"']+)["']|^import\s+["']([^"']+)["']/.exec(raw);
|
|
const source = sourceMatch?.[1] ?? sourceMatch?.[2] ?? "";
|
|
const typeOnly = /^import\s+type\b/.test(raw);
|
|
const clause = raw.replace(/^import\s+(?:type\s+)?/, "").replace(/\s+from\s+["'][^"']+["']\s*;?$/, "").trim();
|
|
const declaration = { source, typeOnly, namedImports: [], raw };
|
|
if (!clause || clause.startsWith('"') || clause.startsWith("'"))
|
|
return declaration;
|
|
if (clause.startsWith("*")) {
|
|
declaration.namespaceImport = /\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(clause)?.[1];
|
|
return declaration;
|
|
}
|
|
let rest = clause;
|
|
if (!rest.startsWith("{")) {
|
|
const comma = findTopLevelChar(rest, ",");
|
|
declaration.defaultImport = (comma < 0 ? rest : rest.slice(0, comma)).trim();
|
|
rest = comma < 0 ? "" : rest.slice(comma + 1).trim();
|
|
}
|
|
const named = /^\{([\s\S]*)\}$/.exec(rest)?.[1];
|
|
if (named !== undefined) {
|
|
declaration.namedImports = splitTopLevel(named).map((item) => {
|
|
const localTypeOnly = /^type\s+/.test(item);
|
|
const cleaned = item.replace(/^type\s+/, "").trim();
|
|
const [imported, local] = cleaned.split(/\s+as\s+/);
|
|
return {
|
|
imported: imported.trim(),
|
|
local: (local ?? imported).trim(),
|
|
typeOnly: typeOnly || localTypeOnly
|
|
};
|
|
});
|
|
}
|
|
return declaration;
|
|
});
|
|
}
|
|
function parseStateDeclarations(source, runtime) {
|
|
const lx = new tokenizer_ts_1.Lexer(source);
|
|
const out = [];
|
|
while (lx.peek().type !== "eof") {
|
|
const nameToken = lx.next();
|
|
if (nameToken.type !== "ident")
|
|
throw new tokenizer_ts_1.LexError(`Expected a state name at offset ${nameToken.pos}`);
|
|
let valueType;
|
|
if (lx.peek().type === "colon") {
|
|
lx.next();
|
|
const annotation = lx.readTypeAnnotation();
|
|
valueType = annotation.type;
|
|
if (!annotation.hasDefault)
|
|
throw new tokenizer_ts_1.LexError(`State '${nameToken.value}' requires an initializer`);
|
|
} else {
|
|
const eq = lx.next();
|
|
if (eq.type !== "eq")
|
|
throw new tokenizer_ts_1.LexError(`Expected '=' after state '${nameToken.value}' at offset ${eq.pos}`);
|
|
}
|
|
out.push({
|
|
name: nameToken.value,
|
|
...valueType ? { valueType } : {},
|
|
expr: lx.readPropInitializer(),
|
|
runtime
|
|
});
|
|
}
|
|
return out;
|
|
}
|
|
function parseComputedDeclarations(source) {
|
|
const lx = new tokenizer_ts_1.Lexer(source);
|
|
const out = [];
|
|
while (lx.peek().type !== "eof") {
|
|
const nameToken = lx.next();
|
|
if (nameToken.type !== "ident")
|
|
throw new tokenizer_ts_1.LexError(`Expected a computed name at offset ${nameToken.pos}`);
|
|
let valueType;
|
|
if (lx.peek().type === "colon") {
|
|
lx.next();
|
|
const annotation = lx.readTypeAnnotation();
|
|
valueType = annotation.type;
|
|
if (!annotation.hasDefault)
|
|
throw new tokenizer_ts_1.LexError(`Computed '${nameToken.value}' requires an expression`);
|
|
} else {
|
|
const eq = lx.next();
|
|
if (eq.type !== "eq")
|
|
throw new tokenizer_ts_1.LexError(`Expected '=' after computed '${nameToken.value}' at offset ${eq.pos}`);
|
|
}
|
|
out.push({
|
|
name: nameToken.value,
|
|
...valueType ? { valueType } : {},
|
|
expr: lx.readPropInitializer()
|
|
});
|
|
}
|
|
return out;
|
|
}
|
|
function nestedBlock(source, name) {
|
|
const match = new RegExp(`\\b${name}\\s*\\{`).exec(source);
|
|
if (!match)
|
|
return;
|
|
const brace = source.indexOf("{", match.index);
|
|
return readBalanced(source, brace, "{", "}").inner.trim() || undefined;
|
|
}
|
|
function parsePersist(source) {
|
|
const storage = /\bstorage\s*=\s*["'](memory|session|local)["']/.exec(source)?.[1];
|
|
const includeRaw = /\binclude\s*=\s*\[([\s\S]*?)\]/.exec(source)?.[1] ?? "";
|
|
const include = Array.from(includeRaw.matchAll(/["']([^"']+)["']/g), (match) => match[1]);
|
|
const version = Number(/\bversion\s*=\s*(\d+)/.exec(source)?.[1] ?? "1");
|
|
const migrations = nestedBlock(source, "migrations");
|
|
const validation = nestedBlock(source, "validate");
|
|
return {
|
|
storage: storage ?? "memory",
|
|
include,
|
|
version,
|
|
...migrations ? { migrations } : {},
|
|
...validation ? { validation } : {}
|
|
};
|
|
}
|
|
function parseStoreLifecycle(source) {
|
|
const out = {};
|
|
for (const hook of ["serverInit", "clientInit", "hydrate", "dispose"]) {
|
|
const start = new RegExp(`\\b${hook}\\s*\\{`).exec(source);
|
|
if (!start)
|
|
continue;
|
|
const brace = source.indexOf("{", start.index);
|
|
out[hook] = readBalanced(source, brace, "{", "}").inner;
|
|
}
|
|
return out;
|
|
}
|
|
},
|
|
"packages/syntax/src/versioning.ts": function(module3, exports3, require2, __filename2, __dirname2) {
|
|
Object.defineProperty(exports3, "__esModule", { value: true });
|
|
exports3.WRN_SYNTAX_FEATURES = exports3.WRN_SYNTAX_VERSION = undefined;
|
|
exports3.createSourceRange = createSourceRange;
|
|
exports3.sliceSource = sliceSource;
|
|
exports3.diagnosticSummary = diagnosticSummary;
|
|
exports3.supportsSyntaxFeature = supportsSyntaxFeature;
|
|
exports3.WRN_SYNTAX_VERSION = "0.4";
|
|
exports3.WRN_SYNTAX_FEATURES = Object.freeze({
|
|
"typed-declarations": true,
|
|
layouts: true,
|
|
"server-client-blocks": true,
|
|
effects: true,
|
|
watch: true,
|
|
lifecycle: true,
|
|
"embedded-api": true,
|
|
realtime: true,
|
|
"runtime-markers": true
|
|
});
|
|
function createSourceRange(start, end) {
|
|
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start) {
|
|
throw new RangeError(`Invalid source range ${start}..${end}`);
|
|
}
|
|
return { start, end };
|
|
}
|
|
function sliceSource(source, range) {
|
|
return source.slice(range.start, range.end);
|
|
}
|
|
function diagnosticSummary(diagnostics) {
|
|
const summary = { errors: 0, warnings: 0, info: 0, codes: {} };
|
|
for (const diagnostic of diagnostics) {
|
|
if (diagnostic.severity === "error")
|
|
summary.errors++;
|
|
else if (diagnostic.severity === "warning")
|
|
summary.warnings++;
|
|
else
|
|
summary.info++;
|
|
summary.codes[diagnostic.code] = (summary.codes[diagnostic.code] ?? 0) + 1;
|
|
}
|
|
return summary;
|
|
}
|
|
function supportsSyntaxFeature(feature) {
|
|
return Object.prototype.hasOwnProperty.call(exports3.WRN_SYNTAX_FEATURES, feature);
|
|
}
|
|
}
|
|
};
|
|
var __aliases = {
|
|
"@wrnexus/syntax": "packages/syntax/src/index.ts",
|
|
"@wrnexus/syntax/parser": "packages/syntax/src/parser.ts",
|
|
"@wrnexus/syntax/tokenizer": "packages/syntax/src/tokenizer.ts",
|
|
"@wrnexus/syntax/types": "packages/syntax/src/types.ts",
|
|
"@wrnexus/syntax/diagnostics": "packages/syntax/src/diagnostics.ts",
|
|
"@wrnexus/syntax/spec": "packages/syntax/src/spec.ts"
|
|
};
|
|
var __cache = Object.create(null);
|
|
function __normalize(id) {
|
|
const normalized = id.split("\\").join("/");
|
|
return normalized.startsWith("./") ? normalized.slice(2) : normalized;
|
|
}
|
|
function __resolve(request, parent) {
|
|
if (__aliases[request])
|
|
return __aliases[request];
|
|
if (!request.startsWith("."))
|
|
return null;
|
|
const base = __normalize(__path.posix.join(__path.posix.dirname(parent), request));
|
|
const candidates = [
|
|
base,
|
|
base.endsWith(".js") ? base.slice(0, -3) + ".ts" : base,
|
|
base.endsWith(".ts") ? base : base + ".ts",
|
|
(base.endsWith("/") ? base.slice(0, -1) : base) + "/index.ts"
|
|
];
|
|
for (const candidate of candidates) {
|
|
if (__modules[candidate])
|
|
return candidate;
|
|
}
|
|
return null;
|
|
}
|
|
function __load(id) {
|
|
if (__cache[id])
|
|
return __cache[id].exports;
|
|
const factory = __modules[id];
|
|
if (!factory)
|
|
throw new Error("WRN editor compiler module not found: " + id);
|
|
const module3 = { exports: {} };
|
|
__cache[id] = module3;
|
|
const localRequire = (request) => {
|
|
const resolved = __resolve(request, id);
|
|
return resolved ? __load(resolved) : __nodeRequire(request);
|
|
};
|
|
factory(module3, module3.exports, localRequire, id, __path.posix.dirname(id));
|
|
return module3.exports;
|
|
}
|
|
module2.exports = __load("packages/compiler/src/index.ts");
|
|
});
|
|
|
|
// editors/vscode/src/formatter.js
|
|
var require_formatter = __commonJS((exports2, module2) => {
|
|
var { formatWrn } = require_compiler();
|
|
module2.exports = { formatWrn };
|
|
});
|
|
|
|
// editors/vscode/src/completion.js
|
|
var require_completion2 = __commonJS((exports2, module2) => {
|
|
var vscode = require("vscode");
|
|
var BLOCK_COMPLETIONS = [
|
|
{
|
|
label: "import",
|
|
detail: "WRN server module import",
|
|
documentation: "Import a package or module before the page, component, or layout declaration for server rendering.",
|
|
snippet: 'import { ${1:appUrl} } from "${2:@wrnexus/helpers}";\n\n$0'
|
|
},
|
|
{
|
|
label: "page",
|
|
detail: "WRN page",
|
|
documentation: "Create a WRN page declaration.",
|
|
snippet: [
|
|
"page ${1:PageName} {",
|
|
' layout = "${2:default}"',
|
|
"",
|
|
" view {",
|
|
" $0",
|
|
" }",
|
|
"}"
|
|
].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "component",
|
|
detail: "WRN component",
|
|
documentation: "Create a reusable WRN component with state, functions, lifecycle hooks, watchers, and a view.",
|
|
snippet: [
|
|
"component ${1:ComponentName} {",
|
|
" state ${2:ready} = false",
|
|
"",
|
|
" functions {",
|
|
" function ${3:initialize}() {",
|
|
" $0",
|
|
" }",
|
|
" }",
|
|
"",
|
|
" lifecycle {",
|
|
" mount {",
|
|
" ${3:initialize}()",
|
|
" }",
|
|
" }",
|
|
"",
|
|
" view {",
|
|
" <div></div>",
|
|
" }",
|
|
"}"
|
|
].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "layout",
|
|
detail: "WRN layout",
|
|
documentation: "Create a reusable WRN layout.",
|
|
snippet: [
|
|
"layout ${1:LayoutName} {",
|
|
" view {",
|
|
" <main>",
|
|
" {content}",
|
|
" </main>",
|
|
" }",
|
|
"}"
|
|
].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "types",
|
|
detail: "TypeScript type declarations block",
|
|
documentation: "Declare interfaces and type aliases used by props, state, and functions.",
|
|
snippet: [
|
|
"types {",
|
|
" interface ${1:Item} {",
|
|
" ${2:id}: ${3:string}",
|
|
" }",
|
|
"}"
|
|
].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "props",
|
|
detail: "Component or layout props block",
|
|
documentation: "Declare values accepted by a component or layout.",
|
|
snippet: ["props {", ' ${1:title}: ${2:string} = "${3:Title}"', "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "seo",
|
|
detail: "SEO metadata block",
|
|
documentation: "Declare title, description, and other page metadata.",
|
|
snippet: [
|
|
"seo {",
|
|
' title = "${1:Page title}"',
|
|
' description = "${2:Page description}"',
|
|
"}"
|
|
].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "view",
|
|
detail: "WRN view block",
|
|
documentation: "Declare the HTML view rendered by the page, component, or layout.",
|
|
snippet: ["view {", " $0", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "state",
|
|
detail: "Reactive state declaration",
|
|
documentation: "Declare reactive state owned by the current component, layout, or page.",
|
|
snippet: 'state ${1:name}: ${2:string} = ${3:"value"}'
|
|
},
|
|
{
|
|
label: "runtime",
|
|
detail: "WRN execution target",
|
|
documentation: "Choose whether this declaration executes on the server, client, or both.",
|
|
snippet: 'runtime = "${1|universal,server,client|}"'
|
|
},
|
|
{
|
|
label: "hydrate",
|
|
detail: "WRN hydration strategy",
|
|
documentation: "Choose when client interactivity is initialized for this declaration.",
|
|
snippet: 'hydrate = "${1|load,idle,visible,interaction,none|}"'
|
|
},
|
|
{
|
|
label: "computed",
|
|
detail: "Derived reactive values block",
|
|
documentation: "Declare values that are recomputed only when their reactive dependencies change.",
|
|
snippet: ["computed {", " ${1:displayName} = ${2:firstName + ' ' + lastName}", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "effect",
|
|
detail: "Reactive side-effect block",
|
|
documentation: "Run browser-side code whenever its referenced reactive values change.",
|
|
snippet: ["effect {", " ${1:console.log(value)}", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "security",
|
|
detail: "Route security metadata block",
|
|
documentation: "Declare authentication, authorization, CSRF, and rate-limit policy metadata.",
|
|
snippet: [
|
|
"security {",
|
|
' auth = "${1|required,optional,public|}"',
|
|
' csrf = "${2:true}"',
|
|
"}"
|
|
].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "load",
|
|
detail: "Typed data-loading block",
|
|
documentation: "Load data on the server or client with an explicit execution boundary.",
|
|
snippet: ["load ${1|server,client|} {", " ${2:return {}}", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "action",
|
|
detail: "Named server action",
|
|
documentation: "Declare a callable mutation with an explicit name and arguments.",
|
|
snippet: ["action ${1:save}(${2:input}) {", " $0", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "functions",
|
|
detail: "Browser component functions block",
|
|
documentation: "Declare functions that can be called from events, lifecycle hooks, and watchers.",
|
|
snippet: [
|
|
"functions {",
|
|
" function ${1:handler}(${2:value}: ${3:unknown}): ${4:void} {",
|
|
" $0",
|
|
" }",
|
|
"}"
|
|
].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "function",
|
|
detail: "WRN component function",
|
|
documentation: "Declare a browser-side function inside a functions block.",
|
|
snippet: ["function ${1:name}(${2:value}: ${3:unknown}): ${4:void} {", " $0", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "lifecycle",
|
|
detail: "Component lifecycle block",
|
|
documentation: "Declare mount, update, and unmount hooks for a component or layout.",
|
|
snippet: [
|
|
"lifecycle {",
|
|
" mount {",
|
|
" $1",
|
|
" }",
|
|
"",
|
|
" update {",
|
|
" $2",
|
|
" }",
|
|
"",
|
|
" unmount {",
|
|
" $0",
|
|
" }",
|
|
"}"
|
|
].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "mount",
|
|
detail: "Lifecycle mount hook",
|
|
documentation: "Runs once after the component is connected and hydrated.",
|
|
snippet: ["mount {", " $0", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "update",
|
|
detail: "Lifecycle update hook",
|
|
documentation: "Runs once after a batch of reactive state changes.",
|
|
snippet: ["update {", " $0", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "unmount",
|
|
detail: "Lifecycle unmount hook",
|
|
documentation: "Runs before the component is removed. Use it to remove global listeners and release resources.",
|
|
snippet: ["unmount {", " $0", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "watch",
|
|
detail: "Reactive state watcher",
|
|
documentation: "Run code when one declared state value changes. The watcher receives `value` and `previous`.",
|
|
snippet: ["watch ${1:stateName} {", " console.log(value, previous)", " $0", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "style",
|
|
detail: "Scoped style block",
|
|
documentation: "Declare styles for the current WRN declaration.",
|
|
snippet: ["style {", " $0", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "import type",
|
|
detail: "WRN v0.6 TypeScript type import",
|
|
snippet: 'import type { ${1:PublicUser} } from "${2:@/types/user.ts}"\n\n$0'
|
|
},
|
|
{
|
|
label: "outputs",
|
|
detail: "Typed callable component outputs",
|
|
snippet: [
|
|
"outputs {",
|
|
" ${1:confirm}(payload: ${2:ConfirmPayload})",
|
|
" ${3:cancel}()",
|
|
"}"
|
|
].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "client function",
|
|
detail: "Browser-only typed function",
|
|
snippet: ["client ${1|,async |}function ${2:name}(${3}): ${4:void} {", " $0", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "server function",
|
|
detail: "Server-only typed function",
|
|
snippet: ["server ${1|,async |}function ${2:name}(${3}): ${4:void} {", " $0", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "shared function",
|
|
detail: "Server-and-browser typed function",
|
|
snippet: ["shared function ${1:name}(${2}): ${3:void} {", " $0", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "state block",
|
|
detail: "Grouped typed reactive state",
|
|
snippet: ["state {", ' ${1:name}: ${2:string} = ${3:""}', "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "client state",
|
|
detail: "Browser-only state block",
|
|
snippet: ["client state {", " ${1:menuOpen}: boolean = false", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "server state",
|
|
detail: "Server-only state block",
|
|
snippet: ["server state {", " ${1:sessionId}: string | null = null", "}"].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "global store",
|
|
detail: "Request-scoped global store",
|
|
snippet: [
|
|
"global store ${1:UserStore} {",
|
|
" state {",
|
|
" ${2:user}: ${3:PublicUser | null} = null",
|
|
" }",
|
|
"",
|
|
" computed {",
|
|
" ${4:authenticated}: boolean = ${2:user} !== null",
|
|
" }",
|
|
"}"
|
|
].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "page store",
|
|
detail: "Route-scoped page store",
|
|
snippet: [
|
|
"page store ${1:PageStore} {",
|
|
" state {",
|
|
" ${2:loading}: boolean = false",
|
|
" }",
|
|
"}"
|
|
].join(`
|
|
`)
|
|
},
|
|
{
|
|
label: "persist",
|
|
detail: "Include-only store persistence",
|
|
snippet: [
|
|
"persist {",
|
|
' storage = "${1|memory,session,local|}"',
|
|
' include = ["${2:field}"]',
|
|
" version = ${3:1}",
|
|
"}"
|
|
].join(`
|
|
`)
|
|
}
|
|
];
|
|
var ATTRIBUTE_COMPLETIONS = [
|
|
["@click", "Click event handler", '@click="${1:handler()}"'],
|
|
["@change", "Change event handler", '@change="${1:handler()}"'],
|
|
["@input", "Input event handler", '@input="${1:handler()}"'],
|
|
["@submit", "Submit event handler", '@submit="${1:handler()}"'],
|
|
["@focus", "Focus event handler", '@focus="${1:handler()}"'],
|
|
["@blur", "Blur event handler", '@blur="${1:handler()}"'],
|
|
["@keydown", "Keyboard key-down event handler", '@keydown="${1:handler()}"'],
|
|
["@keyup", "Keyboard key-up event handler", '@keyup="${1:handler()}"'],
|
|
["@mouseenter", "Pointer enter event handler", '@mouseenter="${1:handler()}"'],
|
|
["@mouseleave", "Pointer leave event handler", '@mouseleave="${1:handler()}"'],
|
|
["@window:scroll", "Window scroll event handler", '@window:scroll="${1:handler()}"'],
|
|
["@window:resize", "Window resize event handler", '@window:resize="${1:handler()}"'],
|
|
["@window:keydown", "Window key-down event handler", '@window:keydown="${1:handler()}"'],
|
|
["@document:click", "Document click event handler", '@document:click="${1:handler()}"'],
|
|
[
|
|
"@document:visibilitychange",
|
|
"Document visibility-change event handler",
|
|
'@document:visibilitychange="${1:handler()}"'
|
|
],
|
|
["data-show", "Conditional visibility", 'data-show="${1:condition}"'],
|
|
["data-for", "Reactive loop", 'data-for="${1:item} in ${2:items}"'],
|
|
["class:", "Conditional CSS class", 'class:${1:border-indigo-500}="${2:condition}"']
|
|
];
|
|
var CONTEXT_COMPLETIONS = [
|
|
["ctx.params", "Dynamic route parameters"],
|
|
["ctx.query", "URL query parameters"],
|
|
["ctx.request", "Current Request object"],
|
|
["ctx.user", "Authenticated user"],
|
|
["ctx.session", "Current session"],
|
|
["ctx.locals", "Request-local data"],
|
|
["ctx.tenant", "Resolved tenant context"],
|
|
["ctx.tracer", "Request tracing interface"]
|
|
];
|
|
var WATCH_VALUE_COMPLETIONS = [
|
|
["value", "Current watcher state value"],
|
|
["previous", "Previous watcher state value"]
|
|
];
|
|
function completionKindFor(label) {
|
|
if (label.startsWith("@")) {
|
|
return vscode.CompletionItemKind.Event;
|
|
}
|
|
if (label.startsWith("class:") || label.startsWith("data-")) {
|
|
return vscode.CompletionItemKind.Property;
|
|
}
|
|
if (label === "function" || label === "functions") {
|
|
return vscode.CompletionItemKind.Function;
|
|
}
|
|
return vscode.CompletionItemKind.Keyword;
|
|
}
|
|
function createCompletion(label, detail, snippet, documentation) {
|
|
const item = new vscode.CompletionItem(label, completionKindFor(label));
|
|
item.detail = detail;
|
|
item.insertText = new vscode.SnippetString(snippet || label);
|
|
item.documentation = new vscode.MarkdownString(documentation || detail);
|
|
return item;
|
|
}
|
|
function createVariableCompletion(label, detail, insertion = label) {
|
|
const item = new vscode.CompletionItem(label, vscode.CompletionItemKind.Variable);
|
|
item.detail = detail;
|
|
item.insertText = insertion;
|
|
return item;
|
|
}
|
|
function createFunctionCompletion(name, parameters = []) {
|
|
const item = new vscode.CompletionItem(name, vscode.CompletionItemKind.Function);
|
|
item.detail = `WRN component function${parameters.length > 0 ? ` (${parameters.join(", ")})` : ""}`;
|
|
item.documentation = new vscode.MarkdownString(`Call the browser function \`${name}\` declared in the current \`functions { ... }\` block.`);
|
|
const placeholders = parameters.map((parameter, index) => `\${${index + 1}:${parameter}}`);
|
|
item.insertText = new vscode.SnippetString(`${name}(${placeholders.join(", ")})`);
|
|
return item;
|
|
}
|
|
function getCurrentOpeningTag(document, position) {
|
|
const textBeforeCursor = document.getText(new vscode.Range(new vscode.Position(position.line, 0), position));
|
|
const lastOpen = textBeforeCursor.lastIndexOf("<");
|
|
const lastClose = textBeforeCursor.lastIndexOf(">");
|
|
if (lastOpen > lastClose) {
|
|
return textBeforeCursor.slice(lastOpen);
|
|
}
|
|
return null;
|
|
}
|
|
function extractRouteParams(document) {
|
|
const fileName = document.fileName.replace(/\\/g, "/");
|
|
const matches = [...fileName.matchAll(/\[([A-Za-z_$][\w$]*)\]/g)];
|
|
return matches.map((match) => match[1]);
|
|
}
|
|
function extractStates(document) {
|
|
const source = document.getText();
|
|
const matches = [...source.matchAll(/^\s*state\s+([A-Za-z_$][\w$]*)(?:\s*:\s*[^=\r\n]+)?\s*=/gm)];
|
|
return [...new Set(matches.map((match) => match[1]))];
|
|
}
|
|
function extractProps(document) {
|
|
const source = document.getText();
|
|
const propsBlockPattern = /\bprops\s*\{([\s\S]*?)\}/g;
|
|
const props = new Set;
|
|
let blockMatch;
|
|
while ((blockMatch = propsBlockPattern.exec(source)) !== null) {
|
|
const body = blockMatch[1];
|
|
for (const match of body.matchAll(/^\s*([A-Za-z_$][\w$]*)(?:\s*:\s*[^=\r\n]+)?(?:\s*=|\s*$)/gm)) {
|
|
props.add(match[1]);
|
|
}
|
|
}
|
|
return [...props];
|
|
}
|
|
function extractFunctions(document) {
|
|
const source = document.getText();
|
|
const functions = [];
|
|
const seen = new Set;
|
|
const pattern = /(?:^|\s)(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)/g;
|
|
let match;
|
|
while ((match = pattern.exec(source)) !== null) {
|
|
const name = match[1];
|
|
if (seen.has(name)) {
|
|
continue;
|
|
}
|
|
seen.add(name);
|
|
const parameters = match[2].split(",").map((parameter) => parameter.trim()).filter(Boolean).map((parameter) => parameter.replace(/=.*$/, "").replace(/\??\s*:\s*[\s\S]+$/, "").trim());
|
|
functions.push({
|
|
name,
|
|
parameters
|
|
});
|
|
}
|
|
return functions;
|
|
}
|
|
function sourceBeforePosition(document, position) {
|
|
return document.getText(new vscode.Range(new vscode.Position(0, 0), position));
|
|
}
|
|
function isInsideNamedBlock(document, position, blockName) {
|
|
const source = sourceBeforePosition(document, position);
|
|
const tokenPattern = new RegExp(`\\b${blockName}\\s*\\{|\\{|\\}`, "g");
|
|
const stack = [];
|
|
let match;
|
|
while ((match = tokenPattern.exec(source)) !== null) {
|
|
const token = match[0];
|
|
if (token.startsWith(blockName)) {
|
|
stack.push(blockName);
|
|
continue;
|
|
}
|
|
if (token === "{") {
|
|
stack.push(null);
|
|
continue;
|
|
}
|
|
if (token === "}") {
|
|
stack.pop();
|
|
}
|
|
}
|
|
return stack.includes(blockName);
|
|
}
|
|
function isInsideLifecycle(document, position) {
|
|
return isInsideNamedBlock(document, position, "lifecycle");
|
|
}
|
|
function isInsideFunctions(document, position) {
|
|
return isInsideNamedBlock(document, position, "functions");
|
|
}
|
|
function isInsideWatch(document, position) {
|
|
const source = sourceBeforePosition(document, position);
|
|
const watchMatches = [...source.matchAll(/\bwatch\s+[A-Za-z_$][\w$]*\s*\{/g)];
|
|
if (watchMatches.length === 0) {
|
|
return false;
|
|
}
|
|
const latest = watchMatches[watchMatches.length - 1];
|
|
const tail = source.slice(latest.index);
|
|
let depth = 0;
|
|
for (const character of tail) {
|
|
if (character === "{") {
|
|
depth += 1;
|
|
} else if (character === "}") {
|
|
depth -= 1;
|
|
}
|
|
}
|
|
return depth > 0;
|
|
}
|
|
function isAfterWatchKeyword(document, position) {
|
|
const linePrefix = document.lineAt(position.line).text.slice(0, position.character);
|
|
return /^\s*watch\s+[A-Za-z0-9_$]*$/.test(linePrefix);
|
|
}
|
|
function addBlockCompletions(items, document, position) {
|
|
const insideLifecycle = isInsideLifecycle(document, position);
|
|
const insideFunctions = isInsideFunctions(document, position);
|
|
for (const completion of BLOCK_COMPLETIONS) {
|
|
if (insideLifecycle && !["mount", "update", "unmount"].includes(completion.label)) {
|
|
continue;
|
|
}
|
|
if (insideFunctions && completion.label !== "function") {
|
|
continue;
|
|
}
|
|
if (!insideLifecycle && ["mount", "update", "unmount"].includes(completion.label)) {
|
|
continue;
|
|
}
|
|
if (!insideFunctions && completion.label === "function") {
|
|
continue;
|
|
}
|
|
items.push(createCompletion(completion.label, completion.detail, completion.snippet, completion.documentation));
|
|
}
|
|
}
|
|
function addStateCompletions(items, document, position) {
|
|
const states = extractStates(document);
|
|
const afterWatch = isAfterWatchKeyword(document, position);
|
|
for (const state of states) {
|
|
const item = createVariableCompletion(state, afterWatch ? "Declared WRN state available for watching" : "WRN reactive state");
|
|
if (afterWatch) {
|
|
item.sortText = `0-${state}`;
|
|
}
|
|
items.push(item);
|
|
}
|
|
}
|
|
function addFunctionCompletions(items, document) {
|
|
for (const fn of extractFunctions(document)) {
|
|
items.push(createFunctionCompletion(fn.name, fn.parameters));
|
|
}
|
|
}
|
|
function provideCompletionItems(document, position) {
|
|
const items = [];
|
|
const linePrefix = document.lineAt(position.line).text.slice(0, position.character);
|
|
const openingTag = getCurrentOpeningTag(document, position);
|
|
if (openingTag !== null) {
|
|
for (const [label, detail, snippet] of ATTRIBUTE_COMPLETIONS) {
|
|
items.push(createCompletion(label, detail, snippet));
|
|
}
|
|
} else if (isAfterWatchKeyword(document, position)) {
|
|
addStateCompletions(items, document, position);
|
|
} else {
|
|
addBlockCompletions(items, document, position);
|
|
}
|
|
if (linePrefix.includes("ctx.") || linePrefix.includes("ctx.params.")) {
|
|
for (const [label, detail] of CONTEXT_COMPLETIONS) {
|
|
items.push(createCompletion(label, detail, label));
|
|
}
|
|
}
|
|
for (const param of extractRouteParams(document)) {
|
|
items.push(createVariableCompletion(param, `Route parameter from [${param}].wrn`));
|
|
items.push(createVariableCompletion(`ctx.params.${param}`, `Route parameter from [${param}].wrn`));
|
|
}
|
|
if (!isAfterWatchKeyword(document, position)) {
|
|
addStateCompletions(items, document, position);
|
|
}
|
|
for (const prop of extractProps(document)) {
|
|
items.push(createVariableCompletion(prop, "WRN component or layout prop"));
|
|
}
|
|
addFunctionCompletions(items, document);
|
|
if (isInsideWatch(document, position)) {
|
|
for (const [label, detail] of WATCH_VALUE_COMPLETIONS) {
|
|
items.push(createVariableCompletion(label, detail));
|
|
}
|
|
}
|
|
return items;
|
|
}
|
|
function registerCompletionProvider(context) {
|
|
const provider = vscode.languages.registerCompletionItemProvider({
|
|
language: "wrn"
|
|
}, {
|
|
provideCompletionItems
|
|
}, "@", ":", ".", "<", " ", "(");
|
|
context.subscriptions.push(provider);
|
|
}
|
|
module2.exports = {
|
|
extractFunctions,
|
|
extractProps,
|
|
extractRouteParams,
|
|
extractStates,
|
|
provideCompletionItems,
|
|
registerCompletionProvider
|
|
};
|
|
});
|
|
|
|
// editors/vscode/src/definition.js
|
|
var require_definition2 = __commonJS((exports2, module2) => {
|
|
var vscode = require("vscode");
|
|
var COMPONENT_DECLARATION = /^\s*(component|layout)\s+([A-Za-z_$][\w$]*)\s*\{/gm;
|
|
function getTagAtPosition(document, position) {
|
|
const range = document.getWordRangeAtPosition(position, /[A-Za-z_$][\w$]*/);
|
|
if (!range) {
|
|
return null;
|
|
}
|
|
const name = document.getText(range);
|
|
if (!/^[A-Z][A-Za-z0-9_$]*$/.test(name)) {
|
|
return null;
|
|
}
|
|
const line = document.lineAt(position.line).text;
|
|
const offset = document.offsetAt(position);
|
|
const lineStart = document.offsetAt(new vscode.Position(position.line, 0));
|
|
const characterOffset = offset - lineStart;
|
|
const before = line.slice(0, characterOffset);
|
|
const after = line.slice(characterOffset);
|
|
const insideTag = before.lastIndexOf("<") > before.lastIndexOf(">") && after.includes(">");
|
|
if (!insideTag) {
|
|
return null;
|
|
}
|
|
return {
|
|
name,
|
|
range
|
|
};
|
|
}
|
|
async function findDeclaration(name) {
|
|
const files = await vscode.workspace.findFiles("**/*.wrn", "**/{node_modules,dist,.wrnexus,.git}/**");
|
|
const matches = [];
|
|
for (const uri of files) {
|
|
let document;
|
|
try {
|
|
document = await vscode.workspace.openTextDocument(uri);
|
|
} catch {
|
|
continue;
|
|
}
|
|
const source = document.getText();
|
|
COMPONENT_DECLARATION.lastIndex = 0;
|
|
let match;
|
|
while ((match = COMPONENT_DECLARATION.exec(source)) !== null) {
|
|
const declarationName = match[2];
|
|
if (declarationName !== name) {
|
|
continue;
|
|
}
|
|
const nameOffset = match.index + match[0].indexOf(declarationName);
|
|
const start = document.positionAt(nameOffset);
|
|
const end = document.positionAt(nameOffset + declarationName.length);
|
|
matches.push(new vscode.Location(uri, new vscode.Range(start, end)));
|
|
}
|
|
}
|
|
return matches;
|
|
}
|
|
async function provideDefinition(document, position) {
|
|
const tag = getTagAtPosition(document, position);
|
|
if (!tag) {
|
|
return null;
|
|
}
|
|
const matches = await findDeclaration(tag.name);
|
|
if (matches.length === 0) {
|
|
return null;
|
|
}
|
|
return matches.length === 1 ? matches[0] : matches;
|
|
}
|
|
function registerDefinitionProvider(context) {
|
|
const disposable = vscode.languages.registerDefinitionProvider({
|
|
language: "wrn"
|
|
}, {
|
|
provideDefinition
|
|
});
|
|
context.subscriptions.push(disposable);
|
|
}
|
|
module2.exports = {
|
|
findDeclaration,
|
|
getTagAtPosition,
|
|
provideDefinition,
|
|
registerDefinitionProvider
|
|
};
|
|
});
|
|
|
|
// editors/vscode/src/component-metadata.js
|
|
var require_component_metadata = __commonJS((exports2, module2) => {
|
|
var COMPONENT_DECLARATION = /\b(component|layout)\s+([A-Za-z_$][\w$]*)\s*\{/;
|
|
function findMatchingBrace(source, openingBrace) {
|
|
let depth = 0;
|
|
let quote = null;
|
|
let escaped = false;
|
|
for (let index = openingBrace;index < source.length; index += 1) {
|
|
const character = source[index];
|
|
if (quote) {
|
|
if (escaped)
|
|
escaped = false;
|
|
else if (character === "\\")
|
|
escaped = true;
|
|
else if (character === quote)
|
|
quote = null;
|
|
continue;
|
|
}
|
|
if (character === '"' || character === "'" || character === "`")
|
|
quote = character;
|
|
else if (character === "{")
|
|
depth += 1;
|
|
else if (character === "}" && --depth === 0)
|
|
return index;
|
|
}
|
|
return -1;
|
|
}
|
|
function inferType(defaultValue) {
|
|
const value = defaultValue.trim();
|
|
if (value === "undefined")
|
|
return "unknown";
|
|
if (/^(?:true|false)$/.test(value))
|
|
return "boolean";
|
|
if (/^-?(?:\d+\.?\d*|\.\d+)$/.test(value))
|
|
return "number";
|
|
if (/^["'`]/.test(value))
|
|
return "string";
|
|
if (value.startsWith("["))
|
|
return "array";
|
|
if (value.startsWith("{"))
|
|
return "object";
|
|
if (value === "null")
|
|
return "null";
|
|
return "unknown";
|
|
}
|
|
function runtimeType(type) {
|
|
const value = String(type || "").trim().replace(/^readonly\s+/, "");
|
|
const unionParts = value.split("|").map((part) => part.trim());
|
|
const concreteParts = unionParts.filter((part) => !/^(?:null|undefined)$/.test(part));
|
|
if (/^(?:string|String)(?:\s*\|\s*(?:null|undefined))*$/.test(value) || concreteParts.length > 0 && concreteParts.every((part) => /^(?:"[^"]*"|'[^']*')$/.test(part)))
|
|
return "string";
|
|
if (/^(?:number|Number)(?:\s*\|\s*(?:null|undefined))*$/.test(value) || concreteParts.length > 0 && concreteParts.every((part) => /^-?(?:\d+\.?\d*|\.\d+)$/.test(part)))
|
|
return "number";
|
|
if (/^(?:boolean|Boolean)(?:\s*\|\s*(?:null|undefined))*$/.test(value) || concreteParts.length > 0 && concreteParts.every((part) => /^(?:true|false)$/.test(part)))
|
|
return "boolean";
|
|
if (/^bigint(?:\s*\|\s*(?:null|undefined))*$/.test(value))
|
|
return "bigint";
|
|
if (/^(?:Array\s*<|ReadonlyArray\s*<|.+\[\])/.test(value) || /^\[/.test(value))
|
|
return "array";
|
|
if (/^(?:Record\s*<|object\b|\{)/.test(value))
|
|
return "object";
|
|
if (/=>|^Function$/.test(value))
|
|
return "function";
|
|
return value || "unknown";
|
|
}
|
|
function stringLiteral(value) {
|
|
const match = /^(?:"([\s\S]*)"|'([\s\S]*)'|`([\s\S]*)`)$/.exec(value.trim());
|
|
return match ? match[1] ?? match[2] ?? match[3] : null;
|
|
}
|
|
function declaredOptions(type) {
|
|
const value = String(type || "").trim();
|
|
if (!value)
|
|
return [];
|
|
const parts = value.split("|").map((part) => part.trim());
|
|
if (!parts.every((part) => /^(?:"[^"]*"|'[^']*')$/.test(part)))
|
|
return [];
|
|
return parts.map((part) => part.slice(1, -1));
|
|
}
|
|
function inferOptions(source, propName) {
|
|
const escaped = propName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
const options = new Set;
|
|
const comparisons = new RegExp(`\\b${escaped}\\s*(?:===|!==|==|!=)\\s*(["'])(.*?)\\1`, "g");
|
|
let match;
|
|
while ((match = comparisons.exec(source)) !== null)
|
|
options.add(match[2]);
|
|
return [...options].sort();
|
|
}
|
|
function parseComponentMetadata(source, uri = null) {
|
|
const declaration = COMPONENT_DECLARATION.exec(source);
|
|
if (!declaration)
|
|
return null;
|
|
const propsKeyword = /\bprops\s*\{/.exec(source.slice(declaration.index));
|
|
const props = [];
|
|
const events = [];
|
|
if (propsKeyword) {
|
|
const start = declaration.index + propsKeyword.index;
|
|
const openingBrace = source.indexOf("{", start);
|
|
const closingBrace = findMatchingBrace(source, openingBrace);
|
|
const bodyEnd = closingBrace === -1 ? source.length : closingBrace;
|
|
const body = source.slice(openingBrace + 1, bodyEnd);
|
|
const linePattern = /^(?:\s*\/\/\s*@required\s*\r?\n)?\s*([A-Za-z_$][\w$]*)(\?)?(?:\s*:\s*([^=\r\n]+?))?(?:\s*=\s*(.*?))?\s*$/gm;
|
|
let propMatch;
|
|
while ((propMatch = linePattern.exec(body)) !== null) {
|
|
const optional = Boolean(propMatch[2]);
|
|
const annotation = propMatch[3] && propMatch[3].trim();
|
|
const hasDefault = propMatch[4] !== undefined;
|
|
const defaultValue = hasDefault ? propMatch[4] : "undefined";
|
|
const name = propMatch[1];
|
|
props.push({
|
|
name,
|
|
defaultValue,
|
|
required: !optional && (!hasDefault || defaultValue.trim() === "undefined" || /^\s*\/\/\s*@required/m.test(propMatch[0])),
|
|
type: annotation || inferType(defaultValue),
|
|
options: declaredOptions(annotation).length > 0 ? declaredOptions(annotation) : inferOptions(source, name)
|
|
});
|
|
}
|
|
const eventPattern = /^\s*@event\s+([A-Za-z_$][\w$]*)\s*=\s*function\s*$/gm;
|
|
let eventMatch;
|
|
while ((eventMatch = eventPattern.exec(body)) !== null)
|
|
events.push(eventMatch[1]);
|
|
}
|
|
const outputsKeyword = /\boutputs\s*\{/.exec(source.slice(declaration.index));
|
|
if (outputsKeyword) {
|
|
const start = declaration.index + outputsKeyword.index;
|
|
const openingBrace = source.indexOf("{", start);
|
|
const closingBrace = findMatchingBrace(source, openingBrace);
|
|
const outputBody = source.slice(openingBrace + 1, closingBrace === -1 ? source.length : closingBrace);
|
|
const outputPattern = /(?:^|\s)([A-Za-z_$][\w$]*)\s*\(/g;
|
|
let outputMatch;
|
|
while ((outputMatch = outputPattern.exec(outputBody)) !== null) {
|
|
if (!events.includes(outputMatch[1]))
|
|
events.push(outputMatch[1]);
|
|
}
|
|
}
|
|
return { kind: declaration[1], name: declaration[2], props, events, uri };
|
|
}
|
|
function unwrapAttributeValue(value) {
|
|
const trimmed = value.trim();
|
|
if (trimmed.startsWith("{") && trimmed.endsWith("}"))
|
|
return trimmed.slice(1, -1).trim();
|
|
return trimmed;
|
|
}
|
|
function isWrappedExpression(value) {
|
|
const trimmed = value.trim();
|
|
return trimmed.startsWith("{") && trimmed.endsWith("}");
|
|
}
|
|
function expressionLiteralType(value) {
|
|
const expression = value.trim();
|
|
if (/^(?:true|false)$/.test(expression))
|
|
return "boolean";
|
|
if (/^-?(?:\d+\.?\d*|\.\d+)$/.test(expression))
|
|
return "number";
|
|
if (/^(?:"[\s\S]*"|'[\s\S]*'|`[\s\S]*`)$/.test(expression))
|
|
return "string";
|
|
if (expression.startsWith("["))
|
|
return "array";
|
|
if (expression.startsWith("{"))
|
|
return "object";
|
|
if (expression === "null")
|
|
return "null";
|
|
return null;
|
|
}
|
|
function attributeValueType(value, symbols = new Map) {
|
|
const expression = isWrappedExpression(value);
|
|
const unwrapped = unwrapAttributeValue(value);
|
|
if (/^[A-Za-z_$][\w$]*$/.test(unwrapped) && symbols.has(unwrapped)) {
|
|
return symbols.get(unwrapped);
|
|
}
|
|
const literal = expressionLiteralType(unwrapped);
|
|
if (literal)
|
|
return literal;
|
|
if (expression) {
|
|
if (/^!\s*/.test(unwrapped) || /(?:===|!==|==|!=|<=|>=|<|>|\bin\b|\binstanceof\b)/.test(unwrapped)) {
|
|
return "boolean";
|
|
}
|
|
return "unknown";
|
|
}
|
|
return "string";
|
|
}
|
|
function isTypeCompatible(prop, value, symbols = new Map) {
|
|
const expected = runtimeType(prop.type);
|
|
if (expected === "unknown" || expected === "null")
|
|
return true;
|
|
const actual = runtimeType(attributeValueType(value, symbols));
|
|
if (actual === "unknown")
|
|
return true;
|
|
if (expected === actual)
|
|
return true;
|
|
if (expected === "number" && actual === "string")
|
|
return Number.isFinite(Number(value));
|
|
if (expected === "boolean" && actual === "string")
|
|
return /^(?:true|false|1|0|yes|no|on|off)?$/i.test(value);
|
|
return false;
|
|
}
|
|
function parseComponentTags(source) {
|
|
const tags = [];
|
|
const pattern = /<([A-Z][A-Za-z0-9_$]*)(\s[\s\S]*?)?\s*\/?>/g;
|
|
let match;
|
|
while ((match = pattern.exec(source)) !== null) {
|
|
const attributes = [];
|
|
const attributeSource = match[2] || "";
|
|
const attributeOffset = match.index + match[0].indexOf(attributeSource);
|
|
const attributePattern = /([^\s=/>]+)\s*=\s*(["'])([\s\S]*?)\2/g;
|
|
let attributeMatch;
|
|
while ((attributeMatch = attributePattern.exec(attributeSource)) !== null) {
|
|
const nameStart = attributeOffset + attributeMatch.index;
|
|
attributes.push({
|
|
name: attributeMatch[1],
|
|
value: attributeMatch[3],
|
|
nameStart,
|
|
nameEnd: nameStart + attributeMatch[1].length
|
|
});
|
|
}
|
|
tags.push({
|
|
name: match[1],
|
|
start: match.index,
|
|
end: match.index + match[0].length,
|
|
nameStart: match.index + 1,
|
|
nameEnd: match.index + 1 + match[1].length,
|
|
attributes
|
|
});
|
|
}
|
|
return tags;
|
|
}
|
|
function validateComponentTags(source, components) {
|
|
const diagnostics = [];
|
|
const own = parseComponentMetadata(source);
|
|
const symbols = new Map((own?.props || []).map((prop) => [prop.name, prop.type]));
|
|
const statePattern = /^\s*state\s+([A-Za-z_$][\w$]*)(?:\s*:\s*([^=\r\n]+?))?\s*=\s*(.*?)\s*$/gm;
|
|
let stateMatch;
|
|
while ((stateMatch = statePattern.exec(source)) !== null) {
|
|
symbols.set(stateMatch[1], stateMatch[2]?.trim() || inferType(stateMatch[3]));
|
|
}
|
|
for (const tag of parseComponentTags(source)) {
|
|
const component = components.get(tag.name);
|
|
if (!component)
|
|
continue;
|
|
const provided = new Map(tag.attributes.map((attribute) => [attribute.name, attribute]));
|
|
const declared = new Map(component.props.map((prop) => [prop.name, prop]));
|
|
const declaredEvents = new Set(component.events || []);
|
|
for (const prop of component.props) {
|
|
if (prop.required && !provided.has(prop.name)) {
|
|
diagnostics.push({
|
|
severity: "error",
|
|
code: "wrn-missing-component-prop",
|
|
message: `<${tag.name}> requires prop \`${prop.name}\` (${prop.type}).`,
|
|
start: tag.nameStart,
|
|
end: tag.nameEnd
|
|
});
|
|
}
|
|
}
|
|
for (const attribute of tag.attributes) {
|
|
if (attribute.name.startsWith("@")) {
|
|
const eventName = attribute.name.slice(1);
|
|
if (!declaredEvents.has(eventName)) {
|
|
diagnostics.push({
|
|
severity: "warning",
|
|
code: "wrn-unknown-component-event",
|
|
message: `Unknown event \`${eventName}\` on <${tag.name}>.`,
|
|
start: attribute.nameStart,
|
|
end: attribute.nameEnd
|
|
});
|
|
}
|
|
continue;
|
|
}
|
|
const prop = declared.get(attribute.name);
|
|
if (!prop) {
|
|
diagnostics.push({
|
|
severity: "warning",
|
|
code: "wrn-unknown-component-prop",
|
|
message: `Unknown prop \`${attribute.name}\` on <${tag.name}>.`,
|
|
start: attribute.nameStart,
|
|
end: attribute.nameEnd
|
|
});
|
|
continue;
|
|
}
|
|
const actualType = attributeValueType(attribute.value, symbols);
|
|
if (!isTypeCompatible(prop, attribute.value, symbols)) {
|
|
diagnostics.push({
|
|
severity: "error",
|
|
code: "wrn-component-prop-type",
|
|
message: `Prop \`${attribute.name}\` on <${tag.name}> expects ${prop.type}, but received ${runtimeType(actualType)}.`,
|
|
start: attribute.nameStart,
|
|
end: attribute.nameEnd
|
|
});
|
|
}
|
|
const optionValue = isWrappedExpression(attribute.value) ? stringLiteral(unwrapAttributeValue(attribute.value)) : stringLiteral(attribute.value) ?? attribute.value;
|
|
if (optionValue !== null && prop.options.length > 0 && !prop.options.includes(optionValue)) {
|
|
diagnostics.push({
|
|
severity: "warning",
|
|
code: "wrn-component-prop-option",
|
|
message: `Prop \`${attribute.name}\` should be one of: ${prop.options.join(", ")}.`,
|
|
start: attribute.nameStart,
|
|
end: attribute.nameEnd
|
|
});
|
|
}
|
|
}
|
|
}
|
|
return diagnostics;
|
|
}
|
|
module2.exports = {
|
|
attributeValueType,
|
|
declaredOptions,
|
|
inferType,
|
|
runtimeType,
|
|
isTypeCompatible,
|
|
parseComponentMetadata,
|
|
parseComponentTags,
|
|
validateComponentTags
|
|
};
|
|
});
|
|
|
|
// editors/vscode/src/component-intelligence.js
|
|
var require_component_intelligence = __commonJS((exports2, module2) => {
|
|
var vscode = require("vscode");
|
|
var path = require("node:path");
|
|
var {
|
|
parseComponentMetadata,
|
|
parseComponentTags,
|
|
validateComponentTags
|
|
} = require_component_metadata();
|
|
var catalogPromise = null;
|
|
async function readMetadata(uri) {
|
|
try {
|
|
const document = await vscode.workspace.openTextDocument(uri);
|
|
return parseComponentMetadata(document.getText(), uri);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
async function installedUiUris() {
|
|
const uris = [];
|
|
for (const folder of vscode.workspace.workspaceFolders || []) {
|
|
const directory = vscode.Uri.joinPath(folder.uri, "node_modules", "@wrnexus", "ui", "components");
|
|
try {
|
|
for (const [name, type] of await vscode.workspace.fs.readDirectory(directory)) {
|
|
if (type === vscode.FileType.File && name.endsWith(".wrn")) {
|
|
uris.push(vscode.Uri.joinPath(directory, name));
|
|
}
|
|
}
|
|
} catch {}
|
|
}
|
|
return uris;
|
|
}
|
|
async function loadComponentCatalog() {
|
|
const localUris = await vscode.workspace.findFiles("**/*.wrn", "**/{node_modules,dist,.wrnexus,.git}/**");
|
|
const uiUris = await installedUiUris();
|
|
const metadata = await Promise.all([...uiUris, ...localUris].map(readMetadata));
|
|
const catalog = new Map;
|
|
for (const component of metadata) {
|
|
if (component && (component.kind === "component" || component.kind === "layout")) {
|
|
catalog.set(component.name, component);
|
|
}
|
|
}
|
|
return catalog;
|
|
}
|
|
function componentCatalog() {
|
|
catalogPromise ||= loadComponentCatalog();
|
|
return catalogPromise;
|
|
}
|
|
function invalidateCatalog() {
|
|
catalogPromise = null;
|
|
}
|
|
function openingTagAt(source, offset) {
|
|
const opening = source.lastIndexOf("<", offset);
|
|
const closing = source.lastIndexOf(">", offset);
|
|
if (opening <= closing)
|
|
return null;
|
|
const fragment = source.slice(opening, offset);
|
|
const match = /^<([A-Z][A-Za-z0-9_$]*)\b/.exec(fragment);
|
|
return match ? { name: match[1], fragment } : null;
|
|
}
|
|
function componentAlreadyImported(source, name) {
|
|
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
return new RegExp(`\\bimport[\\s\\S]*?\\b${escaped}\\b[\\s\\S]*?\\bfrom\\b`).test(source) || new RegExp(`\\b(?:component|layout)\\s+${escaped}\\b`).test(source);
|
|
}
|
|
function importEditForComponent(document, component) {
|
|
if (!component?.uri || componentAlreadyImported(document.getText(), component.name))
|
|
return null;
|
|
const target = component.uri.fsPath.replace(/\\/g, "/");
|
|
const current = document.uri.fsPath.replace(/\\/g, "/");
|
|
let statement;
|
|
if (target.includes("/node_modules/@wrnexus/ui/components/") || target.includes("/packages/ui/components/")) {
|
|
statement = `import { ${component.name} } from "@wrnexus/ui"
|
|
`;
|
|
} else {
|
|
const appMarker = "/app/";
|
|
const appIndex = target.lastIndexOf(appMarker);
|
|
if (appIndex !== -1) {
|
|
statement = `import ${component.name} from "@/${target.slice(appIndex + appMarker.length)}"
|
|
`;
|
|
} else {
|
|
let relative = path.posix.relative(path.posix.dirname(current), target);
|
|
if (!relative.startsWith("."))
|
|
relative = `./${relative}`;
|
|
statement = `import ${component.name} from "${relative}"
|
|
`;
|
|
}
|
|
}
|
|
return vscode.TextEdit.insert(new vscode.Position(0, 0), statement);
|
|
}
|
|
function propSnippet(prop) {
|
|
if (prop.type === "boolean")
|
|
return `${prop.name}="{\${1:false}}"`;
|
|
if (prop.type === "number")
|
|
return `${prop.name}="{\${1:0}}"`;
|
|
if (prop.type === "array")
|
|
return `${prop.name}="{[\${1}]}"`;
|
|
if (prop.type === "object")
|
|
return `${prop.name}="{{ \${1} }}"`;
|
|
if (prop.options.length > 0)
|
|
return `${prop.name}="\${1|${prop.options.join(",")}|}"`;
|
|
return `${prop.name}="\${1}"`;
|
|
}
|
|
function propDocumentation(prop) {
|
|
const lines = [
|
|
`**${prop.name}** — \`${prop.type}\` ${prop.required ? "**required**" : "optional"}`
|
|
];
|
|
if (!prop.required)
|
|
lines.push(`Default: \`${prop.defaultValue}\``);
|
|
if (prop.options.length > 0)
|
|
lines.push(`Allowed: ${prop.options.map((v) => `\`${v}\``).join(", ")}`);
|
|
return lines.join(`
|
|
|
|
`);
|
|
}
|
|
async function provideComponentCompletions(document, position) {
|
|
const source = document.getText();
|
|
const offset = document.offsetAt(position);
|
|
const tag = openingTagAt(source, offset);
|
|
const catalog = await componentCatalog();
|
|
const items = [];
|
|
if (tag) {
|
|
const component = catalog.get(tag.name);
|
|
if (!component)
|
|
return items;
|
|
const used = new Set([...tag.fragment.matchAll(/\s([^\s=/>]+)\s*=/g)].map((m) => m[1]));
|
|
for (const prop of component.props) {
|
|
if (used.has(prop.name))
|
|
continue;
|
|
const item = new vscode.CompletionItem(prop.name, vscode.CompletionItemKind.Property);
|
|
item.detail = `${prop.required ? "required" : "optional"} · ${prop.type}`;
|
|
item.documentation = new vscode.MarkdownString(propDocumentation(prop));
|
|
item.insertText = new vscode.SnippetString(propSnippet(prop));
|
|
item.sortText = `${prop.required ? "0" : "1"}-${prop.name}`;
|
|
items.push(item);
|
|
}
|
|
return items;
|
|
}
|
|
const prefix = source.slice(Math.max(0, offset - 80), offset);
|
|
if (!/<[A-Za-z0-9_$]*$/.test(prefix))
|
|
return items;
|
|
for (const component of catalog.values()) {
|
|
const item = new vscode.CompletionItem(component.name, vscode.CompletionItemKind.Class);
|
|
const required = component.props.filter((prop) => prop.required);
|
|
item.detail = `WRN ${component.kind} · ${component.props.length} props`;
|
|
item.documentation = new vscode.MarkdownString(componentMarkdown(component));
|
|
item.insertText = new vscode.SnippetString(`${component.name}${required.map((prop, index) => ` ${prop.name}="\${${index + 1}}"`).join("")} />`);
|
|
const importEdit = importEditForComponent(document, component);
|
|
if (importEdit)
|
|
item.additionalTextEdits = [importEdit];
|
|
items.push(item);
|
|
}
|
|
return items;
|
|
}
|
|
function componentMarkdown(component) {
|
|
const lines = [
|
|
`### <${component.name}>`,
|
|
"",
|
|
"| Prop | Type | Required | Default / options |",
|
|
"|---|---|---:|---|"
|
|
];
|
|
for (const prop of component.props) {
|
|
const detail = prop.options.length > 0 ? prop.options.join(" \\| ") : prop.required ? "—" : prop.defaultValue;
|
|
lines.push(`| \`${prop.name}\` | \`${prop.type}\` | ${prop.required ? "yes" : "no"} | ${detail} |`);
|
|
}
|
|
return lines.join(`
|
|
`);
|
|
}
|
|
async function provideComponentHover(document, position) {
|
|
const source = document.getText();
|
|
const offset = document.offsetAt(position);
|
|
const catalog = await componentCatalog();
|
|
const tag = parseComponentTags(source).find((candidate) => offset >= candidate.start && offset <= candidate.end);
|
|
if (!tag)
|
|
return null;
|
|
const component = catalog.get(tag.name);
|
|
if (!component)
|
|
return null;
|
|
const attribute = tag.attributes.find((candidate) => offset >= candidate.nameStart && offset <= candidate.nameEnd);
|
|
const markdown = attribute ? propDocumentation(component.props.find((prop) => prop.name === attribute.name) || {
|
|
name: attribute.name,
|
|
type: "unknown",
|
|
required: false,
|
|
defaultValue: "unknown",
|
|
options: []
|
|
}) : componentMarkdown(component);
|
|
return new vscode.Hover(new vscode.MarkdownString(markdown));
|
|
}
|
|
function registerComponentIntelligence(context) {
|
|
const diagnostics = vscode.languages.createDiagnosticCollection("wrnexus-components");
|
|
const update = async (document) => {
|
|
if (document.languageId !== "wrn")
|
|
return;
|
|
const catalog = await componentCatalog();
|
|
const results = validateComponentTags(document.getText(), catalog).map((result) => {
|
|
const diagnostic = new vscode.Diagnostic(new vscode.Range(document.positionAt(result.start), document.positionAt(result.end)), result.message, result.severity === "error" ? vscode.DiagnosticSeverity.Error : vscode.DiagnosticSeverity.Warning);
|
|
diagnostic.source = "WRNexus Components";
|
|
diagnostic.code = result.code;
|
|
return diagnostic;
|
|
});
|
|
diagnostics.set(document.uri, results);
|
|
};
|
|
const watchers = (vscode.workspace.workspaceFolders || []).map((folder) => vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(folder, "app/**/*.wrn")));
|
|
const refreshOpenDocuments = () => {
|
|
invalidateCatalog();
|
|
for (const document of vscode.workspace.textDocuments)
|
|
update(document);
|
|
};
|
|
context.subscriptions.push(diagnostics, ...watchers, ...watchers.flatMap((watcher) => [
|
|
watcher.onDidCreate(refreshOpenDocuments),
|
|
watcher.onDidChange(refreshOpenDocuments),
|
|
watcher.onDidDelete(refreshOpenDocuments)
|
|
]), vscode.workspace.onDidOpenTextDocument(update), vscode.workspace.onDidChangeTextDocument((event) => void update(event.document)), vscode.workspace.onDidSaveTextDocument((document) => {
|
|
invalidateCatalog();
|
|
update(document);
|
|
}), vscode.workspace.onDidCloseTextDocument((document) => diagnostics.delete(document.uri)), vscode.languages.registerCompletionItemProvider({ language: "wrn" }, { provideCompletionItems: provideComponentCompletions }, "<", " "), vscode.languages.registerHoverProvider({ language: "wrn" }, { provideHover: provideComponentHover }));
|
|
for (const document of vscode.workspace.textDocuments)
|
|
update(document);
|
|
}
|
|
module2.exports = {
|
|
componentAlreadyImported,
|
|
componentMarkdown,
|
|
importEditForComponent,
|
|
openingTagAt,
|
|
propDocumentation,
|
|
propSnippet,
|
|
registerComponentIntelligence
|
|
};
|
|
});
|
|
|
|
// editors/vscode/src/diagnostics.js
|
|
var require_diagnostics = __commonJS((exports2, module2) => {
|
|
var vscode = require("vscode");
|
|
var COLLECTION_NAME = "wrnexus";
|
|
var WRN_LANGUAGE_ID = "wrn";
|
|
var TOP_LEVEL_PATTERN = /^\s*((?:global|page)\s+store|page|component|layout)\s+([A-Za-z_$][\w$]*)\s*\{/;
|
|
var VALID_TOP_LEVEL_KINDS = new Set([
|
|
"page",
|
|
"component",
|
|
"layout",
|
|
"global store",
|
|
"page store"
|
|
]);
|
|
var VALID_LIFECYCLE_HOOKS = new Set(["mount", "update", "unmount"]);
|
|
var ROOT_MEMBER_NAMES = [
|
|
"layout",
|
|
"runtime",
|
|
"hydrate",
|
|
"client",
|
|
"types",
|
|
"props",
|
|
"outputs",
|
|
"state",
|
|
"persist",
|
|
"computed",
|
|
"effect",
|
|
"watch",
|
|
"lifecycle",
|
|
"view",
|
|
"seo",
|
|
"security",
|
|
"load",
|
|
"action",
|
|
"api",
|
|
"ssr",
|
|
"realtime",
|
|
"style",
|
|
"functions"
|
|
];
|
|
var VALID_MEMBERS = {
|
|
page: new Set(ROOT_MEMBER_NAMES),
|
|
component: new Set(ROOT_MEMBER_NAMES),
|
|
layout: new Set(ROOT_MEMBER_NAMES),
|
|
"global store": new Set(ROOT_MEMBER_NAMES),
|
|
"page store": new Set(ROOT_MEMBER_NAMES)
|
|
};
|
|
function createDiagnostic(document, startOffset, endOffset, message, severity = vscode.DiagnosticSeverity.Error, code) {
|
|
const diagnostic = new vscode.Diagnostic(new vscode.Range(document.positionAt(startOffset), document.positionAt(endOffset)), message, severity);
|
|
diagnostic.source = "WRNexus";
|
|
if (code) {
|
|
diagnostic.code = code;
|
|
}
|
|
return diagnostic;
|
|
}
|
|
function lineDiagnostic(document, lineNumber, message, severity = vscode.DiagnosticSeverity.Error, code) {
|
|
const line = document.lineAt(lineNumber);
|
|
const diagnostic = new vscode.Diagnostic(line.range, message, severity);
|
|
diagnostic.source = "WRNexus";
|
|
if (code) {
|
|
diagnostic.code = code;
|
|
}
|
|
return diagnostic;
|
|
}
|
|
function maskLeadingTrivia(source) {
|
|
const masked = [...source];
|
|
let offset = 0;
|
|
const importPattern = /import\s+(?:type\s+)?(?:[\s\S]*?\s+from\s+)?["'][^"'\r\n]+["']\s*;?/y;
|
|
while (offset < source.length) {
|
|
if (/\s/u.test(source[offset])) {
|
|
offset += 1;
|
|
continue;
|
|
}
|
|
importPattern.lastIndex = offset;
|
|
const importStatement = importPattern.exec(source);
|
|
if (importStatement) {
|
|
const end = importPattern.lastIndex;
|
|
while (offset < end) {
|
|
if (source[offset] !== `
|
|
` && source[offset] !== "\r")
|
|
masked[offset] = " ";
|
|
offset += 1;
|
|
}
|
|
continue;
|
|
}
|
|
if (!source.startsWith("//", offset))
|
|
break;
|
|
while (offset < source.length && source[offset] !== `
|
|
`) {
|
|
masked[offset] = " ";
|
|
offset += 1;
|
|
}
|
|
}
|
|
return masked.join("");
|
|
}
|
|
function findTopLevelDeclaration(document, source) {
|
|
const sourceWithoutLeadingTrivia = maskLeadingTrivia(source);
|
|
const match = TOP_LEVEL_PATTERN.exec(sourceWithoutLeadingTrivia);
|
|
if (!match) {
|
|
const firstMeaningfulLine = sourceWithoutLeadingTrivia.split(/\r?\n/).findIndex((line) => line.trim().length > 0);
|
|
return {
|
|
diagnostic: lineDiagnostic(document, Math.max(0, firstMeaningfulLine), "A .wrn file must start with `page`, `component`, or `layout`.", vscode.DiagnosticSeverity.Error, "wrn-invalid-root")
|
|
};
|
|
}
|
|
return {
|
|
kind: match[1],
|
|
name: match[2],
|
|
match
|
|
};
|
|
}
|
|
function validateBalancedCharacters(document, source) {
|
|
const diagnostics = [];
|
|
const stack = [];
|
|
let quote = null;
|
|
let escaped = false;
|
|
const pairs = {
|
|
"}": "{",
|
|
"]": "[",
|
|
")": "("
|
|
};
|
|
for (let index = 0;index < source.length; index += 1) {
|
|
const character = source[index];
|
|
if (quote !== null) {
|
|
if (escaped) {
|
|
escaped = false;
|
|
continue;
|
|
}
|
|
if (character === "\\") {
|
|
escaped = true;
|
|
continue;
|
|
}
|
|
if (character === quote) {
|
|
quote = null;
|
|
}
|
|
continue;
|
|
}
|
|
if (source.startsWith("//", index)) {
|
|
const lineEnd = source.indexOf(`
|
|
`, index + 2);
|
|
index = lineEnd === -1 ? source.length : lineEnd;
|
|
continue;
|
|
}
|
|
if (character === "'" && /[\p{L}\p{N}]/u.test(source[index - 1] ?? "") && /[\p{L}\p{N}]/u.test(source[index + 1] ?? "")) {
|
|
continue;
|
|
}
|
|
if (character === '"' || character === "'") {
|
|
quote = character;
|
|
continue;
|
|
}
|
|
if (source.startsWith("<!--", index)) {
|
|
const commentEnd = source.indexOf("-->", index + 4);
|
|
if (commentEnd === -1) {
|
|
diagnostics.push(createDiagnostic(document, index, Math.min(source.length, index + 4), "Unclosed HTML comment.", vscode.DiagnosticSeverity.Error, "wrn-unclosed-comment"));
|
|
break;
|
|
}
|
|
index = commentEnd + 2;
|
|
continue;
|
|
}
|
|
if (character === "{" || character === "[" || character === "(") {
|
|
stack.push({
|
|
character,
|
|
offset: index
|
|
});
|
|
continue;
|
|
}
|
|
if (character === "}" || character === "]" || character === ")") {
|
|
const expectedOpening = pairs[character];
|
|
const opening = stack.pop();
|
|
if (!opening || opening.character !== expectedOpening) {
|
|
diagnostics.push(createDiagnostic(document, index, index + 1, `Unexpected \`${character}\`.`, vscode.DiagnosticSeverity.Error, "wrn-unexpected-closing"));
|
|
}
|
|
}
|
|
}
|
|
for (const opening of stack) {
|
|
const expectedClosing = opening.character === "{" ? "}" : opening.character === "[" ? "]" : ")";
|
|
diagnostics.push(createDiagnostic(document, opening.offset, opening.offset + 1, `Missing closing \`${expectedClosing}\`.`, vscode.DiagnosticSeverity.Error, "wrn-missing-closing"));
|
|
}
|
|
if (quote !== null) {
|
|
diagnostics.push(createDiagnostic(document, Math.max(0, source.length - 1), source.length, `Unclosed ${quote === '"' ? "double" : "single"} quote.`, vscode.DiagnosticSeverity.Error, "wrn-unclosed-string"));
|
|
}
|
|
return diagnostics;
|
|
}
|
|
function maskHtmlComments(source) {
|
|
const masked = [...source];
|
|
let index = 0;
|
|
while (index < source.length) {
|
|
if (!source.startsWith("<!--", index)) {
|
|
index += 1;
|
|
continue;
|
|
}
|
|
const commentEnd = source.indexOf("-->", index + 4);
|
|
const end = commentEnd === -1 ? source.length : commentEnd + 3;
|
|
for (let cursor = index;cursor < end; cursor += 1) {
|
|
if (source[cursor] !== `
|
|
` && source[cursor] !== "\r")
|
|
masked[cursor] = " ";
|
|
}
|
|
index = end;
|
|
}
|
|
return masked.join("");
|
|
}
|
|
function maskTemplateExpressions(source) {
|
|
const masked = [...source];
|
|
let index = 0;
|
|
while (index < source.length) {
|
|
if (source[index] !== "{") {
|
|
index += 1;
|
|
continue;
|
|
}
|
|
const start = index;
|
|
let depth = 0;
|
|
let quote = null;
|
|
let escaped = false;
|
|
while (index < source.length) {
|
|
const character = source[index];
|
|
if (quote !== null) {
|
|
if (escaped)
|
|
escaped = false;
|
|
else if (character === "\\")
|
|
escaped = true;
|
|
else if (character === quote)
|
|
quote = null;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (character === '"' || character === "'" || character === "`") {
|
|
quote = character;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (character === "{")
|
|
depth += 1;
|
|
else if (character === "}") {
|
|
depth -= 1;
|
|
index += 1;
|
|
if (depth === 0)
|
|
break;
|
|
continue;
|
|
}
|
|
index += 1;
|
|
}
|
|
for (let cursor = start;cursor < index; cursor += 1) {
|
|
if (source[cursor] !== `
|
|
` && source[cursor] !== "\r")
|
|
masked[cursor] = " ";
|
|
}
|
|
}
|
|
return masked.join("");
|
|
}
|
|
function findViewRanges(source) {
|
|
const ranges = [];
|
|
const pattern = /\bview\s*\{/g;
|
|
let match;
|
|
while ((match = pattern.exec(source)) !== null) {
|
|
const openingBrace = source.indexOf("{", match.index);
|
|
const closingBrace = findMatchingBrace(source, openingBrace);
|
|
if (closingBrace === -1)
|
|
break;
|
|
ranges.push({ start: openingBrace + 1, end: closingBrace });
|
|
pattern.lastIndex = closingBrace + 1;
|
|
}
|
|
return ranges;
|
|
}
|
|
function validateHtmlTags(document, source) {
|
|
const diagnostics = [];
|
|
const voidElements = new Set([
|
|
"area",
|
|
"base",
|
|
"br",
|
|
"col",
|
|
"embed",
|
|
"hr",
|
|
"img",
|
|
"input",
|
|
"link",
|
|
"meta",
|
|
"param",
|
|
"source",
|
|
"track",
|
|
"wbr"
|
|
]);
|
|
for (const range of findViewRanges(source)) {
|
|
const fragment = source.slice(range.start, range.end);
|
|
const cleaned = maskTemplateExpressions(maskHtmlComments(fragment));
|
|
const stack = [];
|
|
const tagPattern = /<\/?([A-Za-z][A-Za-z0-9_$:.-]*)(?:\s[\s\S]*?)?\/?>/g;
|
|
let match;
|
|
while ((match = tagPattern.exec(cleaned)) !== null) {
|
|
const completeTag = match[0];
|
|
const tagName = match[1];
|
|
const normalizedName = /^[a-z]/.test(tagName) ? tagName.toLowerCase() : tagName;
|
|
const lowerTag = tagName.toLowerCase();
|
|
const absoluteStart = range.start + match.index;
|
|
const isClosing = completeTag.startsWith("</");
|
|
const isSelfClosing = /\/\s*>$/.test(completeTag);
|
|
const isVoid = voidElements.has(lowerTag);
|
|
if (isClosing) {
|
|
const matchingIndex = stack.findLastIndex((item) => item.normalizedName === normalizedName);
|
|
if (matchingIndex === -1) {
|
|
diagnostics.push(createDiagnostic(document, absoluteStart, absoluteStart + completeTag.length, `Unexpected closing tag </${tagName}>.`, vscode.DiagnosticSeverity.Error, "wrn-unexpected-html-close"));
|
|
continue;
|
|
}
|
|
const last = stack.at(-1);
|
|
if (last.normalizedName !== normalizedName) {
|
|
diagnostics.push(createDiagnostic(document, absoluteStart, absoluteStart + completeTag.length, `Mismatched closing tag </${tagName}>. Expected </${last.tagName}>.`, vscode.DiagnosticSeverity.Error, "wrn-mismatched-html-tag"));
|
|
}
|
|
stack.splice(matchingIndex);
|
|
continue;
|
|
}
|
|
if (!isSelfClosing && !isVoid) {
|
|
stack.push({
|
|
tagName,
|
|
normalizedName,
|
|
offset: absoluteStart,
|
|
length: completeTag.length
|
|
});
|
|
}
|
|
}
|
|
for (const tag of stack) {
|
|
diagnostics.push(createDiagnostic(document, tag.offset, tag.offset + tag.length, `Missing closing tag </${tag.tagName}>.`, vscode.DiagnosticSeverity.Error, "wrn-missing-html-close"));
|
|
}
|
|
}
|
|
return diagnostics;
|
|
}
|
|
function getRootBodyRange(source, rootMatch) {
|
|
const openingBrace = rootMatch.index + rootMatch[0].lastIndexOf("{");
|
|
const closingBrace = findMatchingBrace(source, openingBrace);
|
|
return {
|
|
start: openingBrace + 1,
|
|
end: closingBrace === -1 ? source.length : closingBrace
|
|
};
|
|
}
|
|
function findMatchingBrace(source, openingBrace) {
|
|
let depth = 0;
|
|
let quote = null;
|
|
let escaped = false;
|
|
for (let index = openingBrace;index < source.length; index += 1) {
|
|
const character = source[index];
|
|
if (quote !== null) {
|
|
if (escaped) {
|
|
escaped = false;
|
|
continue;
|
|
}
|
|
if (character === "\\") {
|
|
escaped = true;
|
|
continue;
|
|
}
|
|
if (character === quote) {
|
|
quote = null;
|
|
}
|
|
continue;
|
|
}
|
|
if (character === '"' || character === "'") {
|
|
quote = character;
|
|
continue;
|
|
}
|
|
if (source.startsWith("<!--", index)) {
|
|
const commentEnd = source.indexOf("-->", index + 4);
|
|
if (commentEnd === -1) {
|
|
return -1;
|
|
}
|
|
index = commentEnd + 2;
|
|
continue;
|
|
}
|
|
if (character === "{") {
|
|
depth += 1;
|
|
continue;
|
|
}
|
|
if (character === "}") {
|
|
depth -= 1;
|
|
if (depth === 0) {
|
|
return index;
|
|
}
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
function skipWhitespace(source, index, end) {
|
|
while (index < end && /\s/.test(source[index])) {
|
|
index += 1;
|
|
}
|
|
return index;
|
|
}
|
|
function readIdentifier(source, index, end) {
|
|
if (index >= end || !/[A-Za-z_$]/.test(source[index])) {
|
|
return null;
|
|
}
|
|
const start = index;
|
|
index += 1;
|
|
while (index < end && /[A-Za-z0-9_$-]/.test(source[index])) {
|
|
index += 1;
|
|
}
|
|
return {
|
|
name: source.slice(start, index),
|
|
start,
|
|
end: index
|
|
};
|
|
}
|
|
function findRootMembers(source, bodyStart, bodyEnd) {
|
|
const members = [];
|
|
let index = bodyStart;
|
|
let depth = 0;
|
|
let quote = null;
|
|
let escaped = false;
|
|
const skipLine = () => {
|
|
while (index < bodyEnd && source[index] !== `
|
|
` && source[index] !== "\r") {
|
|
index += 1;
|
|
}
|
|
};
|
|
while (index < bodyEnd) {
|
|
const character = source[index];
|
|
if (quote !== null) {
|
|
if (escaped) {
|
|
escaped = false;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (character === "\\") {
|
|
escaped = true;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (character === quote) {
|
|
quote = null;
|
|
}
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (character === '"' || character === "'") {
|
|
quote = character;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (source.startsWith("//", index)) {
|
|
skipLine();
|
|
continue;
|
|
}
|
|
if (source.startsWith("/*", index)) {
|
|
const end = source.indexOf("*/", index + 2);
|
|
index = end === -1 ? bodyEnd : end + 2;
|
|
continue;
|
|
}
|
|
if (source.startsWith("<!--", index)) {
|
|
const end = source.indexOf("-->", index + 4);
|
|
index = end === -1 ? bodyEnd : end + 3;
|
|
continue;
|
|
}
|
|
if (character === "{") {
|
|
depth += 1;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (character === "}") {
|
|
depth = Math.max(0, depth - 1);
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (depth === 0 && /[A-Za-z_$]/.test(character)) {
|
|
const identifier = readIdentifier(source, index, bodyEnd);
|
|
if (!identifier) {
|
|
index += 1;
|
|
continue;
|
|
}
|
|
index = identifier.end;
|
|
members.push({
|
|
name: identifier.name,
|
|
start: identifier.start,
|
|
end: identifier.end
|
|
});
|
|
const assignmentMembers = new Set(["layout", "runtime", "hydrate", "state"]);
|
|
if (assignmentMembers.has(identifier.name)) {
|
|
skipLine();
|
|
continue;
|
|
}
|
|
if (identifier.name === "client") {
|
|
const next = skipWhitespace(source, index, bodyEnd);
|
|
if (source[next] === "=") {
|
|
skipLine();
|
|
continue;
|
|
}
|
|
}
|
|
const blockMembers = new Set([
|
|
"types",
|
|
"props",
|
|
"computed",
|
|
"effect",
|
|
"watch",
|
|
"lifecycle",
|
|
"view",
|
|
"seo",
|
|
"security",
|
|
"load",
|
|
"action",
|
|
"api",
|
|
"ssr",
|
|
"client",
|
|
"realtime",
|
|
"style",
|
|
"functions"
|
|
]);
|
|
if (blockMembers.has(identifier.name)) {
|
|
let cursor = index;
|
|
let parenthesisDepth = 0;
|
|
let bracketDepth = 0;
|
|
let memberQuote = null;
|
|
let memberEscaped = false;
|
|
while (cursor < bodyEnd) {
|
|
const current = source[cursor];
|
|
if (memberQuote !== null) {
|
|
if (memberEscaped) {
|
|
memberEscaped = false;
|
|
} else if (current === "\\") {
|
|
memberEscaped = true;
|
|
} else if (current === memberQuote) {
|
|
memberQuote = null;
|
|
}
|
|
cursor += 1;
|
|
continue;
|
|
}
|
|
if (current === '"' || current === "'") {
|
|
memberQuote = current;
|
|
cursor += 1;
|
|
continue;
|
|
}
|
|
if (current === "(")
|
|
parenthesisDepth += 1;
|
|
if (current === ")")
|
|
parenthesisDepth = Math.max(0, parenthesisDepth - 1);
|
|
if (current === "[")
|
|
bracketDepth += 1;
|
|
if (current === "]")
|
|
bracketDepth = Math.max(0, bracketDepth - 1);
|
|
if (current === "{" && parenthesisDepth === 0 && bracketDepth === 0) {
|
|
index = cursor;
|
|
break;
|
|
}
|
|
cursor += 1;
|
|
}
|
|
if (cursor >= bodyEnd)
|
|
index = bodyEnd;
|
|
}
|
|
continue;
|
|
}
|
|
index += 1;
|
|
}
|
|
return members;
|
|
}
|
|
function findNamedBlocks(source, bodyStart, bodyEnd, blockName) {
|
|
const blocks = [];
|
|
let index = bodyStart;
|
|
while (index < bodyEnd) {
|
|
index = skipWhitespace(source, index, bodyEnd);
|
|
const identifier = readIdentifier(source, index, bodyEnd);
|
|
if (!identifier) {
|
|
index += 1;
|
|
continue;
|
|
}
|
|
index = identifier.end;
|
|
if (identifier.name !== blockName) {
|
|
const possibleBrace = skipWhitespace(source, index, bodyEnd);
|
|
if (source[possibleBrace] === "{") {
|
|
const end = findMatchingBrace(source, possibleBrace);
|
|
index = end === -1 ? bodyEnd : end + 1;
|
|
}
|
|
continue;
|
|
}
|
|
const openingBrace = skipWhitespace(source, index, bodyEnd);
|
|
if (source[openingBrace] !== "{") {
|
|
blocks.push({
|
|
name: blockName,
|
|
nameStart: identifier.start,
|
|
nameEnd: identifier.end,
|
|
openingBrace: -1,
|
|
closingBrace: -1
|
|
});
|
|
continue;
|
|
}
|
|
const closingBrace = findMatchingBrace(source, openingBrace);
|
|
blocks.push({
|
|
name: blockName,
|
|
nameStart: identifier.start,
|
|
nameEnd: identifier.end,
|
|
openingBrace,
|
|
closingBrace
|
|
});
|
|
index = closingBrace === -1 ? bodyEnd : closingBrace + 1;
|
|
}
|
|
return blocks;
|
|
}
|
|
function findStateDeclarations(source, bodyStart, bodyEnd) {
|
|
const states = new Map;
|
|
let index = bodyStart;
|
|
let depth = 0;
|
|
let quote = null;
|
|
let escaped = false;
|
|
while (index < bodyEnd) {
|
|
const character = source[index];
|
|
if (quote !== null) {
|
|
if (escaped) {
|
|
escaped = false;
|
|
} else if (character === "\\") {
|
|
escaped = true;
|
|
} else if (character === quote) {
|
|
quote = null;
|
|
}
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (character === '"' || character === "'") {
|
|
quote = character;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (source.startsWith("<!--", index)) {
|
|
const end = source.indexOf("-->", index + 4);
|
|
index = end === -1 ? bodyEnd : end + 3;
|
|
continue;
|
|
}
|
|
if (character === "{") {
|
|
depth += 1;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (character === "}") {
|
|
depth = Math.max(0, depth - 1);
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (depth === 0 && source.startsWith("state", index) && !/[A-Za-z0-9_$]/.test(source[index - 1] || "") && !/[A-Za-z0-9_$]/.test(source[index + 5] || "")) {
|
|
let cursor = skipWhitespace(source, index + 5, bodyEnd);
|
|
const state = readIdentifier(source, cursor, bodyEnd);
|
|
if (state) {
|
|
states.set(state.name, state);
|
|
index = state.end;
|
|
continue;
|
|
}
|
|
}
|
|
index += 1;
|
|
}
|
|
return states;
|
|
}
|
|
function findWatchDeclarations(source, bodyStart, bodyEnd) {
|
|
const watches = [];
|
|
let index = bodyStart;
|
|
let depth = 0;
|
|
let quote = null;
|
|
let escaped = false;
|
|
while (index < bodyEnd) {
|
|
const character = source[index];
|
|
if (quote !== null) {
|
|
if (escaped) {
|
|
escaped = false;
|
|
} else if (character === "\\") {
|
|
escaped = true;
|
|
} else if (character === quote) {
|
|
quote = null;
|
|
}
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (character === '"' || character === "'") {
|
|
quote = character;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (source.startsWith("<!--", index)) {
|
|
const end = source.indexOf("-->", index + 4);
|
|
index = end === -1 ? bodyEnd : end + 3;
|
|
continue;
|
|
}
|
|
if (character === "{") {
|
|
depth += 1;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (character === "}") {
|
|
depth = Math.max(0, depth - 1);
|
|
index += 1;
|
|
continue;
|
|
}
|
|
if (depth === 0 && source.startsWith("watch", index) && !/[A-Za-z0-9_$]/.test(source[index - 1] || "") && !/[A-Za-z0-9_$]/.test(source[index + 5] || "")) {
|
|
const watchStart = index;
|
|
let cursor = skipWhitespace(source, index + 5, bodyEnd);
|
|
const watchedState = readIdentifier(source, cursor, bodyEnd);
|
|
if (!watchedState) {
|
|
watches.push({
|
|
watchStart,
|
|
watchEnd: index + 5,
|
|
state: null,
|
|
openingBrace: -1,
|
|
closingBrace: -1
|
|
});
|
|
index += 5;
|
|
continue;
|
|
}
|
|
cursor = skipWhitespace(source, watchedState.end, bodyEnd);
|
|
const openingBrace = source[cursor] === "{" ? cursor : -1;
|
|
const closingBrace = openingBrace === -1 ? -1 : findMatchingBrace(source, openingBrace);
|
|
watches.push({
|
|
watchStart,
|
|
watchEnd: index + 5,
|
|
state: watchedState,
|
|
openingBrace,
|
|
closingBrace
|
|
});
|
|
index = closingBrace === -1 ? watchedState.end : closingBrace + 1;
|
|
continue;
|
|
}
|
|
index += 1;
|
|
}
|
|
return watches;
|
|
}
|
|
function validateRootMembers(document, source, rootKind, rootMatch) {
|
|
const diagnostics = [];
|
|
const allowed = VALID_MEMBERS[rootKind];
|
|
if (!allowed) {
|
|
return diagnostics;
|
|
}
|
|
const bodyRange = getRootBodyRange(source, rootMatch);
|
|
const members = findRootMembers(source, bodyRange.start, bodyRange.end);
|
|
for (const member of members) {
|
|
if (allowed.has(member.name)) {
|
|
continue;
|
|
}
|
|
diagnostics.push(createDiagnostic(document, member.start, member.end, `Unknown ${rootKind} member \`${member.name}\`.`, vscode.DiagnosticSeverity.Error, "wrn-unknown-member"));
|
|
}
|
|
return diagnostics;
|
|
}
|
|
function validateLifecycleBlocks(document, source, rootKind, rootMatch) {
|
|
if (rootKind !== "component" && rootKind !== "layout") {
|
|
return [];
|
|
}
|
|
const diagnostics = [];
|
|
const bodyRange = getRootBodyRange(source, rootMatch);
|
|
const blocks = findNamedBlocks(source, bodyRange.start, bodyRange.end, "lifecycle");
|
|
if (blocks.length > 1) {
|
|
for (const block of blocks.slice(1)) {
|
|
diagnostics.push(createDiagnostic(document, block.nameStart, block.nameEnd, "Only one `lifecycle { ... }` block is allowed.", vscode.DiagnosticSeverity.Error, "wrn-duplicate-lifecycle"));
|
|
}
|
|
}
|
|
for (const block of blocks) {
|
|
if (block.openingBrace === -1) {
|
|
diagnostics.push(createDiagnostic(document, block.nameStart, block.nameEnd, "`lifecycle` must be followed by a block.", vscode.DiagnosticSeverity.Error, "wrn-invalid-lifecycle"));
|
|
continue;
|
|
}
|
|
const lifecycleEnd = block.closingBrace === -1 ? bodyRange.end : block.closingBrace;
|
|
let index = block.openingBrace + 1;
|
|
const seenHooks = new Set;
|
|
while (index < lifecycleEnd) {
|
|
index = skipWhitespace(source, index, lifecycleEnd);
|
|
if (index >= lifecycleEnd) {
|
|
break;
|
|
}
|
|
const hook = readIdentifier(source, index, lifecycleEnd);
|
|
if (!hook) {
|
|
index += 1;
|
|
continue;
|
|
}
|
|
index = hook.end;
|
|
if (!VALID_LIFECYCLE_HOOKS.has(hook.name)) {
|
|
diagnostics.push(createDiagnostic(document, hook.start, hook.end, `Unknown lifecycle hook \`${hook.name}\`. Use \`mount\`, \`update\`, or \`unmount\`.`, vscode.DiagnosticSeverity.Error, "wrn-invalid-lifecycle-hook"));
|
|
} else if (seenHooks.has(hook.name)) {
|
|
diagnostics.push(createDiagnostic(document, hook.start, hook.end, `Duplicate lifecycle hook \`${hook.name}\`.`, vscode.DiagnosticSeverity.Error, "wrn-duplicate-lifecycle-hook"));
|
|
} else {
|
|
seenHooks.add(hook.name);
|
|
}
|
|
const openingBrace = skipWhitespace(source, index, lifecycleEnd);
|
|
if (source[openingBrace] !== "{") {
|
|
diagnostics.push(createDiagnostic(document, hook.start, hook.end, `Lifecycle hook \`${hook.name}\` must be followed by a block.`, vscode.DiagnosticSeverity.Error, "wrn-invalid-lifecycle-hook"));
|
|
index = hook.end;
|
|
continue;
|
|
}
|
|
const closingBrace = findMatchingBrace(source, openingBrace);
|
|
index = closingBrace === -1 ? lifecycleEnd : closingBrace + 1;
|
|
}
|
|
}
|
|
return diagnostics;
|
|
}
|
|
function validateWatchBlocks(document, source, rootKind, rootMatch) {
|
|
if (rootKind !== "component" && rootKind !== "layout") {
|
|
return [];
|
|
}
|
|
const diagnostics = [];
|
|
const bodyRange = getRootBodyRange(source, rootMatch);
|
|
const states = findStateDeclarations(source, bodyRange.start, bodyRange.end);
|
|
const watches = findWatchDeclarations(source, bodyRange.start, bodyRange.end);
|
|
for (const watch of watches) {
|
|
if (!watch.state) {
|
|
diagnostics.push(createDiagnostic(document, watch.watchStart, watch.watchEnd, "`watch` must be followed by a declared state name.", vscode.DiagnosticSeverity.Error, "wrn-invalid-watch"));
|
|
continue;
|
|
}
|
|
if (!states.has(watch.state.name)) {
|
|
diagnostics.push(createDiagnostic(document, watch.state.start, watch.state.end, `Cannot watch undeclared state \`${watch.state.name}\`.`, vscode.DiagnosticSeverity.Error, "wrn-unknown-watch-state"));
|
|
}
|
|
if (watch.openingBrace === -1) {
|
|
diagnostics.push(createDiagnostic(document, watch.state.start, watch.state.end, `Watcher for \`${watch.state.name}\` must be followed by a block.`, vscode.DiagnosticSeverity.Error, "wrn-invalid-watch"));
|
|
}
|
|
}
|
|
return diagnostics;
|
|
}
|
|
function validateRequiredView(document, source, rootKind, rootMatch) {
|
|
const bodyRange = getRootBodyRange(source, rootMatch);
|
|
const body = source.slice(bodyRange.start, bodyRange.end);
|
|
if (/\bview\s*\{/.test(body)) {
|
|
return [];
|
|
}
|
|
return [
|
|
createDiagnostic(document, rootMatch.index, rootMatch.index + rootMatch[0].length, `The ${rootKind} \`${rootMatch[2]}\` does not contain a \`view { ... }\` block.`, vscode.DiagnosticSeverity.Warning, "wrn-missing-view")
|
|
];
|
|
}
|
|
function validateLayoutUsage(document, source, rootKind, rootMatch) {
|
|
const diagnostics = [];
|
|
if (rootKind !== "page") {
|
|
const bodyRange = getRootBodyRange(source, rootMatch);
|
|
const layoutMember = findRootMembers(source, bodyRange.start, bodyRange.end).find((member) => member.name === "layout");
|
|
if (layoutMember) {
|
|
diagnostics.push(createDiagnostic(document, layoutMember.start, layoutMember.end, '`layout = "..."` is only valid inside a page.', vscode.DiagnosticSeverity.Error, "wrn-invalid-layout-member"));
|
|
}
|
|
}
|
|
return diagnostics;
|
|
}
|
|
function validateV060Features(document, source) {
|
|
const diagnostics = [];
|
|
const duplicateRuntimeFunctions = new Map;
|
|
for (const match of source.matchAll(/\b(client|server|shared)\s+(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/g)) {
|
|
const key = `${match[1]}:${match[2]}`;
|
|
if (duplicateRuntimeFunctions.has(key)) {
|
|
diagnostics.push(createDiagnostic(document, match.index, match.index + match[0].length, `Duplicate ${match[1]} function '${match[2]}'.`, vscode.DiagnosticSeverity.Error, "WRN-FUNCTION-DUPLICATE"));
|
|
} else
|
|
duplicateRuntimeFunctions.set(key, match.index);
|
|
}
|
|
for (const match of source.matchAll(/\$emit\s*\(/g)) {
|
|
diagnostics.push(createDiagnostic(document, match.index, match.index + match[0].length, "Use typed output.name(payload) instead of deprecated $emit().", vscode.DiagnosticSeverity.Warning, "WRN-OUTPUT-LEGACY-EMIT"));
|
|
}
|
|
for (const match of source.matchAll(/\bevent\.detail\b/g)) {
|
|
diagnostics.push(createDiagnostic(document, match.index, match.index + match[0].length, "Component output handlers receive payload directly.", vscode.DiagnosticSeverity.Warning, "WRN-OUTPUT-LEGACY-DETAIL"));
|
|
}
|
|
for (const match of source.matchAll(/\bserver\s+(?:async\s+)?function\b[\s\S]*?\b(window|document|localStorage|navigator)\b/g)) {
|
|
const offset = match.index + match[0].lastIndexOf(match[1]);
|
|
diagnostics.push(createDiagnostic(document, offset, offset + match[1].length, `Browser API '${match[1]}' is unavailable in a server function.`, vscode.DiagnosticSeverity.Error, "WRN-SERVER-BROWSER-API"));
|
|
}
|
|
return diagnostics;
|
|
}
|
|
function validateDocument(document) {
|
|
if (document.languageId !== WRN_LANGUAGE_ID) {
|
|
return [];
|
|
}
|
|
const source = document.getText();
|
|
if (!source.trim()) {
|
|
return [];
|
|
}
|
|
const diagnostics = [];
|
|
const declaration = findTopLevelDeclaration(document, source);
|
|
if (declaration.diagnostic) {
|
|
diagnostics.push(declaration.diagnostic);
|
|
diagnostics.push(...validateBalancedCharacters(document, source));
|
|
return diagnostics;
|
|
}
|
|
if (!VALID_TOP_LEVEL_KINDS.has(declaration.kind)) {
|
|
diagnostics.push(createDiagnostic(document, declaration.match.index, declaration.match.index + declaration.match[0].length, `Unsupported WRN declaration \`${declaration.kind}\`.`, vscode.DiagnosticSeverity.Error, "wrn-invalid-kind"));
|
|
return diagnostics;
|
|
}
|
|
diagnostics.push(...validateBalancedCharacters(document, source));
|
|
diagnostics.push(...validateHtmlTags(document, source));
|
|
diagnostics.push(...validateRootMembers(document, source, declaration.kind, declaration.match));
|
|
diagnostics.push(...validateLifecycleBlocks(document, source, declaration.kind, declaration.match));
|
|
diagnostics.push(...validateWatchBlocks(document, source, declaration.kind, declaration.match));
|
|
diagnostics.push(...validateRequiredView(document, source, declaration.kind, declaration.match));
|
|
diagnostics.push(...validateLayoutUsage(document, source, declaration.kind, declaration.match));
|
|
diagnostics.push(...validateV060Features(document, source));
|
|
return diagnostics;
|
|
}
|
|
function registerDiagnostics(context) {
|
|
const collection = vscode.languages.createDiagnosticCollection(COLLECTION_NAME);
|
|
const timers = new Map;
|
|
const update = (document) => {
|
|
if (document.languageId !== WRN_LANGUAGE_ID) {
|
|
return;
|
|
}
|
|
const key = document.uri.toString();
|
|
const previousTimer = timers.get(key);
|
|
if (previousTimer) {
|
|
clearTimeout(previousTimer);
|
|
timers.delete(key);
|
|
}
|
|
const configuration = vscode.workspace.getConfiguration("wrnexus", document.uri);
|
|
if (!configuration.get("diagnostics.enable", true)) {
|
|
collection.delete(document.uri);
|
|
return;
|
|
}
|
|
const timer = setTimeout(() => {
|
|
timers.delete(key);
|
|
collection.set(document.uri, validateDocument(document));
|
|
}, 150);
|
|
timers.set(key, timer);
|
|
};
|
|
for (const document of vscode.workspace.textDocuments) {
|
|
update(document);
|
|
}
|
|
context.subscriptions.push(collection, vscode.workspace.onDidOpenTextDocument(update), vscode.workspace.onDidChangeTextDocument((event) => {
|
|
update(event.document);
|
|
}), vscode.workspace.onDidSaveTextDocument(update), vscode.workspace.onDidChangeConfiguration((event) => {
|
|
if (!event.affectsConfiguration("wrnexus.diagnostics.enable")) {
|
|
return;
|
|
}
|
|
for (const document of vscode.workspace.textDocuments) {
|
|
update(document);
|
|
}
|
|
}), vscode.workspace.onDidCloseTextDocument((document) => {
|
|
const key = document.uri.toString();
|
|
const timer = timers.get(key);
|
|
if (timer) {
|
|
clearTimeout(timer);
|
|
timers.delete(key);
|
|
}
|
|
collection.delete(document.uri);
|
|
}), {
|
|
dispose() {
|
|
for (const timer of timers.values()) {
|
|
clearTimeout(timer);
|
|
}
|
|
timers.clear();
|
|
}
|
|
});
|
|
}
|
|
module2.exports = {
|
|
findTopLevelDeclaration,
|
|
maskLeadingTrivia,
|
|
registerDiagnostics,
|
|
validateBalancedCharacters,
|
|
validateDocument,
|
|
validateHtmlTags,
|
|
validateLifecycleBlocks,
|
|
validateLayoutUsage,
|
|
validateRootMembers,
|
|
validateWatchBlocks
|
|
};
|
|
});
|
|
|
|
// editors/vscode/src/v060-language.js
|
|
var require_v060_language = __commonJS((exports2, module2) => {
|
|
var vscode = require("vscode");
|
|
var selector = { language: "wrn" };
|
|
var WRN_GLOB = "**/*.wrn";
|
|
var EXCLUDE_GLOB = "**/{node_modules,dist,.wrnexus,.git}/**";
|
|
function escapeRegExp(value) {
|
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
}
|
|
function identifierAt(document, position) {
|
|
const range = document.getWordRangeAtPosition(position, /[A-Za-z_$][A-Za-z0-9_$]*/);
|
|
if (!range)
|
|
return null;
|
|
return { name: document.getText(range), range };
|
|
}
|
|
function occurrences(document, name) {
|
|
const result = [];
|
|
const pattern = new RegExp(`\\b${escapeRegExp(name)}\\b`, "g");
|
|
const source = document.getText();
|
|
let match;
|
|
while ((match = pattern.exec(source)) !== null) {
|
|
result.push(new vscode.Range(document.positionAt(match.index), document.positionAt(match.index + name.length)));
|
|
}
|
|
return result;
|
|
}
|
|
function declarationRanges(document, name) {
|
|
const source = document.getText();
|
|
const escaped = escapeRegExp(name);
|
|
const patterns = [
|
|
new RegExp(`\\b(?:page|component|layout)\\s+(${escaped})\\b`, "g"),
|
|
new RegExp(`\\b(?:global|page)\\s+store\\s+(${escaped})\\b`, "g"),
|
|
new RegExp(`\\b(?:client|server|shared)?\\s*(?:async\\s+)?function\\s+(${escaped})\\b`, "g"),
|
|
new RegExp(`\\b(?:client|server|shared)?\\s*state\\s+(${escaped})\\b`, "g"),
|
|
new RegExp(`\\boutputs\\s*\\{[\\s\\S]*?\\b(${escaped})\\s*\\(`, "g"),
|
|
new RegExp(`\\b(?:props|state|computed)\\s*\\{[\\s\\S]*?\\b(${escaped})(?:\\?|\\s)*(?=[:=])`, "g"),
|
|
new RegExp(`\\bimport(?:\\s+type)?[\\s\\S]*?\\b(${escaped})\\b[\\s\\S]*?\\bfrom\\b`, "g")
|
|
];
|
|
const ranges = [];
|
|
for (const pattern of patterns) {
|
|
let match;
|
|
while ((match = pattern.exec(source)) !== null) {
|
|
const relative = match[0].lastIndexOf(match[1]);
|
|
const start = match.index + relative;
|
|
ranges.push(new vscode.Range(document.positionAt(start), document.positionAt(start + name.length)));
|
|
}
|
|
}
|
|
return ranges;
|
|
}
|
|
async function wrnDocuments() {
|
|
const uris = await vscode.workspace.findFiles(WRN_GLOB, EXCLUDE_GLOB, 1000);
|
|
const open = new Map(vscode.workspace.textDocuments.filter((item) => item.languageId === "wrn").map((item) => [item.uri.toString(), item]));
|
|
return Promise.all(uris.map((uri) => open.get(uri.toString()) || vscode.workspace.openTextDocument(uri)));
|
|
}
|
|
async function provideReferences(document, position, context, token) {
|
|
const symbol = identifierAt(document, position);
|
|
if (!symbol || token.isCancellationRequested)
|
|
return [];
|
|
const locations = [];
|
|
for (const candidate of await wrnDocuments()) {
|
|
if (token.isCancellationRequested)
|
|
return locations;
|
|
for (const range of occurrences(candidate, symbol.name)) {
|
|
if (!context.includeDeclaration && declarationRanges(candidate, symbol.name).some((decl) => decl.isEqual(range)))
|
|
continue;
|
|
locations.push(new vscode.Location(candidate.uri, range));
|
|
}
|
|
}
|
|
return locations;
|
|
}
|
|
async function prepareRename(document, position) {
|
|
const symbol = identifierAt(document, position);
|
|
if (!symbol)
|
|
throw new Error("Place the cursor on a WRN identifier.");
|
|
return { range: symbol.range, placeholder: symbol.name };
|
|
}
|
|
async function provideRenameEdits(document, position, newName, token) {
|
|
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(newName))
|
|
throw new Error("The new WRN name is not a valid identifier.");
|
|
const symbol = identifierAt(document, position);
|
|
if (!symbol)
|
|
return null;
|
|
const edit = new vscode.WorkspaceEdit;
|
|
for (const candidate of await wrnDocuments()) {
|
|
if (token.isCancellationRequested)
|
|
return edit;
|
|
for (const range of occurrences(candidate, symbol.name))
|
|
edit.replace(candidate.uri, range, newName);
|
|
}
|
|
return edit;
|
|
}
|
|
function importRanges(source) {
|
|
const ranges = [];
|
|
const pattern = /^import(?:\s+type)?[\s\S]*?(?:;\s*|\n(?=import|\s*(?:page|component|layout|global\s+store|page\s+store)\b))/gm;
|
|
let match;
|
|
while ((match = pattern.exec(source)) !== null)
|
|
ranges.push({ start: match.index, end: match.index + match[0].length, text: match[0].trim() });
|
|
return ranges;
|
|
}
|
|
function organizeImportsEdit(document) {
|
|
const source = document.getText();
|
|
const imports = importRanges(source);
|
|
if (imports.length < 2)
|
|
return null;
|
|
const ordered = [...imports].sort((a, b) => {
|
|
const aType = /^import\s+type\b/.test(a.text) ? 0 : 1;
|
|
const bType = /^import\s+type\b/.test(b.text) ? 0 : 1;
|
|
return aType - bType || a.text.localeCompare(b.text);
|
|
});
|
|
const replacement = ordered.map((entry) => entry.text.replace(/;$/, "")).join(`
|
|
`) + `
|
|
`;
|
|
const start = imports[0].start;
|
|
const end = imports.at(-1).end;
|
|
if (source.slice(start, end) === replacement)
|
|
return null;
|
|
return vscode.TextEdit.replace(new vscode.Range(document.positionAt(start), document.positionAt(end)), replacement);
|
|
}
|
|
function provideCodeActions(document, range, context) {
|
|
const actions = [];
|
|
const organizeEdit = organizeImportsEdit(document);
|
|
if (organizeEdit) {
|
|
const action = new vscode.CodeAction("Organize WRN imports", vscode.CodeActionKind.SourceOrganizeImports);
|
|
action.edit = new vscode.WorkspaceEdit;
|
|
action.edit.set(document.uri, [organizeEdit]);
|
|
actions.push(action);
|
|
}
|
|
for (const diagnostic of context.diagnostics) {
|
|
if (diagnostic.code === "WRN-OUTPUT-LEGACY-EMIT") {
|
|
const source = document.getText(diagnostic.range);
|
|
const match = /\$emit\(\s*["']([A-Za-z_$][\w$]*)["']\s*,?/.exec(source);
|
|
if (!match)
|
|
continue;
|
|
const action = new vscode.CodeAction(`Convert $emit to output.${match[1]}`, vscode.CodeActionKind.QuickFix);
|
|
action.diagnostics = [diagnostic];
|
|
action.isPreferred = true;
|
|
action.edit = new vscode.WorkspaceEdit;
|
|
action.edit.replace(document.uri, diagnostic.range, source.replace(/\$emit\(\s*["'][A-Za-z_$][\w$]*["']\s*,?\s*/, `output.${match[1]}(`));
|
|
actions.push(action);
|
|
}
|
|
}
|
|
return actions;
|
|
}
|
|
function registerV060LanguageFeatures(context) {
|
|
context.subscriptions.push(vscode.languages.registerReferenceProvider(selector, { provideReferences }), vscode.languages.registerRenameProvider(selector, { prepareRename, provideRenameEdits }), vscode.languages.registerCodeActionsProvider(selector, { provideCodeActions }, {
|
|
providedCodeActionKinds: [
|
|
vscode.CodeActionKind.QuickFix,
|
|
vscode.CodeActionKind.SourceOrganizeImports
|
|
]
|
|
}));
|
|
}
|
|
module2.exports = {
|
|
declarationRanges,
|
|
importRanges,
|
|
organizeImportsEdit,
|
|
registerV060LanguageFeatures
|
|
};
|
|
});
|
|
|
|
// editors/vscode/src/extension.js
|
|
var vscode = require("vscode");
|
|
var path = require("node:path");
|
|
var { LanguageClient, TransportKind } = require_main5();
|
|
var { formatWrn } = require_formatter();
|
|
var { registerCompletionProvider } = require_completion2();
|
|
var { registerDefinitionProvider } = require_definition2();
|
|
var { registerComponentIntelligence } = require_component_intelligence();
|
|
var { registerDiagnostics } = require_diagnostics();
|
|
var { registerV060LanguageFeatures } = require_v060_language();
|
|
var compiler = null;
|
|
try {
|
|
compiler = require_compiler();
|
|
} catch (error) {
|
|
console.warn("[wrnexus] compiler bundle not found; compiler diagnostics disabled.", error instanceof Error ? error.message : String(error));
|
|
}
|
|
var WRN_LANGUAGE_ID = "wrn";
|
|
var COMPILER_DIAGNOSTIC_COLLECTION = "wrnexus-compiler";
|
|
function registerFormatter(context) {
|
|
const selector = {
|
|
language: WRN_LANGUAGE_ID
|
|
};
|
|
const provider = vscode.languages.registerDocumentFormattingEditProvider(selector, {
|
|
provideDocumentFormattingEdits(document, options, token) {
|
|
if (token.isCancellationRequested) {
|
|
return [];
|
|
}
|
|
const configuration = vscode.workspace.getConfiguration("wrnexus", document.uri);
|
|
const enabled = configuration.get("format.enable", true);
|
|
if (!enabled) {
|
|
return [];
|
|
}
|
|
const source = document.getText();
|
|
if (!source.trim()) {
|
|
return [];
|
|
}
|
|
const printWidth = configuration.get("formatting.printWidth", 100);
|
|
const multilineAttributes = configuration.get("formatting.multilineAttributes", true);
|
|
try {
|
|
const formatted = formatWrn(source, {
|
|
tabSize: options.tabSize || 4,
|
|
insertSpaces: options.insertSpaces !== false,
|
|
printWidth,
|
|
multilineAttributes
|
|
});
|
|
if (typeof formatted !== "string" || formatted === source) {
|
|
return [];
|
|
}
|
|
const fullRange = new vscode.Range(document.positionAt(0), document.positionAt(source.length));
|
|
return [vscode.TextEdit.replace(fullRange, formatted)];
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : String(error);
|
|
console.error("[wrnexus] formatting failed:", message);
|
|
vscode.window.showErrorMessage(`WRNexus formatting failed: ${message}`);
|
|
return [];
|
|
}
|
|
}
|
|
});
|
|
context.subscriptions.push(provider);
|
|
}
|
|
function toCompilerDiagnostic(document, error) {
|
|
const message = error && typeof error === "object" && "message" in error ? String(error.message) : "Failed to compile .wrn file.";
|
|
const offsetMatch = /offset\s+(\d+)/i.exec(message);
|
|
let range;
|
|
if (offsetMatch) {
|
|
const requestedOffset = Number(offsetMatch[1]);
|
|
const safeOffset = Math.max(0, Math.min(requestedOffset, document.getText().length));
|
|
const start = document.positionAt(safeOffset);
|
|
const wordRange = document.getWordRangeAtPosition(start);
|
|
range = wordRange || new vscode.Range(start, document.positionAt(Math.min(safeOffset + 1, document.getText().length)));
|
|
} else {
|
|
const lastLine = document.lineAt(Math.max(0, document.lineCount - 1));
|
|
range = lastLine.range;
|
|
}
|
|
const diagnostic = new vscode.Diagnostic(range, message, vscode.DiagnosticSeverity.Error);
|
|
diagnostic.source = "WRNexus Compiler";
|
|
diagnostic.code = "wrn-compiler-error";
|
|
return diagnostic;
|
|
}
|
|
function registerCompilerDiagnostics(context) {
|
|
const collection = vscode.languages.createDiagnosticCollection(COMPILER_DIAGNOSTIC_COLLECTION);
|
|
const timers = new Map;
|
|
const run = (document) => {
|
|
if (document.languageId !== WRN_LANGUAGE_ID) {
|
|
return;
|
|
}
|
|
const configuration = vscode.workspace.getConfiguration("wrnexus", document.uri);
|
|
const enabled = configuration.get("diagnostics.enable", true);
|
|
if (!enabled) {
|
|
collection.delete(document.uri);
|
|
return;
|
|
}
|
|
if (!compiler || typeof compiler.compileWireFile !== "function") {
|
|
collection.delete(document.uri);
|
|
return;
|
|
}
|
|
const source = document.getText();
|
|
if (!source.trim()) {
|
|
collection.delete(document.uri);
|
|
return;
|
|
}
|
|
try {
|
|
compiler.compileWireFile(source);
|
|
collection.set(document.uri, []);
|
|
} catch (error) {
|
|
collection.set(document.uri, [toCompilerDiagnostic(document, error)]);
|
|
}
|
|
};
|
|
const schedule = (document) => {
|
|
if (document.languageId !== WRN_LANGUAGE_ID) {
|
|
return;
|
|
}
|
|
const key = document.uri.toString();
|
|
const existing = timers.get(key);
|
|
if (existing) {
|
|
clearTimeout(existing);
|
|
}
|
|
const timer = setTimeout(() => {
|
|
timers.delete(key);
|
|
run(document);
|
|
}, 250);
|
|
timers.set(key, timer);
|
|
};
|
|
for (const document of vscode.workspace.textDocuments) {
|
|
run(document);
|
|
}
|
|
context.subscriptions.push(collection, vscode.workspace.onDidOpenTextDocument(run), vscode.workspace.onDidChangeTextDocument((event) => {
|
|
schedule(event.document);
|
|
}), vscode.workspace.onDidSaveTextDocument(run), vscode.workspace.onDidCloseTextDocument((document) => {
|
|
const key = document.uri.toString();
|
|
const timer = timers.get(key);
|
|
if (timer) {
|
|
clearTimeout(timer);
|
|
timers.delete(key);
|
|
}
|
|
collection.delete(document.uri);
|
|
}), vscode.workspace.onDidChangeConfiguration((event) => {
|
|
if (!event.affectsConfiguration("wrnexus.diagnostics.enable")) {
|
|
return;
|
|
}
|
|
for (const document of vscode.workspace.textDocuments) {
|
|
run(document);
|
|
}
|
|
}), {
|
|
dispose() {
|
|
for (const timer of timers.values()) {
|
|
clearTimeout(timer);
|
|
}
|
|
timers.clear();
|
|
}
|
|
});
|
|
}
|
|
function registerSemanticTokens(context) {
|
|
context.subscriptions.push(vscode.languages.registerDocumentSemanticTokensProvider({
|
|
language: WRN_LANGUAGE_ID
|
|
}, wrnSemanticTokensProvider, semanticTokenLegend));
|
|
}
|
|
async function recoverWrnLanguage(document) {
|
|
if (!document.fileName.toLowerCase().endsWith(".wrn"))
|
|
return;
|
|
if (!["plaintext", "wire"].includes(document.languageId))
|
|
return;
|
|
try {
|
|
await vscode.languages.setTextDocumentLanguage(document, WRN_LANGUAGE_ID);
|
|
} catch (error) {
|
|
console.warn("[wrnexus] unable to recover .wrn language association:", error instanceof Error ? error.message : String(error));
|
|
}
|
|
}
|
|
async function activate(context) {
|
|
for (const document of vscode.workspace.textDocuments) {
|
|
recoverWrnLanguage(document);
|
|
}
|
|
context.subscriptions.push(vscode.workspace.onDidOpenTextDocument((document) => {
|
|
recoverWrnLanguage(document);
|
|
}));
|
|
const useLanguageServer = vscode.workspace.getConfiguration("wrnexus").get("languageServer.enable", true);
|
|
let languageServerStarted = false;
|
|
if (useLanguageServer) {
|
|
const module2 = path.join(context.extensionPath, "src", "language-server.cjs");
|
|
const serverOptions = {
|
|
run: { module: module2, transport: TransportKind.stdio },
|
|
debug: { module: module2, transport: TransportKind.stdio, options: { execArgv: ["--nolazy"] } }
|
|
};
|
|
const client = new LanguageClient("wrnexusLanguageServer", "WRNexus Language Server", serverOptions, {
|
|
documentSelector: [{ scheme: "file", language: WRN_LANGUAGE_ID }]
|
|
});
|
|
try {
|
|
await client.start();
|
|
languageServerStarted = true;
|
|
context.subscriptions.push({ dispose: () => void client.stop() });
|
|
} catch (error) {
|
|
console.warn("[wrnexus] language server failed to start; using built-in providers.", error instanceof Error ? error.message : String(error));
|
|
}
|
|
}
|
|
if (!languageServerStarted) {
|
|
registerDiagnostics(context);
|
|
registerCompilerDiagnostics(context);
|
|
registerCompletionProvider(context);
|
|
registerDefinitionProvider(context);
|
|
registerFormatter(context);
|
|
}
|
|
registerComponentIntelligence(context);
|
|
registerSemanticTokens(context);
|
|
registerV060LanguageFeatures(context);
|
|
}
|
|
function deactivate() {}
|
|
var semanticTokenLegend = new vscode.SemanticTokensLegend(["variable"], ["declaration", "modification"]);
|
|
function escapeRegExp(value) {
|
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
}
|
|
function collectStateVariables(text) {
|
|
const states = new Map;
|
|
const statePattern = /\bstate\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?==|;|\r?$)/gm;
|
|
let match;
|
|
while ((match = statePattern.exec(text)) !== null) {
|
|
const name = match[1];
|
|
if (!name) {
|
|
continue;
|
|
}
|
|
const offset = match.index + match[0].lastIndexOf(name);
|
|
const declarations = states.get(name) || new Set;
|
|
declarations.add(offset);
|
|
states.set(name, declarations);
|
|
}
|
|
return states;
|
|
}
|
|
function collectCommentRanges(text) {
|
|
const ranges = [];
|
|
let index = 0;
|
|
let quote = null;
|
|
let escaped = false;
|
|
while (index < text.length) {
|
|
const current = text[index];
|
|
const next = text[index + 1];
|
|
if (quote) {
|
|
if (escaped) {
|
|
escaped = false;
|
|
index++;
|
|
continue;
|
|
}
|
|
if (current === "\\") {
|
|
escaped = true;
|
|
index++;
|
|
continue;
|
|
}
|
|
if (current === quote) {
|
|
quote = null;
|
|
}
|
|
index++;
|
|
continue;
|
|
}
|
|
if (current === '"' || current === "'" || current === "`") {
|
|
quote = current;
|
|
index++;
|
|
continue;
|
|
}
|
|
if (current === "/" && next === "/") {
|
|
const start = index;
|
|
index += 2;
|
|
while (index < text.length && text[index] !== `
|
|
`) {
|
|
index++;
|
|
}
|
|
ranges.push({ start, end: index });
|
|
continue;
|
|
}
|
|
if (current === "/" && next === "*") {
|
|
const start = index;
|
|
index += 2;
|
|
while (index < text.length && !(text[index] === "*" && text[index + 1] === "/")) {
|
|
index++;
|
|
}
|
|
index = Math.min(text.length, index + 2);
|
|
ranges.push({ start, end: index });
|
|
continue;
|
|
}
|
|
index++;
|
|
}
|
|
return ranges;
|
|
}
|
|
function isInsideComment(offset, ranges) {
|
|
let low = 0;
|
|
let high = ranges.length - 1;
|
|
while (low <= high) {
|
|
const middle = Math.floor((low + high) / 2);
|
|
const range = ranges[middle];
|
|
if (!range) {
|
|
return false;
|
|
}
|
|
if (offset < range.start) {
|
|
high = middle - 1;
|
|
} else if (offset >= range.end) {
|
|
low = middle + 1;
|
|
} else {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
function isStateModification(text, offset, length) {
|
|
const after = text.slice(offset + length).match(/^\s*(=|\+=|-=|\*=|\/=|%=|\+\+|--)/);
|
|
if (after) {
|
|
return true;
|
|
}
|
|
const before = text.slice(Math.max(0, offset - 8), offset).match(/(\+\+|--)\s*$/);
|
|
return Boolean(before);
|
|
}
|
|
var wrnSemanticTokensProvider = {
|
|
provideDocumentSemanticTokens(document, token) {
|
|
const builder = new vscode.SemanticTokensBuilder(semanticTokenLegend);
|
|
const text = document.getText();
|
|
const states = collectStateVariables(text);
|
|
const commentRanges = collectCommentRanges(text);
|
|
for (const [name, declarationOffsets] of states) {
|
|
if (token.isCancellationRequested) {
|
|
return builder.build();
|
|
}
|
|
const pattern = new RegExp(`(?<![A-Za-z0-9_$])${escapeRegExp(name)}(?![A-Za-z0-9_$])`, "g");
|
|
let match;
|
|
while ((match = pattern.exec(text)) !== null) {
|
|
const offset = match.index;
|
|
if (isInsideComment(offset, commentRanges)) {
|
|
continue;
|
|
}
|
|
const position = document.positionAt(offset);
|
|
let modifiers = [];
|
|
if (declarationOffsets.has(offset)) {
|
|
modifiers = ["declaration"];
|
|
} else if (isStateModification(text, offset, name.length)) {
|
|
modifiers = ["modification"];
|
|
}
|
|
builder.push(position.line, position.character, name.length, "variable", modifiers);
|
|
}
|
|
}
|
|
return builder.build();
|
|
}
|
|
};
|
|
module.exports = {
|
|
activate,
|
|
deactivate,
|
|
registerCompilerDiagnostics,
|
|
registerFormatter,
|
|
registerSemanticTokens,
|
|
recoverWrnLanguage,
|
|
toCompilerDiagnostic
|
|
};
|