@getcronit/pylon-builder 0.0.49 → 0.0.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/dist/index.js.map +3 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -28,7 +28,7 @@ class Bundler {
|
|
|
28
28
|
this.reportStatus("start");
|
|
29
29
|
const build = async () => {
|
|
30
30
|
const external = new Set([
|
|
31
|
-
"@
|
|
31
|
+
"@getcronit/pylon",
|
|
32
32
|
"hono",
|
|
33
33
|
"@prisma/client",
|
|
34
34
|
"openid-client",
|
|
@@ -831,4 +831,4 @@ export {
|
|
|
831
831
|
build
|
|
832
832
|
};
|
|
833
833
|
|
|
834
|
-
//# debugId=
|
|
834
|
+
//# debugId=A87AFFA45E8756B564756e2164756e21
|
package/dist/index.js.map
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/bundler/bundler.ts", "../src/load-package-json.ts", "../src/bundler/bundler.ts", "../src/schema/builder.ts", "../src/schema/schema-parser.ts", "../src/schema/types-helper.ts", "../src/schema/types-helper.ts", "../src/schema/type-definition-builder.ts", "../src/schema/type-definition-builder.ts", "../src/schema/schema-parser.ts", "../src/schema/builder.ts", "../src/index.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"// bundler.ts\nimport fs from 'fs'\nimport chokidar from 'chokidar'\nimport {loadPackageJson} from '../load-package-json'\nimport ncc from '@vercel/ncc'\nimport path from 'path'\n\nexport interface BundlerBuildOptions {\n getTypeDefs: () => string\n watch?: boolean\n onWatch?: () => void\n}\n\nexport class Bundler {\n sfiFilePath: string\n outputDir: string\n\n constructor(sfiFilePath: string, outputDir: string = './.pylon') {\n this.sfiFilePath = sfiFilePath\n this.outputDir = outputDir\n }\n\n public async build(options: BundlerBuildOptions): Promise<void> {\n this.reportStatus('start')\n\n const build = async () => {\n const external = new Set<string>([\n '@
|
|
5
|
+
"// bundler.ts\nimport fs from 'fs'\nimport chokidar from 'chokidar'\nimport {loadPackageJson} from '../load-package-json'\nimport ncc from '@vercel/ncc'\nimport path from 'path'\n\nexport interface BundlerBuildOptions {\n getTypeDefs: () => string\n watch?: boolean\n onWatch?: () => void\n}\n\nexport class Bundler {\n sfiFilePath: string\n outputDir: string\n\n constructor(sfiFilePath: string, outputDir: string = './.pylon') {\n this.sfiFilePath = sfiFilePath\n this.outputDir = outputDir\n }\n\n public async build(options: BundlerBuildOptions): Promise<void> {\n this.reportStatus('start')\n\n const build = async () => {\n const external = new Set<string>([\n '@getcronit/pylon',\n 'hono',\n '@prisma/client',\n 'openid-client',\n 'hono/http-exception'\n ])\n\n // Read \"external\" from package.json\n const packageJson = await loadPackageJson()\n\n if (packageJson.pylon && packageJson.pylon.external) {\n packageJson.pylon.external.forEach((externalPackage: string) => {\n external.add(externalPackage)\n })\n }\n\n const nccOptions = {\n quiet: true,\n externals: Array.from(external),\n sourceMap: true, // Generate sourcemap\n transpileOnly: true\n }\n\n const inputPath = path.join(process.cwd(), this.sfiFilePath)\n const dir = path.join(process.cwd(), this.outputDir)\n\n const {code, map, assets} = await ncc(inputPath, nccOptions)\n\n fs.mkdirSync(dir, {\n recursive: true\n })\n\n fs.writeFileSync(`${dir}/index.js`, code)\n\n Object.entries(assets).forEach(([name, asset]) => {\n const source = (asset as any).source\n\n if (typeof source === 'string') {\n fs.writeFileSync(`${dir}/${name}`, source)\n } else if (typeof source === 'object') {\n fs.writeFileSync(`${dir}/${name}`, Buffer.from(source))\n }\n })\n\n // attach typeDefs to the output\n this.prependTypeDefs(options.getTypeDefs())\n\n this.reportStatus('done')\n }\n\n if (options.watch) {\n chokidar.watch(this.sfiFilePath).on('change', async () => {\n await build()\n\n if (options.onWatch) {\n options.onWatch()\n }\n })\n }\n\n await build()\n }\n\n private prependTypeDefs(typeDefs: string): void {\n const outputFile = `${this.outputDir}/index.js`\n\n fs.writeFileSync(\n outputFile,\n `\\export const typeDefs = ${JSON.stringify(typeDefs)};\\n` +\n fs.readFileSync(outputFile)\n )\n }\n\n private reportStatus(status: 'start' | 'done'): void {\n if (status === 'start') {\n console.log('\\x1b[32m%s\\x1b[0m', `Bundling Pylon: ${this.sfiFilePath}...`)\n }\n\n if (status === 'done') {\n console.log('\\x1b[32m%s\\x1b[0m', 'Bundling Pylon: done')\n }\n }\n}\n",
|
|
6
6
|
"import path from 'path'\nimport {readFile} from 'fs/promises'\n\nexport async function loadPackageJson(): Promise<{\n baseURL?: string\n pylon?: {\n external?: string[]\n }\n}> {\n const packageJsonPath = path.resolve(process.cwd(), 'package.json')\n\n const file = await readFile(packageJsonPath)\n const packageJson = JSON.parse(file.toString())\n return packageJson\n}\n",
|
|
7
|
-
"// bundler.ts\nimport fs from 'fs'\nimport chokidar from 'chokidar'\nimport {loadPackageJson} from '../load-package-json'\nimport ncc from '@vercel/ncc'\nimport path from 'path'\n\nexport interface BundlerBuildOptions {\n getTypeDefs: () => string\n watch?: boolean\n onWatch?: () => void\n}\n\nexport class Bundler {\n sfiFilePath: string\n outputDir: string\n\n constructor(sfiFilePath: string, outputDir: string = './.pylon') {\n this.sfiFilePath = sfiFilePath\n this.outputDir = outputDir\n }\n\n public async build(options: BundlerBuildOptions): Promise<void> {\n this.reportStatus('start')\n\n const build = async () => {\n const external = new Set<string>([\n '@
|
|
7
|
+
"// bundler.ts\nimport fs from 'fs'\nimport chokidar from 'chokidar'\nimport {loadPackageJson} from '../load-package-json'\nimport ncc from '@vercel/ncc'\nimport path from 'path'\n\nexport interface BundlerBuildOptions {\n getTypeDefs: () => string\n watch?: boolean\n onWatch?: () => void\n}\n\nexport class Bundler {\n sfiFilePath: string\n outputDir: string\n\n constructor(sfiFilePath: string, outputDir: string = './.pylon') {\n this.sfiFilePath = sfiFilePath\n this.outputDir = outputDir\n }\n\n public async build(options: BundlerBuildOptions): Promise<void> {\n this.reportStatus('start')\n\n const build = async () => {\n const external = new Set<string>([\n '@getcronit/pylon',\n 'hono',\n '@prisma/client',\n 'openid-client',\n 'hono/http-exception'\n ])\n\n // Read \"external\" from package.json\n const packageJson = await loadPackageJson()\n\n if (packageJson.pylon && packageJson.pylon.external) {\n packageJson.pylon.external.forEach((externalPackage: string) => {\n external.add(externalPackage)\n })\n }\n\n const nccOptions = {\n quiet: true,\n externals: Array.from(external),\n sourceMap: true, // Generate sourcemap\n transpileOnly: true\n }\n\n const inputPath = path.join(process.cwd(), this.sfiFilePath)\n const dir = path.join(process.cwd(), this.outputDir)\n\n const {code, map, assets} = await ncc(inputPath, nccOptions)\n\n fs.mkdirSync(dir, {\n recursive: true\n })\n\n fs.writeFileSync(`${dir}/index.js`, code)\n\n Object.entries(assets).forEach(([name, asset]) => {\n const source = (asset as any).source\n\n if (typeof source === 'string') {\n fs.writeFileSync(`${dir}/${name}`, source)\n } else if (typeof source === 'object') {\n fs.writeFileSync(`${dir}/${name}`, Buffer.from(source))\n }\n })\n\n // attach typeDefs to the output\n this.prependTypeDefs(options.getTypeDefs())\n\n this.reportStatus('done')\n }\n\n if (options.watch) {\n chokidar.watch(this.sfiFilePath).on('change', async () => {\n await build()\n\n if (options.onWatch) {\n options.onWatch()\n }\n })\n }\n\n await build()\n }\n\n private prependTypeDefs(typeDefs: string): void {\n const outputFile = `${this.outputDir}/index.js`\n\n fs.writeFileSync(\n outputFile,\n `\\export const typeDefs = ${JSON.stringify(typeDefs)};\\n` +\n fs.readFileSync(outputFile)\n )\n }\n\n private reportStatus(status: 'start' | 'done'): void {\n if (status === 'start') {\n console.log('\\x1b[32m%s\\x1b[0m', `Bundling Pylon: ${this.sfiFilePath}...`)\n }\n\n if (status === 'done') {\n console.log('\\x1b[32m%s\\x1b[0m', 'Bundling Pylon: done')\n }\n }\n}\n",
|
|
8
8
|
"import ts from 'typescript'\nimport {SchemaParser} from './schema-parser'\nimport path from 'path'\n\nexport class SchemaBuilder {\n private program: ts.Program\n private checker: ts.TypeChecker\n private sfiFile!: ts.SourceFile\n private sfi!: ts.Symbol\n private sfiFilePath: string\n\n constructor(sfiFilePath: string) {\n this.sfiFilePath = path.join(process.cwd(), sfiFilePath)\n\n this.program = ts.createProgram([this.sfiFilePath], {\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.CommonJS,\n strict: true,\n esModuleInterop: true,\n skipLibCheck: false,\n forceConsistentCasingInFileNames: true,\n noImplicitAny: true,\n experimentalDecorators: true\n })\n\n this.checker = this.program.getTypeChecker()\n\n this.loadSfi()\n }\n\n private loadSfi() {\n const sourceFiles = this.program.getSourceFiles()\n const file = sourceFiles.find(file => file.fileName === this.sfiFilePath)\n\n if (!file) {\n throw new Error('Could not find index.ts (pylon entrypoint)')\n }\n\n this.sfiFile = file\n\n const sfiFileSymbol = this.checker.getSymbolAtLocation(file)!\n const sfiFileExports = this.checker.getExportsOfModule(sfiFileSymbol!)\n const sfiFileDefaultExport = sfiFileExports.find(\n exportSymbol => exportSymbol.escapedName === 'default'\n )\n\n if (!sfiFileDefaultExport) {\n throw new Error('Could not find default export')\n }\n\n this.sfi = sfiFileDefaultExport\n }\n\n public build() {\n const sfiType = this.checker.getTypeOfSymbolAtLocation(\n this.sfi,\n this.sfiFile\n )\n\n const plainResolversProperty = sfiType.getProperty('plainResolvers')\n\n if (!plainResolversProperty) {\n throw new Error('Could not find plainResolvers property')\n }\n\n const plainResolversType = this.checker.getTypeOfSymbolAtLocation(\n plainResolversProperty,\n this.sfiFile\n )\n\n const queryProperty = plainResolversType.getProperty('Query')\n const mutationProperty = plainResolversType.getProperty('Mutation')\n\n const queryType = queryProperty\n ? this.checker.getTypeOfSymbolAtLocation(queryProperty, this.sfiFile)\n : undefined\n const mutationType = mutationProperty\n ? this.checker.getTypeOfSymbolAtLocation(mutationProperty, this.sfiFile)\n : undefined\n\n const parser = new SchemaParser(this.checker, this.sfiFile)\n\n parser.parse({\n Query: queryType,\n Mutation: mutationType\n })\n\n return {\n typeDefs: parser.toString(),\n schema: parser.getSchema()\n }\n }\n}\n",
|
|
9
9
|
"import ts from 'typescript'\nimport {\n getPromiseType,\n getPublicPropertiesOfType,\n isFunction,\n isList,\n isPrimitive,\n isPromise\n} from './types-helper.js'\nimport {\n TypeDefinitionBuilder,\n Union as _Union,\n Enum as _Enum\n} from './type-definition-builder.js'\n\ntype Union = _Union & {\n description: string\n}\n\ntype Enum = _Enum & {\n description: string\n}\n\ninterface TypeDefinition {\n name: string\n isList: boolean\n isRequired: boolean\n description: string\n}\n\ninterface Field {\n name: string\n type: TypeDefinition\n}\n\ninterface Input {\n name: string\n description: string\n fields: Array<{\n name: string\n type: TypeDefinition\n }>\n}\n\ninterface Type {\n name: string\n description: string\n fields: Array<\n Field & {\n args: Array<{\n name: string\n type: TypeDefinition\n }>\n }\n >\n}\n\nexport interface Schema {\n types: Array<Type>\n inputs: Array<Input>\n unions: Array<Union>\n enums: Array<Enum>\n scalars: Array<string>\n}\n\ntype ReferenceSchemaType = {\n returnType: ts.Type\n args: {\n // value needs to be inputs type\n [key: string]: ts.Type\n }\n}\n\ninterface ReferenceSchema {\n types: Map<\n ts.Type,\n {\n [key: string]: ReferenceSchemaType\n }\n >\n inputs: ReferenceSchema['types']\n}\n\ninterface Index {\n Query?: ts.Type\n Mutation?: ts.Type\n}\n\nexport class SchemaParser {\n private schema: Schema\n private checker: ts.TypeChecker\n private sfiFile: ts.SourceFile\n private typeDefinitionBuilder: TypeDefinitionBuilder\n\n constructor(checker: ts.TypeChecker, sfiFile: ts.SourceFile) {\n this.schema = {\n types: [],\n inputs: [],\n unions: [],\n enums: [],\n scalars: [\n 'Number',\n 'Any',\n 'Object',\n 'File',\n 'Date',\n 'JSON',\n 'String',\n 'Boolean'\n ]\n }\n\n this.checker = checker\n this.sfiFile = sfiFile\n\n this.typeDefinitionBuilder = new TypeDefinitionBuilder(checker, this.schema)\n }\n\n public parse(index: Index) {\n const referenceSchema = this.makeReferenceSchema(index)\n\n for (const [type, properties] of referenceSchema.types) {\n let typeName: string | undefined = undefined\n\n if (index.Query === type) {\n typeName = 'Query'\n } else if (index.Mutation === type) {\n typeName = 'Mutation'\n }\n\n this.processSchemaReference(type, properties, typeName, 'types')\n }\n\n for (const [type, properties] of referenceSchema.inputs) {\n this.processSchemaReference(type, properties, undefined, 'inputs')\n }\n\n this.extractForbiddenFieldNamesFromSchema()\n\n this.schema.unions = this.typeDefinitionBuilder\n .getUnions()\n .map((union): Union => {\n return {\n ...union,\n description: this.getJsDocHeaderFromType(union.rawType)\n }\n })\n\n this.schema.enums = this.typeDefinitionBuilder\n .getEnums()\n .map((enumType): Enum => {\n return {\n ...enumType,\n description: this.getJsDocHeaderFromType(enumType.rawType)\n }\n })\n }\n\n public toString() {\n const {typeDefinitionToGraphQLType} = this.typeDefinitionBuilder\n\n const addDescription = (description: string) => {\n if (!description) return ''\n\n return `\"\"\"\\n${description}\\n\"\"\"\\n`\n }\n\n // build a valid GraphQL schema string from the schema object\n let schemaString = ''\n\n // loop over the input objects in the schema\n for (const input of this.schema.inputs) {\n // add the input object to the schema string\n\n schemaString += addDescription(input.description)\n schemaString += `input ${input.name} {\\n`\n\n // add a nop field to the input object if it has no fields\n if (input.fields.length === 0) {\n schemaString += `\\t_ : String\\n`\n }\n\n // loop over the fields in the input object\n for (const field of input.fields) {\n // add the field to the input object in the schema string\n schemaString += `${addDescription(field.type.description)}`\n schemaString += `\\t${field.name}: ${typeDefinitionToGraphQLType(\n field.type\n )}\\n`\n }\n\n schemaString += `}\\n`\n }\n\n // loop over the type objects in the schema\n for (const type of this.schema.types) {\n if (type.fields.length === 0) continue\n\n // add the type object to the schema string\n schemaString += addDescription(type.description)\n schemaString += `type ${type.name} {\\n`\n\n // loop over the fields in the type object\n for (const field of type.fields) {\n // build the argument list for the field if there is at least one argument\n let args = ''\n\n if (field.args.length > 0) {\n args = `(${field.args\n .map(\n arg =>\n `${addDescription(type.description)}${\n arg.name\n }: ${typeDefinitionToGraphQLType(arg.type)}`\n )\n .join(', ')})`\n }\n\n // add the field to the type object in the schema string\n schemaString += `${addDescription(field.type.description)}`\n schemaString += `${field.name}${args}: ${typeDefinitionToGraphQLType(\n field.type\n )}\\n`\n }\n\n schemaString += `}\\n`\n }\n\n // loop over the union objects in the schema\n for (const union of this.schema.unions) {\n // add the union object to the schema string\n schemaString += addDescription(union.description)\n schemaString += `union ${union.name} = ${union.types.join(' | ')}\\n`\n }\n\n // loop over the scalar objects in the schema\n for (const scalar of this.schema.scalars) {\n // add the scalar object to the schema string\n schemaString += `scalar ${scalar}\\n`\n }\n\n // loop over the enum objects in the schema\n for (const enumType of this.schema.enums) {\n // add the enum object to the schema string\n schemaString += addDescription(enumType.description)\n schemaString += `enum ${enumType.name} {\\n`\n\n // loop over the values in the enum object\n for (const value of enumType.values) {\n // add the value to the enum object in the schema string\n schemaString += `\\t${value}\\n`\n }\n\n schemaString += `}\\n`\n }\n\n // return the schema string\n return schemaString\n }\n\n public getSchema() {\n return this.schema\n }\n\n private processSchemaReference(\n type: ts.Type,\n properties: {[key: string]: ReferenceSchemaType},\n typeName?: string,\n processing: 'inputs' | 'types' = 'types'\n ) {\n const {getTypeDefinition} = this.typeDefinitionBuilder\n\n const isInputType = processing === 'inputs'\n\n const def = getTypeDefinition(type, {isInputType})\n\n const name = typeName || def.name\n\n let root = this.schema[processing].find(t => t.name === name)\n\n if (!root) {\n if (this.schema.scalars.includes(name)) {\n return\n } else {\n this.schema[processing].push({\n name,\n description: this.getJsDocHeaderFromType(type),\n fields: []\n })\n\n root = this.schema[processing][this.schema[processing].length - 1]!\n }\n }\n\n for (const [propertyName, property] of Object.entries(properties)) {\n const fieldType = property.returnType\n\n const fieldDef = getTypeDefinition(fieldType, {\n isInputType,\n propertyName\n })\n\n if (processing === 'types') {\n const field: Type['fields'][number] = {\n name: propertyName,\n type: {\n ...fieldDef,\n description: this.getJsDocHeaderFromType(fieldType)\n },\n args: []\n }\n\n if (property.args) {\n for (const [argName, arg] of Object.entries(property.args)) {\n const argType = arg\n\n const fieldDef = getTypeDefinition(argType, {\n isInputType: true,\n propertyName: argName\n })\n\n if (\n this.schema.scalars.includes(this.checker.typeToString(argType))\n ) {\n fieldDef.name = this.checker.typeToString(argType)\n }\n\n field.args.push({\n name: argName,\n type: {\n ...fieldDef,\n description: this.getJsDocHeaderFromType(argType)\n }\n })\n }\n }\n\n root.fields.push(field)\n } else if (processing === 'inputs') {\n const field: Input['fields'][number] = {\n name: propertyName,\n type: {\n ...fieldDef,\n description: this.getJsDocHeaderFromType(fieldType)\n }\n }\n\n if (!root.fields.find(f => f.name === field.name)) {\n root.fields.push(field)\n }\n }\n }\n }\n\n private getJsDocHeaderFromType = (type: ts.Type) => {\n let header = ''\n\n if (type.symbol) {\n const typeDeclaration = type.symbol.declarations?.[0] as unknown as\n | {\n jsDoc: ts.JSDoc[]\n }\n | undefined\n\n const comments = typeDeclaration?.jsDoc?.map(doc => doc.comment).join(' ')\n\n if (comments) {\n header = comments\n }\n\n const tags = type.symbol.getJsDocTags()\n const tagComments = tags\n ?.map(tag => `@${tag.name} ${tag.text?.map(t => t.text).join(' ')}`)\n .join('\\n')\n\n if (tagComments) {\n header = `${header} ${tagComments}`\n }\n }\n\n return header\n }\n\n /**\n * Extracts reserved field names from the schema by removing them from their respective types and inputs.\n */\n private extractForbiddenFieldNamesFromSchema(): void {\n // Define a regular expression to check if a field name is a valid GraphQL field name.\n const validFieldNameRegExp = /^[_A-Za-z][_0-9A-Za-z]*$/\n\n // Define a helper function to check if a field name is reserved.\n const isReserved = (name: string): boolean => {\n if (!validFieldNameRegExp.test(name)) {\n // console.warn(\n // `\\x1b[33mWarning: forbidden field name \"${name}\" detected\\x1b[0m`\n // )\n return true\n }\n // Fields starting with \"__\" are considered reserved.\n return name.startsWith('__')\n }\n\n // Loop over each type in the schema and remove any reserved fields.\n for (const type of this.schema.types) {\n type.fields = type.fields.filter(field => {\n if (isReserved(field.name)) {\n // console.warn(\n // `\\x1b[33mWarning: forbidden field \"${field.name}\" detected in type \"${type.name}\". This field will be excluded from the schema.\\x1b[0m`\n // )\n return false\n }\n return true\n })\n }\n\n // Loop over each input in the schema and remove any reserved fields.\n for (const input of this.schema.inputs) {\n input.fields = input.fields.filter(field => {\n if (isReserved(field.name)) {\n // console.warn(\n // `\\x1b[33mWarning: reserved field \"${field.name}\" detected in input \"${input.name}\". This field will be excluded from the schema.\\x1b[0m`\n // )\n return false\n }\n return true\n })\n }\n }\n\n private makeReferenceSchema(index: Index): ReferenceSchema {\n const referenceSchema: ReferenceSchema = {\n types: new Map(),\n inputs: new Map()\n }\n\n const recLoop = (\n type: ts.Type,\n info: {\n propetyName?: string\n parentType?: ts.Type\n } = {},\n processing: 'inputs' | 'types' = 'types',\n path: Array<string> = []\n ) => {\n if (referenceSchema[processing].has(type)) {\n return\n }\n\n // check if argType is a real type to ignore '[]'\n const wrongType = this.checker.typeToString(type) === '[]'\n\n if (wrongType) {\n return\n }\n\n // skip if scalar\n if (this.schema.scalars.includes(this.checker.typeToString(type))) {\n return\n }\n\n if (isPrimitive(type)) {\n return\n }\n\n if (isPromise(type)) {\n // skip if input\n if (processing === 'inputs') {\n return\n }\n\n const promiseType = getPromiseType(type)\n\n if (promiseType) {\n recLoop(promiseType, info, processing, [...path, 'PROMISE'])\n }\n\n return\n }\n\n if (type.isUnion()) {\n if (processing === 'types') {\n type.types.forEach(t => {\n // if null or undefined, skip\n if (\n t.flags & ts.TypeFlags.Null ||\n t.flags & ts.TypeFlags.Undefined ||\n isPrimitive(t)\n ) {\n return\n }\n\n recLoop(t, info, processing, [\n ...path,\n t.symbol?.getName() || `N/A ${this.checker.typeToString(t)}`\n ])\n })\n } else {\n let properties = getPublicPropertiesOfType(\n this.checker,\n type.getNonNullableType()\n )\n\n if (properties.length === 0) {\n //get first union type of non nullable type\n const nt = type.getNonNullableType()\n if (nt.isUnion()) {\n properties = getPublicPropertiesOfType(this.checker, nt.types[0]!)\n }\n }\n\n if (properties.length > 0) {\n if (!referenceSchema[processing].has(type)) {\n referenceSchema[processing].set(type, {})\n }\n\n // Go through all properties of the union type and add them to the reference schema\n properties.forEach(property => {\n const propertyType = this.checker.getTypeOfSymbolAtLocation(\n property,\n this.sfiFile\n )\n\n if (!isFunction(propertyType)) {\n referenceSchema[processing].get(type)![\n property.escapedName as string\n ] = {\n returnType: propertyType,\n args: {}\n }\n\n recLoop(\n propertyType,\n {\n propetyName: property.escapedName as string,\n parentType: type\n },\n processing,\n [...path, property.escapedName as string]\n )\n }\n })\n }\n }\n } else if (isFunction(type)) {\n // skip fn for inputs\n if (processing === 'inputs') {\n return\n }\n\n if (!info.parentType) {\n throw new Error('Cannot have a function without a parent type')\n }\n\n const signature = type.getCallSignatures()[0]\n const args = signature?.getParameters() || []\n const returnType = signature?.getReturnType()\n\n const schemaType = referenceSchema[processing].get(info.parentType)![\n info.propetyName!\n ]!\n\n args.forEach(arg => {\n if (\n arg.valueDeclaration &&\n ts.isParameter(arg.valueDeclaration) &&\n arg.valueDeclaration.dotDotDotToken\n ) {\n console.warn(\n 'Cannot handle rest parameters yet, skipping',\n arg.escapedName\n )\n } else {\n const argType = this.checker.getTypeOfSymbolAtLocation(\n arg,\n this.sfiFile\n )\n\n // set args to empty object if not set\n if (schemaType.args) {\n schemaType.args[arg.escapedName as string] = argType\n\n recLoop(\n argType,\n {\n parentType: type\n },\n 'inputs',\n [...path, arg.escapedName as string]\n )\n }\n }\n })\n\n if (returnType) {\n recLoop(returnType, info, processing, [...path, 'RETURN_TYPE'])\n }\n } else if (isList(this.checker, type)) {\n const itemType = this.checker.getIndexTypeOfType(\n type,\n ts.IndexKind.Number\n )\n\n if (itemType && !isPrimitive(itemType)) {\n if (!referenceSchema[processing].has(type)) {\n referenceSchema[processing].set(type, {})\n }\n\n recLoop(itemType, info, processing, [...path, 'ITEM_TYPE'])\n }\n } else if (!isPrimitive(type)) {\n const properties = getPublicPropertiesOfType(this.checker, type)\n\n if (!referenceSchema[processing].has(type)) {\n referenceSchema[processing].set(type, {})\n }\n\n properties.forEach(property => {\n const propertyType = this.checker.getTypeOfSymbolAtLocation(\n property,\n this.sfiFile\n )\n\n if (\n !referenceSchema[processing].get(type)![\n property.escapedName as string\n ]\n ) {\n referenceSchema[processing].get(type)![\n property.escapedName as string\n ] = {\n returnType: propertyType,\n args: {}\n }\n }\n\n recLoop(\n propertyType,\n {\n propetyName: property.escapedName as string,\n parentType: type\n },\n processing,\n [...path, property.escapedName as string]\n )\n })\n }\n }\n\n if (index.Query) {\n recLoop(index.Query)\n }\n\n if (index.Mutation) {\n recLoop(index.Mutation)\n }\n\n return referenceSchema\n }\n}\n",
|
|
10
10
|
"import ts from 'typescript'\n\nexport const isEmptyObject = (type: ts.Type) => {\n return (\n type.flags & ts.TypeFlags.Object &&\n type.getProperties().length === 0 &&\n type.getCallSignatures().length === 0\n )\n}\n\nexport const isList = (checker: ts.TypeChecker, type: ts.Type) => {\n const typeNode = checker.typeToTypeNode(type, undefined, undefined)\n\n const is = !!(\n typeNode &&\n (typeNode.kind === ts.SyntaxKind.ArrayType ||\n typeNode.kind === ts.SyntaxKind.TupleType)\n )\n\n return is\n}\n\nexport const isBoolean = (type: ts.Type) => {\n // check if is union and all types are boolean\n if (type.isUnion()) {\n const isAllBooleans = type.types.every(\n t => t.flags & ts.TypeFlags.BooleanLiteral\n )\n\n return isAllBooleans\n }\n\n return false\n}\n\nexport const isPrimitive = (type: ts.Type) => {\n const primitive =\n type.flags & ts.TypeFlags.String ||\n type.flags & ts.TypeFlags.Number ||\n type.flags & ts.TypeFlags.Boolean ||\n type.flags & ts.TypeFlags.StringLiteral ||\n type.flags & ts.TypeFlags.NumberLiteral ||\n type.flags & ts.TypeFlags.BooleanLiteral\n\n return primitive\n}\n\nexport const isFunction = (type: ts.Type) => {\n return type.getCallSignatures().length > 0\n}\n\nexport const isEnum = (type: ts.Type) => {\n if (isPrimitive(type)) return false\n\n const isUnion = (type as ts.UnionType).types?.length > 1\n\n if (isUnion) {\n // check if all types are primitives\n const isAllPrimitives = (type as ts.UnionType).types.every(\n t =>\n t.flags & ts.TypeFlags.StringLiteral ||\n t.flags & ts.TypeFlags.NumberLiteral ||\n t.flags & ts.TypeFlags.BooleanLiteral\n )\n\n if (isAllPrimitives) {\n return true\n }\n }\n\n return false\n}\n\nexport const isPromise = (type: ts.Type) => {\n // check if type is a promise\n return type.getSymbol()?.getName() === 'Promise'\n}\n\nexport const getPromiseType = (type: ts.Type) => {\n let objectType = type as ts.ObjectType\n\n if (objectType.objectFlags & ts.ObjectFlags.Reference) {\n const reference = type as ts.TypeReference\n const typeArguments = reference.typeArguments\n if (typeArguments && typeArguments.length > 0) {\n return typeArguments[0]\n }\n }\n}\n\nexport const excludeNullUndefinedFromType = (type: ts.Type) => {\n if (!type.isUnion())\n return {\n type,\n wasOptional: false\n }\n\n const types = type.types.filter(\n t => !(t.flags & ts.TypeFlags.Undefined || t.flags & ts.TypeFlags.Null)\n )\n\n const wasOptional = types.length !== type.types.length\n\n return {\n type: type.getNonNullableType(),\n wasOptional\n }\n}\n\nexport function getPublicPropertiesOfType(\n checker: ts.TypeChecker,\n _type: ts.Type\n): ts.Symbol[] {\n let type = _type\n\n if (type.isUnion()) {\n // Filter out array types from the union if their non-array counterparts are also present\n const nonArrayTypes = type.types.filter(\n t =>\n !(\n t.flags & ts.TypeFlags.Object &&\n (t as ts.ObjectType).objectFlags & ts.ObjectFlags.Reference &&\n (t as ts.TypeReference).typeArguments?.length\n )\n )\n const arrayElementTypes = type.types\n .filter(\n t =>\n t.flags & ts.TypeFlags.Object &&\n (t as ts.ObjectType).objectFlags & ts.ObjectFlags.Reference &&\n (t as ts.TypeReference).typeArguments?.length\n )\n .map(t => (t as ts.TypeReference).typeArguments![0])\n const filteredTypes = nonArrayTypes.filter(\n t => !arrayElementTypes.some(et => et === t)\n )\n // .filter(t => {\n // // filter out primitive types\n // return !isPrimitive(t)\n // })\n\n // Create a new type that is the union of all the types in the union\n // This is necessary because the type checker will not resolve properties\n // that are only present on some types in the union\n // getUnionType is not available in TS 3.7, so we have to use the private API\n type = (checker as any).getUnionType(filteredTypes) as ts.Type\n }\n\n const properties: ts.Symbol[] = []\n\n // if type is a primitive, return empty array\n if (isList(checker, type) || isPrimitive(type) || isEnum(type))\n return properties\n\n let typeProperties: ts.Symbol[] = []\n\n typeProperties =\n (type as any).resolvedProperties || type.getProperties() || []\n\n for (const prop of typeProperties) {\n const isPublic =\n prop.valueDeclaration &&\n !(\n ts.getCombinedModifierFlags(prop.valueDeclaration) &\n ts.ModifierFlags.Private\n ) &&\n !prop.getName().startsWith('#')\n\n if (isPublic === false) {\n continue\n }\n\n properties.push(prop)\n }\n\n return properties\n}\n\nexport const safeTypeName = (name: string) => {\n return name.replace(/[^0-9a-zA-Z_]/g, '_')\n}\n",
|
|
@@ -16,6 +16,6 @@
|
|
|
16
16
|
"import {Bundler} from './bundler/bundler.js'\nimport {SchemaBuilder} from './schema/builder.js'\n\nexport interface BuildOptions {\n sfiFilePath: string\n outputFilePath: string\n watch?: boolean\n onWatch?: () => void\n}\n\nexport const build = async (options: BuildOptions) => {\n const bundler = new Bundler(options.sfiFilePath, options.outputFilePath)\n\n await bundler.build({\n getTypeDefs: () => {\n const builder = new SchemaBuilder(options.sfiFilePath)\n\n const built = builder.build()\n\n // Write typedefs to file (only for debugging purposes)\n const typeDefs = built.typeDefs\n\n return typeDefs\n },\n watch: options.watch,\n onWatch: options.onWatch\n })\n}\n"
|
|
17
17
|
],
|
|
18
18
|
"mappings": ";;AA/////fACA;AACA;;;ACjgggggBAAA;AACA;AAEA,eAAsB,eAAe,GAKlC;AACD,QAAM,kBAAkB,KAAK,QAAQ,QAAQ,IAAI,GAAG,cAAc;AAElE,QAAM,OAAO,MAAM,SAAS,eAAe;AAC3C,QAAM,cAAc,KAAK,MAAM,KAAK,SAAS,CAAC;AAC9C,SAAO;AAAA;;;AC5gggggBTAA;;;AC/////fAAA;;;AC/////fAAA;AA6GO,SAAS,yBAAyB,CACvC,SACA,OACa;AACb,MAAI,OAAO;AAEX,MAAI,KAAK,QAAQ,GAAG;AAElB,UAAM,gBAAgB,KAAK,MAAM,OAC/B,SAEI,EAAE,QAAQ,GAAG,UAAU,UACtB,EAAoB,cAAc,GAAG,YAAY,aACjD,EAAuB,eAAe,OAE7C;AACA,UAAM,oBAAoB,KAAK,MAC5B,OACC,OACE,EAAE,QAAQ,GAAG,UAAU,UACtB,EAAoB,cAAc,GAAG,YAAY,aACjD,EAAuB,eAAe,MAC3C,EACC,IAAI,OAAM,EAAuB,cAAe,EAAE;AACrD,UAAM,gBAAgB,cAAc,OAClC,QAAM,kBAAkB,KAAK,QAAM,OAAO,CAAC,CAC7C;AAUA,WAAQ,QAAgB,aAAa,aAAa;AAAA,EACpD;AAEA,QAAM,aAA0B,CAAC;AAGjC,MAAI,OAAO,SAAS,IAAI,KAAK,YAAY,IAAI,KAAK,OAAO,IAAI;AAC3D,WAAO;AAET,MAAI,iBAA8B,CAAC;AAEnC,mBACG,KAAa,sBAAsB,KAAK,cAAc,KAAK,CAAC;AAE/D,aAAW,QAAQ,gBAAgB;AACjC,UAAM,WACJ,KAAK,sBAEH,GAAG,yBAAyB,KAAK,gBAAgB,IACjD,GAAG,cAAc,aAElB,KAAK,QAAQ,EAAE,WAAW,GAAG;AAEhC,QAAI,aAAa,OAAO;AACtB;AAAA,IACF;AAEA,eAAW,KAAK,IAAI;AAAA,EACtB;AAEA,SAAO;AAAA;AA7KF,IAAM,gBAAgB,CAAC,SAAkB;AAC9C,SACE,KAAK,QAAQ,GAAG,UAAU,UAC1B,KAAK,cAAc,EAAE,WAAW,KAChC,KAAK,kBAAkB,EAAE,WAAW;AAAA;AAIjC,IAAM,SAAS,CAAC,SAAyB,SAAkB;AAChE,QAAM,WAAW,QAAQ,eAAe,MAAM,WAAW,SAAS;AAElE,QAAM,QACJ,aACC,SAAS,SAAS,GAAG,WAAW,aAC/B,SAAS,SAAS,GAAG,WAAW;AAGpC,SAAO;AAAA;;;AClhggggBTAA;;;AC/////fAUO,IAAM,QAAQ,OAAO,YAA0B;AACpD,QAAM,WAAU,IAAI,QAAQ,QAAQ,aAAa,QAAQ,cAAc;AAEvE,QAAM,SAAQ,MAAM;AAAA,IAClB,aAAa,MAAM;AACjB,YAAM,WAAU,IAAI,cAAc,QAAQ,WAAW;AAErD,YAAM,QAAQ,SAAQ,MAAM;AAG5B,YAAM,WAAW,MAAM;AAEvB,aAAO;AAAA;AAAA,IAET,OAAO,QAAQ;AAAA,IACf,SAAS,QAAQ;AAAA,EACnB,CAAC;AAAA;",
|
|
19
|
-
"debugId": "
|
|
19
|
+
"debugId": "A87AFFA45E8756B564756e2164756e21",
|
|
20
20
|
"names": []
|
|
21
21
|
}
|