diff --git a/lib/_tsc.js b/lib/_tsc.js index 43be2b1071e09..6f80d54badab1 100644 --- a/lib/_tsc.js +++ b/lib/_tsc.js @@ -15,6 +15,11 @@ and limitations under the License. "use strict"; +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; // src/compiler/corePublic.ts var versionMajorMinor = "6.0"; @@ -5382,6 +5387,9 @@ function getEncodedRootLength(path) { } return ~path.length; } + if (path.startsWith("data:")) { + return ~path.length; + } return 0; } function getRootLength(path) { @@ -5609,6 +5617,9 @@ function removeTrailingDirectorySeparator(path) { } function ensureTrailingDirectorySeparator(path) { if (!hasTrailingDirectorySeparator(path)) { + if (path.startsWith("data:")) { + return path; + } return path + directorySeparator; } return path; @@ -8020,6 +8031,225 @@ var Diagnostics = { _0_is_not_a_valid_meta_property_for_keyword_import_Did_you_mean_meta_or_defer: diag(18061, 1 /* Error */, "_0_is_not_a_valid_meta_property_for_keyword_import_Did_you_mean_meta_or_defer_18061", "'{0}' is not a valid meta-property for keyword 'import'. Did you mean 'meta' or 'defer'?") }; +// src/compiler/deno.ts +var deno_exports = {}; +__export(deno_exports, { + createDenoForkContext: () => createDenoForkContext, + enterSpan: () => enterSpan, + exitSpan: () => exitSpan, + isTypesNodePkgPath: () => isTypesNodePkgPath, + parseNpmPackageReference: () => parseNpmPackageReference, + setEnterSpan: () => setEnterSpan, + setExitSpan: () => setExitSpan, + setIsNodeSourceFileCallback: () => setIsNodeSourceFileCallback, + setNodeBuiltInModuleNames: () => setNodeBuiltInModuleNames, + setNodeOnlyGlobalNames: () => setNodeOnlyGlobalNames, + setTypesNodeIgnorableNames: () => setTypesNodeIgnorableNames, + spanned: () => spanned, + tryParseNpmPackageReference: () => tryParseNpmPackageReference +}); +var isNodeSourceFile = () => false; +var nodeBuiltInModuleNames = /* @__PURE__ */ new Set(); +var nodeOnlyGlobalNames = /* @__PURE__ */ new Set(); +var typesNodeIgnorableNames = /* @__PURE__ */ new Set(); +var enterSpan = () => ({}); +var exitSpan = () => { +}; +function setEnterSpan(f) { + enterSpan = f; +} +function setExitSpan(f) { + exitSpan = f; +} +function spanned(name, f) { + const span = enterSpan(name); + let needsExit = true; + try { + const result = f(); + if (result instanceof Promise) { + needsExit = false; + return result.finally(() => exitSpan(span)); + } else { + return result; + } + } finally { + if (needsExit) { + exitSpan(span); + } + } +} +function setIsNodeSourceFileCallback(callback) { + isNodeSourceFile = callback; +} +function setNodeBuiltInModuleNames(names) { + nodeBuiltInModuleNames = new Set(names); +} +function setNodeOnlyGlobalNames(names) { + nodeBuiltInModuleNames = new Set(names); + nodeOnlyGlobalNames = new Set(names); +} +function setTypesNodeIgnorableNames(names) { + typesNodeIgnorableNames = names; +} +function createDenoForkContext({ + mergeSymbol, + globals, + nodeGlobals, + ambientModuleSymbolRegex: ambientModuleSymbolRegex2 +}) { + return { + hasNodeSourceFile, + getGlobalsForName, + mergeGlobalSymbolTable, + combinedGlobals: createNodeGlobalsSymbolTable() + }; + function hasNodeSourceFile(node) { + if (!node) return false; + const sourceFile = getSourceFileOfNode(node); + return isNodeSourceFile(sourceFile); + } + function getGlobalsForName(id) { + if (ambientModuleSymbolRegex2.test(id)) { + if (id.startsWith('"node:')) { + const name = id.slice(6, -1); + if (nodeBuiltInModuleNames.has(name)) { + return globals; + } + } + return nodeGlobals; + } + return nodeOnlyGlobalNames.has(id) ? nodeGlobals : globals; + } + function mergeGlobalSymbolTable(node, source, unidirectional = false) { + const sourceFile = getSourceFileOfNode(node); + const isNodeFile = hasNodeSourceFile(sourceFile); + const isTypesNodeSourceFile = isNodeFile && isTypesNodePkgPath2(sourceFile.path); + source.forEach((sourceSymbol, id) => { + const target = isNodeFile ? getGlobalsForName(id) : globals; + const targetSymbol = target.get(id); + if (isTypesNodeSourceFile && targetSymbol !== void 0 && typesNodeIgnorableNames.has(id) && !symbolHasAnyTypesNodePkgDecl(targetSymbol)) { + return; + } + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol); + }); + } + function symbolHasAnyTypesNodePkgDecl(symbol) { + if (symbol.declarations) { + for (const decl of symbol.declarations) { + const sourceFile = getSourceFileOfNode(decl); + const isNodeFile = hasNodeSourceFile(sourceFile); + if (isNodeFile && isTypesNodePkgPath2(sourceFile.path)) { + return true; + } + } + } + return false; + } + function isTypesNodePkgPath2(path) { + return path.endsWith(".d.ts") && path.includes("/@types/node/"); + } + function createNodeGlobalsSymbolTable() { + return new Proxy(globals, { + get(target, prop, receiver) { + if (prop === "get") { + return (key) => { + return nodeGlobals.get(key) ?? globals.get(key); + }; + } else if (prop === "has") { + return (key) => { + return nodeGlobals.has(key) || globals.has(key); + }; + } else if (prop === "size") { + let i = 0; + for (const _ignore of getEntries((entry) => entry)) { + i++; + } + return i; + } else if (prop === "forEach") { + return (action) => { + for (const [key, value] of getEntries((entry) => entry)) { + action(value, key); + } + }; + } else if (prop === "entries") { + return () => { + return getEntries((kv) => kv); + }; + } else if (prop === "keys") { + return () => { + return getEntries((kv) => kv[0]); + }; + } else if (prop === "values") { + return () => { + return getEntries((kv) => kv[1]); + }; + } else if (prop === Symbol.iterator) { + return () => { + return Array.from(getEntries((kv) => kv))[Symbol.iterator](); + }; + } else { + const value = target[prop]; + if (value instanceof Function) { + return function(...args) { + return value.apply(this === receiver ? target : this, args); + }; + } + return value; + } + } + }); + function* getEntries(transform) { + const foundKeys = /* @__PURE__ */ new Set(); + for (const entries of [nodeGlobals.entries(), globals.entries()]) { + for (const entry of entries) { + if (!foundKeys.has(entry[0])) { + yield transform(entry); + foundKeys.add(entry[0]); + } + } + } + } + } +} +function isTypesNodePkgPath(path) { + return path.endsWith(".d.ts") && path.includes("/@types/node/"); +} +function tryParseNpmPackageReference(text) { + try { + return parseNpmPackageReference(text); + } catch { + return void 0; + } +} +function parseNpmPackageReference(text) { + if (!text.startsWith("npm:")) { + throw new Error(`Not an npm specifier: ${text}`); + } + text = text.replace(/^npm:\/?/, ""); + const parts = text.split("/"); + const namePartLen = text.startsWith("@") ? 2 : 1; + if (parts.length < namePartLen) { + throw new Error(`Not a valid package: ${text}`); + } + const nameParts = parts.slice(0, namePartLen); + const lastNamePart = nameParts[nameParts.length - 1]; + const lastAtIndex = lastNamePart.lastIndexOf("@"); + let versionReq; + if (lastAtIndex > 0) { + versionReq = lastNamePart.substring(lastAtIndex + 1); + nameParts[nameParts.length - 1] = lastNamePart.substring(0, lastAtIndex); + } + const name = nameParts.join("/"); + if (name.length === 0) { + throw new Error(`Npm specifier did not have a name: ${text}`); + } + return { + name, + versionReq, + subPath: parts.length > nameParts.length ? parts.slice(nameParts.length).join("/") : void 0 + }; +} + // src/compiler/scanner.ts function tokenIsIdentifierOrKeyword(token) { return token >= 80 /* Identifier */; @@ -18303,6 +18533,7 @@ function getJSXTransformEnabled(options) { return jsx === 2 /* React */ || jsx === 4 /* ReactJSX */ || jsx === 5 /* ReactJSXDev */; } function getJSXImplicitImportBase(compilerOptions, file) { + var _a; const jsxImportSourcePragmas = file == null ? void 0 : file.pragmas.get("jsximportsource"); const jsxImportSourcePragma = isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; const jsxRuntimePragmas = file == null ? void 0 : file.pragmas.get("jsxruntime"); @@ -18310,6 +18541,10 @@ function getJSXImplicitImportBase(compilerOptions, file) { if ((jsxRuntimePragma == null ? void 0 : jsxRuntimePragma.arguments.factory) === "classic") { return void 0; } + { + const resolvedJsxImportSource = file && ((_a = compilerOptions.resolveJsxImportSource) == null ? void 0 : _a.call(compilerOptions, file.fileName)); + if (resolvedJsxImportSource) return resolvedJsxImportSource; + } return compilerOptions.jsx === 4 /* ReactJSX */ || compilerOptions.jsx === 5 /* ReactJSXDev */ || compilerOptions.jsxImportSource || jsxImportSourcePragma || (jsxRuntimePragma == null ? void 0 : jsxRuntimePragma.arguments.factory) === "automatic" ? (jsxImportSourcePragma == null ? void 0 : jsxImportSourcePragma.arguments.factory) || compilerOptions.jsxImportSource || "react" : void 0; } function getJSXRuntimeImport(base, options) { @@ -19519,7 +19754,9 @@ function createNameResolver({ argumentsSymbol, error, getSymbolOfDeclaration, - globals, + denoGlobals, + nodeGlobals, + denoContext, lookup, setRequiresScopeChangeCache = returnUndefined, getRequiresScopeChangeCache = returnUndefined, @@ -19775,7 +20012,12 @@ function createNameResolver({ } } if (!excludeGlobals) { - result = lookup(globals, name, meaning); + if (denoContext.hasNodeSourceFile(lastLocation)) { + result = lookup(nodeGlobals, name, meaning); + } + if (!result) { + result = lookup(denoGlobals, name, meaning); + } } } if (!result) { @@ -36444,6 +36686,7 @@ var libEntries = [ ["dom", "lib.dom.d.ts"], ["dom.iterable", "lib.dom.iterable.d.ts"], ["dom.asynciterable", "lib.dom.asynciterable.d.ts"], + ["dom.extras", "lib.dom.extras.d.ts"], ["webworker", "lib.webworker.d.ts"], ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], ["webworker.iterable", "lib.webworker.iterable.d.ts"], @@ -46483,13 +46726,24 @@ function createTypeChecker(host) { evaluateElementAccessExpression, evaluateEntityNameExpression }); - var globals = createSymbolTable(); + var denoGlobals = createSymbolTable(); + var nodeGlobals = createSymbolTable(); var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); undefinedSymbol.declarations = []; - var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); - globalThisSymbol.exports = globals; - globalThisSymbol.declarations = []; - globals.set(globalThisSymbol.escapedName, globalThisSymbol); + var denoGlobalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); + denoGlobalThisSymbol.exports = denoGlobals; + denoGlobalThisSymbol.declarations = []; + denoGlobals.set(denoGlobalThisSymbol.escapedName, denoGlobalThisSymbol); + const denoContext = deno_exports.createDenoForkContext({ + globals: denoGlobals, + nodeGlobals, + mergeSymbol, + ambientModuleSymbolRegex + }); + const nodeGlobalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); + nodeGlobalThisSymbol.exports = denoContext.combinedGlobals; + nodeGlobalThisSymbol.declarations = []; + nodeGlobals.set(nodeGlobalThisSymbol.escapedName, nodeGlobalThisSymbol); var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); var isolatedModulesLikeFlagName = compilerOptions.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules"; @@ -46503,7 +46757,9 @@ function createTypeChecker(host) { compilerOptions, requireSymbol, argumentsSymbol, - globals, + denoGlobals, + nodeGlobals, + denoContext, getSymbolOfDeclaration, error, getRequiresScopeChangeCache, @@ -46517,7 +46773,9 @@ function createTypeChecker(host) { compilerOptions, requireSymbol, argumentsSymbol, - globals, + denoGlobals, + nodeGlobals, + denoContext, getSymbolOfDeclaration, error, getRequiresScopeChangeCache, @@ -47330,6 +47588,7 @@ function createTypeChecker(host) { var reverseMappedCache = /* @__PURE__ */ new Map(); var reverseHomomorphicMappedCache = /* @__PURE__ */ new Map(); var ambientModulesCache; + var nodeAmbientModulesCache; var patternAmbientModules; var patternAmbientModuleAugmentations; var globalObjectType; @@ -47477,7 +47736,8 @@ function createTypeChecker(host) { ) || unknownSymbol); } if (!isIdentifier(node.expression.expression)) return false; - return idText(node.expression.name) === "Symbol" && idText(node.expression.expression) === "globalThis" && getResolvedSymbol(node.expression.expression) === globalThisSymbol; + const resolvedGlobalThis = getResolvedSymbol(node.expression.expression); + return idText(node.expression.name) === "Symbol" && idText(node.expression.expression) === "globalThis" && (resolvedGlobalThis === denoGlobalThisSymbol || resolvedGlobalThis === nodeGlobalThisSymbol); } function getCachedType(key) { return key ? cachedTypes.get(key) : void 0; @@ -47739,7 +47999,7 @@ function createTypeChecker(host) { recordMergedSymbol(target, source); } } else if (target.flags & 1024 /* NamespaceModule */) { - if (target !== globalThisSymbol) { + if (target !== denoGlobalThisSymbol && target !== nodeGlobalThisSymbol) { error( source.declarations && getNameOfDeclaration(source.declarations[0]), Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, @@ -47833,7 +48093,7 @@ function createTypeChecker(host) { return; } if (isGlobalScopeAugmentation(moduleAugmentation)) { - mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + denoContext.mergeGlobalSymbolTable(moduleAugmentation, moduleAugmentation.symbol.exports); } else { const moduleNotFoundError = !(moduleName.parent.parent.flags & 33554432 /* Ambient */) ? Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : void 0; let mainModule = resolveExternalModuleNameWorker( @@ -47879,15 +48139,17 @@ function createTypeChecker(host) { } function addUndefinedToGlobalsOrErrorOnRedeclaration() { const name = undefinedSymbol.escapedName; - const targetSymbol = globals.get(name); - if (targetSymbol) { - forEach(targetSymbol.declarations, (declaration) => { - if (!isTypeDeclaration(declaration)) { - diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, unescapeLeadingUnderscores(name))); - } - }); - } else { - globals.set(name, undefinedSymbol); + for (const globals of [nodeGlobals, denoGlobals]) { + const targetSymbol = globals.get(name); + if (targetSymbol) { + forEach(targetSymbol.declarations, (declaration) => { + if (!isTypeDeclaration(declaration)) { + diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, unescapeLeadingUnderscores(name))); + } + }); + } else { + globals.set(name, undefinedSymbol); + } } } function getSymbolLinks(symbol) { @@ -48190,7 +48452,9 @@ function createTypeChecker(host) { } } if (compilerOptions.isolatedModules && result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */) { - const isGlobal = getSymbol(globals, name, meaning) === result; + const isNodeFile = denoContext.hasNodeSourceFile(lastLocation); + const fileGlobals = isNodeFile ? nodeGlobals : denoGlobals; + const isGlobal = getSymbol(fileGlobals, name, meaning) === result; const nonValueSymbol = isGlobal && isSourceFile(lastLocation) && lastLocation.locals && getSymbol(lastLocation.locals, name, ~111551 /* Value */); if (nonValueSymbol) { const importDecl = (_a = nonValueSymbol.declarations) == null ? void 0 : _a.find((d) => d.kind === 277 /* ImportSpecifier */ || d.kind === 274 /* ImportClause */ || d.kind === 275 /* NamespaceImport */ || d.kind === 272 /* ImportEqualsDeclaration */); @@ -48594,7 +48858,7 @@ function createTypeChecker(host) { const usageMode = file && getEmitSyntaxForModuleSpecifierExpression(usage); if (file && usageMode !== void 0) { const targetMode = host.getImpliedNodeFormatForEmit(file); - if (usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */ && 100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) { + if (usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */) { return true; } if (usageMode === 99 /* ESNext */ && targetMode === 99 /* ESNext */) { @@ -49469,6 +49733,25 @@ function createTypeChecker(host) { return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, !ignoreErrors ? moduleReferenceExpression : void 0, isForAugmentation) : void 0; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) { + var _a; + const result = resolveExternalModuleInner(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation); + if (moduleReference.startsWith("npm:") && (result === void 0 || ((_a = result == null ? void 0 : result.exports) == null ? void 0 : _a.size) === 0)) { + const npmPackageRef = deno_exports.tryParseNpmPackageReference(moduleReference); + if (npmPackageRef) { + const bareSpecifier = npmPackageRef.name + (npmPackageRef.subPath === void 0 ? "" : "/" + npmPackageRef.subPath); + const ambientModule = tryFindAmbientModule( + bareSpecifier, + /*withAugmentations*/ + true + ); + if (ambientModule) { + return ambientModule; + } + } + } + return result; + } + function resolveExternalModuleInner(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l; if (errorNode && startsWith(moduleReference, "@types/")) { const diag2 = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; @@ -50278,8 +50561,20 @@ function createTypeChecker(host) { break; } } + if (denoContext.hasNodeSourceFile(enclosingDeclaration)) { + result = callback( + nodeGlobals, + /*ignoreQualification*/ + void 0, + /*isLocalNameLookup*/ + true + ); + if (result) { + return result; + } + } return callback( - globals, + denoGlobals, /*ignoreQualification*/ void 0, /*isLocalNameLookup*/ @@ -50354,7 +50649,11 @@ function createTypeChecker(host) { } } }); - return result2 || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : void 0); + if (result2) { + return result2; + } + const globalSymbol = symbols === nodeGlobals ? nodeGlobalThisSymbol : symbols === denoGlobals ? denoGlobalThisSymbol : void 0; + return globalSymbol !== void 0 ? getCandidateListForSymbol(globalSymbol, globalSymbol, ignoreQualification) : void 0; } function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) { if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { @@ -58338,7 +58637,7 @@ function createTypeChecker(host) { } let members = getExportsOfSymbol(symbol); let indexInfos; - if (symbol === globalThisSymbol) { + if (symbol === denoGlobalThisSymbol || symbol === nodeGlobalThisSymbol) { const varsOnly = /* @__PURE__ */ new Map(); members.forEach((p) => { var _a; @@ -59498,7 +59797,7 @@ function createTypeChecker(host) { if (isExternalModuleNameRelative(moduleName)) { return void 0; } - const symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */); + const symbol = getSymbol(denoContext.combinedGlobals, '"' + moduleName + '"', 512 /* ValueModule */); return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } function hasEffectiveQuestionToken(node) { @@ -62300,7 +62599,9 @@ function createTypeChecker(host) { return getUnionType(append(types, undefinedType)); } } - if (objectType.symbol === globalThisSymbol && propName !== void 0 && globalThisSymbol.exports.has(propName) && globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */) { + if (objectType.symbol === denoGlobalThisSymbol && propName !== void 0 && denoGlobalThisSymbol.exports.has(propName) && denoGlobalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */) { + error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); + } else if (objectType.symbol === nodeGlobalThisSymbol && propName !== void 0 && nodeGlobalThisSymbol.exports.has(propName) && nodeGlobalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */) { error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); } else if (noImplicitAny && !(accessFlags & 128 /* SuppressNoImplicitAnyError */)) { if (propName !== void 0 && typeHasStaticProperty(propName, objectType)) { @@ -71851,7 +72152,7 @@ function createTypeChecker(host) { /*isUse*/ true ); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === denoGlobalThisSymbol || symbol === nodeGlobalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { } else { const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol); if (!target || getSymbolFlags(target) & 111551 /* Value */) { @@ -72402,8 +72703,8 @@ function createTypeChecker(host) { container ); if (noImplicitThis) { - const globalThisType2 = getTypeOfSymbol(globalThisSymbol); - if (type === globalThisType2 && capturedByArrowFunction) { + const globalThisType2 = getTypeOfSymbol(denoGlobalThisSymbol); + if ((type === globalThisType2 || type === getTypeOfSymbol(nodeGlobalThisSymbol)) && capturedByArrowFunction) { error(node, Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this); } else if (!type) { const diag2 = error(node, Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); @@ -72455,7 +72756,10 @@ function createTypeChecker(host) { } else if (container.externalModuleIndicator) { return undefinedType; } else if (includeGlobalThis) { - return getTypeOfSymbol(globalThisSymbol); + if (denoContext.hasNodeSourceFile(container)) { + return getTypeOfSymbol(nodeGlobalThisSymbol); + } + return getTypeOfSymbol(denoGlobalThisSymbol); } } } @@ -75275,14 +75579,17 @@ function createTypeChecker(host) { if (!isUncheckedJS && isJSLiteralType(leftType)) { return anyType; } - if (leftType.symbol === globalThisSymbol) { - if (globalThisSymbol.exports.has(right.escapedText) && globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */) { + if (leftType.symbol === denoGlobalThisSymbol) { + if (denoGlobalThisSymbol.exports.has(right.escapedText) && denoGlobalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */) { error(right, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(right.escapedText), typeToString(leftType)); } else if (noImplicitAny) { error(right, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType)); } return anyType; } + if (leftType.symbol === nodeGlobalThisSymbol) { + return anyType; + } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType, isUncheckedJS); } @@ -75521,7 +75828,7 @@ function createTypeChecker(host) { const symbol = getSymbol(symbols, name, meaning); if (symbol) return symbol; let candidates = arrayFrom(symbols.values()); - if (symbols === globals) { + if (symbols === denoGlobals || symbols == nodeGlobals) { const primitives = mapDefined( ["string", "number", "boolean", "object", "bigint", "symbol"], (s) => symbols.has(s.charAt(0).toUpperCase() + s.slice(1)) ? createSymbol(524288 /* TypeAlias */, s) : void 0 @@ -86375,7 +86682,7 @@ function createTypeChecker(host) { /*isUse*/ true ); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === denoGlobalThisSymbol || symbol === nodeGlobalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName)); } else { markLinkedReferences(node, 7 /* ExportSpecifier */); @@ -86490,7 +86797,9 @@ function createTypeChecker(host) { grammarErrorOnNode(node.expression, Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); } if (node.isExportEquals) { - if (moduleKind >= 5 /* ES2015 */ && moduleKind !== 200 /* Preserve */ && (node.flags & 33554432 /* Ambient */ && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) === 99 /* ESNext */ || !(node.flags & 33554432 /* Ambient */) && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) !== 1 /* CommonJS */)) { + if (moduleKind >= 5 /* ES2015 */ && moduleKind !== 200 /* Preserve */ && // deno: temporarily disable this one until Deno 2.0 (https://github.com/microsoft/TypeScript/pull/52109) + /* (node.flags & NodeFlags.Ambient && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) === ModuleKind.ESNext) || */ + (!(node.flags & 33554432 /* Ambient */) && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) !== 1 /* CommonJS */)) { grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } else if (moduleKind === 4 /* System */ && !(node.flags & 33554432 /* Ambient */)) { grammarErrorOnNode(node, Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); @@ -87183,7 +87492,10 @@ function createTypeChecker(host) { isStaticSymbol = isStatic(location); location = location.parent; } - copySymbols(globals, meaning); + if (denoContext.hasNodeSourceFile(location)) { + copySymbols(nodeGlobals, meaning); + } + copySymbols(denoGlobals, meaning); } function copySymbol(symbol, meaning2) { if (getCombinedLocalAndExportSymbolFlags(symbol) & meaning2) { @@ -88392,7 +88704,7 @@ function createTypeChecker(host) { return nodeBuilder.serializeTypeForExpression(expr, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker); } function hasGlobalName(name) { - return globals.has(escapeLeadingUnderscores(name)); + return denoGlobals.has(escapeLeadingUnderscores(name)); } function getReferencedValueSymbol(reference, startInDeclarationContainer) { const resolvedSymbol = getNodeLinks(reference).resolvedSymbol; @@ -88744,10 +89056,10 @@ function createTypeChecker(host) { diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis")); } } - mergeSymbolTable(globals, file.locals); + denoContext.mergeGlobalSymbolTable(file, file.locals); } if (file.jsGlobalAugmentations) { - mergeSymbolTable(globals, file.jsGlobalAugmentations); + denoContext.mergeGlobalSymbolTable(file, file.jsGlobalAugmentations); } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = concatenate(patternAmbientModules, file.patternAmbientModules); @@ -88757,9 +89069,11 @@ function createTypeChecker(host) { } if (file.symbol && file.symbol.globalExports) { const source = file.symbol.globalExports; + const isNodeFile = denoContext.hasNodeSourceFile(file); source.forEach((sourceSymbol, id) => { - if (!globals.has(id)) { - globals.set(id, sourceSymbol); + const envGlobals = isNodeFile ? denoContext.getGlobalsForName(id) : denoGlobals; + if (!envGlobals.has(id)) { + envGlobals.set(id, sourceSymbol); } }); } @@ -88782,7 +89096,8 @@ function createTypeChecker(host) { true ); getSymbolLinks(unknownSymbol).type = errorType; - getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol); + getSymbolLinks(denoGlobalThisSymbol).type = createObjectType(16 /* Anonymous */, denoGlobalThisSymbol); + getSymbolLinks(nodeGlobalThisSymbol).type = createObjectType(16 /* Anonymous */, nodeGlobalThisSymbol); globalArrayType = getGlobalType( "Array", /*arity*/ @@ -90380,16 +90695,28 @@ function createTypeChecker(host) { } return false; } - function getAmbientModules() { - if (!ambientModulesCache) { - ambientModulesCache = []; - globals.forEach((global2, sym) => { + function getAmbientModules(sourceFile) { + const isNode = denoContext.hasNodeSourceFile(sourceFile); + if (isNode) { + if (!nodeAmbientModulesCache) { + nodeAmbientModulesCache = getAmbientModulesFromGlobals(denoContext.combinedGlobals); + } + return nodeAmbientModulesCache; + } else { + if (!ambientModulesCache) { + ambientModulesCache = getAmbientModulesFromGlobals(denoGlobals); + } + return ambientModulesCache; + } + function getAmbientModulesFromGlobals(envGlobals) { + const result = []; + envGlobals.forEach((global2, sym) => { if (ambientModuleSymbolRegex.test(sym)) { - ambientModulesCache.push(global2); + result.push(global2); } }); + return result; } - return ambientModulesCache; } function checkGrammarImportClause(node) { var _a, _b; @@ -122062,14 +122389,6 @@ function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) { } return sourceFile; } : void 0; - host.fileExists = (fileName) => { - const key = toPath3(fileName); - const value = fileExistsCache.get(key); - if (value !== void 0) return value; - const newValue = originalFileExists.call(host, fileName); - fileExistsCache.set(key, !!newValue); - return newValue; - }; if (originalWriteFile) { host.writeFile = (fileName, data, ...rest) => { const key = toPath3(fileName); @@ -122621,7 +122940,7 @@ function createCreateProgramOptions(rootNames, options, host, oldProgram, config }; } function createProgram(_rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { - var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p; + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q; let _createProgramOptions = isArray(_rootNamesOrOptions) ? createCreateProgramOptions(_rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : _rootNamesOrOptions; const { rootNames, options, configFileParsingDiagnostics, projectReferences, typeScriptVersion: typeScriptVersion2, host: createProgramOptionsHost } = _createProgramOptions; let { oldProgram } = _createProgramOptions; @@ -122756,6 +123075,8 @@ function createProgram(_rootNamesOrOptions, _options, _host, _oldProgram, _confi let usesUriStyleNodeCoreModules; const filesByName = /* @__PURE__ */ new Map(); const libFiles = /* @__PURE__ */ new Set(); + let shouldLoadNodeTypes = false; + let foundNodeTypes = false; let missingFileNames = /* @__PURE__ */ new Map(); const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? /* @__PURE__ */ new Map() : void 0; let resolvedProjectReferences; @@ -122869,6 +123190,23 @@ function createProgram(_rootNamesOrOptions, _options, _host, _oldProgram, _confi }); } } + const hasTypesNodePackage = () => { + for (const path of filesByName.keys()) { + if (deno_exports.isTypesNodePkgPath(path)) { + return true; + } + } + return false; + }; + if (foundNodeTypes && !hasTypesNodePackage()) { + shouldLoadNodeTypes = true; + processRootFile( + "asset:///lib.node.d.ts", + /*isDefaultLib*/ + true, + { kind: 6 /* LibFile */, index: ((_o = options.lib) == null ? void 0 : _o.length) ?? 0 } + ); + } files = toSorted(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); processingDefaultLibFiles = void 0; processingOtherFiles = void 0; @@ -122989,7 +123327,7 @@ function createProgram(_rootNamesOrOptions, _options, _host, _oldProgram, _confi readFile, directoryExists, getSymlinkCache, - realpath: (_o = host.realpath) == null ? void 0 : _o.bind(host), + realpath: (_p = host.realpath) == null ? void 0 : _p.bind(host), useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(), getCanonicalFileName, getFileIncludeReasons: () => programDiagnostics.getFileReasons(), @@ -123003,7 +123341,7 @@ function createProgram(_rootNamesOrOptions, _options, _host, _oldProgram, _confi } mark("afterProgram"); measure("Program", "beforeProgram", "afterProgram"); - (_p = tracing) == null ? void 0 : _p.pop(); + (_q = tracing) == null ? void 0 : _q.pop(); return program; function getResolvedModule(file, moduleName, mode) { var _a2; @@ -124208,6 +124546,10 @@ function createProgram(_rootNamesOrOptions, _options, _host, _oldProgram, _confi } } function processSourceFile(fileName, isDefaultLib, packageId, reason) { + if (fileName === "asset:///lib.node.d.ts" && !shouldLoadNodeTypes) { + foundNodeTypes = true; + return; + } getSourceFileFromReferenceWorker( fileName, (fileName2) => findSourceFile(fileName2, isDefaultLib, reason, packageId), @@ -126136,7 +126478,7 @@ var BuilderState; addReferenceFromAmbientModule(symbol); } } - for (const ambientModule of program.getTypeChecker().getAmbientModules()) { + for (const ambientModule of program.getTypeChecker().getAmbientModules(sourceFile)) { if (ambientModule.declarations && ambientModule.declarations.length > 1) { addReferenceFromAmbientModule(ambientModule); } diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 9e127c3f5a524..c66b496392998 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -30285,6 +30285,7 @@ declare var ReadableStream: { new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number }): ReadableStream>; new(underlyingSource: UnderlyingDefaultSource, strategy?: QueuingStrategy): ReadableStream; new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + from(asyncIterable: AsyncIterable | Iterable>): ReadableStream; }; /** diff --git a/lib/lib.es2020.intl.d.ts b/lib/lib.es2020.intl.d.ts index 055c63b70cac9..8e9057c332786 100644 --- a/lib/lib.es2020.intl.d.ts +++ b/lib/lib.es2020.intl.d.ts @@ -285,7 +285,7 @@ declare namespace Intl { } interface DateTimeFormatOptions { - calendar?: string | undefined; + calendar?: string | (typeof globalThis extends { Temporal: { CalendarProtocol: infer T; }; } ? T : undefined) | undefined; dayPeriod?: "narrow" | "short" | "long" | undefined; numberingSystem?: string | undefined; diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 496166ca309c2..ab0e2ce3cb550 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -4522,7 +4522,7 @@ declare namespace Intl { timeZoneName?: "short" | "long" | "shortOffset" | "longOffset" | "shortGeneric" | "longGeneric" | undefined; formatMatcher?: "best fit" | "basic" | undefined; hour12?: boolean | undefined; - timeZone?: string | undefined; + timeZone?: string | (typeof globalThis extends { Temporal: { TimeZoneProtocol: infer T; }; } ? T : undefined) | undefined; } interface ResolvedDateTimeFormatOptions { diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 45c6a6134821d..e3e455ccb9219 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -9211,6 +9211,7 @@ declare var ReadableStream: { new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number }): ReadableStream>; new(underlyingSource: UnderlyingDefaultSource, strategy?: QueuingStrategy): ReadableStream; new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + from(asyncIterable: AsyncIterable | Iterable>): ReadableStream; }; /** diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 0f39eae746a04..bf4938d9e5664 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -3642,6 +3642,40 @@ declare namespace ts { responseRequired?: boolean; } } + namespace deno { + function setEnterSpan(f: EnterSpan): void; + function setExitSpan(f: ExitSpan): void; + function spanned(name: string, f: () => T): T; + function setIsNodeSourceFileCallback(callback: IsNodeSourceFileCallback): void; + function setNodeBuiltInModuleNames(names: readonly string[]): void; + function setNodeOnlyGlobalNames(names: readonly string[]): void; + function setTypesNodeIgnorableNames(names: Set): void; + function createDenoForkContext({ mergeSymbol, globals, nodeGlobals, ambientModuleSymbolRegex }: { + mergeSymbol(target: ts.Symbol, source: ts.Symbol, unidirectional?: boolean): ts.Symbol; + globals: ts.SymbolTable; + nodeGlobals: ts.SymbolTable; + ambientModuleSymbolRegex: RegExp; + }): DenoForkContext; + function isTypesNodePkgPath(path: ts.Path): boolean; + function tryParseNpmPackageReference(text: string): NpmPackageReference | undefined; + function parseNpmPackageReference(text: string): NpmPackageReference; + type IsNodeSourceFileCallback = (sourceFile: ts.SourceFile) => boolean; + type EnterSpan = (name: string) => object; + type ExitSpan = (span: object) => void; + let enterSpan: EnterSpan; + let exitSpan: ExitSpan; + interface DenoForkContext { + hasNodeSourceFile: (node: ts.Node | undefined) => boolean; + getGlobalsForName: (id: ts.__String) => ts.SymbolTable; + mergeGlobalSymbolTable: (node: ts.Node, source: ts.SymbolTable, unidirectional?: boolean) => void; + combinedGlobals: ts.SymbolTable; + } + interface NpmPackageReference { + name: string; + versionReq: string | undefined; + subPath: string | undefined; + } + } namespace JsTyping { interface TypingResolutionHost { directoryExists(path: string): boolean; @@ -6282,7 +6316,7 @@ declare namespace ts { getExportsOfModule(moduleSymbol: Symbol): Symbol[]; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; - getAmbientModules(): Symbol[]; + getAmbientModules(sourceFile?: SourceFile): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; getBaseConstraintOfType(type: Type): Type | undefined; @@ -11307,6 +11341,34 @@ declare namespace ts { span: TextSpan; preferences: UserPreferences; } + enum ExportKind { + Named = 0, + Default = 1, + ExportEquals = 2, + UMD = 3, + Module = 4, + } + interface SymbolExportInfo { + readonly symbol: Symbol; + readonly moduleSymbol: Symbol; + /** Set if `moduleSymbol` is an external module, not an ambient module */ + moduleFileName: string | undefined; + exportKind: ExportKind; + targetFlags: SymbolFlags; + /** True if export was only found via the package.json AutoImportProvider (for telemetry). */ + isFromPackageJson: boolean; + } + interface ExportInfoMap { + isUsableByFile(importingFile: Path): boolean; + clear(): void; + add(importingFile: Path, symbol: Symbol, key: __String, moduleSymbol: Symbol, moduleFile: SourceFile | undefined, exportKind: ExportKind, isFromPackageJson: boolean, checker: TypeChecker): void; + get(importingFile: Path, key: ExportMapInfoKey): readonly SymbolExportInfo[] | undefined; + search(importingFile: Path, preferCapitalized: boolean, matches: (name: string, targetFlags: SymbolFlags) => boolean, action: (info: readonly SymbolExportInfo[], symbolName: string, isFromAmbientModule: boolean, key: ExportMapInfoKey) => T | undefined): T | undefined; + releaseSymbols(): void; + isEmpty(): boolean; + /** @returns Whether the change resulted in the cache being cleared */ + onFileChanged(oldSourceFile: SourceFile, newSourceFile: SourceFile, typeAcquisitionEnabled: boolean): boolean; + } type ExportMapInfoKey = string & { __exportInfoKey: void; }; diff --git a/lib/typescript.js b/lib/typescript.js index d322bce730854..5d7868350dc60 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -492,6 +492,7 @@ __export(typescript_exports, { defaultHoverMaximumTruncationLength: () => defaultHoverMaximumTruncationLength, defaultInitCompilerOptions: () => defaultInitCompilerOptions, defaultMaximumTruncationLength: () => defaultMaximumTruncationLength, + deno: () => deno_exports, diagnosticCategoryName: () => diagnosticCategoryName, diagnosticToString: () => diagnosticToString, diagnosticsEqualityComparer: () => diagnosticsEqualityComparer, @@ -8782,6 +8783,9 @@ function getEncodedRootLength(path) { } return ~path.length; } + if (path.startsWith("data:")) { + return ~path.length; + } return 0; } function getRootLength(path) { @@ -9009,6 +9013,9 @@ function removeTrailingDirectorySeparator(path) { } function ensureTrailingDirectorySeparator(path) { if (!hasTrailingDirectorySeparator(path)) { + if (path.startsWith("data:")) { + return path; + } return path + directorySeparator; } return path; @@ -11426,6 +11433,225 @@ var Diagnostics = { _0_is_not_a_valid_meta_property_for_keyword_import_Did_you_mean_meta_or_defer: diag(18061, 1 /* Error */, "_0_is_not_a_valid_meta_property_for_keyword_import_Did_you_mean_meta_or_defer_18061", "'{0}' is not a valid meta-property for keyword 'import'. Did you mean 'meta' or 'defer'?") }; +// src/compiler/deno.ts +var deno_exports = {}; +__export(deno_exports, { + createDenoForkContext: () => createDenoForkContext, + enterSpan: () => enterSpan, + exitSpan: () => exitSpan, + isTypesNodePkgPath: () => isTypesNodePkgPath, + parseNpmPackageReference: () => parseNpmPackageReference, + setEnterSpan: () => setEnterSpan, + setExitSpan: () => setExitSpan, + setIsNodeSourceFileCallback: () => setIsNodeSourceFileCallback, + setNodeBuiltInModuleNames: () => setNodeBuiltInModuleNames, + setNodeOnlyGlobalNames: () => setNodeOnlyGlobalNames, + setTypesNodeIgnorableNames: () => setTypesNodeIgnorableNames, + spanned: () => spanned, + tryParseNpmPackageReference: () => tryParseNpmPackageReference +}); +var isNodeSourceFile = () => false; +var nodeBuiltInModuleNames = /* @__PURE__ */ new Set(); +var nodeOnlyGlobalNames = /* @__PURE__ */ new Set(); +var typesNodeIgnorableNames = /* @__PURE__ */ new Set(); +var enterSpan = () => ({}); +var exitSpan = () => { +}; +function setEnterSpan(f) { + enterSpan = f; +} +function setExitSpan(f) { + exitSpan = f; +} +function spanned(name, f) { + const span = enterSpan(name); + let needsExit = true; + try { + const result = f(); + if (result instanceof Promise) { + needsExit = false; + return result.finally(() => exitSpan(span)); + } else { + return result; + } + } finally { + if (needsExit) { + exitSpan(span); + } + } +} +function setIsNodeSourceFileCallback(callback) { + isNodeSourceFile = callback; +} +function setNodeBuiltInModuleNames(names) { + nodeBuiltInModuleNames = new Set(names); +} +function setNodeOnlyGlobalNames(names) { + nodeBuiltInModuleNames = new Set(names); + nodeOnlyGlobalNames = new Set(names); +} +function setTypesNodeIgnorableNames(names) { + typesNodeIgnorableNames = names; +} +function createDenoForkContext({ + mergeSymbol, + globals, + nodeGlobals, + ambientModuleSymbolRegex: ambientModuleSymbolRegex2 +}) { + return { + hasNodeSourceFile, + getGlobalsForName, + mergeGlobalSymbolTable, + combinedGlobals: createNodeGlobalsSymbolTable() + }; + function hasNodeSourceFile(node) { + if (!node) return false; + const sourceFile = getSourceFileOfNode(node); + return isNodeSourceFile(sourceFile); + } + function getGlobalsForName(id) { + if (ambientModuleSymbolRegex2.test(id)) { + if (id.startsWith('"node:')) { + const name = id.slice(6, -1); + if (nodeBuiltInModuleNames.has(name)) { + return globals; + } + } + return nodeGlobals; + } + return nodeOnlyGlobalNames.has(id) ? nodeGlobals : globals; + } + function mergeGlobalSymbolTable(node, source, unidirectional = false) { + const sourceFile = getSourceFileOfNode(node); + const isNodeFile = hasNodeSourceFile(sourceFile); + const isTypesNodeSourceFile = isNodeFile && isTypesNodePkgPath2(sourceFile.path); + source.forEach((sourceSymbol, id) => { + const target = isNodeFile ? getGlobalsForName(id) : globals; + const targetSymbol = target.get(id); + if (isTypesNodeSourceFile && targetSymbol !== void 0 && typesNodeIgnorableNames.has(id) && !symbolHasAnyTypesNodePkgDecl(targetSymbol)) { + return; + } + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol); + }); + } + function symbolHasAnyTypesNodePkgDecl(symbol) { + if (symbol.declarations) { + for (const decl of symbol.declarations) { + const sourceFile = getSourceFileOfNode(decl); + const isNodeFile = hasNodeSourceFile(sourceFile); + if (isNodeFile && isTypesNodePkgPath2(sourceFile.path)) { + return true; + } + } + } + return false; + } + function isTypesNodePkgPath2(path) { + return path.endsWith(".d.ts") && path.includes("/@types/node/"); + } + function createNodeGlobalsSymbolTable() { + return new Proxy(globals, { + get(target, prop, receiver) { + if (prop === "get") { + return (key) => { + return nodeGlobals.get(key) ?? globals.get(key); + }; + } else if (prop === "has") { + return (key) => { + return nodeGlobals.has(key) || globals.has(key); + }; + } else if (prop === "size") { + let i = 0; + for (const _ignore of getEntries((entry) => entry)) { + i++; + } + return i; + } else if (prop === "forEach") { + return (action) => { + for (const [key, value] of getEntries((entry) => entry)) { + action(value, key); + } + }; + } else if (prop === "entries") { + return () => { + return getEntries((kv) => kv); + }; + } else if (prop === "keys") { + return () => { + return getEntries((kv) => kv[0]); + }; + } else if (prop === "values") { + return () => { + return getEntries((kv) => kv[1]); + }; + } else if (prop === Symbol.iterator) { + return () => { + return Array.from(getEntries((kv) => kv))[Symbol.iterator](); + }; + } else { + const value = target[prop]; + if (value instanceof Function) { + return function(...args) { + return value.apply(this === receiver ? target : this, args); + }; + } + return value; + } + } + }); + function* getEntries(transform2) { + const foundKeys = /* @__PURE__ */ new Set(); + for (const entries of [nodeGlobals.entries(), globals.entries()]) { + for (const entry of entries) { + if (!foundKeys.has(entry[0])) { + yield transform2(entry); + foundKeys.add(entry[0]); + } + } + } + } + } +} +function isTypesNodePkgPath(path) { + return path.endsWith(".d.ts") && path.includes("/@types/node/"); +} +function tryParseNpmPackageReference(text) { + try { + return parseNpmPackageReference(text); + } catch { + return void 0; + } +} +function parseNpmPackageReference(text) { + if (!text.startsWith("npm:")) { + throw new Error(`Not an npm specifier: ${text}`); + } + text = text.replace(/^npm:\/?/, ""); + const parts = text.split("/"); + const namePartLen = text.startsWith("@") ? 2 : 1; + if (parts.length < namePartLen) { + throw new Error(`Not a valid package: ${text}`); + } + const nameParts = parts.slice(0, namePartLen); + const lastNamePart = nameParts[nameParts.length - 1]; + const lastAtIndex = lastNamePart.lastIndexOf("@"); + let versionReq; + if (lastAtIndex > 0) { + versionReq = lastNamePart.substring(lastAtIndex + 1); + nameParts[nameParts.length - 1] = lastNamePart.substring(0, lastAtIndex); + } + const name = nameParts.join("/"); + if (name.length === 0) { + throw new Error(`Npm specifier did not have a name: ${text}`); + } + return { + name, + versionReq, + subPath: parts.length > nameParts.length ? parts.slice(nameParts.length).join("/") : void 0 + }; +} + // src/compiler/scanner.ts function tokenIsIdentifierOrKeyword(token) { return token >= 80 /* Identifier */; @@ -22278,6 +22504,7 @@ function getJSXTransformEnabled(options) { return jsx === 2 /* React */ || jsx === 4 /* ReactJSX */ || jsx === 5 /* ReactJSXDev */; } function getJSXImplicitImportBase(compilerOptions, file) { + var _a; const jsxImportSourcePragmas = file == null ? void 0 : file.pragmas.get("jsximportsource"); const jsxImportSourcePragma = isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; const jsxRuntimePragmas = file == null ? void 0 : file.pragmas.get("jsxruntime"); @@ -22285,6 +22512,10 @@ function getJSXImplicitImportBase(compilerOptions, file) { if ((jsxRuntimePragma == null ? void 0 : jsxRuntimePragma.arguments.factory) === "classic") { return void 0; } + { + const resolvedJsxImportSource = file && ((_a = compilerOptions.resolveJsxImportSource) == null ? void 0 : _a.call(compilerOptions, file.fileName)); + if (resolvedJsxImportSource) return resolvedJsxImportSource; + } return compilerOptions.jsx === 4 /* ReactJSX */ || compilerOptions.jsx === 5 /* ReactJSXDev */ || compilerOptions.jsxImportSource || jsxImportSourcePragma || (jsxRuntimePragma == null ? void 0 : jsxRuntimePragma.arguments.factory) === "automatic" ? (jsxImportSourcePragma == null ? void 0 : jsxImportSourcePragma.arguments.factory) || compilerOptions.jsxImportSource || "react" : void 0; } function getJSXRuntimeImport(base, options) { @@ -23638,7 +23869,9 @@ function createNameResolver({ argumentsSymbol, error: error2, getSymbolOfDeclaration, - globals, + denoGlobals, + nodeGlobals, + denoContext, lookup, setRequiresScopeChangeCache = returnUndefined, getRequiresScopeChangeCache = returnUndefined, @@ -23894,7 +24127,12 @@ function createNameResolver({ } } if (!excludeGlobals) { - result = lookup(globals, name, meaning); + if (denoContext.hasNodeSourceFile(lastLocation)) { + result = lookup(nodeGlobals, name, meaning); + } + if (!result) { + result = lookup(denoGlobals, name, meaning); + } } } if (!result) { @@ -40727,6 +40965,7 @@ var libEntries = [ ["dom", "lib.dom.d.ts"], ["dom.iterable", "lib.dom.iterable.d.ts"], ["dom.asynciterable", "lib.dom.asynciterable.d.ts"], + ["dom.extras", "lib.dom.extras.d.ts"], ["webworker", "lib.webworker.d.ts"], ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], ["webworker.iterable", "lib.webworker.iterable.d.ts"], @@ -51118,13 +51357,24 @@ function createTypeChecker(host) { evaluateElementAccessExpression, evaluateEntityNameExpression }); - var globals = createSymbolTable(); + var denoGlobals = createSymbolTable(); + var nodeGlobals = createSymbolTable(); var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); undefinedSymbol.declarations = []; - var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); - globalThisSymbol.exports = globals; - globalThisSymbol.declarations = []; - globals.set(globalThisSymbol.escapedName, globalThisSymbol); + var denoGlobalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); + denoGlobalThisSymbol.exports = denoGlobals; + denoGlobalThisSymbol.declarations = []; + denoGlobals.set(denoGlobalThisSymbol.escapedName, denoGlobalThisSymbol); + const denoContext = deno_exports.createDenoForkContext({ + globals: denoGlobals, + nodeGlobals, + mergeSymbol, + ambientModuleSymbolRegex + }); + const nodeGlobalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); + nodeGlobalThisSymbol.exports = denoContext.combinedGlobals; + nodeGlobalThisSymbol.declarations = []; + nodeGlobals.set(nodeGlobalThisSymbol.escapedName, nodeGlobalThisSymbol); var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); var isolatedModulesLikeFlagName = compilerOptions.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules"; @@ -51138,7 +51388,9 @@ function createTypeChecker(host) { compilerOptions, requireSymbol, argumentsSymbol, - globals, + denoGlobals, + nodeGlobals, + denoContext, getSymbolOfDeclaration, error: error2, getRequiresScopeChangeCache, @@ -51152,7 +51404,9 @@ function createTypeChecker(host) { compilerOptions, requireSymbol, argumentsSymbol, - globals, + denoGlobals, + nodeGlobals, + denoContext, getSymbolOfDeclaration, error: error2, getRequiresScopeChangeCache, @@ -51965,6 +52219,7 @@ function createTypeChecker(host) { var reverseMappedCache = /* @__PURE__ */ new Map(); var reverseHomomorphicMappedCache = /* @__PURE__ */ new Map(); var ambientModulesCache; + var nodeAmbientModulesCache; var patternAmbientModules; var patternAmbientModuleAugmentations; var globalObjectType; @@ -52112,7 +52367,8 @@ function createTypeChecker(host) { ) || unknownSymbol); } if (!isIdentifier(node.expression.expression)) return false; - return idText(node.expression.name) === "Symbol" && idText(node.expression.expression) === "globalThis" && getResolvedSymbol(node.expression.expression) === globalThisSymbol; + const resolvedGlobalThis = getResolvedSymbol(node.expression.expression); + return idText(node.expression.name) === "Symbol" && idText(node.expression.expression) === "globalThis" && (resolvedGlobalThis === denoGlobalThisSymbol || resolvedGlobalThis === nodeGlobalThisSymbol); } function getCachedType(key) { return key ? cachedTypes.get(key) : void 0; @@ -52374,7 +52630,7 @@ function createTypeChecker(host) { recordMergedSymbol(target, source); } } else if (target.flags & 1024 /* NamespaceModule */) { - if (target !== globalThisSymbol) { + if (target !== denoGlobalThisSymbol && target !== nodeGlobalThisSymbol) { error2( source.declarations && getNameOfDeclaration(source.declarations[0]), Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, @@ -52468,7 +52724,7 @@ function createTypeChecker(host) { return; } if (isGlobalScopeAugmentation(moduleAugmentation)) { - mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + denoContext.mergeGlobalSymbolTable(moduleAugmentation, moduleAugmentation.symbol.exports); } else { const moduleNotFoundError = !(moduleName.parent.parent.flags & 33554432 /* Ambient */) ? Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : void 0; let mainModule = resolveExternalModuleNameWorker( @@ -52514,15 +52770,17 @@ function createTypeChecker(host) { } function addUndefinedToGlobalsOrErrorOnRedeclaration() { const name = undefinedSymbol.escapedName; - const targetSymbol = globals.get(name); - if (targetSymbol) { - forEach(targetSymbol.declarations, (declaration) => { - if (!isTypeDeclaration(declaration)) { - diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, unescapeLeadingUnderscores(name))); - } - }); - } else { - globals.set(name, undefinedSymbol); + for (const globals of [nodeGlobals, denoGlobals]) { + const targetSymbol = globals.get(name); + if (targetSymbol) { + forEach(targetSymbol.declarations, (declaration) => { + if (!isTypeDeclaration(declaration)) { + diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, unescapeLeadingUnderscores(name))); + } + }); + } else { + globals.set(name, undefinedSymbol); + } } } function getSymbolLinks(symbol) { @@ -52825,7 +53083,9 @@ function createTypeChecker(host) { } } if (compilerOptions.isolatedModules && result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */) { - const isGlobal = getSymbol2(globals, name, meaning) === result; + const isNodeFile = denoContext.hasNodeSourceFile(lastLocation); + const fileGlobals = isNodeFile ? nodeGlobals : denoGlobals; + const isGlobal = getSymbol2(fileGlobals, name, meaning) === result; const nonValueSymbol = isGlobal && isSourceFile(lastLocation) && lastLocation.locals && getSymbol2(lastLocation.locals, name, ~111551 /* Value */); if (nonValueSymbol) { const importDecl = (_a = nonValueSymbol.declarations) == null ? void 0 : _a.find((d) => d.kind === 277 /* ImportSpecifier */ || d.kind === 274 /* ImportClause */ || d.kind === 275 /* NamespaceImport */ || d.kind === 272 /* ImportEqualsDeclaration */); @@ -53229,7 +53489,7 @@ function createTypeChecker(host) { const usageMode = file && getEmitSyntaxForModuleSpecifierExpression(usage); if (file && usageMode !== void 0) { const targetMode = host.getImpliedNodeFormatForEmit(file); - if (usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */ && 100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) { + if (usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */) { return true; } if (usageMode === 99 /* ESNext */ && targetMode === 99 /* ESNext */) { @@ -54104,6 +54364,25 @@ function createTypeChecker(host) { return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, !ignoreErrors ? moduleReferenceExpression : void 0, isForAugmentation) : void 0; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) { + var _a; + const result = resolveExternalModuleInner(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation); + if (moduleReference.startsWith("npm:") && (result === void 0 || ((_a = result == null ? void 0 : result.exports) == null ? void 0 : _a.size) === 0)) { + const npmPackageRef = deno_exports.tryParseNpmPackageReference(moduleReference); + if (npmPackageRef) { + const bareSpecifier = npmPackageRef.name + (npmPackageRef.subPath === void 0 ? "" : "/" + npmPackageRef.subPath); + const ambientModule = tryFindAmbientModule( + bareSpecifier, + /*withAugmentations*/ + true + ); + if (ambientModule) { + return ambientModule; + } + } + } + return result; + } + function resolveExternalModuleInner(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l; if (errorNode && startsWith(moduleReference, "@types/")) { const diag2 = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; @@ -54913,8 +55192,20 @@ function createTypeChecker(host) { break; } } + if (denoContext.hasNodeSourceFile(enclosingDeclaration)) { + result = callback( + nodeGlobals, + /*ignoreQualification*/ + void 0, + /*isLocalNameLookup*/ + true + ); + if (result) { + return result; + } + } return callback( - globals, + denoGlobals, /*ignoreQualification*/ void 0, /*isLocalNameLookup*/ @@ -54989,7 +55280,11 @@ function createTypeChecker(host) { } } }); - return result2 || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : void 0); + if (result2) { + return result2; + } + const globalSymbol = symbols === nodeGlobals ? nodeGlobalThisSymbol : symbols === denoGlobals ? denoGlobalThisSymbol : void 0; + return globalSymbol !== void 0 ? getCandidateListForSymbol(globalSymbol, globalSymbol, ignoreQualification) : void 0; } function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) { if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) { @@ -62973,7 +63268,7 @@ function createTypeChecker(host) { } let members = getExportsOfSymbol(symbol); let indexInfos; - if (symbol === globalThisSymbol) { + if (symbol === denoGlobalThisSymbol || symbol === nodeGlobalThisSymbol) { const varsOnly = /* @__PURE__ */ new Map(); members.forEach((p) => { var _a; @@ -64133,7 +64428,7 @@ function createTypeChecker(host) { if (isExternalModuleNameRelative(moduleName)) { return void 0; } - const symbol = getSymbol2(globals, '"' + moduleName + '"', 512 /* ValueModule */); + const symbol = getSymbol2(denoContext.combinedGlobals, '"' + moduleName + '"', 512 /* ValueModule */); return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } function hasEffectiveQuestionToken(node) { @@ -66935,7 +67230,9 @@ function createTypeChecker(host) { return getUnionType(append(types, undefinedType)); } } - if (objectType.symbol === globalThisSymbol && propName !== void 0 && globalThisSymbol.exports.has(propName) && globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */) { + if (objectType.symbol === denoGlobalThisSymbol && propName !== void 0 && denoGlobalThisSymbol.exports.has(propName) && denoGlobalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */) { + error2(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); + } else if (objectType.symbol === nodeGlobalThisSymbol && propName !== void 0 && nodeGlobalThisSymbol.exports.has(propName) && nodeGlobalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */) { error2(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); } else if (noImplicitAny && !(accessFlags & 128 /* SuppressNoImplicitAnyError */)) { if (propName !== void 0 && typeHasStaticProperty(propName, objectType)) { @@ -76486,7 +76783,7 @@ function createTypeChecker(host) { /*isUse*/ true ); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === denoGlobalThisSymbol || symbol === nodeGlobalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { } else { const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol); if (!target || getSymbolFlags(target) & 111551 /* Value */) { @@ -77037,8 +77334,8 @@ function createTypeChecker(host) { container ); if (noImplicitThis) { - const globalThisType2 = getTypeOfSymbol(globalThisSymbol); - if (type === globalThisType2 && capturedByArrowFunction) { + const globalThisType2 = getTypeOfSymbol(denoGlobalThisSymbol); + if ((type === globalThisType2 || type === getTypeOfSymbol(nodeGlobalThisSymbol)) && capturedByArrowFunction) { error2(node, Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this); } else if (!type) { const diag2 = error2(node, Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); @@ -77090,7 +77387,10 @@ function createTypeChecker(host) { } else if (container.externalModuleIndicator) { return undefinedType; } else if (includeGlobalThis) { - return getTypeOfSymbol(globalThisSymbol); + if (denoContext.hasNodeSourceFile(container)) { + return getTypeOfSymbol(nodeGlobalThisSymbol); + } + return getTypeOfSymbol(denoGlobalThisSymbol); } } } @@ -79910,14 +80210,17 @@ function createTypeChecker(host) { if (!isUncheckedJS && isJSLiteralType(leftType)) { return anyType; } - if (leftType.symbol === globalThisSymbol) { - if (globalThisSymbol.exports.has(right.escapedText) && globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */) { + if (leftType.symbol === denoGlobalThisSymbol) { + if (denoGlobalThisSymbol.exports.has(right.escapedText) && denoGlobalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */) { error2(right, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(right.escapedText), typeToString(leftType)); } else if (noImplicitAny) { error2(right, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType)); } return anyType; } + if (leftType.symbol === nodeGlobalThisSymbol) { + return anyType; + } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType, isUncheckedJS); } @@ -80156,7 +80459,7 @@ function createTypeChecker(host) { const symbol = getSymbol2(symbols, name, meaning); if (symbol) return symbol; let candidates = arrayFrom(symbols.values()); - if (symbols === globals) { + if (symbols === denoGlobals || symbols == nodeGlobals) { const primitives = mapDefined( ["string", "number", "boolean", "object", "bigint", "symbol"], (s) => symbols.has(s.charAt(0).toUpperCase() + s.slice(1)) ? createSymbol(524288 /* TypeAlias */, s) : void 0 @@ -91010,7 +91313,7 @@ function createTypeChecker(host) { /*isUse*/ true ); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === denoGlobalThisSymbol || symbol === nodeGlobalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error2(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName)); } else { markLinkedReferences(node, 7 /* ExportSpecifier */); @@ -91125,7 +91428,9 @@ function createTypeChecker(host) { grammarErrorOnNode(node.expression, Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); } if (node.isExportEquals) { - if (moduleKind >= 5 /* ES2015 */ && moduleKind !== 200 /* Preserve */ && (node.flags & 33554432 /* Ambient */ && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) === 99 /* ESNext */ || !(node.flags & 33554432 /* Ambient */) && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) !== 1 /* CommonJS */)) { + if (moduleKind >= 5 /* ES2015 */ && moduleKind !== 200 /* Preserve */ && // deno: temporarily disable this one until Deno 2.0 (https://github.com/microsoft/TypeScript/pull/52109) + /* (node.flags & NodeFlags.Ambient && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) === ModuleKind.ESNext) || */ + (!(node.flags & 33554432 /* Ambient */) && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) !== 1 /* CommonJS */)) { grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } else if (moduleKind === 4 /* System */ && !(node.flags & 33554432 /* Ambient */)) { grammarErrorOnNode(node, Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); @@ -91818,7 +92123,10 @@ function createTypeChecker(host) { isStaticSymbol = isStatic(location); location = location.parent; } - copySymbols(globals, meaning); + if (denoContext.hasNodeSourceFile(location)) { + copySymbols(nodeGlobals, meaning); + } + copySymbols(denoGlobals, meaning); } function copySymbol(symbol, meaning2) { if (getCombinedLocalAndExportSymbolFlags(symbol) & meaning2) { @@ -93027,7 +93335,7 @@ function createTypeChecker(host) { return nodeBuilder.serializeTypeForExpression(expr, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker); } function hasGlobalName(name) { - return globals.has(escapeLeadingUnderscores(name)); + return denoGlobals.has(escapeLeadingUnderscores(name)); } function getReferencedValueSymbol(reference, startInDeclarationContainer) { const resolvedSymbol = getNodeLinks(reference).resolvedSymbol; @@ -93379,10 +93687,10 @@ function createTypeChecker(host) { diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis")); } } - mergeSymbolTable(globals, file.locals); + denoContext.mergeGlobalSymbolTable(file, file.locals); } if (file.jsGlobalAugmentations) { - mergeSymbolTable(globals, file.jsGlobalAugmentations); + denoContext.mergeGlobalSymbolTable(file, file.jsGlobalAugmentations); } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = concatenate(patternAmbientModules, file.patternAmbientModules); @@ -93392,9 +93700,11 @@ function createTypeChecker(host) { } if (file.symbol && file.symbol.globalExports) { const source = file.symbol.globalExports; + const isNodeFile = denoContext.hasNodeSourceFile(file); source.forEach((sourceSymbol, id) => { - if (!globals.has(id)) { - globals.set(id, sourceSymbol); + const envGlobals = isNodeFile ? denoContext.getGlobalsForName(id) : denoGlobals; + if (!envGlobals.has(id)) { + envGlobals.set(id, sourceSymbol); } }); } @@ -93417,7 +93727,8 @@ function createTypeChecker(host) { true ); getSymbolLinks(unknownSymbol).type = errorType; - getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol); + getSymbolLinks(denoGlobalThisSymbol).type = createObjectType(16 /* Anonymous */, denoGlobalThisSymbol); + getSymbolLinks(nodeGlobalThisSymbol).type = createObjectType(16 /* Anonymous */, nodeGlobalThisSymbol); globalArrayType = getGlobalType( "Array", /*arity*/ @@ -95015,16 +95326,28 @@ function createTypeChecker(host) { } return false; } - function getAmbientModules() { - if (!ambientModulesCache) { - ambientModulesCache = []; - globals.forEach((global2, sym) => { + function getAmbientModules(sourceFile) { + const isNode = denoContext.hasNodeSourceFile(sourceFile); + if (isNode) { + if (!nodeAmbientModulesCache) { + nodeAmbientModulesCache = getAmbientModulesFromGlobals(denoContext.combinedGlobals); + } + return nodeAmbientModulesCache; + } else { + if (!ambientModulesCache) { + ambientModulesCache = getAmbientModulesFromGlobals(denoGlobals); + } + return ambientModulesCache; + } + function getAmbientModulesFromGlobals(envGlobals) { + const result = []; + envGlobals.forEach((global2, sym) => { if (ambientModuleSymbolRegex.test(sym)) { - ambientModulesCache.push(global2); + result.push(global2); } }); + return result; } - return ambientModulesCache; } function checkGrammarImportClause(node) { var _a, _b; @@ -126902,14 +127225,6 @@ function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) { } return sourceFile; } : void 0; - host.fileExists = (fileName) => { - const key = toPath3(fileName); - const value = fileExistsCache.get(key); - if (value !== void 0) return value; - const newValue = originalFileExists.call(host, fileName); - fileExistsCache.set(key, !!newValue); - return newValue; - }; if (originalWriteFile) { host.writeFile = (fileName, data, ...rest) => { const key = toPath3(fileName); @@ -127495,7 +127810,7 @@ function createCreateProgramOptions(rootNames, options, host, oldProgram, config }; } function createProgram(_rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { - var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p; + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q; let _createProgramOptions = isArray(_rootNamesOrOptions) ? createCreateProgramOptions(_rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : _rootNamesOrOptions; const { rootNames, options, configFileParsingDiagnostics, projectReferences, typeScriptVersion: typeScriptVersion3, host: createProgramOptionsHost } = _createProgramOptions; let { oldProgram } = _createProgramOptions; @@ -127630,6 +127945,8 @@ function createProgram(_rootNamesOrOptions, _options, _host, _oldProgram, _confi let usesUriStyleNodeCoreModules; const filesByName = /* @__PURE__ */ new Map(); const libFiles = /* @__PURE__ */ new Set(); + let shouldLoadNodeTypes = false; + let foundNodeTypes = false; let missingFileNames = /* @__PURE__ */ new Map(); const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? /* @__PURE__ */ new Map() : void 0; let resolvedProjectReferences; @@ -127743,6 +128060,23 @@ function createProgram(_rootNamesOrOptions, _options, _host, _oldProgram, _confi }); } } + const hasTypesNodePackage = () => { + for (const path of filesByName.keys()) { + if (deno_exports.isTypesNodePkgPath(path)) { + return true; + } + } + return false; + }; + if (foundNodeTypes && !hasTypesNodePackage()) { + shouldLoadNodeTypes = true; + processRootFile( + "asset:///lib.node.d.ts", + /*isDefaultLib*/ + true, + { kind: 6 /* LibFile */, index: ((_o = options.lib) == null ? void 0 : _o.length) ?? 0 } + ); + } files = toSorted(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); processingDefaultLibFiles = void 0; processingOtherFiles = void 0; @@ -127863,7 +128197,7 @@ function createProgram(_rootNamesOrOptions, _options, _host, _oldProgram, _confi readFile, directoryExists, getSymlinkCache, - realpath: (_o = host.realpath) == null ? void 0 : _o.bind(host), + realpath: (_p = host.realpath) == null ? void 0 : _p.bind(host), useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(), getCanonicalFileName, getFileIncludeReasons: () => programDiagnostics.getFileReasons(), @@ -127877,7 +128211,7 @@ function createProgram(_rootNamesOrOptions, _options, _host, _oldProgram, _confi } mark("afterProgram"); measure("Program", "beforeProgram", "afterProgram"); - (_p = tracing) == null ? void 0 : _p.pop(); + (_q = tracing) == null ? void 0 : _q.pop(); return program; function getResolvedModule(file, moduleName, mode) { var _a2; @@ -129082,6 +129416,10 @@ function createProgram(_rootNamesOrOptions, _options, _host, _oldProgram, _confi } } function processSourceFile(fileName, isDefaultLib, packageId, reason) { + if (fileName === "asset:///lib.node.d.ts" && !shouldLoadNodeTypes) { + foundNodeTypes = true; + return; + } getSourceFileFromReferenceWorker( fileName, (fileName2) => findSourceFile(fileName2, isDefaultLib, reason, packageId), @@ -131024,7 +131362,7 @@ var BuilderState; addReferenceFromAmbientModule(symbol); } } - for (const ambientModule of program.getTypeChecker().getAmbientModules()) { + for (const ambientModule of program.getTypeChecker().getAmbientModules(sourceFile)) { if (ambientModule.declarations && ambientModule.declarations.length > 1) { addReferenceFromAmbientModule(ambientModule); } @@ -171316,7 +171654,7 @@ function isProbablyGlobalType(type, sourceFile, checker) { const globalThisSymbol = checker.resolveName( "globalThis", /*location*/ - void 0, + sourceFile, 111551 /* Value */, /*excludeGlobals*/ false @@ -184441,6 +184779,7 @@ __export(ts_exports2, { defaultHoverMaximumTruncationLength: () => defaultHoverMaximumTruncationLength, defaultInitCompilerOptions: () => defaultInitCompilerOptions, defaultMaximumTruncationLength: () => defaultMaximumTruncationLength, + deno: () => deno_exports, diagnosticCategoryName: () => diagnosticCategoryName, diagnosticToString: () => diagnosticToString, diagnosticsEqualityComparer: () => diagnosticsEqualityComparer, @@ -199223,6 +199562,7 @@ if (typeof console !== "undefined") { defaultHoverMaximumTruncationLength, defaultInitCompilerOptions, defaultMaximumTruncationLength, + deno, diagnosticCategoryName, diagnosticToString, diagnosticsEqualityComparer, diff --git a/src/compiler/_namespaces/ts.ts b/src/compiler/_namespaces/ts.ts index bd9684e481982..eb761d74f11fb 100644 --- a/src/compiler/_namespaces/ts.ts +++ b/src/compiler/_namespaces/ts.ts @@ -10,6 +10,7 @@ export * from "../types.js"; export * from "../sys.js"; export * from "../path.js"; export * from "../diagnosticInformationMap.generated.js"; +export * as deno from "../deno.js"; export * from "../scanner.js"; export * from "../utilitiesPublic.js"; export * from "../utilities.js"; diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts index 625a64e266fee..058afa3d75b8b 100644 --- a/src/compiler/builderState.ts +++ b/src/compiler/builderState.ts @@ -260,7 +260,7 @@ export namespace BuilderState { } // From ambient modules - for (const ambientModule of program.getTypeChecker().getAmbientModules()) { + for (const ambientModule of program.getTypeChecker().getAmbientModules(sourceFile)) { if (ambientModule.declarations && ambientModule.declarations.length > 1) { addReferenceFromAmbientModule(ambientModule); } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0567712f11da3..2860ea67a20a4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -145,6 +145,7 @@ import { defaultMaximumTruncationLength, DeferredTypeReference, DeleteExpression, + deno, Diagnostic, DiagnosticAndArguments, DiagnosticArguments, @@ -1555,14 +1556,27 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { evaluateEntityNameExpression, }); - var globals = createSymbolTable(); + var denoGlobals = createSymbolTable(); + var nodeGlobals = createSymbolTable(); var undefinedSymbol = createSymbol(SymbolFlags.Property, "undefined" as __String); undefinedSymbol.declarations = []; - var globalThisSymbol = createSymbol(SymbolFlags.Module, "globalThis" as __String, CheckFlags.Readonly); - globalThisSymbol.exports = globals; - globalThisSymbol.declarations = []; - globals.set(globalThisSymbol.escapedName, globalThisSymbol); + var denoGlobalThisSymbol = createSymbol(SymbolFlags.Module, "globalThis" as __String, CheckFlags.Readonly); + denoGlobalThisSymbol.exports = denoGlobals; + denoGlobalThisSymbol.declarations = []; + denoGlobals.set(denoGlobalThisSymbol.escapedName, denoGlobalThisSymbol); + + const denoContext = deno.createDenoForkContext({ + globals: denoGlobals, + nodeGlobals, + mergeSymbol, + ambientModuleSymbolRegex, + }); + + const nodeGlobalThisSymbol = createSymbol(SymbolFlags.Module, "globalThis" as __String, CheckFlags.Readonly); + nodeGlobalThisSymbol.exports = denoContext.combinedGlobals; + nodeGlobalThisSymbol.declarations = []; + nodeGlobals.set(nodeGlobalThisSymbol.escapedName, nodeGlobalThisSymbol); var argumentsSymbol = createSymbol(SymbolFlags.Property, "arguments" as __String); var requireSymbol = createSymbol(SymbolFlags.Property, "require" as __String); @@ -1580,7 +1594,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { compilerOptions, requireSymbol, argumentsSymbol, - globals, + denoGlobals, + nodeGlobals, + denoContext, getSymbolOfDeclaration, error, getRequiresScopeChangeCache, @@ -1595,7 +1611,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { compilerOptions, requireSymbol, argumentsSymbol, - globals, + denoGlobals, + nodeGlobals, + denoContext, getSymbolOfDeclaration, error, getRequiresScopeChangeCache, @@ -2245,6 +2263,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { var reverseMappedCache = new Map(); var reverseHomomorphicMappedCache = new Map(); var ambientModulesCache: Symbol[] | undefined; + var nodeAmbientModulesCache: Symbol[] | undefined; /** * List of every ambient module with a "*" wildcard. * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. @@ -2421,7 +2440,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (!isIdentifier(node.expression.expression)) return false; // Exactly `globalThis.Symbol.something` and `globalThis` resolves to the global `globalThis` - return idText(node.expression.name) === "Symbol" && idText(node.expression.expression) === "globalThis" && getResolvedSymbol(node.expression.expression) === globalThisSymbol; + const resolvedGlobalThis = getResolvedSymbol(node.expression.expression); + return idText(node.expression.name) === "Symbol" && idText(node.expression.expression) === "globalThis" && (resolvedGlobalThis === denoGlobalThisSymbol || resolvedGlobalThis === nodeGlobalThisSymbol); } function getCachedType(key: string | undefined) { @@ -2747,7 +2767,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Do not report an error when merging `var globalThis` with the built-in `globalThis`, // as we will already report a "Declaration name conflicts..." error, and this error // won't make much sense. - if (target !== globalThisSymbol) { + if (target !== denoGlobalThisSymbol && target !== nodeGlobalThisSymbol) { error( source.declarations && getNameOfDeclaration(source.declarations[0]), Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, @@ -2865,7 +2885,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (isGlobalScopeAugmentation(moduleAugmentation)) { - mergeSymbolTable(globals, moduleAugmentation.symbol.exports!); + denoContext.mergeGlobalSymbolTable(moduleAugmentation, moduleAugmentation.symbol.exports!); } else { // find a module that about to be augmented @@ -2915,17 +2935,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function addUndefinedToGlobalsOrErrorOnRedeclaration() { const name = undefinedSymbol.escapedName; - const targetSymbol = globals.get(name); - if (targetSymbol) { - forEach(targetSymbol.declarations, declaration => { - // checkTypeNameIsReserved will have added better diagnostics for type declarations. - if (!isTypeDeclaration(declaration)) { - diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, unescapeLeadingUnderscores(name))); - } - }); - } - else { - globals.set(name, undefinedSymbol); + for (const globals of [nodeGlobals, denoGlobals]) { + const targetSymbol = globals.get(name); + if (targetSymbol) { + forEach(targetSymbol.declarations, declaration => { + // checkTypeNameIsReserved will have added better diagnostics for type declarations. + if (!isTypeDeclaration(declaration)) { + diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, unescapeLeadingUnderscores(name))); + } + }); + } + else { + globals.set(name, undefinedSymbol); + } } } @@ -3367,7 +3389,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Look at 'compilerOptions.isolatedModules' and not 'getIsolatedModules(...)' (which considers 'verbatimModuleSyntax') // here because 'verbatimModuleSyntax' will already have an error for importing a type without 'import type'. if (compilerOptions.isolatedModules && result && isInExternalModule && (meaning & SymbolFlags.Value) === SymbolFlags.Value) { - const isGlobal = getSymbol(globals, name, meaning) === result; + const isNodeFile = denoContext.hasNodeSourceFile(lastLocation); + const fileGlobals = isNodeFile ? nodeGlobals : denoGlobals; + const isGlobal = getSymbol(fileGlobals, name, meaning) === result; const nonValueSymbol = isGlobal && isSourceFile(lastLocation) && lastLocation.locals && getSymbol(lastLocation.locals, name, ~SymbolFlags.Value); if (nonValueSymbol) { const importDecl = nonValueSymbol.declarations?.find(d => d.kind === SyntaxKind.ImportSpecifier || d.kind === SyntaxKind.ImportClause || d.kind === SyntaxKind.NamespaceImport || d.kind === SyntaxKind.ImportEqualsDeclaration); @@ -3792,7 +3816,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const usageMode = file && getEmitSyntaxForModuleSpecifierExpression(usage); if (file && usageMode !== undefined) { const targetMode = host.getImpliedNodeFormatForEmit(file); - if (usageMode === ModuleKind.ESNext && targetMode === ModuleKind.CommonJS && ModuleKind.Node16 <= moduleKind && moduleKind <= ModuleKind.NodeNext) { + // deno: change the condition here to not be dependent on the global module resolution setting, but just the impliedNodeFormat + if (usageMode === ModuleKind.ESNext && targetMode === ModuleKind.CommonJS) { // In Node.js, CommonJS modules always have a synthetic default when imported into ESM return true; } @@ -4728,6 +4753,25 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function resolveExternalModule(location: Node, moduleReference: string, moduleNotFoundError: DiagnosticMessage | undefined, errorNode: Node | undefined, isForAugmentation = false): Symbol | undefined { + const result = resolveExternalModuleInner(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation); + + // deno: attempt to resolve an npm package reference to its bare specifier w/ path ambient module + // when not found and the symbol has zero exports + if (moduleReference.startsWith("npm:") && (result === undefined || result?.exports?.size === 0)) { + const npmPackageRef = deno.tryParseNpmPackageReference(moduleReference); + if (npmPackageRef) { + const bareSpecifier = npmPackageRef.name + (npmPackageRef.subPath === undefined ? "" : "/" + npmPackageRef.subPath); + const ambientModule = tryFindAmbientModule(bareSpecifier, /*withAugmentations*/ true); + if (ambientModule) { + return ambientModule; + } + } + } + + return result; + } + + function resolveExternalModuleInner(location: Node, moduleReference: string, moduleNotFoundError: DiagnosticMessage | undefined, errorNode: Node | undefined, isForAugmentation = false): Symbol | undefined { if (errorNode && startsWith(moduleReference, "@types/")) { const diag = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; const withoutAtTypePrefix = removePrefix(moduleReference, "@types/"); @@ -5726,7 +5770,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - return callback(globals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); + if (denoContext.hasNodeSourceFile(enclosingDeclaration)) { + result = callback(nodeGlobals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); + if (result) { + return result; + } + } + + return callback(denoGlobals, /*ignoreQualification*/ undefined, /*isLocalNameLookup*/ true); } function getQualifiedLeftMeaning(rightMeaning: SymbolFlags) { @@ -5820,7 +5871,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { }); // If there's no result and we're looking at the global symbol table, treat `globalThis` like an alias and try to lookup thru that - return result || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : undefined); + if (result) { + return result; + } + const globalSymbol = symbols === nodeGlobals ? nodeGlobalThisSymbol : symbols === denoGlobals ? denoGlobalThisSymbol : undefined; + return globalSymbol !== undefined ? getCandidateListForSymbol(globalSymbol, globalSymbol, ignoreQualification) : undefined; } function getCandidateListForSymbol(symbolFromSymbolTable: Symbol, resolvedImportedSymbol: Symbol, ignoreQualification: boolean | undefined) { @@ -14615,7 +14670,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Combinations of function, class, enum and module let members = getExportsOfSymbol(symbol); let indexInfos: IndexInfo[] | undefined; - if (symbol === globalThisSymbol) { + if (symbol === denoGlobalThisSymbol || symbol === nodeGlobalThisSymbol) { const varsOnly = new Map<__String, Symbol>(); members.forEach(p => { if (!(p.flags & SymbolFlags.BlockScoped) && !(p.flags & SymbolFlags.ValueModule && p.declarations?.length && every(p.declarations, isAmbientModule))) { @@ -16079,7 +16134,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isExternalModuleNameRelative(moduleName)) { return undefined; } - const symbol = getSymbol(globals, '"' + moduleName + '"' as __String, SymbolFlags.ValueModule); + const symbol = getSymbol(denoContext.combinedGlobals, '"' + moduleName + '"' as __String, SymbolFlags.ValueModule); // merged symbol is module declaration symbol combined with all augmentations return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } @@ -19340,7 +19395,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } - if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports!.has(propName) && (globalThisSymbol.exports!.get(propName)!.flags & SymbolFlags.BlockScoped)) { + if (objectType.symbol === denoGlobalThisSymbol && propName !== undefined && denoGlobalThisSymbol.exports!.has(propName) && (denoGlobalThisSymbol.exports!.get(propName)!.flags & SymbolFlags.BlockScoped)) { + error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + // deno: ensure condition and body match the above + else if (objectType.symbol === nodeGlobalThisSymbol && propName !== undefined && nodeGlobalThisSymbol.exports!.has(propName) && (nodeGlobalThisSymbol.exports!.get(propName)!.flags & SymbolFlags.BlockScoped)) { error(accessExpression, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(propName), typeToString(objectType)); } else if (noImplicitAny && !(accessFlags & AccessFlags.SuppressNoImplicitAnyError)) { @@ -30746,7 +30805,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return; // Skip for invalid syntax like this: export { "x" } } const symbol = resolveName(exportedName, exportedName.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === denoGlobalThisSymbol || symbol === nodeGlobalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { // Do nothing, non-local symbol } else { @@ -31467,8 +31526,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container); if (noImplicitThis) { - const globalThisType = getTypeOfSymbol(globalThisSymbol); - if (type === globalThisType && capturedByArrowFunction) { + const globalThisType = getTypeOfSymbol(denoGlobalThisSymbol); + if ((type === globalThisType || type === getTypeOfSymbol(nodeGlobalThisSymbol)) && capturedByArrowFunction) { error(node, Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this); } else if (!type) { @@ -31530,7 +31589,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return undefinedType; } else if (includeGlobalThis) { - return getTypeOfSymbol(globalThisSymbol); + if (denoContext.hasNodeSourceFile(container)) { + return getTypeOfSymbol(nodeGlobalThisSymbol); + } + return getTypeOfSymbol(denoGlobalThisSymbol); } } } @@ -34954,8 +35016,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!isUncheckedJS && isJSLiteralType(leftType)) { return anyType; } - if (leftType.symbol === globalThisSymbol) { - if (globalThisSymbol.exports!.has(right.escapedText) && (globalThisSymbol.exports!.get(right.escapedText)!.flags & SymbolFlags.BlockScoped)) { + if (leftType.symbol === denoGlobalThisSymbol) { + if (denoGlobalThisSymbol.exports!.has(right.escapedText) && (denoGlobalThisSymbol.exports!.get(right.escapedText)!.flags & SymbolFlags.BlockScoped)) { error(right, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(right.escapedText), typeToString(leftType)); } else if (noImplicitAny) { @@ -34963,6 +35025,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } return anyType; } + // deno: ensure condition matches above + if (leftType.symbol === nodeGlobalThisSymbol) { + // deno: don't bother with errors like above for simplicity + return anyType; + } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType, isUncheckedJS); } @@ -35278,7 +35345,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. if (symbol) return symbol; let candidates = arrayFrom(symbols.values()); - if (symbols === globals) { + if (symbols === denoGlobals || symbols == nodeGlobals) { const primitives = mapDefined( ["string", "number", "boolean", "object", "bigint", "symbol"], s => symbols.has((s.charAt(0).toUpperCase() + s.slice(1)) as __String) @@ -48830,7 +48897,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) const symbol = resolveName(exportedName, exportedName.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === denoGlobalThisSymbol || symbol === nodeGlobalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName)); } else { @@ -48982,8 +49049,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if ( moduleKind >= ModuleKind.ES2015 && moduleKind !== ModuleKind.Preserve && - ((node.flags & NodeFlags.Ambient && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) === ModuleKind.ESNext) || - (!(node.flags & NodeFlags.Ambient) && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) !== ModuleKind.CommonJS)) + // deno: temporarily disable this one until Deno 2.0 (https://github.com/microsoft/TypeScript/pull/52109) + ( + /* (node.flags & NodeFlags.Ambient && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) === ModuleKind.ESNext) || */ + !(node.flags & NodeFlags.Ambient) && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) !== ModuleKind.CommonJS + ) ) { // export assignment is not supported in es6 modules grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); @@ -49829,7 +49899,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { location = location.parent; } - copySymbols(globals, meaning); + if (denoContext.hasNodeSourceFile(location)) { + copySymbols(nodeGlobals, meaning); + } + + copySymbols(denoGlobals, meaning); } /** @@ -51219,7 +51293,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function hasGlobalName(name: string): boolean { - return globals.has(escapeLeadingUnderscores(name)); + // deno: seems ok not to bother with nodeGlobals here since + // this is just a public api function that we don't bother with + // NOTICE: Make sure to check that's still the case when upgrading!! + return denoGlobals.has(escapeLeadingUnderscores(name)); } function getReferencedValueSymbol(reference: Identifier, startInDeclarationContainer?: boolean): Symbol | undefined { @@ -51574,10 +51651,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis")); } } - mergeSymbolTable(globals, file.locals!); + denoContext.mergeGlobalSymbolTable(file, file.locals!); } if (file.jsGlobalAugmentations) { - mergeSymbolTable(globals, file.jsGlobalAugmentations); + denoContext.mergeGlobalSymbolTable(file, file.jsGlobalAugmentations); } if (file.patternAmbientModules && file.patternAmbientModules.length) { patternAmbientModules = concatenate(patternAmbientModules, file.patternAmbientModules); @@ -51588,9 +51665,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (file.symbol && file.symbol.globalExports) { // Merge in UMD exports with first-in-wins semantics (see #9771) const source = file.symbol.globalExports; + const isNodeFile = denoContext.hasNodeSourceFile(file); source.forEach((sourceSymbol, id) => { - if (!globals.has(id)) { - globals.set(id, sourceSymbol); + const envGlobals = isNodeFile ? denoContext.getGlobalsForName(id) : denoGlobals; + if (!envGlobals.has(id)) { + envGlobals.set(id, sourceSymbol); } }); } @@ -51618,7 +51697,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { getSymbolLinks(undefinedSymbol).type = undefinedWideningType; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments" as __String, /*arity*/ 0, /*reportErrors*/ true); getSymbolLinks(unknownSymbol).type = errorType; - getSymbolLinks(globalThisSymbol).type = createObjectType(ObjectFlags.Anonymous, globalThisSymbol); + getSymbolLinks(denoGlobalThisSymbol).type = createObjectType(ObjectFlags.Anonymous, denoGlobalThisSymbol); + getSymbolLinks(nodeGlobalThisSymbol).type = createObjectType(ObjectFlags.Anonymous, nodeGlobalThisSymbol); // Initialize special types globalArrayType = getGlobalType("Array" as __String, /*arity*/ 1, /*reportErrors*/ true); @@ -53576,17 +53656,31 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return false; } - function getAmbientModules(): Symbol[] { - if (!ambientModulesCache) { - ambientModulesCache = []; - globals.forEach((global, sym) => { + function getAmbientModules(sourceFile?: SourceFile): Symbol[] { + const isNode = denoContext.hasNodeSourceFile(sourceFile); + if (isNode) { + if (!nodeAmbientModulesCache) { + nodeAmbientModulesCache = getAmbientModulesFromGlobals(denoContext.combinedGlobals); + } + return nodeAmbientModulesCache; + } + else { + if (!ambientModulesCache) { + ambientModulesCache = getAmbientModulesFromGlobals(denoGlobals); + } + return ambientModulesCache; + } + + function getAmbientModulesFromGlobals(envGlobals: SymbolTable) { + const result: Symbol[] = []; + envGlobals.forEach((global, sym) => { // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module. if (ambientModuleSymbolRegex.test(sym as string)) { - ambientModulesCache!.push(global); + result.push(global); } }); + return result; } - return ambientModulesCache; } function checkGrammarImportClause(node: ImportClause): boolean { diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index c17cc4ef9ca01..55ec03fa6e72b 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -169,6 +169,7 @@ const libEntries: [string, string][] = [ ["dom", "lib.dom.d.ts"], ["dom.iterable", "lib.dom.iterable.d.ts"], ["dom.asynciterable", "lib.dom.asynciterable.d.ts"], + ["dom.extras", "lib.dom.extras.d.ts"], ["webworker", "lib.webworker.d.ts"], ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], ["webworker.iterable", "lib.webworker.iterable.d.ts"], diff --git a/src/compiler/deno.ts b/src/compiler/deno.ts new file mode 100644 index 0000000000000..b4d2e7b6603cf --- /dev/null +++ b/src/compiler/deno.ts @@ -0,0 +1,277 @@ +import * as ts from "./_namespaces/ts"; + +export type IsNodeSourceFileCallback = (sourceFile: ts.SourceFile) => boolean; + +let isNodeSourceFile: IsNodeSourceFileCallback = () => false; +let nodeBuiltInModuleNames = new Set(); +let nodeOnlyGlobalNames = new Set(); +let typesNodeIgnorableNames = new Set(); + +export type EnterSpan = (name: string) => object; +export type ExitSpan = (span: object) => void; + +export let enterSpan: EnterSpan = () => ({}); +export let exitSpan: ExitSpan = () => {}; + +export function setEnterSpan(f: EnterSpan): void { + enterSpan = f; +} +export function setExitSpan(f: ExitSpan): void { + exitSpan = f; +} + +export function spanned(name: string, f: () => T): T { + const span = enterSpan(name); + let needsExit = true; + try { + const result = f(); + if (result instanceof Promise) { + needsExit = false; + return result.finally(() => exitSpan(span)) as T; + } + else { + return result; + } + } + finally { + if (needsExit) { + exitSpan(span); + } + } +} + +export function setIsNodeSourceFileCallback(callback: IsNodeSourceFileCallback): void { + isNodeSourceFile = callback; +} + +export function setNodeBuiltInModuleNames(names: readonly string[]): void { + nodeBuiltInModuleNames = new Set(names); +} + +export function setNodeOnlyGlobalNames(names: readonly string[]): void { + nodeBuiltInModuleNames = new Set(names); + nodeOnlyGlobalNames = new Set(names) as Set; +} + +export function setTypesNodeIgnorableNames(names: Set): void { + typesNodeIgnorableNames = names as Set; +} + +// When upgrading: +// Inspect all usages of "globals" and "globalThisSymbol" in checker.ts +// - Beware that `globalThisType` might refer to the global `this` type +// and not the global `globalThis` type + +export interface DenoForkContext { + hasNodeSourceFile: (node: ts.Node | undefined) => boolean; + getGlobalsForName: (id: ts.__String) => ts.SymbolTable; + mergeGlobalSymbolTable: (node: ts.Node, source: ts.SymbolTable, unidirectional?: boolean) => void; + combinedGlobals: ts.SymbolTable; +} + +export function createDenoForkContext({ + mergeSymbol, + globals, + nodeGlobals, + ambientModuleSymbolRegex, +}: { + mergeSymbol(target: ts.Symbol, source: ts.Symbol, unidirectional?: boolean): ts.Symbol; + globals: ts.SymbolTable; + nodeGlobals: ts.SymbolTable; + ambientModuleSymbolRegex: RegExp; +}): DenoForkContext { + return { + hasNodeSourceFile, + getGlobalsForName, + mergeGlobalSymbolTable, + combinedGlobals: createNodeGlobalsSymbolTable(), + }; + + function hasNodeSourceFile(node: ts.Node | undefined) { + if (!node) return false; + const sourceFile = ts.getSourceFileOfNode(node); + return isNodeSourceFile(sourceFile); + } + + function getGlobalsForName(id: ts.__String) { + // Node ambient modules are only accessible in the node code, + // so put them on the node globals + if (ambientModuleSymbolRegex.test(id as string)) { + if ((id as string).startsWith('"node:')) { + // check if it's a node specifier that we support + const name = (id as string).slice(6, -1); + if (nodeBuiltInModuleNames.has(name)) { + return globals; + } + } + return nodeGlobals; + } + return nodeOnlyGlobalNames.has(id) ? nodeGlobals : globals; + } + + function mergeGlobalSymbolTable(node: ts.Node, source: ts.SymbolTable, unidirectional = false) { + const sourceFile = ts.getSourceFileOfNode(node); + const isNodeFile = hasNodeSourceFile(sourceFile); + const isTypesNodeSourceFile = isNodeFile && isTypesNodePkgPath(sourceFile.path); + source.forEach((sourceSymbol, id) => { + const target = isNodeFile ? getGlobalsForName(id) : globals; + const targetSymbol = target.get(id); + if ( + isTypesNodeSourceFile + && targetSymbol !== undefined + && typesNodeIgnorableNames.has(id) + // if the symbol has a @types/node package then that means the global + // was created within the @types/node package and not the lib.d.ts files, + // so allow merging to it (useful when someone has DOM and deno types disabled) + && !symbolHasAnyTypesNodePkgDecl(targetSymbol) + ) { + return; + } + target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol); + }); + } + + function symbolHasAnyTypesNodePkgDecl(symbol: ts.Symbol) { + if (symbol.declarations) { + for (const decl of symbol.declarations) { + const sourceFile = ts.getSourceFileOfNode(decl); + const isNodeFile = hasNodeSourceFile(sourceFile); + if (isNodeFile && isTypesNodePkgPath(sourceFile.path)) { + return true; + } + } + } + return false; + } + + function isTypesNodePkgPath(path: ts.Path) { + return path.endsWith(".d.ts") && path.includes("/@types/node/"); + } + + function createNodeGlobalsSymbolTable() { + return new Proxy(globals, { + get(target, prop: string | symbol, receiver) { + if (prop === "get") { + return (key: ts.__String) => { + return nodeGlobals.get(key) ?? globals.get(key); + }; + } + else if (prop === "has") { + return (key: ts.__String) => { + return nodeGlobals.has(key) || globals.has(key); + }; + } + else if (prop === "size") { + let i = 0; + for (const _ignore of getEntries(entry => entry)) { + i++; + } + return i; + } + else if (prop === "forEach") { + return (action: (value: ts.Symbol, key: ts.__String) => void) => { + for (const [key, value] of getEntries(entry => entry)) { + action(value, key); + } + }; + } + else if (prop === "entries") { + return () => { + return getEntries(kv => kv); + }; + } + else if (prop === "keys") { + return () => { + return getEntries(kv => kv[0]); + }; + } + else if (prop === "values") { + return () => { + return getEntries(kv => kv[1]); + }; + } + else if (prop === Symbol.iterator) { + return () => { + // Need to convert this to an array since typescript targets ES5 + // and providing back the iterator won't work here. I don't want + // to change the target to ES6 because I'm not sure if that would + // surface any issues. + return Array.from(getEntries(kv => kv))[Symbol.iterator](); + }; + } + else { + const value = (target as any)[prop]; + if (value instanceof Function) { + return function (this: any, ...args: any[]) { + return value.apply(this === receiver ? target : this, args); + }; + } + return value; + } + }, + }); + + function* getEntries( + transform: (value: [ts.__String, ts.Symbol]) => R, + ) { + const foundKeys = new Set(); + // prefer the node globals over the deno globalThis + for (const entries of [nodeGlobals.entries(), globals.entries()]) { + for (const entry of entries) { + if (!foundKeys.has(entry[0])) { + yield transform(entry); + foundKeys.add(entry[0]); + } + } + } + } + } +} + +export function isTypesNodePkgPath(path: ts.Path): boolean { + return path.endsWith(".d.ts") && path.includes("/@types/node/"); +} + +export interface NpmPackageReference { + name: string; + versionReq: string | undefined; + subPath: string | undefined; +} + +export function tryParseNpmPackageReference(text: string): NpmPackageReference | undefined { + try { + return parseNpmPackageReference(text); + } + catch { + return undefined; + } +} + +export function parseNpmPackageReference(text: string): NpmPackageReference { + if (!text.startsWith("npm:")) { + throw new Error(`Not an npm specifier: ${text}`); + } + text = text.replace(/^npm:\/?/, ""); // todo: remove this regex + const parts = text.split("/"); + const namePartLen = text.startsWith("@") ? 2 : 1; + if (parts.length < namePartLen) { + throw new Error(`Not a valid package: ${text}`); + } + const nameParts = parts.slice(0, namePartLen); + const lastNamePart = nameParts[nameParts.length - 1]!; + const lastAtIndex = lastNamePart.lastIndexOf("@"); + let versionReq: string | undefined; + if (lastAtIndex > 0) { + versionReq = lastNamePart.substring(lastAtIndex + 1); + nameParts[nameParts.length - 1] = lastNamePart.substring(0, lastAtIndex); + } + const name = nameParts.join("/"); + if (name.length === 0) { + throw new Error(`Npm specifier did not have a name: ${text}`); + } + return { + name: name, + versionReq: versionReq, + subPath: parts.length > nameParts.length ? parts.slice(nameParts.length).join("/") : undefined, + }; +} diff --git a/src/compiler/path.ts b/src/compiler/path.ts index a06359d51e549..82356f9473283 100644 --- a/src/compiler/path.ts +++ b/src/compiler/path.ts @@ -216,6 +216,11 @@ function getEncodedRootLength(path: string): number { return ~path.length; // URL: "file://server", "http://server" } + // deno: temporary hack until https://github.com/microsoft/TypeScript/issues/53605 is fixed + if (path.startsWith("data:")) { + return ~path.length; + } + // relative return 0; } @@ -806,6 +811,11 @@ export function ensureTrailingDirectorySeparator(path: string): string; /** @internal */ export function ensureTrailingDirectorySeparator(path: string) { if (!hasTrailingDirectorySeparator(path)) { + // deno: added this so that data urls don't get a trailing slash + // https://github.com/microsoft/TypeScript/issues/53605#issuecomment-1492167313 + if (path.startsWith("data:")) { + return path; + } return path + directorySeparator; } diff --git a/src/compiler/program.ts b/src/compiler/program.ts index b44a155f0146c..5a49e4c850d15 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -51,6 +51,7 @@ import { createTypeReferenceDirectiveResolutionCache, CustomTransformers, Debug, + deno, DeclarationWithTypeParameterChildren, Diagnostic, DiagnosticArguments, @@ -569,15 +570,16 @@ export function changeCompilerHostLikeToUseCache( return sourceFile; } : undefined; + // deno: disable this cache because we always return false here // fileExists for any kind of extension - host.fileExists = fileName => { - const key = toPath(fileName); - const value = fileExistsCache.get(key); - if (value !== undefined) return value; - const newValue = originalFileExists.call(host, fileName); - fileExistsCache.set(key, !!newValue); - return newValue; - }; + // host.fileExists = fileName => { + // const key = toPath(fileName); + // const value = fileExistsCache.get(key); + // if (value !== undefined) return value; + // const newValue = originalFileExists.call(host, fileName); + // fileExistsCache.set(key, !!newValue); + // return newValue; + // }; if (originalWriteFile) { host.writeFile = (fileName, data, ...rest) => { const key = toPath(fileName); @@ -1708,6 +1710,8 @@ export function createProgram(_rootNamesOrOptions: readonly string[] | CreatePro */ const filesByName = new Map(); const libFiles = new Set(); + let shouldLoadNodeTypes = false; + let foundNodeTypes = false; let missingFileNames = new Map(); // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing @@ -1823,6 +1827,23 @@ export function createProgram(_rootNamesOrOptions: readonly string[] | CreatePro } } + // deno: load built-in node types if no @types/node package was found + const hasTypesNodePackage = (): boolean => { + for (const path of filesByName.keys()) { + if (deno.isTypesNodePkgPath(path as Path)) { + return true; + } + } + return false; + }; + if (foundNodeTypes && !hasTypesNodePackage()) { + shouldLoadNodeTypes = true; + processRootFile( + "asset:///lib.node.d.ts", + /*isDefaultLib*/ true, + { kind: FileIncludeKind.LibFile, index: options.lib?.length ?? 0 }, + ); + } files = toSorted(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); processingDefaultLibFiles = undefined; processingOtherFiles = undefined; @@ -3484,6 +3505,11 @@ export function createProgram(_rootNamesOrOptions: readonly string[] | CreatePro /** This has side effects through `findSourceFile`. */ function processSourceFile(fileName: string, isDefaultLib: boolean, packageId: PackageId | undefined, reason: FileIncludeReason): void { + // deno: skip loading built-in node types when @types/node is present + if (fileName === "asset:///lib.node.d.ts" && !shouldLoadNodeTypes) { + foundNodeTypes = true; + return; + } getSourceFileFromReferenceWorker( fileName, fileName => findSourceFile(fileName, isDefaultLib, reason, packageId), // TODO: GH#18217 diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 4d8d22afb54e6..7fc039d6ebb0b 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -5274,7 +5274,7 @@ export interface TypeChecker { /** @internal */ forEachExportAndPropertyOfModule(moduleSymbol: Symbol, cb: (symbol: Symbol, key: __String) => void): void; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; - getAmbientModules(): Symbol[]; + getAmbientModules(sourceFile?: SourceFile): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; /** diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 38425f9ab052e..aa3c1a1025448 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -92,6 +92,7 @@ import { DeclarationWithTypeParameters, Decorator, DefaultClause, + deno, DestructuringAssignment, Diagnostic, DiagnosticArguments, @@ -9417,6 +9418,11 @@ export function getJSXImplicitImportBase(compilerOptions: CompilerOptions, file? if (jsxRuntimePragma?.arguments.factory === "classic") { return undefined; } + // deno: resolve jsx import source per-file for workspace members + { + const resolvedJsxImportSource = file && (compilerOptions as any).resolveJsxImportSource?.(file.fileName); + if (resolvedJsxImportSource) return resolvedJsxImportSource; + } return compilerOptions.jsx === JsxEmit.ReactJSX || compilerOptions.jsx === JsxEmit.ReactJSXDev || compilerOptions.jsxImportSource || @@ -11466,7 +11472,9 @@ export interface NameResolverOptions { compilerOptions: CompilerOptions; getSymbolOfDeclaration: (node: Declaration) => Symbol; error: (location: Node | undefined, message: DiagnosticMessage, ...args: DiagnosticArguments) => void; - globals: SymbolTable; + denoGlobals: SymbolTable; + nodeGlobals: SymbolTable; + denoContext: deno.DenoForkContext; argumentsSymbol: Symbol; requireSymbol: Symbol; lookup: (symbols: SymbolTable, name: __String, meaning: SymbolFlags) => Symbol | undefined; @@ -11494,7 +11502,9 @@ export function createNameResolver({ argumentsSymbol, error, getSymbolOfDeclaration, - globals, + denoGlobals, + nodeGlobals, + denoContext, lookup, setRequiresScopeChangeCache = returnUndefined, getRequiresScopeChangeCache = returnUndefined, @@ -11877,7 +11887,12 @@ export function createNameResolver({ } if (!excludeGlobals) { - result = lookup(globals, name, meaning); + if (denoContext.hasNodeSourceFile(lastLocation)) { + result = lookup(nodeGlobals, name, meaning); + } + if (!result) { + result = lookup(denoGlobals, name, meaning); + } } } if (!result) { diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index d667879250cf4..71a11bb579435 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -30269,6 +30269,7 @@ declare var ReadableStream: { new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number }): ReadableStream>; new(underlyingSource: UnderlyingDefaultSource, strategy?: QueuingStrategy): ReadableStream; new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + from(asyncIterable: AsyncIterable | Iterable>): ReadableStream; }; /** diff --git a/src/lib/es2020.intl.d.ts b/src/lib/es2020.intl.d.ts index 5ab347994647e..5543b39ccc752 100644 --- a/src/lib/es2020.intl.d.ts +++ b/src/lib/es2020.intl.d.ts @@ -269,7 +269,7 @@ declare namespace Intl { } interface DateTimeFormatOptions { - calendar?: string | undefined; + calendar?: string | (typeof globalThis extends { Temporal: { CalendarProtocol: infer T; }; } ? T : undefined) | undefined; dayPeriod?: "narrow" | "short" | "long" | undefined; numberingSystem?: string | undefined; diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index 43ff5837a9500..d80a06c29d8a7 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -4506,7 +4506,7 @@ declare namespace Intl { timeZoneName?: "short" | "long" | "shortOffset" | "longOffset" | "shortGeneric" | "longGeneric" | undefined; formatMatcher?: "best fit" | "basic" | undefined; hour12?: boolean | undefined; - timeZone?: string | undefined; + timeZone?: string | (typeof globalThis extends { Temporal: { TimeZoneProtocol: infer T; }; } ? T : undefined) | undefined; } interface ResolvedDateTimeFormatOptions { diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index e1de8865ba1f7..b0e51b11daf52 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -9195,6 +9195,7 @@ declare var ReadableStream: { new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number }): ReadableStream>; new(underlyingSource: UnderlyingDefaultSource, strategy?: QueuingStrategy): ReadableStream; new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + from(asyncIterable: AsyncIterable | Iterable>): ReadableStream; }; /** diff --git a/src/services/completions.ts b/src/services/completions.ts index 28d29136dab89..02a71132d523f 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -5846,7 +5846,8 @@ function isProbablyGlobalType(type: Type, sourceFile: SourceFile, checker: TypeC if (globalSymbol && checker.getTypeOfSymbolAtLocation(globalSymbol, sourceFile) === type) { return true; } - const globalThisSymbol = checker.resolveName("globalThis", /*location*/ undefined, SymbolFlags.Value, /*excludeGlobals*/ false); + // deno: provide sourceFile so that it can figure out if it's a node or deno globalThis + const globalThisSymbol = checker.resolveName("globalThis", /*location*/ sourceFile, SymbolFlags.Value, /*excludeGlobals*/ false); if (globalThisSymbol && checker.getTypeOfSymbolAtLocation(globalThisSymbol, sourceFile) === type) { return true; } diff --git a/src/services/exportInfoMap.ts b/src/services/exportInfoMap.ts index dfd00ce2e9170..02ab14736ebd2 100644 --- a/src/services/exportInfoMap.ts +++ b/src/services/exportInfoMap.ts @@ -68,7 +68,6 @@ export const enum ImportKind { CommonJS, } -/** @internal */ export const enum ExportKind { Named, Default, @@ -77,7 +76,6 @@ export const enum ExportKind { Module, } -/** @internal */ export interface SymbolExportInfo { readonly symbol: Symbol; readonly moduleSymbol: Symbol; @@ -114,7 +112,6 @@ interface CachedSymbolExportInfo { isFromPackageJson: boolean; } -/** @internal */ export interface ExportInfoMap { isUsableByFile(importingFile: Path): boolean; clear(): void;