@ensnode/ponder-subgraph 0.35.0 → 0.36.0

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.d.ts CHANGED
@@ -2,14 +2,14 @@ import * as hono_types from 'hono/types';
2
2
  import { GraphQLSchema } from 'graphql';
3
3
  import { PgTable, TableConfig } from 'drizzle-orm/pg-core';
4
4
 
5
- declare const graphql: ({ db, graphqlSchema, }: {
6
- db: any;
5
+ declare function subgraphGraphQLMiddleware({ drizzle, graphqlSchema, }: {
6
+ drizzle: any;
7
7
  graphqlSchema: GraphQLSchema;
8
8
  }, { maxOperationTokens, maxOperationDepth, maxOperationAliases, }?: {
9
9
  maxOperationTokens?: number;
10
10
  maxOperationDepth?: number;
11
11
  maxOperationAliases?: number;
12
- }) => hono_types.MiddlewareHandler<any, string, {}>;
12
+ }): hono_types.MiddlewareHandler<any, string, {}>;
13
13
 
14
14
  type SubgraphMetaBlock = {
15
15
  /** Block number */
@@ -87,6 +87,4 @@ interface BuildGraphQLSchemaOptions {
87
87
  }
88
88
  declare function buildGraphQLSchema({ schema: _schema, polymorphicConfig: _polymorphicConfig, metadataProvider, }: BuildGraphQLSchemaOptions): GraphQLSchema;
89
89
 
90
- declare const capitalize: (str: string) => string;
91
-
92
- export { type PonderMetadataProvider, type SubgraphMetaBlock, buildGraphQLSchema, capitalize, graphql };
90
+ export { type PonderMetadataProvider, type SubgraphMetaBlock, buildGraphQLSchema, subgraphGraphQLMiddleware };
package/dist/index.js CHANGED
@@ -39,7 +39,6 @@ import {
39
39
  } from "drizzle-orm";
40
40
  import { toSnakeCase } from "drizzle-orm/casing";
41
41
  import {
42
- PgDialect,
43
42
  PgEnumColumn,
44
43
  PgInteger,
45
44
  PgSerial,
@@ -577,7 +576,7 @@ async function executePluralQuery(table, from, drizzle, args, extraConditions =
577
576
  const isSlowQuery = queryDurationSeconds > 2;
578
577
  if (isSlowQuery) {
579
578
  console.warn(`Slow Query Detected (${queryDurationSeconds.toFixed(4)}s)`);
580
- console.warn(new PgDialect().sqlToQuery(query.getSQL()).sql);
579
+ console.warn(query.toSQL().sql);
581
580
  console.log("\n");
582
581
  }
583
582
  return rows;
@@ -887,8 +886,8 @@ function getForeignKeyFieldName(table, parentTypeName) {
887
886
  }
888
887
 
889
888
  // src/middleware.ts
890
- var graphql = ({
891
- db,
889
+ function subgraphGraphQLMiddleware({
890
+ drizzle,
892
891
  graphqlSchema
893
892
  }, {
894
893
  maxOperationTokens = 1e3,
@@ -900,14 +899,14 @@ var graphql = ({
900
899
  maxOperationTokens: 1e3,
901
900
  maxOperationDepth: 100,
902
901
  maxOperationAliases: 30
903
- }) => {
902
+ }) {
904
903
  const yoga = createYoga({
905
904
  graphqlEndpoint: "*",
906
905
  // Disable built-in route validation, use Hono routing instead
907
906
  schema: graphqlSchema,
908
907
  context: () => {
909
- const getDataLoader = buildDataLoaderCache({ drizzle: db });
910
- return { drizzle: db, getDataLoader };
908
+ const getDataLoader = buildDataLoaderCache({ drizzle });
909
+ return { drizzle, getDataLoader };
911
910
  },
912
911
  maskedErrors: process.env.NODE_ENV === "production" ? true : {
913
912
  maskError(error) {
@@ -930,10 +929,9 @@ var graphql = ({
930
929
  response.statusText = "OK";
931
930
  return response;
932
931
  });
933
- };
932
+ }
934
933
  export {
935
934
  buildGraphQLSchema,
936
- capitalize,
937
- graphql
935
+ subgraphGraphQLMiddleware
938
936
  };
939
937
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/middleware.ts","../src/graphql.ts","../src/helpers.ts","../src/serialize.ts"],"sourcesContent":["/**\n * This is ponder's graphql/middleware.ts with the following changes:\n * 0. removes internal typings\n * 1. removed ponder's GraphiQL, enabled graphql-yoga's GraphiQL.\n * 2. builds our custom subgraph-compatible schema instead of ponder's\n * 3. removes schema.graphql generation\n * 4. emits stack traces to console.log\n */\n\nimport { maxAliasesPlugin } from \"@escape.tech/graphql-armor-max-aliases\";\nimport { maxDepthPlugin } from \"@escape.tech/graphql-armor-max-depth\";\nimport { maxTokensPlugin } from \"@escape.tech/graphql-armor-max-tokens\";\nimport type { GraphQLSchema } from \"graphql\";\nimport { createYoga } from \"graphql-yoga\";\nimport { createMiddleware } from \"hono/factory\";\nimport { buildDataLoaderCache } from \"./graphql\";\n\nexport const graphql = (\n {\n db,\n graphqlSchema,\n }: {\n db: any;\n graphqlSchema: GraphQLSchema;\n },\n {\n maxOperationTokens = 1000,\n maxOperationDepth = 100,\n maxOperationAliases = 30,\n }: {\n maxOperationTokens?: number;\n maxOperationDepth?: number;\n maxOperationAliases?: number;\n } = {\n // Default limits are from Apollo:\n // https://www.apollographql.com/blog/prevent-graph-misuse-with-operation-size-and-complexity-limit\n maxOperationTokens: 1000,\n maxOperationDepth: 100,\n maxOperationAliases: 30,\n },\n) => {\n const yoga = createYoga({\n graphqlEndpoint: \"*\", // Disable built-in route validation, use Hono routing instead\n schema: graphqlSchema,\n context: () => {\n const getDataLoader = buildDataLoaderCache({ drizzle: db });\n\n return { drizzle: db, getDataLoader };\n },\n maskedErrors:\n process.env.NODE_ENV === \"production\"\n ? true\n : {\n maskError(error: any) {\n console.error(error.originalError);\n return error;\n },\n },\n logging: false,\n graphiql: true,\n parserAndValidationCache: false,\n plugins: [\n maxTokensPlugin({ n: maxOperationTokens }),\n maxDepthPlugin({ n: maxOperationDepth, ignoreIntrospection: false }),\n maxAliasesPlugin({ n: maxOperationAliases, allowList: [] }),\n ],\n });\n\n return createMiddleware(async (c) => {\n const response = await yoga.handle(c.req.raw);\n // TODO: Figure out why Yoga is returning 500 status codes for GraphQL errors.\n // @ts-expect-error\n response.status = 200;\n // @ts-expect-error\n response.statusText = \"OK\";\n\n return response;\n });\n};\n","/**\n * This is a graphql schema generated from a drizzle (sql) schema, initially based on ponder's.\n * https://github.com/ponder-sh/ponder/blob/main/packages/core/src/graphql/index.ts\n *\n * Its goal is to mimic the subgraph graphql api for queries we've deemed relevant (see docs).\n *\n * 1. inlines some ponder internal types\n * 2. implement subgraph's simpler offset pagination with first & skip w/out Page types\n * 3. PascalCase entity names\n * 4. Polymorphic Interfaces\n * 5. lower-case and/or filters\n * 6. relation id shorthand filters (i.e. domains(where: { owner_id: String }))\n * 7. sortable id columns\n * 8. temporarily ignores column normalization that was fixed in\n * https://github.com/ponder-sh/ponder/pull/1517/files\n */\n\n// here we inline the following types from this original import\n// import type { Drizzle, OnchainTable, Schema } from \"ponder\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport type { PgliteDatabase } from \"drizzle-orm/pglite\";\n\nexport type Drizzle<TSchema extends Schema = { [name: string]: never }> =\n | NodePgDatabase<TSchema>\n | PgliteDatabase<TSchema>;\n\nexport type Schema = { [name: string]: unknown };\n\nexport const onchain = Symbol.for(\"ponder:onchain\");\n\nexport type OnchainTable<\n T extends TableConfig & {\n extra: PgTableExtraConfig | undefined;\n } = TableConfig & { extra: PgTableExtraConfig | undefined },\n> = PgTable<T> & {\n [Key in keyof T[\"columns\"]]: T[\"columns\"][Key];\n} & { [onchain]: true } & {\n enableRLS: () => Omit<OnchainTable<T>, \"enableRLS\">;\n};\n\nimport DataLoader from \"dataloader\";\nimport {\n type Column,\n Many,\n One,\n type SQL,\n Subquery,\n type TableRelationalConfig,\n and,\n arrayContained,\n arrayContains,\n asc,\n createTableRelationsHelpers,\n desc,\n eq,\n extractTablesRelationalConfig,\n getTableColumns,\n getTableUniqueName,\n gt,\n gte,\n inArray,\n is,\n isNotNull,\n isNull,\n like,\n lt,\n lte,\n ne,\n not,\n notInArray,\n notLike,\n or,\n relations,\n sql,\n} from \"drizzle-orm\";\nimport { toSnakeCase } from \"drizzle-orm/casing\";\nimport {\n type PgColumnBuilderBase,\n PgDialect,\n type PgEnum,\n PgEnumColumn,\n PgInteger,\n PgSerial,\n PgTable,\n PgTableExtraConfig,\n TableConfig,\n isPgEnum,\n pgTable,\n} from \"drizzle-orm/pg-core\";\nimport { PgViewBase } from \"drizzle-orm/pg-core/view-base\";\nimport { Relation } from \"drizzle-orm/relations\";\nimport {\n GraphQLBoolean,\n GraphQLEnumType,\n type GraphQLEnumValueConfigMap,\n type GraphQLFieldConfig,\n type GraphQLFieldConfigMap,\n GraphQLFloat,\n type GraphQLInputFieldConfigMap,\n GraphQLInputObjectType,\n type GraphQLInputType,\n GraphQLInt,\n GraphQLInterfaceType,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n type GraphQLOutputType,\n GraphQLScalarType,\n GraphQLSchema,\n GraphQLString,\n} from \"graphql\";\nimport { GraphQLJSON } from \"graphql-scalars\";\n\nimport { capitalize, intersectionOf } from \"./helpers\";\nimport { deserialize, serialize } from \"./serialize\";\nimport type { PonderMetadataProvider } from \"./types\";\n\ntype Parent = Record<string, any>;\ntype Context = {\n getDataLoader: ReturnType<typeof buildDataLoaderCache>;\n drizzle: Drizzle<{ [key: string]: OnchainTable }>;\n};\n\n// NOTE: subgraph-style pagination\ntype PluralArgs = {\n where?: { [key: string]: number | string };\n first?: number;\n skip?: number;\n orderBy?: string;\n orderDirection?: \"asc\" | \"desc\";\n};\n\n// NOTE: subgraph defaults to 100 entities in a plural\nconst DEFAULT_LIMIT = 100 as const;\n// NOTE: subgraph also has a max of 1000 entities in a plural\nconst MAX_LIMIT = 1000 as const;\n\n// subgraph uses an OrderDirection Enum rather than string union\nconst OrderDirectionEnum = new GraphQLEnumType({\n name: \"OrderDirection\",\n values: {\n asc: { value: \"asc\" },\n desc: { value: \"desc\" },\n },\n});\n\n/**\n * the following type describes:\n * 1. `types` — mapping a polymorphic type name to the set of entities that implement that interface\n * ex: DomainEvent -> [TransferEvent, ...]\n * 2. `fields` — mapping a typeName to the polymorphic type it represents\n * ex: Domain.events -> DomainEvent\n *\n * NOTE: in future implementations of ponder, this information could be provided by the schema\n * using materialized views, and most/all of this code can be removed.\n */\nexport interface PolymorphicConfig {\n types: Record<string, PgTable<TableConfig>[]>;\n fields: Record<string, string>;\n}\n\ninterface BuildGraphQLSchemaOptions {\n schema: Schema;\n polymorphicConfig?: PolymorphicConfig;\n metadataProvider: PonderMetadataProvider;\n}\n\nexport function buildGraphQLSchema({\n schema: _schema,\n polymorphicConfig: _polymorphicConfig,\n metadataProvider,\n}: BuildGraphQLSchemaOptions): GraphQLSchema {\n const polymorphicConfig = _polymorphicConfig ?? { types: {}, fields: {} };\n\n // copy schema to avoid injecting `intersection_table`s into ponder's schema object\n const schema: Schema = { ..._schema };\n\n // first, construct TablesRelationConfig with the existing schema. this is necessary because\n // we need access to relations by table, which this helper resolves\n const _tablesConfig = extractTablesRelationalConfig(schema, createTableRelationsHelpers);\n\n // next, remap polymorphicConfig.types to interfaceTypeName -> implementing TableRelationalConfig[]\n const polymorphicTableConfigs = Object.fromEntries(\n Object.entries(polymorphicConfig.types).map(([interfaceTypeName, implementingTables]) => [\n interfaceTypeName,\n implementingTables\n .map((table) => getTableUniqueName(table))\n .map((tableName) => _tablesConfig.tables[_tablesConfig.tableNamesMap[tableName]!]!),\n ]),\n );\n\n // use this TablesRelationalConfig to generate the intersection table & relationships\n // and inject our 'fake' intersection tables into the schema so filters and orderBy entities are\n // auto generated as normal.\n Object.assign(\n schema,\n ...Object.keys(polymorphicConfig.types).map((interfaceTypeName) =>\n getIntersectionTableSchema(interfaceTypeName, polymorphicTableConfigs[interfaceTypeName]!),\n ),\n );\n\n // restructure `Type.fieldName` into `[Type, fieldName]` for simpler logic later\n const polymorphicFields = Object.entries(polymorphicConfig.fields)\n // split fieldPath into segments\n .map<[[string, string], string]>(([fieldPath, interfaceTypeName]) => [\n fieldPath.split(\".\") as [string, string],\n interfaceTypeName,\n ]);\n\n const tablesConfig = extractTablesRelationalConfig(schema, createTableRelationsHelpers);\n const tables = Object.values(tablesConfig.tables) as TableRelationalConfig[];\n\n const enums = Object.entries(schema).filter((el): el is [string, PgEnum<[string, ...string[]]>] =>\n isPgEnum(el[1]),\n );\n const enumTypes: Record<string, GraphQLEnumType> = {};\n for (const [enumTsName, enumObject] of enums) {\n // Note that this is keyed by enumName (the SQL name) because that's what is\n // available on the PgEnumColumn type. See `columnToGraphQLCore` for context.\n enumTypes[enumObject.enumName] = new GraphQLEnumType({\n name: enumTsName,\n values: enumObject.enumValues.reduce(\n (acc: Record<string, {}>, cur) => ({ ...acc, [cur]: {} }),\n {},\n ),\n });\n }\n\n // construct Entity_orderBy enums\n const entityOrderByEnums: Record<string, GraphQLEnumType> = {};\n for (const table of tables) {\n // Scalar fields\n const values = Object.keys(table.columns).reduce<GraphQLEnumValueConfigMap>(\n (acc, columnName) => ({\n ...acc,\n [columnName]: { value: columnName },\n }),\n {},\n );\n\n // NOTE: if implementing single-level nested OrderBy relationships i.e. orderBy: parent__labelName\n // here is where you'd do it\n\n entityOrderByEnums[table.tsName] = new GraphQLEnumType({\n name: `${getSubgraphEntityName(table.tsName)}_orderBy`,\n values,\n });\n }\n\n const entityFilterTypes: Record<string, GraphQLInputObjectType> = {};\n for (const table of tables) {\n const filterType = new GraphQLInputObjectType({\n name: `${getSubgraphEntityName(table.tsName)}_filter`,\n fields: () => {\n const filterFields: GraphQLInputFieldConfigMap = {\n // Logical operators\n // NOTE: lower case and/or\n and: { type: new GraphQLList(filterType) },\n or: { type: new GraphQLList(filterType) },\n };\n\n for (const [columnName, column] of Object.entries(table.columns)) {\n const type = columnToGraphQLCore(column, enumTypes);\n\n // List fields => universal, plural\n if (type instanceof GraphQLList) {\n const baseType = innerType(type);\n\n conditionSuffixes.universal.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = {\n type: new GraphQLList(baseType),\n };\n });\n\n conditionSuffixes.plural.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = { type: baseType };\n });\n }\n\n // JSON => no filters.\n // Boolean => universal and singular only.\n // All other scalar => universal, singular, numeric OR string depending on type\n if (type instanceof GraphQLScalarType || type instanceof GraphQLEnumType) {\n if (type.name === \"JSON\") continue;\n\n conditionSuffixes.universal.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = {\n type,\n };\n });\n\n conditionSuffixes.singular.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = {\n type: new GraphQLList(type),\n };\n });\n\n if ([\"String\", \"ID\"].includes(type.name)) {\n conditionSuffixes.string.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = {\n type: type,\n };\n });\n\n // NOTE: support lexigraphical gt/lt filters for string ids\n conditionSuffixes.numeric.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = {\n type: type,\n };\n });\n }\n\n if ([\"Int\", \"Float\", \"BigInt\"].includes(type.name)) {\n conditionSuffixes.numeric.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = {\n type: type,\n };\n });\n }\n }\n }\n\n // NOTE: add support for relational filters like Domain_filter's { owner_not: String }\n for (const [relationName, relation] of Object.entries(table.relations)) {\n if (is(relation, One)) {\n // TODO: get the type of the relation's reference column & make this like above\n // NOTE: for now, hardcode that singular relation filters are string ids\n conditionSuffixes.universal.forEach((suffix) => {\n filterFields[`${relation.fieldName}${suffix}`] = {\n type: GraphQLString,\n };\n });\n }\n }\n\n return filterFields;\n },\n });\n entityFilterTypes[table.tsName] = filterType;\n }\n\n const entityTypes: Record<string, GraphQLObjectType<Parent, Context>> = {};\n const interfaceTypes: Record<string, GraphQLInterfaceType> = {};\n const entityPageTypes: Record<string, GraphQLOutputType> = {};\n\n // for each polymorphic interface type name\n for (const interfaceTypeName of Object.keys(polymorphicTableConfigs)) {\n const table = tablesConfig.tables[interfaceTypeName]!;\n\n // construct a GraphQLInterfaceType representing the intersection table\n interfaceTypes[interfaceTypeName] = new GraphQLInterfaceType({\n name: interfaceTypeName,\n fields: () => {\n const fieldConfigMap: GraphQLFieldConfigMap<Parent, Context> = {};\n\n for (const [columnName, column] of Object.entries(table.columns)) {\n const type = columnToGraphQLCore(column, enumTypes);\n fieldConfigMap[columnName] = {\n type: column.notNull ? new GraphQLNonNull(type) : type,\n };\n }\n\n return fieldConfigMap;\n },\n });\n }\n\n // construct object type for each entity\n for (const table of tables) {\n // don't make entityTypes for our fake intersection tables\n if (isInterfaceType(polymorphicConfig, table.tsName)) continue;\n\n const entityTypeName = getSubgraphEntityName(table.tsName);\n entityTypes[table.tsName] = new GraphQLObjectType({\n name: entityTypeName,\n interfaces: Object.entries(polymorphicTableConfigs)\n // if this entity implements an interface...\n .filter(([, implementingTables]) =>\n implementingTables.map((table) => table.tsName).includes(table.tsName),\n )\n // include the interfaceType here\n .map(([interfaceTypeName]) => interfaceTypes[interfaceTypeName]!),\n fields: () => {\n const fieldConfigMap: GraphQLFieldConfigMap<Parent, Context> = {};\n\n // Scalar fields\n for (const [columnName, column] of Object.entries(table.columns)) {\n const type = columnToGraphQLCore(column, enumTypes);\n fieldConfigMap[columnName] = {\n type: column.notNull ? new GraphQLNonNull(type) : type,\n };\n }\n\n // Relations\n const relations = Object.entries(table.relations);\n for (const [relationName, relation] of relations) {\n const referencedTable = tables.find(\n (table) => table.dbName === relation.referencedTableName,\n );\n if (!referencedTable)\n throw new Error(\n `Internal error: Referenced table \"${relation.referencedTableName}\" not found`,\n );\n\n const referencedEntityType = entityTypes[referencedTable.tsName];\n const referencedEntityPageType = entityPageTypes[referencedTable.tsName];\n const referencedEntityFilterType = entityFilterTypes[referencedTable.tsName];\n if (\n referencedEntityType === undefined ||\n referencedEntityPageType === undefined ||\n referencedEntityFilterType === undefined\n )\n throw new Error(\n `Internal error: Referenced entity types not found for table \"${referencedTable.tsName}\" `,\n );\n\n if (is(relation, One)) {\n const fields = relation.config?.fields ?? [];\n const references = relation.config?.references ?? [];\n\n if (fields.length !== references.length) {\n throw new Error(\n \"Internal error: Fields and references arrays must be the same length\",\n );\n }\n\n fieldConfigMap[relationName] = {\n // Note: There is a `relation.isNullable` field here but it appears\n // to be internal / incorrect. Until we have support for foriegn\n // key constraints, all `one` relations must be nullable.\n type: referencedEntityType,\n resolve: (parent, _args, context) => {\n const loader = context.getDataLoader({ table: referencedTable });\n\n const rowFragment: Record<string, unknown> = {};\n for (let i = 0; i < references.length; i++) {\n const referenceColumn = references[i]!;\n const fieldColumn = fields[i]!;\n\n const fieldColumnTsName = getColumnTsName(fieldColumn);\n const referenceColumnTsName = getColumnTsName(referenceColumn);\n\n rowFragment[referenceColumnTsName] = parent[fieldColumnTsName];\n }\n\n const encodedId = encodeRowFragment(rowFragment);\n return loader.load(encodedId);\n },\n };\n } else if (is(relation, Many)) {\n // Search the relations of the referenced table for the corresponding `one` relation.\n // If \"relationName\" is not provided, use the first `one` relation that references this table.\n let oneRelation: One | undefined;\n\n for (const _relation of Object.values(referencedTable.relations)) {\n if (is(_relation, One) && relation.relationName === _relation.relationName) {\n oneRelation = _relation;\n }\n }\n\n if (oneRelation === undefined) {\n for (const _relation of Object.values(referencedTable.relations)) {\n if (is(_relation, One) && table.dbName === _relation.referencedTableName) {\n oneRelation = _relation;\n }\n }\n }\n\n if (oneRelation === undefined)\n throw new Error(\n `Internal error: Relation \"${relationName}\" not found in table \"${referencedTable.tsName}\"`,\n );\n\n const fields = oneRelation.config?.fields ?? [];\n const references = oneRelation.config?.references ?? [];\n\n const referencedEntityOrderByType = entityOrderByEnums[referencedTable.tsName];\n if (!referencedEntityOrderByType)\n throw new Error(`Entity_orderBy Enum not found for ${referencedTable.tsName}`);\n\n fieldConfigMap[relationName] = {\n type: referencedEntityPageType,\n args: {\n where: { type: referencedEntityFilterType },\n orderBy: { type: referencedEntityOrderByType },\n orderDirection: { type: OrderDirectionEnum },\n first: { type: GraphQLInt },\n skip: { type: GraphQLInt },\n },\n resolve: (parent, args: PluralArgs, context, info) => {\n const relationalConditions = [] as (SQL | undefined)[];\n for (let i = 0; i < references.length; i++) {\n const column = fields[i]!;\n const value = parent[references[i]!.name];\n relationalConditions.push(eq(column, value));\n }\n\n return executePluralQuery(\n referencedTable,\n schema[referencedTable.tsName] as PgTable,\n context.drizzle,\n args,\n relationalConditions,\n );\n },\n };\n } else {\n throw new Error(\n `Internal error: Relation \"${relationName}\" is unsupported, expected One or Many`,\n );\n }\n }\n\n // Polymorphic Plural Entity Fields\n // NOTE: overrides any automatic field definitions from the above\n polymorphicFields\n // filter by fields on this type\n .filter(([[parent]]) => parent === entityTypeName)\n // define each polymorphic plural field\n .forEach(([[, fieldName], interfaceTypeName]) => {\n fieldConfigMap[fieldName] = definePolymorphicPluralField({\n schema,\n interfaceType: interfaceTypes[interfaceTypeName]!,\n filterType: entityFilterTypes[interfaceTypeName]!,\n orderByType: entityOrderByEnums[interfaceTypeName]!,\n intersectionTableConfig: tablesConfig.tables[interfaceTypeName]!,\n implementingTableConfigs: polymorphicTableConfigs[interfaceTypeName]!,\n });\n });\n\n return fieldConfigMap;\n },\n });\n\n entityPageTypes[table.tsName] = new GraphQLNonNull(\n new GraphQLList(new GraphQLNonNull(entityTypes[table.tsName]!)),\n );\n }\n\n const queryFields: Record<string, GraphQLFieldConfig<Parent, Context>> = {};\n for (const table of tables) {\n // skip making top level query fields for our fake intersection tables\n if (isInterfaceType(polymorphicConfig, table.tsName)) continue;\n\n const entityType = entityTypes[table.tsName]!;\n const entityPageType = entityPageTypes[table.tsName]!;\n const entityFilterType = entityFilterTypes[table.tsName]!;\n\n const singularFieldName = table.tsName.charAt(0).toLowerCase() + table.tsName.slice(1);\n const pluralFieldName = `${singularFieldName}s`;\n\n queryFields[singularFieldName] = {\n type: entityType,\n // Find the primary key columns and GraphQL core types and include them\n // as arguments to the singular query type.\n args: Object.fromEntries(\n table.primaryKey.map((column) => [\n getColumnTsName(column),\n {\n type: new GraphQLNonNull(columnToGraphQLCore(column, enumTypes) as GraphQLInputType),\n },\n ]),\n ),\n resolve: async (_parent, args, context) => {\n const loader = context.getDataLoader({ table });\n\n // The `args` object here should be a valid `where` argument that\n // uses the `eq` shorthand for each primary key column.\n const encodedId = encodeRowFragment(args);\n return loader.load(encodedId);\n },\n };\n\n const entityOrderByType = entityOrderByEnums[table.tsName];\n if (!entityOrderByType) throw new Error(`Entity_orderBy Enum not found for ${table.tsName}`);\n\n queryFields[pluralFieldName] = {\n type: entityPageType,\n args: {\n where: { type: entityFilterType },\n orderBy: { type: entityOrderByType },\n orderDirection: { type: OrderDirectionEnum },\n first: { type: GraphQLInt },\n skip: { type: GraphQLInt },\n },\n resolve: async (_parent, args: PluralArgs, context, info) => {\n return executePluralQuery(table, schema[table.tsName] as PgTable, context.drizzle, args);\n },\n };\n }\n\n // Polymorphic Plural Query Fields\n // NOTE: overrides any automatic field definitions from the above\n polymorphicFields\n // filter by fieldPaths that have a parent of Query\n .filter(([[parent]]) => parent === \"Query\")\n // build each polymorphic plural field\n .forEach(([[, fieldName], interfaceTypeName]) => {\n queryFields[fieldName] = definePolymorphicPluralField({\n schema,\n interfaceType: interfaceTypes[interfaceTypeName]!,\n filterType: entityFilterTypes[interfaceTypeName]!,\n orderByType: entityOrderByEnums[interfaceTypeName]!,\n intersectionTableConfig: tablesConfig.tables[interfaceTypeName]!,\n implementingTableConfigs: polymorphicTableConfigs[interfaceTypeName]!,\n });\n });\n\n // Subgraph Meta Field\n queryFields._meta = {\n type: new GraphQLObjectType({\n name: \"_Meta_\",\n fields: {\n block: {\n type: new GraphQLNonNull(\n new GraphQLObjectType({\n name: \"_Block_\",\n description: \"Information about a specific block.\",\n fields: {\n hash: { type: GraphQLString },\n number: { type: new GraphQLNonNull(GraphQLInt) },\n timestamp: { type: new GraphQLNonNull(GraphQLInt) },\n parentHash: { type: GraphQLString },\n },\n }),\n ),\n },\n deployment: {\n type: new GraphQLNonNull(GraphQLString),\n description:\n \"An ID representing this instance of ENSNode. It is composed of the ENSNode version (https://github.com/namehash/ensnode/releases) and the Ponder build_id (https://ponder.sh/docs/api-reference/database#instance-lifecycle).\",\n },\n hasIndexingErrors: {\n type: new GraphQLNonNull(GraphQLBoolean),\n description:\n \"If true, ENSIndexer has reported an indexing error and is not actively indexing blocks.\",\n },\n },\n }),\n resolve: async (_source, _args) => {\n try {\n const [lastIndexedBlock, hasIndexingErrors, ponderBuildId] = await Promise.all([\n metadataProvider.getLastIndexedENSRootChainBlock(),\n metadataProvider.hasIndexingErrors(),\n metadataProvider.getPonderBuildId(),\n ]);\n\n return {\n deployment: `${metadataProvider.version}-${ponderBuildId}`,\n hasIndexingErrors,\n block: {\n number: Number(lastIndexedBlock.number),\n timestamp: Number(lastIndexedBlock.timestamp),\n hash: lastIndexedBlock.hash,\n parentHash: lastIndexedBlock.parentHash,\n },\n };\n } catch (error) {\n console.error(\"Cannot build subgraph _Meta_\", error);\n return null;\n }\n },\n };\n\n return new GraphQLSchema({\n // Include these here so they are listed first in the printed schema.\n types: [GraphQLJSON, GraphQLBigInt, GraphQLPageInfo],\n query: new GraphQLObjectType({\n name: \"Query\",\n fields: queryFields,\n }),\n });\n}\n\nconst GraphQLPageInfo = new GraphQLObjectType({\n name: \"PageInfo\",\n fields: {\n hasNextPage: { type: new GraphQLNonNull(GraphQLBoolean) },\n hasPreviousPage: { type: new GraphQLNonNull(GraphQLBoolean) },\n startCursor: { type: GraphQLString },\n endCursor: { type: GraphQLString },\n },\n});\n\nconst GraphQLBigInt = new GraphQLScalarType({\n name: \"BigInt\",\n serialize: (value) => String(value),\n parseValue: (value) => BigInt(value as any),\n parseLiteral: (value) => {\n if (value.kind === \"StringValue\") {\n return BigInt(value.value);\n } else {\n throw new Error(\n `Invalid value kind provided for field of type BigInt: ${value.kind}. Expected: StringValue`,\n );\n }\n },\n});\n\nconst columnToGraphQLCore = (\n column: Column,\n enumTypes: Record<string, GraphQLEnumType>,\n): GraphQLOutputType => {\n if (column.columnType === \"PgEvmBigint\") {\n return GraphQLBigInt;\n }\n\n if (column instanceof PgEnumColumn) {\n if (column.enum === undefined) {\n throw new Error(\n `Internal error: Expected enum column \"${getColumnTsName(column)}\" to have an \"enum\" property`,\n );\n }\n const enumType = enumTypes[column.enum.enumName];\n if (enumType === undefined) {\n throw new Error(\n `Internal error: Expected to find a GraphQL enum named \"${column.enum.enumName}\"`,\n );\n }\n\n return enumType;\n }\n\n switch (column.dataType) {\n case \"boolean\":\n return GraphQLBoolean;\n case \"json\":\n return GraphQLJSON;\n case \"date\":\n return GraphQLString;\n case \"string\":\n return GraphQLString;\n case \"bigint\":\n return GraphQLString;\n case \"number\":\n return is(column, PgInteger) || is(column, PgSerial) ? GraphQLInt : GraphQLFloat;\n case \"buffer\":\n return new GraphQLList(new GraphQLNonNull(GraphQLInt));\n case \"array\": {\n if (column.columnType === \"PgVector\") {\n return new GraphQLList(new GraphQLNonNull(GraphQLFloat));\n }\n\n if (column.columnType === \"PgGeometry\") {\n return new GraphQLList(new GraphQLNonNull(GraphQLFloat));\n }\n\n const innerType = columnToGraphQLCore((column as any).baseColumn, enumTypes);\n\n return new GraphQLList(new GraphQLNonNull(innerType));\n }\n default:\n throw new Error(`Type ${column.dataType} is not implemented`);\n }\n};\n\nconst innerType = (type: GraphQLOutputType): GraphQLScalarType | GraphQLEnumType => {\n if (type instanceof GraphQLScalarType || type instanceof GraphQLEnumType) return type;\n if (type instanceof GraphQLList || type instanceof GraphQLNonNull) return innerType(type.ofType);\n throw new Error(`Type ${type.toString()} is not implemented`);\n};\n\nasync function executePluralQuery(\n table: TableRelationalConfig,\n from: PgTable | Subquery | PgViewBase | SQL,\n drizzle: Drizzle<any>,\n args: PluralArgs,\n extraConditions: (SQL | undefined)[] = [],\n) {\n const limit = args.first ?? DEFAULT_LIMIT;\n if (limit > MAX_LIMIT) {\n throw new Error(`Invalid limit. Got ${limit}, expected <=${MAX_LIMIT}.`);\n }\n\n const skip = args.skip ?? 0;\n\n const orderBySchema = buildOrderBySchema(table, args);\n const orderBy = orderBySchema.map(([columnName, direction]) => {\n const column = table.columns[columnName];\n if (column === undefined) {\n throw new Error(`Unknown column \"${columnName}\" used in orderBy argument`);\n }\n\n return direction === \"asc\" ? asc(column) : desc(column);\n });\n\n const whereConditions = buildWhereConditions(args.where, table);\n\n const query = drizzle\n .select()\n .from(from)\n .where(and(...whereConditions, ...extraConditions))\n .orderBy(...orderBy)\n .limit(limit)\n .offset(skip);\n\n const startTime = performance.now();\n\n // actually execute the query\n const rows = await query;\n\n const queryDurationSeconds = (performance.now() - startTime) / 1000;\n const isSlowQuery = queryDurationSeconds > 2;\n if (isSlowQuery) {\n console.warn(`Slow Query Detected (${queryDurationSeconds.toFixed(4)}s)`);\n console.warn(new PgDialect().sqlToQuery(query.getSQL()).sql);\n console.log(\"\\n\");\n }\n\n return rows;\n}\n\nconst conditionSuffixes = {\n universal: [\"\", \"_not\"],\n singular: [\"_in\", \"_not_in\"],\n plural: [\"_has\", \"_not_has\"],\n numeric: [\"_gt\", \"_lt\", \"_gte\", \"_lte\"],\n string: [\n \"_contains\",\n \"_not_contains\",\n \"_starts_with\",\n \"_ends_with\",\n \"_not_starts_with\",\n \"_not_ends_with\",\n ],\n} as const;\n\nconst conditionSuffixesByLengthDesc = Object.values(conditionSuffixes)\n .flat()\n .sort((a, b) => b.length - a.length);\n\nfunction buildWhereConditions(\n where: Record<string, any> | undefined,\n table: TableRelationalConfig,\n): (SQL | undefined)[] {\n const conditions: (SQL | undefined)[] = [];\n\n if (where === undefined) return conditions;\n\n for (const [whereKey, rawValue] of Object.entries(where)) {\n // Handle the `AND` and `OR` operators\n if (whereKey === \"and\" || whereKey === \"or\") {\n if (!Array.isArray(rawValue)) {\n throw new Error(\n `Invalid query: Expected an array for the ${whereKey} operator. Got: ${rawValue}`,\n );\n }\n\n const nestedConditions = rawValue.flatMap((subWhere) =>\n buildWhereConditions(subWhere, table),\n );\n\n if (nestedConditions.length > 0) {\n conditions.push(whereKey === \"and\" ? and(...nestedConditions) : or(...nestedConditions));\n }\n continue;\n }\n\n // Search for a valid filter suffix, traversing the list from longest to shortest\n // to avoid ambiguity between cases like `_not_in` and `_in`.\n const conditionSuffix = conditionSuffixesByLengthDesc.find((s) => whereKey.endsWith(s));\n if (conditionSuffix === undefined) {\n throw new Error(`Invariant violation: Condition suffix not found for where key ${whereKey}`);\n }\n\n // Remove the condition suffix and use the remaining string as the column name.\n const columnName = whereKey.slice(0, whereKey.length - conditionSuffix.length);\n\n const column =\n columnName in table.relations\n ? // if the referenced name is a relation, the relevant column is this table's `${relationName}Id`\n table.columns[`${columnName}Id`]\n : // otherwise validate that the column name is present in the table\n table.columns[columnName];\n\n if (column === undefined) {\n throw new Error(`Invalid query: Where clause contains unknown column ${columnName}`);\n }\n\n switch (conditionSuffix) {\n case \"\":\n if (column.columnType === \"PgArray\") {\n conditions.push(and(arrayContains(column, rawValue), arrayContained(column, rawValue)));\n } else {\n if (rawValue === null) {\n conditions.push(isNull(column));\n } else {\n conditions.push(eq(column, rawValue));\n }\n }\n break;\n case \"_not\":\n if (column.columnType === \"PgArray\") {\n conditions.push(\n not(and(arrayContains(column, rawValue), arrayContained(column, rawValue))!),\n );\n } else {\n if (rawValue === null) {\n conditions.push(isNotNull(column));\n } else {\n conditions.push(ne(column, rawValue));\n }\n }\n break;\n case \"_in\":\n conditions.push(inArray(column, rawValue));\n break;\n case \"_not_in\":\n conditions.push(notInArray(column, rawValue));\n break;\n case \"_has\":\n conditions.push(arrayContains(column, [rawValue]));\n break;\n case \"_not_has\":\n conditions.push(not(arrayContains(column, [rawValue])));\n break;\n case \"_gt\":\n conditions.push(gt(column, rawValue));\n break;\n case \"_lt\":\n conditions.push(lt(column, rawValue));\n break;\n case \"_gte\":\n conditions.push(gte(column, rawValue));\n break;\n case \"_lte\":\n conditions.push(lte(column, rawValue));\n break;\n case \"_contains\":\n conditions.push(like(column, `%${rawValue}%`));\n break;\n case \"_not_contains\":\n conditions.push(notLike(column, `%${rawValue}%`));\n break;\n case \"_starts_with\":\n conditions.push(like(column, `${rawValue}%`));\n break;\n case \"_ends_with\":\n conditions.push(like(column, `%${rawValue}`));\n break;\n case \"_not_starts_with\":\n conditions.push(notLike(column, `${rawValue}%`));\n break;\n case \"_not_ends_with\":\n conditions.push(notLike(column, `%${rawValue}`));\n break;\n default:\n throw new Error(`Invalid Condition Suffix ${conditionSuffix}`);\n }\n }\n\n return conditions;\n}\n\nfunction buildOrderBySchema(table: TableRelationalConfig, args: PluralArgs) {\n // If the user-provided order by does not include the ALL of the ID columns,\n // add any missing ID columns to the end of the order by clause (asc).\n // This ensures a consistent sort order to unblock cursor pagination.\n const userDirection = args.orderDirection ?? \"asc\";\n const userColumns: [string, \"asc\" | \"desc\"][] =\n args.orderBy !== undefined ? [[args.orderBy, userDirection]] : [];\n const pkColumns = table.primaryKey.map((column) => [getColumnTsName(column), userDirection]);\n const missingPkColumns = pkColumns.filter(\n (pkColumn) => !userColumns.some((userColumn) => userColumn[0] === pkColumn[0]),\n ) as [string, \"asc\" | \"desc\"][];\n return [...userColumns, ...missingPkColumns];\n}\n\nexport function buildDataLoaderCache({ drizzle }: { drizzle: Drizzle<Schema> }) {\n const dataLoaderMap = new Map<TableRelationalConfig, DataLoader<string, any> | undefined>();\n return ({ table }: { table: TableRelationalConfig }) => {\n const baseQuery = (drizzle as Drizzle<{ [key: string]: OnchainTable }>).query[table.tsName];\n if (baseQuery === undefined)\n throw new Error(`Internal error: Unknown table \"${table.tsName}\" in data loader cache`);\n\n let dataLoader = dataLoaderMap.get(table);\n if (dataLoader === undefined) {\n dataLoader = new DataLoader(\n async (encodedIds) => {\n const decodedRowFragments = encodedIds.map(decodeRowFragment);\n\n // The decoded row fragments should be valid `where` objects\n // which use the `eq` object shorthand for each primary key column.\n const idConditions = decodedRowFragments.map((decodedRowFragment) =>\n and(...buildWhereConditions(decodedRowFragment, table)),\n );\n\n const rows = await baseQuery.findMany({\n where: or(...idConditions),\n limit: encodedIds.length,\n });\n\n // Now, we need to order the rows coming out of the database to match\n // the order of the IDs passed in. To accomplish this, we need to do\n // a comparison of the decoded row PK fragments with the database rows.\n // This is tricky because the decoded row PK fragments are not normalized,\n // so some comparisons will fail (eg for our PgHex column type).\n // To fix this, we need to normalize the values before doing the comparison.\n return (\n decodedRowFragments\n // Normalize the decoded row fragments\n // .map((fragment) =>\n // Object.fromEntries(\n // Object.entries(fragment).map(([col, val]) => {\n // const column = table.columns[col];\n // if (column === undefined) {\n // throw new Error(\n // `Unknown column '${table.tsName}.${col}' used in dataloader row ID fragment`,\n // );\n // }\n // return [col, normalizeColumn(column, val, false)];\n // }),\n // ),\n // )\n // Find the database row corresponding to each normalized row fragment\n .map((fragment) =>\n rows.find((row) =>\n Object.entries(fragment).every(([col, val]) => row[col] === val),\n ),\n )\n );\n },\n { maxBatchSize: 1_000 },\n );\n dataLoaderMap.set(table, dataLoader);\n }\n\n return dataLoader;\n };\n}\n\nfunction getColumnTsName(column: Column) {\n const tableColumns = getTableColumns(column.table);\n return Object.entries(tableColumns).find(([_, c]) => c.name === column.name)![0];\n}\n\nfunction encodeRowFragment(rowFragment: { [k: string]: unknown }): string {\n return Buffer.from(serialize(rowFragment)).toString(\"base64\");\n}\n\nfunction decodeRowFragment(encodedRowFragment: string): {\n [k: string]: unknown;\n} {\n return deserialize(Buffer.from(encodedRowFragment, \"base64\").toString());\n}\n\n// the subgraph's GraphQL types are just the capitalized version of ponder's tsName\nfunction getSubgraphEntityName(tsName: string) {\n return capitalize(tsName);\n}\n\nfunction isInterfaceType(polymorphicConfig: PolymorphicConfig, columnName: string) {\n return columnName in polymorphicConfig.types;\n}\n\n// defines a table and relations that is the intersection of the provided `tableConfigs`\nfunction getIntersectionTableSchema(\n interfaceTypeName: string,\n tableConfigs: TableRelationalConfig[],\n) {\n if (tableConfigs.length === 0) throw new Error(\"Must have some tables to intersect\");\n\n const baseColumns = tableConfigs[0]!.columns;\n const baseRelations = tableConfigs[0]!.relations;\n\n // compute the common columnNames\n const commonColumnNames = intersectionOf(\n tableConfigs.map((table) => Object.keys(table.columns)), //\n );\n\n // compute the common relationshipNames\n const commonRelationsNames = intersectionOf(\n tableConfigs.map((table) => Object.keys(table.relations)),\n );\n\n // define a pgTable by cloning the common columns w/ builder functions\n // TODO: can we more easily clone theses instead of using builder fns? Object.assign?\n // NOTE: it's important that this table's dbName is intersection_table, as that is what the\n // UNION ALL subquery is aliased to later\n // TODO: can we use drizzle's .with or something to avoid the magic string?\n const intersectionTable = pgTable(\"intersection_table\", (t) =>\n commonColumnNames.reduce<Record<string, PgColumnBuilderBase>>((memo, columnName) => {\n const column = baseColumns[columnName]!;\n const sqlType = column.getSQLType();\n const snakeCaseColumnName = toSnakeCase(column.name);\n\n let newColumn: any =\n sqlType === \"numeric(78)\"\n ? // special case for bigint whose sqltype is \"numeric(78)\"\n t.numeric(snakeCaseColumnName, { precision: 78 })\n : // handle standard types, removing any parameters from the SQLType\n // @ts-expect-error we know the key is valid and this is callable\n t[sqlType.split(\"(\")[0]! as keyof typeof t](snakeCaseColumnName);\n\n // include .primaryKey if necessary\n newColumn = column.primary ? newColumn.primaryKey() : newColumn;\n\n // include notNull\n newColumn = newColumn.notNull(column.notNull);\n\n memo[columnName] = newColumn;\n return memo;\n }, {}),\n );\n\n // define the relationships for this table by cloning the common relationships\n const intersectionTableRelations = relations(intersectionTable, ({ one }) =>\n commonRelationsNames.reduce<Record<string, Relation<any>>>((memo, relationName) => {\n const relation = baseRelations[relationName];\n\n if (is(relation, One)) {\n memo[relationName] = one(relation.referencedTable, relation.config as any);\n } else if (is(relation, Many)) {\n // NOTE: unimplemented — only One relations are necessary for relationalConditions later\n }\n\n return memo;\n }, {}),\n );\n\n return {\n [interfaceTypeName]: intersectionTable,\n [`${interfaceTypeName}Relations`]: intersectionTableRelations,\n };\n}\n\n// produces Record<string, Column> that is the union of all columns in tables\nfunction getColumnsUnion(tables: TableRelationalConfig[]): Record<string, Column> {\n return tables.reduce(\n (memo, table) => ({\n ...memo,\n ...table.columns,\n }),\n {},\n );\n}\n\n// builds a drizzle subquery from the set of provided tables with given `where` filter\nfunction buildUnionAllQuery(\n drizzle: Drizzle<{ [key: string]: OnchainTable }>,\n schema: Schema,\n tables: TableRelationalConfig[],\n where: Record<string, unknown> = {},\n) {\n const allColumns = getColumnsUnion(tables);\n const allColumnNames = Object.keys(allColumns).sort();\n\n // builds a subquery per-table like `SELECT columns... from :table (WHERE fk = fkv)`\n const subqueries = tables.map((table) => {\n // NOTE: every subquery of union must have the same columns of the same types so we\n // build select object with nulls for missing columns, manually casting them to the correct type\n const selectAllColumnsIncludingNulls = allColumnNames.reduce((memo, columnName) => {\n const column = allColumns[columnName]!;\n const snakeCaseColumnName = toSnakeCase(column.name);\n const dbColumnName = table.columns[columnName] ? snakeCaseColumnName : \"NULL\";\n\n return {\n ...memo,\n [columnName]: sql.raw(`${dbColumnName}::${column.getSQLType()}`).as(snakeCaseColumnName),\n };\n }, {});\n\n // apply the relation filter at subquery level to minimize merged data\n // NOTE: that we use this table's Column so the generated sql references the correct table\n const relationalConditions: SQL[] = Object.entries(where).map(\n ([foreignKeyName, foreignKeyValue]) => eq(table.columns[foreignKeyName]!, foreignKeyValue),\n );\n\n return drizzle\n .select({\n ...selectAllColumnsIncludingNulls,\n // inject __typename into each subquery\n __typename: sql.raw(`'${getSubgraphEntityName(table.tsName)}'`).as(\"__typename\"),\n })\n .from(schema[table.tsName] as PgTable)\n .where(and(...relationalConditions))\n .$dynamic();\n });\n\n // joins the subqueries with UNION ALL and aliases it to `intersection_table`\n return subqueries\n .reduce((memo, fragment, i) => (i === 0 ? fragment : memo.unionAll(fragment)))\n .as(\"intersection_table\");\n}\n\n/**\n * creates the GraphQLFieldConfig for a polymorphic plural field\n *\n * @param schema the database schema containing table definitions\n * @param interfaceType the GraphQL interface type for the polymorphic field\n * @param filterType the GraphQL input type for filtering records\n * @param orderByType the GraphQL enum type for ordering records\n * @param intersectionTableConfig the TableConfig representing the intersection\n * of `implementingTableConfigs`\n * @param implementingTableConfigs array of table configs that implement the interface\n */\nfunction definePolymorphicPluralField({\n schema,\n interfaceType,\n filterType,\n orderByType,\n intersectionTableConfig,\n implementingTableConfigs,\n}: {\n schema: Schema;\n interfaceType: GraphQLInterfaceType;\n filterType: GraphQLInputObjectType;\n orderByType: GraphQLEnumType;\n intersectionTableConfig: TableRelationalConfig;\n implementingTableConfigs: TableRelationalConfig[];\n}): GraphQLFieldConfig<Parent, Context> {\n return {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(interfaceType))),\n args: {\n where: { type: filterType },\n orderBy: { type: orderByType },\n orderDirection: { type: OrderDirectionEnum },\n first: { type: GraphQLInt },\n skip: { type: GraphQLInt },\n },\n resolve: async (parent, args: PluralArgs, { drizzle }, info) => {\n // find the relation field that references the parent type\n const foreignKeyName = getForeignKeyFieldName(intersectionTableConfig, info.parentType.name);\n\n // include it in the relationalFilter iff necessary\n const relationalFilter = foreignKeyName ? { [foreignKeyName]: parent.id } : {};\n\n // construct a UNION ALL subquery\n const subquery = buildUnionAllQuery(\n drizzle,\n schema,\n implementingTableConfigs,\n relationalFilter,\n );\n\n // pass it to executePluralQuery as usual\n return executePluralQuery(intersectionTableConfig, subquery, drizzle, args);\n },\n };\n}\n\n// finds the foreign key name in a table that references a given GraphQL parentTypeName\nfunction getForeignKeyFieldName(table: TableRelationalConfig, parentTypeName: string) {\n // 1. find the first relation field that references the parent type name\n const relationName = Object.keys(table.relations).find(\n (relationName) => getSubgraphEntityName(relationName) === parentTypeName,\n );\n if (!relationName) return;\n\n // ignore if this isn't a One relation\n const relation = table.relations[relationName];\n if (!is(relation, One)) return;\n\n // 2. find the columnName of the correct column\n const fkEntry = Object.entries(relation.config?.fields?.[0]?.table ?? {}).find(\n ([_, column]) => column.name === relation.config?.fields?.[0]?.name,\n );\n\n // 3. columnName is the name of the foreign key column in `table`\n return fkEntry?.[0];\n}\n","// https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore?tab=readme-ov-file#_intersection\nexport const intersectionOf = <T>(arrays: T[][]) =>\n arrays.reduce((a, b) => a.filter((c) => b.includes(c)));\n\nexport const capitalize = (str: string): string => {\n if (!str) return str;\n return `${str.charAt(0).toUpperCase()}${str.slice(1)}`;\n};\n","// https://github.com/ponder-sh/ponder/blob/main/packages/core/src/utils/serialize.ts\n\n/**\n * Serialize function that handles BigInt.\n *\n * Forked from https://github.com/wevm/wagmi\n *\n * @param value to stringify\n * @returns the stringified output\n */\nexport function serialize(value: any) {\n return JSON.stringify(value, (_, v) =>\n typeof v === \"bigint\" ? { __type: \"bigint\", value: v.toString() } : v,\n );\n}\n\n/**\n * Deserialize function that handles BigInt.\n *\n * Forked from https://github.com/wevm/wagmi\n *\n * @param value to parse\n * @returns the output object\n */\nexport function deserialize<type>(value: string): type {\n return JSON.parse(value, (_, value_) =>\n value_?.__type === \"bigint\" ? BigInt(value_.value) : value_,\n );\n}\n"],"mappings":";AASA,SAAS,wBAAwB;AACjC,SAAS,sBAAsB;AAC/B,SAAS,uBAAuB;AAEhC,SAAS,kBAAkB;AAC3B,SAAS,wBAAwB;;;AC0BjC,OAAO,gBAAgB;AACvB;AAAA,EAEE;AAAA,EACA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB;AAC5B;AAAA,EAEE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAIA;AAAA,EACA;AAAA,OACK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EAIA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB;;;AC9GrB,IAAM,iBAAiB,CAAI,WAChC,OAAO,OAAO,CAAC,GAAG,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;AAEjD,IAAM,aAAa,CAAC,QAAwB;AACjD,MAAI,CAAC,IAAK,QAAO;AACjB,SAAO,GAAG,IAAI,OAAO,CAAC,EAAE,YAAY,CAAC,GAAG,IAAI,MAAM,CAAC,CAAC;AACtD;;;ACGO,SAAS,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,EAAE,GAAG,qBAAqB,WAAW,CAAC,EAAE,CAAC;AAAA,IAC5D;AAAA,EACF,CAAC;AAED,SAAO,iBAAiB,OAAO,MAAM;AACnC,UAAM,WAAW,MAAM,KAAK,OAAO,EAAE,IAAI,GAAG;AAG5C,aAAS,SAAS;AAElB,aAAS,aAAa;AAEtB,WAAO;AAAA,EACT,CAAC;AACH;","names":["table","relations","innerType","relationName","_a","_b","_c"]}
1
+ {"version":3,"sources":["../src/middleware.ts","../src/graphql.ts","../src/helpers.ts","../src/serialize.ts"],"sourcesContent":["/**\n * This is ponder's graphql/middleware.ts with the following changes:\n * 0. removes internal typings\n * 1. removed ponder's GraphiQL, enabled graphql-yoga's GraphiQL.\n * 2. builds our custom subgraph-compatible schema instead of ponder's\n * 3. removes schema.graphql generation\n * 4. emits stack traces to console.log\n */\n\nimport { maxAliasesPlugin } from \"@escape.tech/graphql-armor-max-aliases\";\nimport { maxDepthPlugin } from \"@escape.tech/graphql-armor-max-depth\";\nimport { maxTokensPlugin } from \"@escape.tech/graphql-armor-max-tokens\";\nimport { GraphQLSchema } from \"graphql\";\nimport { createYoga } from \"graphql-yoga\";\nimport { createMiddleware } from \"hono/factory\";\nimport { buildDataLoaderCache } from \"./graphql\";\n\nexport function subgraphGraphQLMiddleware(\n {\n drizzle,\n graphqlSchema,\n }: {\n drizzle: any;\n graphqlSchema: GraphQLSchema;\n },\n {\n maxOperationTokens = 1000,\n maxOperationDepth = 100,\n maxOperationAliases = 30,\n }: {\n maxOperationTokens?: number;\n maxOperationDepth?: number;\n maxOperationAliases?: number;\n } = {\n // Default limits are from Apollo:\n // https://www.apollographql.com/blog/prevent-graph-misuse-with-operation-size-and-complexity-limit\n maxOperationTokens: 1000,\n maxOperationDepth: 100,\n maxOperationAliases: 30,\n },\n) {\n const yoga = createYoga({\n graphqlEndpoint: \"*\", // Disable built-in route validation, use Hono routing instead\n schema: graphqlSchema,\n context: () => {\n const getDataLoader = buildDataLoaderCache({ drizzle });\n\n return { drizzle, getDataLoader };\n },\n maskedErrors:\n process.env.NODE_ENV === \"production\"\n ? true\n : {\n maskError(error: any) {\n console.error(error.originalError);\n return error;\n },\n },\n logging: false,\n graphiql: true,\n parserAndValidationCache: false,\n plugins: [\n maxTokensPlugin({ n: maxOperationTokens }),\n maxDepthPlugin({ n: maxOperationDepth, ignoreIntrospection: false }),\n maxAliasesPlugin({ n: maxOperationAliases, allowList: [] }),\n ],\n });\n\n return createMiddleware(async (c) => {\n const response = await yoga.handle(c.req.raw);\n // TODO: Figure out why Yoga is returning 500 status codes for GraphQL errors.\n // @ts-expect-error\n response.status = 200;\n // @ts-expect-error\n response.statusText = \"OK\";\n\n return response;\n });\n}\n","/**\n * This is a graphql schema generated from a drizzle (sql) schema, initially based on ponder's.\n * https://github.com/ponder-sh/ponder/blob/main/packages/core/src/graphql/index.ts\n *\n * Its goal is to mimic the subgraph graphql api for queries we've deemed relevant (see docs).\n *\n * 1. inlines some ponder internal types\n * 2. implement subgraph's simpler offset pagination with first & skip w/out Page types\n * 3. PascalCase entity names\n * 4. Polymorphic Interfaces\n * 5. lower-case and/or filters\n * 6. relation id shorthand filters (i.e. domains(where: { owner_id: String }))\n * 7. sortable id columns\n * 8. temporarily ignores column normalization that was fixed in\n * https://github.com/ponder-sh/ponder/pull/1517/files\n */\n\n// here we inline the following types from this original import\n// import type { Drizzle, OnchainTable, Schema } from \"ponder\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport type { PgliteDatabase } from \"drizzle-orm/pglite\";\n\nexport type Drizzle<TSchema extends Schema = { [name: string]: never }> =\n | NodePgDatabase<TSchema>\n | PgliteDatabase<TSchema>;\n\nexport type Schema = { [name: string]: unknown };\n\nexport const onchain = Symbol.for(\"ponder:onchain\");\n\nexport type OnchainTable<\n T extends TableConfig & {\n extra: PgTableExtraConfig | undefined;\n } = TableConfig & { extra: PgTableExtraConfig | undefined },\n> = PgTable<T> & {\n [Key in keyof T[\"columns\"]]: T[\"columns\"][Key];\n} & { [onchain]: true } & {\n enableRLS: () => Omit<OnchainTable<T>, \"enableRLS\">;\n};\n\nimport DataLoader from \"dataloader\";\nimport {\n type Column,\n Many,\n One,\n type SQL,\n Subquery,\n type TableRelationalConfig,\n and,\n arrayContained,\n arrayContains,\n asc,\n createTableRelationsHelpers,\n desc,\n eq,\n extractTablesRelationalConfig,\n getTableColumns,\n getTableUniqueName,\n gt,\n gte,\n inArray,\n is,\n isNotNull,\n isNull,\n like,\n lt,\n lte,\n ne,\n not,\n notInArray,\n notLike,\n or,\n relations,\n sql,\n} from \"drizzle-orm\";\nimport { toSnakeCase } from \"drizzle-orm/casing\";\nimport {\n type PgColumnBuilderBase,\n type PgEnum,\n PgEnumColumn,\n PgInteger,\n PgSerial,\n PgTable,\n PgTableExtraConfig,\n TableConfig,\n isPgEnum,\n pgTable,\n} from \"drizzle-orm/pg-core\";\nimport { PgViewBase } from \"drizzle-orm/pg-core/view-base\";\nimport { Relation } from \"drizzle-orm/relations\";\nimport {\n GraphQLBoolean,\n GraphQLEnumType,\n type GraphQLEnumValueConfigMap,\n type GraphQLFieldConfig,\n type GraphQLFieldConfigMap,\n GraphQLFloat,\n type GraphQLInputFieldConfigMap,\n GraphQLInputObjectType,\n type GraphQLInputType,\n GraphQLInt,\n GraphQLInterfaceType,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n type GraphQLOutputType,\n GraphQLScalarType,\n GraphQLSchema,\n GraphQLString,\n} from \"graphql\";\nimport { GraphQLJSON } from \"graphql-scalars\";\n\nimport { capitalize, intersectionOf } from \"./helpers\";\nimport { deserialize, serialize } from \"./serialize\";\nimport type { PonderMetadataProvider } from \"./types\";\n\ntype Parent = Record<string, any>;\ntype Context = {\n getDataLoader: ReturnType<typeof buildDataLoaderCache>;\n drizzle: Drizzle<{ [key: string]: OnchainTable }>;\n};\n\n// NOTE: subgraph-style pagination\ntype PluralArgs = {\n where?: { [key: string]: number | string };\n first?: number;\n skip?: number;\n orderBy?: string;\n orderDirection?: \"asc\" | \"desc\";\n};\n\n// NOTE: subgraph defaults to 100 entities in a plural\nconst DEFAULT_LIMIT = 100 as const;\n// NOTE: subgraph also has a max of 1000 entities in a plural\nconst MAX_LIMIT = 1000 as const;\n\n// subgraph uses an OrderDirection Enum rather than string union\nconst OrderDirectionEnum = new GraphQLEnumType({\n name: \"OrderDirection\",\n values: {\n asc: { value: \"asc\" },\n desc: { value: \"desc\" },\n },\n});\n\n/**\n * the following type describes:\n * 1. `types` — mapping a polymorphic type name to the set of entities that implement that interface\n * ex: DomainEvent -> [TransferEvent, ...]\n * 2. `fields` — mapping a typeName to the polymorphic type it represents\n * ex: Domain.events -> DomainEvent\n *\n * NOTE: in future implementations of ponder, this information could be provided by the schema\n * using materialized views, and most/all of this code can be removed.\n */\nexport interface PolymorphicConfig {\n types: Record<string, PgTable<TableConfig>[]>;\n fields: Record<string, string>;\n}\n\ninterface BuildGraphQLSchemaOptions {\n schema: Schema;\n polymorphicConfig?: PolymorphicConfig;\n metadataProvider: PonderMetadataProvider;\n}\n\nexport function buildGraphQLSchema({\n schema: _schema,\n polymorphicConfig: _polymorphicConfig,\n metadataProvider,\n}: BuildGraphQLSchemaOptions): GraphQLSchema {\n const polymorphicConfig = _polymorphicConfig ?? { types: {}, fields: {} };\n\n // copy schema to avoid injecting `intersection_table`s into ponder's schema object\n const schema: Schema = { ..._schema };\n\n // first, construct TablesRelationConfig with the existing schema. this is necessary because\n // we need access to relations by table, which this helper resolves\n const _tablesConfig = extractTablesRelationalConfig(schema, createTableRelationsHelpers);\n\n // next, remap polymorphicConfig.types to interfaceTypeName -> implementing TableRelationalConfig[]\n const polymorphicTableConfigs = Object.fromEntries(\n Object.entries(polymorphicConfig.types).map(([interfaceTypeName, implementingTables]) => [\n interfaceTypeName,\n implementingTables\n .map((table) => getTableUniqueName(table))\n .map((tableName) => _tablesConfig.tables[_tablesConfig.tableNamesMap[tableName]!]!),\n ]),\n );\n\n // use this TablesRelationalConfig to generate the intersection table & relationships\n // and inject our 'fake' intersection tables into the schema so filters and orderBy entities are\n // auto generated as normal.\n Object.assign(\n schema,\n ...Object.keys(polymorphicConfig.types).map((interfaceTypeName) =>\n getIntersectionTableSchema(interfaceTypeName, polymorphicTableConfigs[interfaceTypeName]!),\n ),\n );\n\n // restructure `Type.fieldName` into `[Type, fieldName]` for simpler logic later\n const polymorphicFields = Object.entries(polymorphicConfig.fields)\n // split fieldPath into segments\n .map<[[string, string], string]>(([fieldPath, interfaceTypeName]) => [\n fieldPath.split(\".\") as [string, string],\n interfaceTypeName,\n ]);\n\n const tablesConfig = extractTablesRelationalConfig(schema, createTableRelationsHelpers);\n const tables = Object.values(tablesConfig.tables) as TableRelationalConfig[];\n\n const enums = Object.entries(schema).filter((el): el is [string, PgEnum<[string, ...string[]]>] =>\n isPgEnum(el[1]),\n );\n const enumTypes: Record<string, GraphQLEnumType> = {};\n for (const [enumTsName, enumObject] of enums) {\n // Note that this is keyed by enumName (the SQL name) because that's what is\n // available on the PgEnumColumn type. See `columnToGraphQLCore` for context.\n enumTypes[enumObject.enumName] = new GraphQLEnumType({\n name: enumTsName,\n values: enumObject.enumValues.reduce(\n (acc: Record<string, {}>, cur) => ({ ...acc, [cur]: {} }),\n {},\n ),\n });\n }\n\n // construct Entity_orderBy enums\n const entityOrderByEnums: Record<string, GraphQLEnumType> = {};\n for (const table of tables) {\n // Scalar fields\n const values = Object.keys(table.columns).reduce<GraphQLEnumValueConfigMap>(\n (acc, columnName) => ({\n ...acc,\n [columnName]: { value: columnName },\n }),\n {},\n );\n\n // NOTE: if implementing single-level nested OrderBy relationships i.e. orderBy: parent__labelName\n // here is where you'd do it\n\n entityOrderByEnums[table.tsName] = new GraphQLEnumType({\n name: `${getSubgraphEntityName(table.tsName)}_orderBy`,\n values,\n });\n }\n\n const entityFilterTypes: Record<string, GraphQLInputObjectType> = {};\n for (const table of tables) {\n const filterType = new GraphQLInputObjectType({\n name: `${getSubgraphEntityName(table.tsName)}_filter`,\n fields: () => {\n const filterFields: GraphQLInputFieldConfigMap = {\n // Logical operators\n // NOTE: lower case and/or\n and: { type: new GraphQLList(filterType) },\n or: { type: new GraphQLList(filterType) },\n };\n\n for (const [columnName, column] of Object.entries(table.columns)) {\n const type = columnToGraphQLCore(column, enumTypes);\n\n // List fields => universal, plural\n if (type instanceof GraphQLList) {\n const baseType = innerType(type);\n\n conditionSuffixes.universal.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = {\n type: new GraphQLList(baseType),\n };\n });\n\n conditionSuffixes.plural.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = { type: baseType };\n });\n }\n\n // JSON => no filters.\n // Boolean => universal and singular only.\n // All other scalar => universal, singular, numeric OR string depending on type\n if (type instanceof GraphQLScalarType || type instanceof GraphQLEnumType) {\n if (type.name === \"JSON\") continue;\n\n conditionSuffixes.universal.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = {\n type,\n };\n });\n\n conditionSuffixes.singular.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = {\n type: new GraphQLList(type),\n };\n });\n\n if ([\"String\", \"ID\"].includes(type.name)) {\n conditionSuffixes.string.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = {\n type: type,\n };\n });\n\n // NOTE: support lexigraphical gt/lt filters for string ids\n conditionSuffixes.numeric.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = {\n type: type,\n };\n });\n }\n\n if ([\"Int\", \"Float\", \"BigInt\"].includes(type.name)) {\n conditionSuffixes.numeric.forEach((suffix) => {\n filterFields[`${columnName}${suffix}`] = {\n type: type,\n };\n });\n }\n }\n }\n\n // NOTE: add support for relational filters like Domain_filter's { owner_not: String }\n for (const [relationName, relation] of Object.entries(table.relations)) {\n if (is(relation, One)) {\n // TODO: get the type of the relation's reference column & make this like above\n // NOTE: for now, hardcode that singular relation filters are string ids\n conditionSuffixes.universal.forEach((suffix) => {\n filterFields[`${relation.fieldName}${suffix}`] = {\n type: GraphQLString,\n };\n });\n }\n }\n\n return filterFields;\n },\n });\n entityFilterTypes[table.tsName] = filterType;\n }\n\n const entityTypes: Record<string, GraphQLObjectType<Parent, Context>> = {};\n const interfaceTypes: Record<string, GraphQLInterfaceType> = {};\n const entityPageTypes: Record<string, GraphQLOutputType> = {};\n\n // for each polymorphic interface type name\n for (const interfaceTypeName of Object.keys(polymorphicTableConfigs)) {\n const table = tablesConfig.tables[interfaceTypeName]!;\n\n // construct a GraphQLInterfaceType representing the intersection table\n interfaceTypes[interfaceTypeName] = new GraphQLInterfaceType({\n name: interfaceTypeName,\n fields: () => {\n const fieldConfigMap: GraphQLFieldConfigMap<Parent, Context> = {};\n\n for (const [columnName, column] of Object.entries(table.columns)) {\n const type = columnToGraphQLCore(column, enumTypes);\n fieldConfigMap[columnName] = {\n type: column.notNull ? new GraphQLNonNull(type) : type,\n };\n }\n\n return fieldConfigMap;\n },\n });\n }\n\n // construct object type for each entity\n for (const table of tables) {\n // don't make entityTypes for our fake intersection tables\n if (isInterfaceType(polymorphicConfig, table.tsName)) continue;\n\n const entityTypeName = getSubgraphEntityName(table.tsName);\n entityTypes[table.tsName] = new GraphQLObjectType({\n name: entityTypeName,\n interfaces: Object.entries(polymorphicTableConfigs)\n // if this entity implements an interface...\n .filter(([, implementingTables]) =>\n implementingTables.map((table) => table.tsName).includes(table.tsName),\n )\n // include the interfaceType here\n .map(([interfaceTypeName]) => interfaceTypes[interfaceTypeName]!),\n fields: () => {\n const fieldConfigMap: GraphQLFieldConfigMap<Parent, Context> = {};\n\n // Scalar fields\n for (const [columnName, column] of Object.entries(table.columns)) {\n const type = columnToGraphQLCore(column, enumTypes);\n fieldConfigMap[columnName] = {\n type: column.notNull ? new GraphQLNonNull(type) : type,\n };\n }\n\n // Relations\n const relations = Object.entries(table.relations);\n for (const [relationName, relation] of relations) {\n const referencedTable = tables.find(\n (table) => table.dbName === relation.referencedTableName,\n );\n if (!referencedTable)\n throw new Error(\n `Internal error: Referenced table \"${relation.referencedTableName}\" not found`,\n );\n\n const referencedEntityType = entityTypes[referencedTable.tsName];\n const referencedEntityPageType = entityPageTypes[referencedTable.tsName];\n const referencedEntityFilterType = entityFilterTypes[referencedTable.tsName];\n if (\n referencedEntityType === undefined ||\n referencedEntityPageType === undefined ||\n referencedEntityFilterType === undefined\n )\n throw new Error(\n `Internal error: Referenced entity types not found for table \"${referencedTable.tsName}\" `,\n );\n\n if (is(relation, One)) {\n const fields = relation.config?.fields ?? [];\n const references = relation.config?.references ?? [];\n\n if (fields.length !== references.length) {\n throw new Error(\n \"Internal error: Fields and references arrays must be the same length\",\n );\n }\n\n fieldConfigMap[relationName] = {\n // Note: There is a `relation.isNullable` field here but it appears\n // to be internal / incorrect. Until we have support for foriegn\n // key constraints, all `one` relations must be nullable.\n type: referencedEntityType,\n resolve: (parent, _args, context) => {\n const loader = context.getDataLoader({ table: referencedTable });\n\n const rowFragment: Record<string, unknown> = {};\n for (let i = 0; i < references.length; i++) {\n const referenceColumn = references[i]!;\n const fieldColumn = fields[i]!;\n\n const fieldColumnTsName = getColumnTsName(fieldColumn);\n const referenceColumnTsName = getColumnTsName(referenceColumn);\n\n rowFragment[referenceColumnTsName] = parent[fieldColumnTsName];\n }\n\n const encodedId = encodeRowFragment(rowFragment);\n return loader.load(encodedId);\n },\n };\n } else if (is(relation, Many)) {\n // Search the relations of the referenced table for the corresponding `one` relation.\n // If \"relationName\" is not provided, use the first `one` relation that references this table.\n let oneRelation: One | undefined;\n\n for (const _relation of Object.values(referencedTable.relations)) {\n if (is(_relation, One) && relation.relationName === _relation.relationName) {\n oneRelation = _relation;\n }\n }\n\n if (oneRelation === undefined) {\n for (const _relation of Object.values(referencedTable.relations)) {\n if (is(_relation, One) && table.dbName === _relation.referencedTableName) {\n oneRelation = _relation;\n }\n }\n }\n\n if (oneRelation === undefined)\n throw new Error(\n `Internal error: Relation \"${relationName}\" not found in table \"${referencedTable.tsName}\"`,\n );\n\n const fields = oneRelation.config?.fields ?? [];\n const references = oneRelation.config?.references ?? [];\n\n const referencedEntityOrderByType = entityOrderByEnums[referencedTable.tsName];\n if (!referencedEntityOrderByType)\n throw new Error(`Entity_orderBy Enum not found for ${referencedTable.tsName}`);\n\n fieldConfigMap[relationName] = {\n type: referencedEntityPageType,\n args: {\n where: { type: referencedEntityFilterType },\n orderBy: { type: referencedEntityOrderByType },\n orderDirection: { type: OrderDirectionEnum },\n first: { type: GraphQLInt },\n skip: { type: GraphQLInt },\n },\n resolve: (parent, args: PluralArgs, context, info) => {\n const relationalConditions = [] as (SQL | undefined)[];\n for (let i = 0; i < references.length; i++) {\n const column = fields[i]!;\n const value = parent[references[i]!.name];\n relationalConditions.push(eq(column, value));\n }\n\n return executePluralQuery(\n referencedTable,\n schema[referencedTable.tsName] as PgTable,\n context.drizzle,\n args,\n relationalConditions,\n );\n },\n };\n } else {\n throw new Error(\n `Internal error: Relation \"${relationName}\" is unsupported, expected One or Many`,\n );\n }\n }\n\n // Polymorphic Plural Entity Fields\n // NOTE: overrides any automatic field definitions from the above\n polymorphicFields\n // filter by fields on this type\n .filter(([[parent]]) => parent === entityTypeName)\n // define each polymorphic plural field\n .forEach(([[, fieldName], interfaceTypeName]) => {\n fieldConfigMap[fieldName] = definePolymorphicPluralField({\n schema,\n interfaceType: interfaceTypes[interfaceTypeName]!,\n filterType: entityFilterTypes[interfaceTypeName]!,\n orderByType: entityOrderByEnums[interfaceTypeName]!,\n intersectionTableConfig: tablesConfig.tables[interfaceTypeName]!,\n implementingTableConfigs: polymorphicTableConfigs[interfaceTypeName]!,\n });\n });\n\n return fieldConfigMap;\n },\n });\n\n entityPageTypes[table.tsName] = new GraphQLNonNull(\n new GraphQLList(new GraphQLNonNull(entityTypes[table.tsName]!)),\n );\n }\n\n const queryFields: Record<string, GraphQLFieldConfig<Parent, Context>> = {};\n for (const table of tables) {\n // skip making top level query fields for our fake intersection tables\n if (isInterfaceType(polymorphicConfig, table.tsName)) continue;\n\n const entityType = entityTypes[table.tsName]!;\n const entityPageType = entityPageTypes[table.tsName]!;\n const entityFilterType = entityFilterTypes[table.tsName]!;\n\n const singularFieldName = table.tsName.charAt(0).toLowerCase() + table.tsName.slice(1);\n const pluralFieldName = `${singularFieldName}s`;\n\n queryFields[singularFieldName] = {\n type: entityType,\n // Find the primary key columns and GraphQL core types and include them\n // as arguments to the singular query type.\n args: Object.fromEntries(\n table.primaryKey.map((column) => [\n getColumnTsName(column),\n {\n type: new GraphQLNonNull(columnToGraphQLCore(column, enumTypes) as GraphQLInputType),\n },\n ]),\n ),\n resolve: async (_parent, args, context) => {\n const loader = context.getDataLoader({ table });\n\n // The `args` object here should be a valid `where` argument that\n // uses the `eq` shorthand for each primary key column.\n const encodedId = encodeRowFragment(args);\n return loader.load(encodedId);\n },\n };\n\n const entityOrderByType = entityOrderByEnums[table.tsName];\n if (!entityOrderByType) throw new Error(`Entity_orderBy Enum not found for ${table.tsName}`);\n\n queryFields[pluralFieldName] = {\n type: entityPageType,\n args: {\n where: { type: entityFilterType },\n orderBy: { type: entityOrderByType },\n orderDirection: { type: OrderDirectionEnum },\n first: { type: GraphQLInt },\n skip: { type: GraphQLInt },\n },\n resolve: async (_parent, args: PluralArgs, context, info) => {\n return executePluralQuery(table, schema[table.tsName] as PgTable, context.drizzle, args);\n },\n };\n }\n\n // Polymorphic Plural Query Fields\n // NOTE: overrides any automatic field definitions from the above\n polymorphicFields\n // filter by fieldPaths that have a parent of Query\n .filter(([[parent]]) => parent === \"Query\")\n // build each polymorphic plural field\n .forEach(([[, fieldName], interfaceTypeName]) => {\n queryFields[fieldName] = definePolymorphicPluralField({\n schema,\n interfaceType: interfaceTypes[interfaceTypeName]!,\n filterType: entityFilterTypes[interfaceTypeName]!,\n orderByType: entityOrderByEnums[interfaceTypeName]!,\n intersectionTableConfig: tablesConfig.tables[interfaceTypeName]!,\n implementingTableConfigs: polymorphicTableConfigs[interfaceTypeName]!,\n });\n });\n\n // Subgraph Meta Field\n queryFields._meta = {\n type: new GraphQLObjectType({\n name: \"_Meta_\",\n fields: {\n block: {\n type: new GraphQLNonNull(\n new GraphQLObjectType({\n name: \"_Block_\",\n description: \"Information about a specific block.\",\n fields: {\n hash: { type: GraphQLString },\n number: { type: new GraphQLNonNull(GraphQLInt) },\n timestamp: { type: new GraphQLNonNull(GraphQLInt) },\n parentHash: { type: GraphQLString },\n },\n }),\n ),\n },\n deployment: {\n type: new GraphQLNonNull(GraphQLString),\n description:\n \"An ID representing this instance of ENSNode. It is composed of the ENSNode version (https://github.com/namehash/ensnode/releases) and the Ponder build_id (https://ponder.sh/docs/api-reference/database#instance-lifecycle).\",\n },\n hasIndexingErrors: {\n type: new GraphQLNonNull(GraphQLBoolean),\n description:\n \"If true, ENSIndexer has reported an indexing error and is not actively indexing blocks.\",\n },\n },\n }),\n resolve: async (_source, _args) => {\n try {\n const [lastIndexedBlock, hasIndexingErrors, ponderBuildId] = await Promise.all([\n metadataProvider.getLastIndexedENSRootChainBlock(),\n metadataProvider.hasIndexingErrors(),\n metadataProvider.getPonderBuildId(),\n ]);\n\n return {\n deployment: `${metadataProvider.version}-${ponderBuildId}`,\n hasIndexingErrors,\n block: {\n number: Number(lastIndexedBlock.number),\n timestamp: Number(lastIndexedBlock.timestamp),\n hash: lastIndexedBlock.hash,\n parentHash: lastIndexedBlock.parentHash,\n },\n };\n } catch (error) {\n console.error(\"Cannot build subgraph _Meta_\", error);\n return null;\n }\n },\n };\n\n return new GraphQLSchema({\n // Include these here so they are listed first in the printed schema.\n types: [GraphQLJSON, GraphQLBigInt, GraphQLPageInfo],\n query: new GraphQLObjectType({\n name: \"Query\",\n fields: queryFields,\n }),\n });\n}\n\nconst GraphQLPageInfo = new GraphQLObjectType({\n name: \"PageInfo\",\n fields: {\n hasNextPage: { type: new GraphQLNonNull(GraphQLBoolean) },\n hasPreviousPage: { type: new GraphQLNonNull(GraphQLBoolean) },\n startCursor: { type: GraphQLString },\n endCursor: { type: GraphQLString },\n },\n});\n\nconst GraphQLBigInt = new GraphQLScalarType({\n name: \"BigInt\",\n serialize: (value) => String(value),\n parseValue: (value) => BigInt(value as any),\n parseLiteral: (value) => {\n if (value.kind === \"StringValue\") {\n return BigInt(value.value);\n } else {\n throw new Error(\n `Invalid value kind provided for field of type BigInt: ${value.kind}. Expected: StringValue`,\n );\n }\n },\n});\n\nconst columnToGraphQLCore = (\n column: Column,\n enumTypes: Record<string, GraphQLEnumType>,\n): GraphQLOutputType => {\n if (column.columnType === \"PgEvmBigint\") {\n return GraphQLBigInt;\n }\n\n if (column instanceof PgEnumColumn) {\n if (column.enum === undefined) {\n throw new Error(\n `Internal error: Expected enum column \"${getColumnTsName(column)}\" to have an \"enum\" property`,\n );\n }\n const enumType = enumTypes[column.enum.enumName];\n if (enumType === undefined) {\n throw new Error(\n `Internal error: Expected to find a GraphQL enum named \"${column.enum.enumName}\"`,\n );\n }\n\n return enumType;\n }\n\n switch (column.dataType) {\n case \"boolean\":\n return GraphQLBoolean;\n case \"json\":\n return GraphQLJSON;\n case \"date\":\n return GraphQLString;\n case \"string\":\n return GraphQLString;\n case \"bigint\":\n return GraphQLString;\n case \"number\":\n return is(column, PgInteger) || is(column, PgSerial) ? GraphQLInt : GraphQLFloat;\n case \"buffer\":\n return new GraphQLList(new GraphQLNonNull(GraphQLInt));\n case \"array\": {\n if (column.columnType === \"PgVector\") {\n return new GraphQLList(new GraphQLNonNull(GraphQLFloat));\n }\n\n if (column.columnType === \"PgGeometry\") {\n return new GraphQLList(new GraphQLNonNull(GraphQLFloat));\n }\n\n const innerType = columnToGraphQLCore((column as any).baseColumn, enumTypes);\n\n return new GraphQLList(new GraphQLNonNull(innerType));\n }\n default:\n throw new Error(`Type ${column.dataType} is not implemented`);\n }\n};\n\nconst innerType = (type: GraphQLOutputType): GraphQLScalarType | GraphQLEnumType => {\n if (type instanceof GraphQLScalarType || type instanceof GraphQLEnumType) return type;\n if (type instanceof GraphQLList || type instanceof GraphQLNonNull) return innerType(type.ofType);\n throw new Error(`Type ${type.toString()} is not implemented`);\n};\n\nasync function executePluralQuery(\n table: TableRelationalConfig,\n from: PgTable | Subquery | PgViewBase | SQL,\n drizzle: Drizzle<any>,\n args: PluralArgs,\n extraConditions: (SQL | undefined)[] = [],\n) {\n const limit = args.first ?? DEFAULT_LIMIT;\n if (limit > MAX_LIMIT) {\n throw new Error(`Invalid limit. Got ${limit}, expected <=${MAX_LIMIT}.`);\n }\n\n const skip = args.skip ?? 0;\n\n const orderBySchema = buildOrderBySchema(table, args);\n const orderBy = orderBySchema.map(([columnName, direction]) => {\n const column = table.columns[columnName];\n if (column === undefined) {\n throw new Error(`Unknown column \"${columnName}\" used in orderBy argument`);\n }\n\n return direction === \"asc\" ? asc(column) : desc(column);\n });\n\n const whereConditions = buildWhereConditions(args.where, table);\n\n const query = drizzle\n .select()\n .from(from)\n .where(and(...whereConditions, ...extraConditions))\n .orderBy(...orderBy)\n .limit(limit)\n .offset(skip);\n\n const startTime = performance.now();\n\n // actually execute the query\n const rows = await query;\n\n const queryDurationSeconds = (performance.now() - startTime) / 1000;\n const isSlowQuery = queryDurationSeconds > 2;\n if (isSlowQuery) {\n console.warn(`Slow Query Detected (${queryDurationSeconds.toFixed(4)}s)`);\n console.warn(query.toSQL().sql);\n console.log(\"\\n\");\n }\n\n return rows;\n}\n\nconst conditionSuffixes = {\n universal: [\"\", \"_not\"],\n singular: [\"_in\", \"_not_in\"],\n plural: [\"_has\", \"_not_has\"],\n numeric: [\"_gt\", \"_lt\", \"_gte\", \"_lte\"],\n string: [\n \"_contains\",\n \"_not_contains\",\n \"_starts_with\",\n \"_ends_with\",\n \"_not_starts_with\",\n \"_not_ends_with\",\n ],\n} as const;\n\nconst conditionSuffixesByLengthDesc = Object.values(conditionSuffixes)\n .flat()\n .sort((a, b) => b.length - a.length);\n\nfunction buildWhereConditions(\n where: Record<string, any> | undefined,\n table: TableRelationalConfig,\n): (SQL | undefined)[] {\n const conditions: (SQL | undefined)[] = [];\n\n if (where === undefined) return conditions;\n\n for (const [whereKey, rawValue] of Object.entries(where)) {\n // Handle the `AND` and `OR` operators\n if (whereKey === \"and\" || whereKey === \"or\") {\n if (!Array.isArray(rawValue)) {\n throw new Error(\n `Invalid query: Expected an array for the ${whereKey} operator. Got: ${rawValue}`,\n );\n }\n\n const nestedConditions = rawValue.flatMap((subWhere) =>\n buildWhereConditions(subWhere, table),\n );\n\n if (nestedConditions.length > 0) {\n conditions.push(whereKey === \"and\" ? and(...nestedConditions) : or(...nestedConditions));\n }\n continue;\n }\n\n // Search for a valid filter suffix, traversing the list from longest to shortest\n // to avoid ambiguity between cases like `_not_in` and `_in`.\n const conditionSuffix = conditionSuffixesByLengthDesc.find((s) => whereKey.endsWith(s));\n if (conditionSuffix === undefined) {\n throw new Error(`Invariant violation: Condition suffix not found for where key ${whereKey}`);\n }\n\n // Remove the condition suffix and use the remaining string as the column name.\n const columnName = whereKey.slice(0, whereKey.length - conditionSuffix.length);\n\n const column =\n columnName in table.relations\n ? // if the referenced name is a relation, the relevant column is this table's `${relationName}Id`\n table.columns[`${columnName}Id`]\n : // otherwise validate that the column name is present in the table\n table.columns[columnName];\n\n if (column === undefined) {\n throw new Error(`Invalid query: Where clause contains unknown column ${columnName}`);\n }\n\n switch (conditionSuffix) {\n case \"\":\n if (column.columnType === \"PgArray\") {\n conditions.push(and(arrayContains(column, rawValue), arrayContained(column, rawValue)));\n } else {\n if (rawValue === null) {\n conditions.push(isNull(column));\n } else {\n conditions.push(eq(column, rawValue));\n }\n }\n break;\n case \"_not\":\n if (column.columnType === \"PgArray\") {\n conditions.push(\n not(and(arrayContains(column, rawValue), arrayContained(column, rawValue))!),\n );\n } else {\n if (rawValue === null) {\n conditions.push(isNotNull(column));\n } else {\n conditions.push(ne(column, rawValue));\n }\n }\n break;\n case \"_in\":\n conditions.push(inArray(column, rawValue));\n break;\n case \"_not_in\":\n conditions.push(notInArray(column, rawValue));\n break;\n case \"_has\":\n conditions.push(arrayContains(column, [rawValue]));\n break;\n case \"_not_has\":\n conditions.push(not(arrayContains(column, [rawValue])));\n break;\n case \"_gt\":\n conditions.push(gt(column, rawValue));\n break;\n case \"_lt\":\n conditions.push(lt(column, rawValue));\n break;\n case \"_gte\":\n conditions.push(gte(column, rawValue));\n break;\n case \"_lte\":\n conditions.push(lte(column, rawValue));\n break;\n case \"_contains\":\n conditions.push(like(column, `%${rawValue}%`));\n break;\n case \"_not_contains\":\n conditions.push(notLike(column, `%${rawValue}%`));\n break;\n case \"_starts_with\":\n conditions.push(like(column, `${rawValue}%`));\n break;\n case \"_ends_with\":\n conditions.push(like(column, `%${rawValue}`));\n break;\n case \"_not_starts_with\":\n conditions.push(notLike(column, `${rawValue}%`));\n break;\n case \"_not_ends_with\":\n conditions.push(notLike(column, `%${rawValue}`));\n break;\n default:\n throw new Error(`Invalid Condition Suffix ${conditionSuffix}`);\n }\n }\n\n return conditions;\n}\n\nfunction buildOrderBySchema(table: TableRelationalConfig, args: PluralArgs) {\n // If the user-provided order by does not include the ALL of the ID columns,\n // add any missing ID columns to the end of the order by clause (asc).\n // This ensures a consistent sort order to unblock cursor pagination.\n const userDirection = args.orderDirection ?? \"asc\";\n const userColumns: [string, \"asc\" | \"desc\"][] =\n args.orderBy !== undefined ? [[args.orderBy, userDirection]] : [];\n const pkColumns = table.primaryKey.map((column) => [getColumnTsName(column), userDirection]);\n const missingPkColumns = pkColumns.filter(\n (pkColumn) => !userColumns.some((userColumn) => userColumn[0] === pkColumn[0]),\n ) as [string, \"asc\" | \"desc\"][];\n return [...userColumns, ...missingPkColumns];\n}\n\nexport function buildDataLoaderCache({ drizzle }: { drizzle: Drizzle<Schema> }) {\n const dataLoaderMap = new Map<TableRelationalConfig, DataLoader<string, any> | undefined>();\n return ({ table }: { table: TableRelationalConfig }) => {\n const baseQuery = (drizzle as Drizzle<{ [key: string]: OnchainTable }>).query[table.tsName];\n if (baseQuery === undefined)\n throw new Error(`Internal error: Unknown table \"${table.tsName}\" in data loader cache`);\n\n let dataLoader = dataLoaderMap.get(table);\n if (dataLoader === undefined) {\n dataLoader = new DataLoader(\n async (encodedIds) => {\n const decodedRowFragments = encodedIds.map(decodeRowFragment);\n\n // The decoded row fragments should be valid `where` objects\n // which use the `eq` object shorthand for each primary key column.\n const idConditions = decodedRowFragments.map((decodedRowFragment) =>\n and(...buildWhereConditions(decodedRowFragment, table)),\n );\n\n const rows = await baseQuery.findMany({\n where: or(...idConditions),\n limit: encodedIds.length,\n });\n\n // Now, we need to order the rows coming out of the database to match\n // the order of the IDs passed in. To accomplish this, we need to do\n // a comparison of the decoded row PK fragments with the database rows.\n // This is tricky because the decoded row PK fragments are not normalized,\n // so some comparisons will fail (eg for our PgHex column type).\n // To fix this, we need to normalize the values before doing the comparison.\n return (\n decodedRowFragments\n // Normalize the decoded row fragments\n // .map((fragment) =>\n // Object.fromEntries(\n // Object.entries(fragment).map(([col, val]) => {\n // const column = table.columns[col];\n // if (column === undefined) {\n // throw new Error(\n // `Unknown column '${table.tsName}.${col}' used in dataloader row ID fragment`,\n // );\n // }\n // return [col, normalizeColumn(column, val, false)];\n // }),\n // ),\n // )\n // Find the database row corresponding to each normalized row fragment\n .map((fragment) =>\n rows.find((row) =>\n Object.entries(fragment).every(([col, val]) => row[col] === val),\n ),\n )\n );\n },\n { maxBatchSize: 1_000 },\n );\n dataLoaderMap.set(table, dataLoader);\n }\n\n return dataLoader;\n };\n}\n\nfunction getColumnTsName(column: Column) {\n const tableColumns = getTableColumns(column.table);\n return Object.entries(tableColumns).find(([_, c]) => c.name === column.name)![0];\n}\n\nfunction encodeRowFragment(rowFragment: { [k: string]: unknown }): string {\n return Buffer.from(serialize(rowFragment)).toString(\"base64\");\n}\n\nfunction decodeRowFragment(encodedRowFragment: string): {\n [k: string]: unknown;\n} {\n return deserialize(Buffer.from(encodedRowFragment, \"base64\").toString());\n}\n\n// the subgraph's GraphQL types are just the capitalized version of ponder's tsName\nfunction getSubgraphEntityName(tsName: string) {\n return capitalize(tsName);\n}\n\nfunction isInterfaceType(polymorphicConfig: PolymorphicConfig, columnName: string) {\n return columnName in polymorphicConfig.types;\n}\n\n// defines a table and relations that is the intersection of the provided `tableConfigs`\nfunction getIntersectionTableSchema(\n interfaceTypeName: string,\n tableConfigs: TableRelationalConfig[],\n) {\n if (tableConfigs.length === 0) throw new Error(\"Must have some tables to intersect\");\n\n const baseColumns = tableConfigs[0]!.columns;\n const baseRelations = tableConfigs[0]!.relations;\n\n // compute the common columnNames\n const commonColumnNames = intersectionOf(\n tableConfigs.map((table) => Object.keys(table.columns)), //\n );\n\n // compute the common relationshipNames\n const commonRelationsNames = intersectionOf(\n tableConfigs.map((table) => Object.keys(table.relations)),\n );\n\n // define a pgTable by cloning the common columns w/ builder functions\n // TODO: can we more easily clone theses instead of using builder fns? Object.assign?\n // NOTE: it's important that this table's dbName is intersection_table, as that is what the\n // UNION ALL subquery is aliased to later\n // TODO: can we use drizzle's .with or something to avoid the magic string?\n const intersectionTable = pgTable(\"intersection_table\", (t) =>\n commonColumnNames.reduce<Record<string, PgColumnBuilderBase>>((memo, columnName) => {\n const column = baseColumns[columnName]!;\n const sqlType = column.getSQLType();\n const snakeCaseColumnName = toSnakeCase(column.name);\n\n let newColumn: any =\n sqlType === \"numeric(78)\"\n ? // special case for bigint whose sqltype is \"numeric(78)\"\n t.numeric(snakeCaseColumnName, { precision: 78 })\n : // handle standard types, removing any parameters from the SQLType\n // @ts-expect-error we know the key is valid and this is callable\n t[sqlType.split(\"(\")[0]! as keyof typeof t](snakeCaseColumnName);\n\n // include .primaryKey if necessary\n newColumn = column.primary ? newColumn.primaryKey() : newColumn;\n\n // include notNull\n newColumn = newColumn.notNull(column.notNull);\n\n memo[columnName] = newColumn;\n return memo;\n }, {}),\n );\n\n // define the relationships for this table by cloning the common relationships\n const intersectionTableRelations = relations(intersectionTable, ({ one }) =>\n commonRelationsNames.reduce<Record<string, Relation<any>>>((memo, relationName) => {\n const relation = baseRelations[relationName];\n\n if (is(relation, One)) {\n memo[relationName] = one(relation.referencedTable, relation.config as any);\n } else if (is(relation, Many)) {\n // NOTE: unimplemented — only One relations are necessary for relationalConditions later\n }\n\n return memo;\n }, {}),\n );\n\n return {\n [interfaceTypeName]: intersectionTable,\n [`${interfaceTypeName}Relations`]: intersectionTableRelations,\n };\n}\n\n// produces Record<string, Column> that is the union of all columns in tables\nfunction getColumnsUnion(tables: TableRelationalConfig[]): Record<string, Column> {\n return tables.reduce(\n (memo, table) => ({\n ...memo,\n ...table.columns,\n }),\n {},\n );\n}\n\n// builds a drizzle subquery from the set of provided tables with given `where` filter\nfunction buildUnionAllQuery(\n drizzle: Drizzle<{ [key: string]: OnchainTable }>,\n schema: Schema,\n tables: TableRelationalConfig[],\n where: Record<string, unknown> = {},\n) {\n const allColumns = getColumnsUnion(tables);\n const allColumnNames = Object.keys(allColumns).sort();\n\n // builds a subquery per-table like `SELECT columns... from :table (WHERE fk = fkv)`\n const subqueries = tables.map((table) => {\n // NOTE: every subquery of union must have the same columns of the same types so we\n // build select object with nulls for missing columns, manually casting them to the correct type\n const selectAllColumnsIncludingNulls = allColumnNames.reduce((memo, columnName) => {\n const column = allColumns[columnName]!;\n const snakeCaseColumnName = toSnakeCase(column.name);\n const dbColumnName = table.columns[columnName] ? snakeCaseColumnName : \"NULL\";\n\n return {\n ...memo,\n [columnName]: sql.raw(`${dbColumnName}::${column.getSQLType()}`).as(snakeCaseColumnName),\n };\n }, {});\n\n // apply the relation filter at subquery level to minimize merged data\n // NOTE: that we use this table's Column so the generated sql references the correct table\n const relationalConditions: SQL[] = Object.entries(where).map(\n ([foreignKeyName, foreignKeyValue]) => eq(table.columns[foreignKeyName]!, foreignKeyValue),\n );\n\n return drizzle\n .select({\n ...selectAllColumnsIncludingNulls,\n // inject __typename into each subquery\n __typename: sql.raw(`'${getSubgraphEntityName(table.tsName)}'`).as(\"__typename\"),\n })\n .from(schema[table.tsName] as PgTable)\n .where(and(...relationalConditions))\n .$dynamic();\n });\n\n // joins the subqueries with UNION ALL and aliases it to `intersection_table`\n return subqueries\n .reduce((memo, fragment, i) => (i === 0 ? fragment : memo.unionAll(fragment)))\n .as(\"intersection_table\");\n}\n\n/**\n * creates the GraphQLFieldConfig for a polymorphic plural field\n *\n * @param schema the database schema containing table definitions\n * @param interfaceType the GraphQL interface type for the polymorphic field\n * @param filterType the GraphQL input type for filtering records\n * @param orderByType the GraphQL enum type for ordering records\n * @param intersectionTableConfig the TableConfig representing the intersection\n * of `implementingTableConfigs`\n * @param implementingTableConfigs array of table configs that implement the interface\n */\nfunction definePolymorphicPluralField({\n schema,\n interfaceType,\n filterType,\n orderByType,\n intersectionTableConfig,\n implementingTableConfigs,\n}: {\n schema: Schema;\n interfaceType: GraphQLInterfaceType;\n filterType: GraphQLInputObjectType;\n orderByType: GraphQLEnumType;\n intersectionTableConfig: TableRelationalConfig;\n implementingTableConfigs: TableRelationalConfig[];\n}): GraphQLFieldConfig<Parent, Context> {\n return {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(interfaceType))),\n args: {\n where: { type: filterType },\n orderBy: { type: orderByType },\n orderDirection: { type: OrderDirectionEnum },\n first: { type: GraphQLInt },\n skip: { type: GraphQLInt },\n },\n resolve: async (parent, args: PluralArgs, { drizzle }, info) => {\n // find the relation field that references the parent type\n const foreignKeyName = getForeignKeyFieldName(intersectionTableConfig, info.parentType.name);\n\n // include it in the relationalFilter iff necessary\n const relationalFilter = foreignKeyName ? { [foreignKeyName]: parent.id } : {};\n\n // construct a UNION ALL subquery\n const subquery = buildUnionAllQuery(\n drizzle,\n schema,\n implementingTableConfigs,\n relationalFilter,\n );\n\n // pass it to executePluralQuery as usual\n return executePluralQuery(intersectionTableConfig, subquery, drizzle, args);\n },\n };\n}\n\n// finds the foreign key name in a table that references a given GraphQL parentTypeName\nfunction getForeignKeyFieldName(table: TableRelationalConfig, parentTypeName: string) {\n // 1. find the first relation field that references the parent type name\n const relationName = Object.keys(table.relations).find(\n (relationName) => getSubgraphEntityName(relationName) === parentTypeName,\n );\n if (!relationName) return;\n\n // ignore if this isn't a One relation\n const relation = table.relations[relationName];\n if (!is(relation, One)) return;\n\n // 2. find the columnName of the correct column\n const fkEntry = Object.entries(relation.config?.fields?.[0]?.table ?? {}).find(\n ([_, column]) => column.name === relation.config?.fields?.[0]?.name,\n );\n\n // 3. columnName is the name of the foreign key column in `table`\n return fkEntry?.[0];\n}\n","// https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore?tab=readme-ov-file#_intersection\nexport const intersectionOf = <T>(arrays: T[][]) =>\n arrays.reduce((a, b) => a.filter((c) => b.includes(c)));\n\nexport const capitalize = (str: string): string => {\n if (!str) return str;\n return `${str.charAt(0).toUpperCase()}${str.slice(1)}`;\n};\n","// https://github.com/ponder-sh/ponder/blob/main/packages/core/src/utils/serialize.ts\n\n/**\n * Serialize function that handles BigInt.\n *\n * Forked from https://github.com/wevm/wagmi\n *\n * @param value to stringify\n * @returns the stringified output\n */\nexport function serialize(value: any) {\n return JSON.stringify(value, (_, v) =>\n typeof v === \"bigint\" ? { __type: \"bigint\", value: v.toString() } : v,\n );\n}\n\n/**\n * Deserialize function that handles BigInt.\n *\n * Forked from https://github.com/wevm/wagmi\n *\n * @param value to parse\n * @returns the output object\n */\nexport function deserialize<type>(value: string): type {\n return JSON.parse(value, (_, value_) =>\n value_?.__type === \"bigint\" ? BigInt(value_.value) : value_,\n );\n}\n"],"mappings":";AASA,SAAS,wBAAwB;AACjC,SAAS,sBAAsB;AAC/B,SAAS,uBAAuB;AAEhC,SAAS,kBAAkB;AAC3B,SAAS,wBAAwB;;;AC0BjC,OAAO,gBAAgB;AACvB;AAAA,EAEE;AAAA,EACA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB;AAC5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tB,iBAAiB;AAAA;AAAA,IACjB,QAAQ;AAAA,IACR,SAAS,MAAM;AACb,YAAM,gBAAgB,qBAAqB,EAAE,QAAQ,CAAC;AAEtD,aAAO,EAAE,SAAS,cAAc;AAAA,IAClC;AAAA,IACA,cACE,QAAQ,IAAI,aAAa,eACrB,OACA;AAAA,MACE,UAAU,OAAY;AACpB,gBAAQ,MAAM,MAAM,aAAa;AACjC,eAAO;AAAA,MACT;AAAA,IACF;AAAA,IACN,SAAS;AAAA,IACT,UAAU;AAAA,IACV,0BAA0B;AAAA,IAC1B,SAAS;AAAA,MACP,gBAAgB,EAAE,GAAG,mBAAmB,CAAC;AAAA,MACzC,eAAe,EAAE,GAAG,mBAAmB,qBAAqB,MAAM,CAAC;AAAA,MACnE,iBAAiB,EAAE,GAAG,qBAAqB,WAAW,CAAC,EAAE,CAAC;AAAA,IAC5D;AAAA,EACF,CAAC;AAED,SAAO,iBAAiB,OAAO,MAAM;AACnC,UAAM,WAAW,MAAM,KAAK,OAAO,EAAE,IAAI,GAAG;AAG5C,aAAS,SAAS;AAElB,aAAS,aAAa;AAEtB,WAAO;AAAA,EACT,CAAC;AACH;","names":["table","relations","innerType","relationName","_a","_b","_c"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ensnode/ponder-subgraph",
3
- "version": "0.35.0",
3
+ "version": "0.36.0",
4
4
  "type": "module",
5
5
  "description": "A Hono middleware for generating Subgraph-compatible GraphQL schema.",
6
6
  "license": "MIT",
@@ -39,13 +39,13 @@
39
39
  "devDependencies": {
40
40
  "@biomejs/biome": "^1.9.4",
41
41
  "@types/node": "^22.14.0",
42
- "hono": "^4.7.6",
42
+ "hono": "^4.9.7",
43
43
  "tsup": "^8.3.6",
44
44
  "typescript": "^5.7.3",
45
- "@ensnode/shared-configs": "0.35.0"
45
+ "@ensnode/shared-configs": "0.36.0"
46
46
  },
47
47
  "peerDependencies": {
48
- "hono": "^4.7.6"
48
+ "hono": "^4.9.7"
49
49
  },
50
50
  "scripts": {
51
51
  "prepublish": "tsup",