Comparing version 4.15.0 to 5.0.0
@@ -1,3 +0,4 @@ | ||
import { Node } from './Node'; | ||
import { Options } from 'prettier'; | ||
import { Node } from "./Node"; | ||
import dprint from "dprint-node"; | ||
export declare type Options = Exclude<Parameters<typeof dprint.format>[2], undefined>; | ||
/** Options for `toStringWithImports`, i.e. for the top-level, per-file output. */ | ||
@@ -13,4 +14,4 @@ export interface ToStringOpts { | ||
prefix?: string; | ||
/** Optional per-file overrides for the prettier config, i.e. to use longer-than-normal line lengths. */ | ||
prettierOverrides?: Options; | ||
/** dprint config settings. */ | ||
dprintOptions?: Options; | ||
/** optional importMappings */ | ||
@@ -27,8 +28,3 @@ importMappings?: { | ||
constructor(literals: TemplateStringsArray, placeholders: any[]); | ||
/** | ||
* Returns the code with any necessary import statements prefixed. | ||
* | ||
* This method will also use any local `.prettierrc` settings, hence needs | ||
* to return a `Promise<String>`. | ||
*/ | ||
/** Returns the code with any necessary import statements prefixed. */ | ||
toStringWithImports(opts?: ToStringOpts): Promise<string>; | ||
@@ -35,0 +31,0 @@ /** |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
}) : (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
o[k2] = m[k]; | ||
})); | ||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { | ||
Object.defineProperty(o, "default", { enumerable: true, value: v }); | ||
}) : function(o, v) { | ||
o["default"] = v; | ||
}); | ||
var __importStar = (this && this.__importStar) || function (mod) { | ||
if (mod && mod.__esModule) return mod; | ||
var result = {}; | ||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); | ||
__setModuleDefault(result, mod); | ||
return result; | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
@@ -28,7 +9,6 @@ return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
const Import_1 = require("./Import"); | ||
const prettier_1 = __importStar(require("prettier")); | ||
const parser_typescript_1 = __importDefault(require("prettier/parser-typescript")); | ||
const is_plain_object_1 = require("./is-plain-object"); | ||
const ConditionalOutput_1 = require("./ConditionalOutput"); | ||
const index_1 = require("./index"); | ||
const dprint_node_1 = __importDefault(require("dprint-node")); | ||
// We only have a single top-level Code.toStringWithImports running at a time, | ||
@@ -46,11 +26,6 @@ // so use a global var to capture this contextual state. | ||
} | ||
/** | ||
* Returns the code with any necessary import statements prefixed. | ||
* | ||
* This method will also use any local `.prettierrc` settings, hence needs | ||
* to return a `Promise<String>`. | ||
*/ | ||
/** Returns the code with any necessary import statements prefixed. */ | ||
toStringWithImports(opts) { | ||
const { path = '', forceDefaultImport, forceModuleImport, prefix, prettierOverrides = {}, importMappings = {} } = opts || {}; | ||
const ourModulePath = path.replace(/\.[tj]sx?/, ''); | ||
const { path = "", forceDefaultImport, forceModuleImport, prefix, dprintOptions = {}, importMappings = {} } = opts || {}; | ||
const ourModulePath = path.replace(/\.[tj]sx?/, ""); | ||
if (forceDefaultImport || forceModuleImport) { | ||
@@ -65,4 +40,4 @@ this.deepReplaceNamedImports(forceDefaultImport || [], forceModuleImport || []); | ||
const bodyPart = this.generateCode(); | ||
const maybePrefix = prefix ? `${prefix}\n` : ''; | ||
return maybePrettyWithConfig(maybePrefix + importPart + '\n' + bodyPart, prettierOverrides); | ||
const maybePrefix = prefix ? `${prefix}\n` : ""; | ||
return Promise.resolve(maybePretty(maybePrefix + importPart + "\n" + bodyPart, dprintOptions)); | ||
} | ||
@@ -185,3 +160,3 @@ /** | ||
const { literals, placeholders } = this; | ||
let result = ''; | ||
let result = ""; | ||
// interleave the literals with the placeholders | ||
@@ -197,3 +172,3 @@ for (let i = 0; i < placeholders.length; i++) { | ||
if (this.oneline) { | ||
result = result.replace(/\n/g, ''); | ||
result = result.replace(/\n/g, ""); | ||
} | ||
@@ -205,3 +180,3 @@ return result; | ||
function deepGenerate(object) { | ||
let result = ''; | ||
let result = ""; | ||
let todo = [object]; | ||
@@ -222,3 +197,3 @@ while (todo.length > 0) { | ||
else if (current === null) { | ||
result += 'null'; | ||
result += "null"; | ||
} | ||
@@ -234,3 +209,3 @@ else if (current !== undefined) { | ||
else { | ||
result += 'undefined'; | ||
result += "undefined"; | ||
} | ||
@@ -241,14 +216,2 @@ } | ||
exports.deepGenerate = deepGenerate; | ||
// Use an optional call here in case we are using standalone prettier. This can happen when loaded through a CDN from | ||
// a browser (or Deno), because prettier has `"browser": "./standalone.js"` in it's package.json. | ||
const configPromise = prettier_1.resolveConfig === null || prettier_1.resolveConfig === void 0 ? void 0 : prettier_1.resolveConfig('./'); | ||
async function maybePrettyWithConfig(input, options) { | ||
try { | ||
const config = await configPromise; | ||
return prettier_1.default.format(input.trim(), { parser: 'typescript', plugins: [parser_typescript_1.default], ...config, ...options }); | ||
} | ||
catch (e) { | ||
return input; // assume it's invalid syntax and ignore | ||
} | ||
} | ||
/** Finds any namespace collisions of a named import colliding with def and assigns the import an alias it. */ | ||
@@ -287,5 +250,12 @@ function assignAliasesIfNeeded(defs, imports, ourModulePath) { | ||
} | ||
function maybePretty(input) { | ||
// This default options are both "pretty-ish" plus also suite the ts-poet pre-formatted | ||
// output which is all bunched together, so we want to force braces / force new lines. | ||
const baseOptions = { | ||
useTabs: false, | ||
useBraces: "always", | ||
singleBodyPosition: "nextLine", | ||
}; | ||
function maybePretty(input, options) { | ||
try { | ||
return prettier_1.default.format(input.trim(), { parser: 'typescript', plugins: [parser_typescript_1.default] }); | ||
return dprint_node_1.default.format("file.ts", input.trim(), { ...baseOptions, ...options }); | ||
} | ||
@@ -292,0 +262,0 @@ catch (e) { |
@@ -1,3 +0,3 @@ | ||
import { Node } from './Node'; | ||
import { Code } from './Code'; | ||
import { Node } from "./Node"; | ||
import { Code } from "./Code"; | ||
/** | ||
@@ -4,0 +4,0 @@ * Helps output conditional helper methods. |
@@ -1,2 +0,2 @@ | ||
import { Node } from './Node'; | ||
import { Node } from "./Node"; | ||
export declare const importType = "[*@+=]"; | ||
@@ -3,0 +3,0 @@ /** |
@@ -21,15 +21,12 @@ "use strict"; | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.sameModule = exports.maybeRelativePath = exports.emitImports = exports.SideEffect = exports.Augmented = exports.ImportsAll = exports.ImportsDefault = exports.ImportsName = exports.Imported = exports.Implicit = exports.Import = exports.importType = void 0; | ||
const lodash_1 = __importDefault(require("lodash")); | ||
const path = __importStar(require("path")); | ||
const Node_1 = require("./Node"); | ||
const typeImportMarker = '(?:t:)?'; | ||
const fileNamePattern = '(?:[a-zA-Z0-9._-]+)'; | ||
const utils_1 = require("./utils"); | ||
const typeImportMarker = "(?:t:)?"; | ||
const fileNamePattern = "(?:[a-zA-Z0-9._-]+)"; | ||
const modulePattern = `@?(?:(?:${fileNamePattern}(?:/${fileNamePattern})*))`; | ||
const identPattern = `(?:(?:[a-zA-Z][_a-zA-Z0-9.]*)|(?:[_a-zA-Z][_a-zA-Z0-9.]+))`; | ||
exports.importType = '[*@+=]'; | ||
exports.importType = "[*@+=]"; | ||
const importPattern = `^(${typeImportMarker}${identPattern})?(${exports.importType})(${modulePattern})(?:#(${identPattern}))?`; | ||
@@ -86,16 +83,16 @@ const sourceIdentPattern = `(?:(?:${identPattern}:)?)`; | ||
const modulePath = matched[3]; | ||
const kind = matched[2] || '@'; | ||
const symbolName = matched[1] || lodash_1.default.last(modulePath.split('/')) || ''; | ||
const kind = matched[2] || "@"; | ||
const symbolName = matched[1] || utils_1.last(modulePath.split("/")) || ""; | ||
const targetName = matched[4]; | ||
switch (kind) { | ||
case '*': | ||
case "*": | ||
return Import.importsAll(symbolName, modulePath); | ||
case '@': | ||
const isTypeImport = symbolName.startsWith('t:'); | ||
case "@": | ||
const isTypeImport = symbolName.startsWith("t:"); | ||
let exportedNames; | ||
if (isTypeImport) { | ||
exportedNames = symbolName.substring(2).split(':'); | ||
exportedNames = symbolName.substring(2).split(":"); | ||
} | ||
else { | ||
exportedNames = symbolName.split(':'); | ||
exportedNames = symbolName.split(":"); | ||
} | ||
@@ -105,5 +102,5 @@ const exportedName = exportedNames.pop(); | ||
return Import.importsName(exportedName, modulePath, isTypeImport, sourceExportedName); | ||
case '=': | ||
case "=": | ||
return Import.importsDefault(symbolName, modulePath); | ||
case '+': | ||
case "+": | ||
return targetName | ||
@@ -113,3 +110,3 @@ ? Import.augmented(symbolName, modulePath, targetName) | ||
default: | ||
throw new Error('Invalid import kind character'); | ||
throw new Error("Invalid import kind character"); | ||
} | ||
@@ -120,3 +117,3 @@ } | ||
static fromMaybeString(spec) { | ||
return typeof spec === 'string' ? Import.from(spec) : spec; | ||
return typeof spec === "string" ? Import.from(spec) : spec; | ||
} | ||
@@ -298,8 +295,8 @@ toCodeString() { | ||
if (imports.length == 0) { | ||
return ''; | ||
return ""; | ||
} | ||
let result = ''; | ||
const augmentImports = lodash_1.default.groupBy(filterInstances(imports, Augmented), (a) => a.augmented); | ||
let result = ""; | ||
const augmentImports = utils_1.groupBy(filterInstances(imports, Augmented), (a) => a.augmented); | ||
// Group the imports by source module they're imported from | ||
const importsByModule = lodash_1.default.groupBy(imports.filter((it) => it.source !== undefined && | ||
const importsByModule = utils_1.groupBy(imports.filter((it) => it.source !== undefined && | ||
// Ignore imports that are in our own file | ||
@@ -331,5 +328,5 @@ !(it instanceof ImportsName && it.definedIn && sameModule(it.definedIn, ourModulePath))), (it) => it.source); | ||
if (names.length > 0 || def.length > 0) { | ||
const namesPart = names.length > 0 ? [`{ ${names.join(', ')} }`] : []; | ||
const namesPart = names.length > 0 ? [`{ ${names.join(", ")} }`] : []; | ||
const defPart = def.length > 0 ? [def[0]] : []; | ||
result += `import ${[...defPart, ...namesPart].join(', ')} from '${importPath}';\n`; | ||
result += `import ${[...defPart, ...namesPart].join(", ")} from '${importPath}';\n`; | ||
[...names, ...def].forEach((name) => { | ||
@@ -348,6 +345,6 @@ const augments = augmentImports[name]; | ||
if (typeImports.length > 0) { | ||
result += `import type { ${typeImports.join(', ')} } from '${importPath}';\n`; | ||
result += `import type { ${typeImports.join(", ")} } from '${importPath}';\n`; | ||
} | ||
}); | ||
const sideEffectImports = lodash_1.default.groupBy(filterInstances(imports, SideEffect), (a) => a.source); | ||
const sideEffectImports = utils_1.groupBy(filterInstances(imports, SideEffect), (a) => a.source); | ||
Object.keys(sideEffectImports).forEach((it) => (result += `import '${it}';\n`)); | ||
@@ -364,3 +361,3 @@ return result; | ||
function maybeRelativePath(outputPath, importPath) { | ||
if (!importPath.startsWith('./')) { | ||
if (!importPath.startsWith("./")) { | ||
return importPath; | ||
@@ -372,5 +369,5 @@ } | ||
let relativePath = path.relative(outputPathDir, importPath).split(path.sep).join(path.posix.sep); | ||
if (!relativePath.startsWith('.')) { | ||
if (!relativePath.startsWith(".")) { | ||
// ensure the js compiler recognizes this is a relative path. | ||
relativePath = './' + relativePath; | ||
relativePath = "./" + relativePath; | ||
} | ||
@@ -384,5 +381,5 @@ return relativePath; | ||
// Check the base paths (without the .js or .ts suffix). | ||
const [basePath1, basePath2] = [path1, path2].map((p) => p.replace(/\.[tj]sx?/, '')); | ||
const [basePath1, basePath2] = [path1, path2].map((p) => p.replace(/\.[tj]sx?/, "")); | ||
return basePath1 === basePath2 || path.resolve(basePath1) === path.resolve(basePath2); | ||
} | ||
exports.sameModule = sameModule; |
@@ -1,7 +0,7 @@ | ||
import { Import } from './Import'; | ||
import { Code, Def } from './Code'; | ||
import { Node } from './Node'; | ||
import { ConditionalOutput } from './ConditionalOutput'; | ||
export { Code } from './Code'; | ||
export { Import } from './Import'; | ||
import { Import } from "./Import"; | ||
import { Code, Def } from "./Code"; | ||
import { Node } from "./Node"; | ||
import { ConditionalOutput } from "./ConditionalOutput"; | ||
export { Code } from "./Code"; | ||
export { Import } from "./Import"; | ||
/** A template literal to format code and auto-organize imports. */ | ||
@@ -8,0 +8,0 @@ export declare function code(literals: TemplateStringsArray, ...placeholders: unknown[]): Code; |
@@ -34,8 +34,8 @@ "use strict"; | ||
function joinCode(chunks, opts = {}) { | ||
const { on = '', trim = true } = opts; | ||
const literals = ['']; | ||
const { on = "", trim = true } = opts; | ||
const literals = [""]; | ||
for (let i = 0; i < chunks.length - 1; i++) { | ||
literals.push(on); | ||
} | ||
literals.push(''); | ||
literals.push(""); | ||
if (trim) { | ||
@@ -42,0 +42,0 @@ chunks.forEach((c) => (c.trim = true)); |
@@ -23,3 +23,3 @@ "use strict"; | ||
// If constructor does not have an Object-specific method | ||
if (!ctor.prototype.hasOwnProperty('isPrototypeOf')) | ||
if (!ctor.prototype.hasOwnProperty("isPrototypeOf")) | ||
return false; | ||
@@ -31,3 +31,3 @@ // Most likely a plain Object | ||
function isObject(o) { | ||
return Object.prototype.toString.call(o) === '[object Object]'; | ||
return Object.prototype.toString.call(o) === "[object Object]"; | ||
} |
@@ -1,2 +0,2 @@ | ||
import { Node } from './Node'; | ||
import { Node } from "./Node"; | ||
/** | ||
@@ -3,0 +3,0 @@ * A literal source representation of the provided object |
@@ -21,9 +21,9 @@ "use strict"; | ||
.map((node) => { | ||
if (typeof node === 'string') | ||
if (typeof node === "string") | ||
return node; | ||
if (node instanceof Node_1.Node) | ||
return node.toCodeString(); | ||
return ''; | ||
return ""; | ||
}) | ||
.join(' '); | ||
.join(" "); | ||
} | ||
@@ -33,6 +33,6 @@ } | ||
function flatten(o) { | ||
if (typeof o === 'undefined') { | ||
return ['undefined']; | ||
if (typeof o === "undefined") { | ||
return ["undefined"]; | ||
} | ||
if (typeof o === 'object' && o != null) { | ||
if (typeof o === "object" && o != null) { | ||
if (o instanceof Node_1.Node || o instanceof ConditionalOutput_1.MaybeOutput) { | ||
@@ -42,21 +42,21 @@ return [o]; | ||
else if (Array.isArray(o)) { | ||
const nodes = ['[']; | ||
const nodes = ["["]; | ||
for (let i = 0; i < o.length; i++) { | ||
if (i !== 0) | ||
nodes.push(','); | ||
nodes.push(","); | ||
nodes.push(...flatten(o[i])); | ||
} | ||
nodes.push(']'); | ||
nodes.push("]"); | ||
return nodes; | ||
} | ||
else if (is_plain_object_1.isPlainObject(o)) { | ||
const nodes = ['{']; | ||
const nodes = ["{"]; | ||
const entries = Object.entries(o); | ||
for (let i = 0; i < entries.length; i++) { | ||
if (i !== 0) | ||
nodes.push(','); | ||
nodes.push(","); | ||
const [key, value] = entries[i]; | ||
nodes.push(JSON.stringify(key), ':', ...flatten(value)); | ||
nodes.push(JSON.stringify(key), ":", ...flatten(value)); | ||
} | ||
nodes.push('}'); | ||
nodes.push("}"); | ||
return nodes; | ||
@@ -63,0 +63,0 @@ } |
{ | ||
"name": "ts-poet", | ||
"version": "4.15.0", | ||
"version": "5.0.0", | ||
"description": "code generation DSL for TypeScript", | ||
@@ -11,3 +11,4 @@ "main": "build/index.js", | ||
"build": "yarn tsc", | ||
"lint": "yarn tslint --project ." | ||
"lint": "yarn tslint --project .", | ||
"format": "prettier --write 'src/**/*.{ts,tsx}'" | ||
}, | ||
@@ -31,2 +32,3 @@ "repository": { | ||
"jest": "^26.6.3", | ||
"prettier": "^2.7.1", | ||
"ts-jest": "^26.5.1", | ||
@@ -36,5 +38,4 @@ "typescript": "^4.1.5" | ||
"dependencies": { | ||
"lodash": "^4.17.15", | ||
"prettier": "^2.5.1" | ||
"dprint-node": "^1.0.7" | ||
} | ||
} |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
1
86874
12
1522
+ Addeddprint-node@^1.0.7
+ Addeddetect-libc@1.0.3(transitive)
+ Addeddprint-node@1.0.8(transitive)
- Removedlodash@^4.17.15
- Removedprettier@^2.5.1
- Removedlodash@4.17.21(transitive)
- Removedprettier@2.8.8(transitive)