Skip to content

Commit

Permalink
[dev-tool] Allow relative-path imports in sample files. (Azure#14665)
Browse files Browse the repository at this point in the history
  • Loading branch information
witemple-msft authored and vindicatesociety committed Apr 26, 2021
1 parent 763bd9b commit b3fbed3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
28 changes: 25 additions & 3 deletions common/tools/dev-tool/src/commands/samples/publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,28 @@ function createPackageJson(info: SampleGenerationInfo, outputKind: OutputKind):
};
}

/**
* Determines whether a module specifier is a package dependency.
*
* A dependency is a module specifier that does not refer to a node builtin and
* is not a relative path.
*
* Absolute path imports are not supported in samples (because the package base
* is not fixed relative to the source file).
*
* @param moduleSpecifier - the string given to `import` or `require`
* @returns - true if `moduleSpecifier` should be considered a reference to a
* node module dependency
*/
function isDependency(moduleSpecifier: string): boolean {
if (nodeBuiltins.includes(moduleSpecifier)) return false;

// This seems like a reasonable test for "is a relative path" as long as
// absolute path imports are forbidden.
const isRelativePath = /^\.\.?\//.test(moduleSpecifier);
return !isRelativePath;
}

async function processSources(
projectInfo: ProjectInfo,
sources: string[],
Expand Down Expand Up @@ -217,7 +239,7 @@ async function processSources(
}
}),
summary: summary ?? fail(`${relativeSourcePath} does not include an @summary tag.`),
importedModules: importedModules.filter((name) => !nodeBuiltins.includes(name)),
importedModules: importedModules.filter(isDependency),
usedEnvironmentVariables,
azSdkTags
};
Expand Down Expand Up @@ -328,10 +350,10 @@ async function makeSampleGenerationInfo(
packageJson.dependencies[dependency];
if (dependencyVersion === undefined) {
log.error(
`Dependency "${dependency}", imported by ${source.filePath}, has an unknown version.`
`Dependency "${dependency}", imported by ${source.filePath}, has an unknown version. (Are you missing "./" for a relative path?)`
);
log.error(
"Specify a version for it by including it in the package's `devDependencies`."
`Specify a version for "${dependency}" by including it in the package's "devDependencies".`
);
}

Expand Down
2 changes: 2 additions & 0 deletions common/tools/dev-tool/src/util/sampleGenerationInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ export const DEFAULT_TYPESCRIPT_CONFIG = {
compilerOptions: {
target: "ES2018",
module: "commonjs",

moduleResolution: "node",
resolveJsonModule: true,

esModuleInterop: true,
allowSyntheticDefaultImports: true,
Expand Down

0 comments on commit b3fbed3

Please sign in to comment.