Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move NodePackage type out of module resolver and add more properties #4595

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
# Change versionKind to one of: internal, fix, dependencies, feature, deprecation, breaking
changeKind: feature
packages:
- "@typespec/compiler"
---

Expose more accurate `PackageJson` type and deprecate `NodePackage`
4 changes: 2 additions & 2 deletions packages/compiler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@
"default": "./dist/src/testing/index.js"
},
"./module-resolver": {
"types": "./dist/src/core/module-resolver.d.ts",
"default": "./dist/src/core/module-resolver.js"
"types": "./dist/module-resolver/module-resolver.d.ts",
"default": "./dist/src/module-resolver/module-resolver.js"
},
"./emitter-framework": {
"types": "./dist/src/emitter-framework/index.d.ts",
Expand Down
2 changes: 1 addition & 1 deletion packages/compiler/src/core/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from "../manifest.js";
export * from "../module-resolver/module-resolver.js";
export * from "./checker.js";
export * from "./decorator-utils.js";
export * from "./deprecation.js";
Expand Down Expand Up @@ -39,7 +40,6 @@ export {
setTypeSpecNamespace,
} from "./library.js";
export { resolveLinterDefinition } from "./linter.js";
export * from "./module-resolver.js";
export { NodeHost } from "./node-host.js";
export { Numeric, isNumeric } from "./numeric.js";
export * from "./options.js";
Expand Down
37 changes: 19 additions & 18 deletions packages/compiler/src/core/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ import { createAssetEmitter } from "../emitter-framework/asset-emitter.js";
import { setCurrentProgram } from "../experimental/typekit/define-kit.js";
import { validateEncodedNamesConflicts } from "../lib/encoded-names.js";
import { MANIFEST } from "../manifest.js";
import {
ModuleResolutionResult,
ResolveModuleHost,
ResolvedModule,
resolveModule,
} from "../module-resolver/module-resolver.js";
import { PackageJson } from "../types/package-json.js";
import { deepEquals, findProjectRoot, isDefined, mapEquals, mutate } from "../utils/misc.js";
import { createBinder } from "./binder.js";
import { Checker, createChecker } from "./checker.js";
Expand All @@ -15,13 +22,6 @@ import { createLinter, resolveLinterDefinition } from "./linter.js";
import { createLogger } from "./logger/index.js";
import { createTracer } from "./logger/tracer.js";
import { createDiagnostic } from "./messages.js";
import {
ModuleResolutionResult,
NodePackage,
ResolveModuleHost,
ResolvedModule,
resolveModule,
} from "./module-resolver.js";
import { CompilerOptions } from "./options.js";
import { parse, parseStandaloneTypeReference } from "./parser.js";
import { getDirectoryPath, joinPaths, resolvePath } from "./path-utils.js";
Expand Down Expand Up @@ -125,7 +125,7 @@ interface Validator {

interface TypeSpecLibraryReference {
path: string;
manifest: NodePackage;
manifest: PackageJson;
}

export async function compile(
Expand Down Expand Up @@ -269,17 +269,18 @@ export async function compile(
for (const root of loadedRoots) {
const packageJsonPath = joinPaths(root, "package.json");
try {
const packageJson: NodePackage = JSON.parse((await host.readFile(packageJsonPath)).text);
const found = libraries.get(packageJson.name);
if (found && found.path !== root && found.manifest.version !== packageJson.version) {
let incompatibleIndex: TypeSpecLibraryReference[] | undefined = incompatibleLibraries.get(
packageJson.name,
);
if (incompatibleIndex === undefined) {
incompatibleIndex = [found];
incompatibleLibraries.set(packageJson.name, incompatibleIndex);
const packageJson: PackageJson = JSON.parse((await host.readFile(packageJsonPath)).text);
if (packageJson.name) {
const found = libraries.get(packageJson.name);
if (found && found.path !== root && found.manifest.version !== packageJson.version) {
let incompatibleIndex: TypeSpecLibraryReference[] | undefined =
incompatibleLibraries.get(packageJson.name);
if (incompatibleIndex === undefined) {
incompatibleIndex = [found];
incompatibleLibraries.set(packageJson.name, incompatibleIndex);
}
incompatibleIndex.push({ path: root, manifest: packageJson });
}
incompatibleIndex.push({ path: root, manifest: packageJson });
}
} catch {}
}
Expand Down
14 changes: 7 additions & 7 deletions packages/compiler/src/core/source-loader.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { deepEquals, doIO, resolveTspMain } from "../utils/misc.js";
import { compilerAssert, createDiagnosticCollector } from "./diagnostics.js";
import { resolveTypeSpecEntrypointForDir } from "./entrypoint-resolution.js";
import { createDiagnostic } from "./messages.js";
import {
ModuleResolutionResult,
NodePackage,
ResolvedModule,
resolveModule,
ResolveModuleHost,
} from "./module-resolver.js";
} from "../module-resolver/module-resolver.js";
import { PackageJson } from "../types/package-json.js";
import { deepEquals, doIO, resolveTspMain } from "../utils/misc.js";
import { compilerAssert, createDiagnosticCollector } from "./diagnostics.js";
import { resolveTypeSpecEntrypointForDir } from "./entrypoint-resolution.js";
import { createDiagnostic } from "./messages.js";
import { isImportStatement, parse } from "./parser.js";
import { getDirectoryPath } from "./path-utils.js";
import { createSourceFile } from "./source-file.js";
Expand Down Expand Up @@ -43,7 +43,7 @@ export interface SourceResolution {

interface TypeSpecLibraryReference {
path: string;
manifest: NodePackage;
manifest: PackageJson;
}

export interface LoadSourceOptions {
Expand Down
2 changes: 1 addition & 1 deletion packages/compiler/src/core/types.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { JSONSchemaType as AjvJSONSchemaType } from "ajv";
import type { TypeEmitter } from "../emitter-framework/type-emitter.js";
import type { AssetEmitter } from "../emitter-framework/types.js";
import type { ModuleResolutionResult } from "../module-resolver/module-resolver.js";
import type { YamlPathTarget, YamlScript } from "../yaml/types.js";
import type { ModuleResolutionResult } from "./module-resolver.js";
import type { Numeric } from "./numeric.js";
import type { Program } from "./program.js";
import type { TokenFlags } from "./scanner.js";
Expand Down
3 changes: 3 additions & 0 deletions packages/compiler/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,6 @@ export const CadlPrettierPlugin = TypeSpecPrettierPlugin;

/** @internal for Typespec compiler */
export { $decorators } from "./lib/tsp-index.js";
export { PackageJson } from "./types/package-json.js";
/** @deprecated use `PackageJson` */
export { PackageJson as NodePackage } from "./types/package-json.js";
4 changes: 2 additions & 2 deletions packages/compiler/src/init/scaffold.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { stringify } from "yaml";
import { TypeSpecConfigFilename } from "../config/config-loader.js";
import { formatTypeSpec } from "../core/formatter.js";
import { NodePackage } from "../core/module-resolver.js";
import { getDirectoryPath, joinPaths } from "../core/path-utils.js";
import { CompilerHost } from "../core/types.js";
import { PackageJson } from "../types/package-json.js";
import { readUrlOrPath, resolveRelativeUrlOrPath } from "../utils/misc.js";
import { FileTemplatingContext, createFileTemplatingContext, render } from "./file-templating.js";
import {
Expand Down Expand Up @@ -117,7 +117,7 @@ async function writePackageJson(host: CompilerHost, config: ScaffoldingConfig) {
devDependencies[library.name] = await getLibraryVersion(library);
}

const packageJson: NodePackage = {
const packageJson: PackageJson = {
name: config.name,
version: "0.1.0",
type: "module",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getDirectoryPath, joinPaths, resolvePath } from "./path-utils.js";

import { getDirectoryPath, joinPaths, resolvePath } from "../core/path-utils.js";
import { PackageJson } from "../types/package-json.js";
export interface ResolveModuleOptions {
baseDir: string;

Expand Down Expand Up @@ -33,27 +33,6 @@ export interface ResolveModuleHost {
readFile(path: string): Promise<string>;
}

/**
* Type for package.json https://docs.npmjs.com/cli/v8/configuring-npm/package-json
*/
export interface NodePackage {
name: string;
description?: string;
type?: "module" | "commonjs";
main?: string;
version: string;
tspMain?: string;
homepage?: string;
bugs?: {
url?: string;
email?: string;
};
private?: boolean;
dependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
}

type ResolveModuleErrorCode = "MODULE_NOT_FOUND" | "INVALID_MAIN";
export class ResolveModuleError extends Error {
public constructor(
Expand Down Expand Up @@ -89,7 +68,7 @@ export interface ResolvedModule {
/**
* Value of package.json.
*/
manifest: NodePackage;
manifest: PackageJson;
}

/**
Expand Down Expand Up @@ -210,7 +189,7 @@ export async function resolveModule(

async function loadPackage(
directory: string,
pkg: NodePackage,
pkg: PackageJson,
): Promise<ResolvedModule | undefined> {
const mainFile = options.resolveMain ? options.resolveMain(pkg) : pkg.main;
if (typeof mainFile !== "string") {
Expand Down Expand Up @@ -265,7 +244,7 @@ export async function resolveModule(
}
}

async function readPackage(host: ResolveModuleHost, pkgfile: string): Promise<NodePackage> {
async function readPackage(host: ResolveModuleHost, pkgfile: string): Promise<PackageJson> {
const content = await host.readFile(pkgfile);
return JSON.parse(content);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/compiler/src/runner.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { access, readFile, realpath, stat } from "fs/promises";
import { join, resolve } from "path";
import { fileURLToPath, pathToFileURL } from "url";
import { ResolveModuleHost, resolveModule } from "./core/module-resolver.js";
import { ResolveModuleHost, resolveModule } from "./module-resolver/module-resolver.js";

/**
* Run script given by relative path from @typespec/compiler package root.
Expand Down
4 changes: 2 additions & 2 deletions packages/compiler/src/server/completion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
IdentifierNode,
Node,
NodeFlags,
NodePackage,
PositionDetail,
Program,
StringLiteralNode,
Expand All @@ -32,6 +31,7 @@ import {
hasTrailingDirectorySeparator,
resolvePath,
} from "../core/path-utils.js";
import { PackageJson } from "../types/package-json.js";
import { findProjectRoot, loadFile, resolveTspMain } from "../utils/misc.js";
import { getSymbolDetails } from "./type-details.js";

Expand Down Expand Up @@ -250,7 +250,7 @@ function addKeywordCompletion(area: keyof KeywordArea, completions: CompletionLi
}
}

async function loadPackageJson(host: CompilerHost, path: string): Promise<NodePackage> {
async function loadPackageJson(host: CompilerHost, path: string): Promise<PackageJson> {
const [libPackageJson] = await loadFile(host, path, JSON.parse, () => {});
return libPackageJson;
}
Expand Down
40 changes: 40 additions & 0 deletions packages/compiler/src/types/package-json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Type for package.json https://docs.npmjs.com/cli/configuring-npm/package-json
*/
export interface PackageJson {
/** Package name */
name: string;
/** Package version */
version?: string;
/** Package description */
description?: string;
type?: "module" | "commonjs";
main?: string;
tspMain?: string;
homepage?: string;
bugs?: {
url?: string;
email?: string;
};
/**
* Subpath exports to define entry points of the package.
* [Read more.](https://nodejs.org/api/packages.html#subpath-exports)
*/
exports?: Exports;
private?: boolean;
dependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
}

/**
* Entry points of a module, optionally with conditions and subpath exports.
*/
type Exports = null | string | Array<string | ExportConditions> | ExportConditions;

/**
A mapping of conditions and the paths to which they resolve.
*/
type ExportConditions = {
[condition: string]: Exports;
};
4 changes: 2 additions & 2 deletions packages/compiler/test/checker/imports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
LibraryLocationContext,
LocationContext,
ModuleLibraryMetadata,
NodePackage,
ProjectLocationContext,
} from "../../src/core/index.js";
import {
Expand All @@ -13,6 +12,7 @@ import {
expectDiagnostics,
resolveVirtualPath,
} from "../../src/testing/index.js";
import { PackageJson } from "../../src/types/package-json.js";

describe("compiler: imports", () => {
let host: TestHost;
Expand Down Expand Up @@ -183,7 +183,7 @@ describe("compiler: imports", () => {

interface Structure {
[key: TspFile]: string[];
[key: PkgJson]: Partial<NodePackage>;
[key: PkgJson]: Partial<PackageJson>;
}

interface ScopeExpectation<T extends Structure> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import {
CompilerHost,
Decorator,
Diagnostic,
NodePackage,
Program,
compile,
createDiagnosticCollector,
Expand All @@ -11,6 +10,7 @@ import {
joinPaths,
navigateProgram,
resolvePath,
type PackageJson,
} from "@typespec/compiler";
import prettier from "prettier";
import { generateSignatureTests, generateSignatures } from "./decorators-signatures.js";
Expand Down Expand Up @@ -45,7 +45,7 @@ export async function generateExternSignatures(
return diagnostics.diagnostics;
}

async function readPackageJson(host: CompilerHost, libraryPath: string): Promise<NodePackage> {
async function readPackageJson(host: CompilerHost, libraryPath: string): Promise<PackageJson> {
const file = await host.readFile(joinPaths(libraryPath, "package.json"));
return JSON.parse(file.text);
}
Expand Down
4 changes: 2 additions & 2 deletions packages/tspd/src/ref-doc/experimental.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
Diagnostic,
joinPaths,
NodeHost,
NodePackage,
type PackageJson,
} from "@typespec/compiler";
import { mkdir, readFile, writeFile } from "fs/promises";
import prettier from "prettier";
Expand Down Expand Up @@ -64,7 +64,7 @@ export async function resolveLibraryRefDocsBase(
return undefined;
}

async function readPackageJson(libraryPath: string): Promise<NodePackage> {
async function readPackageJson(libraryPath: string): Promise<PackageJson> {
const buffer = await readFile(joinPaths(libraryPath, "package.json"));
return JSON.parse(buffer.toString());
}
Expand Down
4 changes: 2 additions & 2 deletions packages/tspd/src/ref-doc/extractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import {
navigateProgram,
navigateTypesInNamespace,
NodeHost,
NodePackage,
NoTarget,
Operation,
Program,
Expand All @@ -39,6 +38,7 @@ import {
Type,
TypeSpecLibrary,
Union,
type PackageJson,
} from "@typespec/compiler";
import { readFile } from "fs/promises";
import { pathToFileURL } from "url";
Expand Down Expand Up @@ -122,7 +122,7 @@ export async function extractLibraryRefDocs(
return diagnostics.wrap(refDoc);
}

async function readPackageJson(libraryPath: string): Promise<NodePackage> {
async function readPackageJson(libraryPath: string): Promise<PackageJson> {
const buffer = await readFile(joinPaths(libraryPath, "package.json"));
return JSON.parse(buffer.toString());
}
Expand Down
Loading
Loading