{"version":3,"file":"index.mjs","names":["warnings: string[]","varRefs: Record<string, AnyVarRef>","bundledCode: string","finalExports: Record<string, unknown>","schemas: Record<string, AnyGraphqlSchema>"],"sources":["../src/prebuilt/extractor.ts","../src/schema-loader.ts"],"sourcesContent":["/**\n * Field selection extractor for prebuilt type generation.\n *\n * Extracts field selection data from evaluated Fragment and Operation elements\n * for use in type string generation.\n *\n * @module\n */\n\nimport type { CanonicalId } from \"@soda-gql/common\";\nimport { type AnyFieldsExtended, type AnyVarRef, createVarRefFromVariable, type VariableDefinitions } from \"@soda-gql/core\";\nimport { Kind, type OperationDefinitionNode, type VariableDefinitionNode } from \"graphql\";\nimport type { IntermediateArtifactElement } from \"../intermediate-module\";\n\n/**\n * Field selection data for a single element.\n */\nexport type FieldSelectionData =\n  | {\n      readonly type: \"fragment\";\n      readonly schemaLabel: string;\n      readonly key: string | undefined;\n      readonly typename: string;\n      readonly fields: AnyFieldsExtended;\n      readonly variableDefinitions: VariableDefinitions;\n    }\n  | {\n      readonly type: \"operation\";\n      readonly schemaLabel: string;\n      readonly operationName: string;\n      readonly operationType: string;\n      readonly fields: AnyFieldsExtended;\n      readonly variableDefinitions: readonly VariableDefinitionNode[];\n    };\n\n/**\n * Map of canonical IDs to their field selection data.\n */\nexport type FieldSelectionsMap = ReadonlyMap<CanonicalId, FieldSelectionData>;\n\n/**\n * Result of field selection extraction including any warnings.\n */\nexport type FieldSelectionsResult = {\n  readonly selections: FieldSelectionsMap;\n  readonly warnings: readonly string[];\n};\n\n/**\n * Extract field selections from evaluated intermediate elements.\n *\n * For fragments, calls `spread()` with empty/default variables to get field selections.\n * For operations, calls `documentSource()` to get field selections.\n *\n * @param elements - Record of canonical ID to intermediate artifact element\n * @returns Object containing selections map and any warnings encountered\n */\nexport const extractFieldSelections = (elements: Record<CanonicalId, IntermediateArtifactElement>): FieldSelectionsResult => {\n  const selections = new Map<CanonicalId, FieldSelectionData>();\n  const warnings: string[] = [];\n\n  for (const [id, element] of Object.entries(elements)) {\n    // Object.entries returns string keys, cast back to CanonicalId\n    const canonicalId = id as CanonicalId;\n\n    try {\n      if (element.type === \"fragment\") {\n        // Access variableDefinitions directly from the fragment\n        const variableDefinitions = element.element.variableDefinitions;\n\n        // Create VarRef objects for each variable to call spread\n        // Field selection structure doesn't depend on variable values, only on variable references\n        const varRefs: Record<string, AnyVarRef> = Object.fromEntries(\n          Object.keys(variableDefinitions).map((k) => [k, createVarRefFromVariable(k)]),\n        );\n        const fields = element.element.spread(varRefs);\n\n        selections.set(canonicalId, {\n          type: \"fragment\",\n          schemaLabel: element.element.schemaLabel,\n          key: element.element.key,\n          typename: element.element.typename,\n          fields,\n          variableDefinitions,\n        });\n      } else if (element.type === \"operation\") {\n        // For operations, invoke documentSource to get fields\n        const fields = element.element.documentSource();\n\n        // Extract variable definitions from the GraphQL document AST\n        const document = element.element.document;\n        const operationDef = document.definitions.find(\n          (def): def is OperationDefinitionNode => def.kind === Kind.OPERATION_DEFINITION,\n        );\n        const variableDefinitions = operationDef?.variableDefinitions ?? [];\n\n        selections.set(canonicalId, {\n          type: \"operation\",\n          schemaLabel: element.element.schemaLabel,\n          operationName: element.element.operationName,\n          operationType: element.element.operationType,\n          fields,\n          variableDefinitions,\n        });\n      }\n    } catch (error) {\n      warnings.push(\n        `[prebuilt] Failed to extract field selections for ${canonicalId}: ${error instanceof Error ? error.message : String(error)}`,\n      );\n    }\n  }\n\n  return { selections, warnings };\n};\n","/**\n * Schema loader for CJS bundle evaluation.\n *\n * Loads AnyGraphqlSchema from the generated CJS bundle by accessing\n * the `$schema` property on each gql composer.\n *\n * @module\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { AnyGraphqlSchema } from \"@soda-gql/core\";\nimport { err, ok, type Result } from \"neverthrow\";\nimport type { BuilderError } from \"./errors\";\nimport { executeSandbox } from \"./vm/sandbox\";\n\n/**\n * Result of loading schemas from a CJS bundle.\n */\nexport type LoadSchemasResult = Result<Record<string, AnyGraphqlSchema>, BuilderError>;\n\n/**\n * Load AnyGraphqlSchema from a generated CJS bundle.\n *\n * The generated CJS bundle exports a `gql` object where each property\n * is a GQL element composer with a `$schema` property containing the\n * schema definition. This function executes the bundle in a VM context\n * and extracts those schemas.\n *\n * @param cjsPath - Absolute path to the CJS bundle file\n * @param schemaNames - Names of schemas to load (e.g., [\"default\", \"admin\"])\n * @returns Record mapping schema names to AnyGraphqlSchema objects\n *\n * @example\n * ```typescript\n * const result = loadSchemasFromBundle(\n *   \"/path/to/generated/index.cjs\",\n *   [\"default\"]\n * );\n *\n * if (result.isOk()) {\n *   const schemas = result.value;\n *   console.log(schemas.default); // AnyGraphqlSchema\n * }\n * ```\n */\nexport const loadSchemasFromBundle = (cjsPath: string, schemaNames: readonly string[]): LoadSchemasResult => {\n  const resolvedPath = resolve(cjsPath);\n\n  // Check if file exists\n  if (!existsSync(resolvedPath)) {\n    return err({\n      code: \"CONFIG_NOT_FOUND\",\n      message: `CJS bundle not found: ${resolvedPath}. Run 'soda-gql codegen' first.`,\n      path: resolvedPath,\n    });\n  }\n\n  // Read the bundled code\n  let bundledCode: string;\n  try {\n    bundledCode = readFileSync(resolvedPath, \"utf-8\");\n  } catch (error) {\n    return err({\n      code: \"DISCOVERY_IO_ERROR\",\n      message: `Failed to read CJS bundle: ${error instanceof Error ? error.message : String(error)}`,\n      path: resolvedPath,\n      cause: error,\n    });\n  }\n\n  // Execute the bundle in sandbox\n  let finalExports: Record<string, unknown>;\n  try {\n    finalExports = executeSandbox(bundledCode, resolvedPath);\n  } catch (error) {\n    return err({\n      code: \"RUNTIME_MODULE_LOAD_FAILED\",\n      message: `Failed to execute CJS bundle: ${error instanceof Error ? error.message : String(error)}`,\n      filePath: resolvedPath,\n      astPath: \"\",\n      cause: error,\n    });\n  }\n\n  // Extract gql object from exports\n  const gql = finalExports.gql as Record<string, { $schema?: unknown }> | undefined;\n\n  if (!gql || typeof gql !== \"object\") {\n    return err({\n      code: \"CONFIG_INVALID\",\n      message: \"CJS bundle does not export 'gql' object. Ensure codegen was run successfully.\",\n      path: resolvedPath,\n    });\n  }\n\n  const schemas: Record<string, AnyGraphqlSchema> = {};\n\n  for (const name of schemaNames) {\n    const composer = gql[name];\n\n    if (!composer) {\n      const availableSchemas = Object.keys(gql).join(\", \");\n      return err({\n        code: \"SCHEMA_NOT_FOUND\",\n        message: `Schema '${name}' not found in gql exports. Available: ${availableSchemas || \"(none)\"}`,\n        schemaLabel: name,\n        canonicalId: `gql.${name}`,\n      });\n    }\n\n    const schema = composer.$schema;\n\n    // Validate that the $schema property exists and is an object\n    if (!schema || typeof schema !== \"object\") {\n      return err({\n        code: \"CONFIG_INVALID\",\n        message: `gql.${name}.$schema is not a valid schema object. Ensure codegen version is up to date.`,\n        path: resolvedPath,\n      });\n    }\n\n    schemas[name] = schema as AnyGraphqlSchema;\n  }\n\n  return ok(schemas);\n};\n\n/**\n * Load AnyGraphqlSchema from a generated CJS bundle using `__fullSchema_*` exports.\n *\n * Unlike `loadSchemasFromBundle` which reads schemas from `gql.$schema`,\n * this function reads the `__fullSchema_*` named exports directly.\n * These contain the full AnyGraphqlSchema with complete scalar/enum/input\n * definitions needed for type generation.\n *\n * @param cjsPath - Absolute path to the CJS bundle file\n * @param schemaNames - Names of schemas to load (e.g., [\"default\", \"admin\"])\n * @returns Record mapping schema names to AnyGraphqlSchema objects\n *\n * @example\n * ```typescript\n * const result = loadFullSchemasFromBundle(\n *   \"/path/to/generated/index.cjs\",\n *   [\"default\"]\n * );\n *\n * if (result.isOk()) {\n *   const schemas = result.value;\n *   console.log(schemas.default); // AnyGraphqlSchema\n * }\n * ```\n */\nexport const loadFullSchemasFromBundle = (cjsPath: string, schemaNames: readonly string[]): LoadSchemasResult => {\n  const resolvedPath = resolve(cjsPath);\n\n  // Check if file exists\n  if (!existsSync(resolvedPath)) {\n    return err({\n      code: \"CONFIG_NOT_FOUND\",\n      message: `CJS bundle not found: ${resolvedPath}. Run 'soda-gql codegen' first.`,\n      path: resolvedPath,\n    });\n  }\n\n  // Read the bundled code\n  let bundledCode: string;\n  try {\n    bundledCode = readFileSync(resolvedPath, \"utf-8\");\n  } catch (error) {\n    return err({\n      code: \"DISCOVERY_IO_ERROR\",\n      message: `Failed to read CJS bundle: ${error instanceof Error ? error.message : String(error)}`,\n      path: resolvedPath,\n      cause: error,\n    });\n  }\n\n  // Execute the bundle in sandbox\n  let finalExports: Record<string, unknown>;\n  try {\n    finalExports = executeSandbox(bundledCode, resolvedPath);\n  } catch (error) {\n    return err({\n      code: \"RUNTIME_MODULE_LOAD_FAILED\",\n      message: `Failed to execute CJS bundle: ${error instanceof Error ? error.message : String(error)}`,\n      filePath: resolvedPath,\n      astPath: \"\",\n      cause: error,\n    });\n  }\n\n  const schemas: Record<string, AnyGraphqlSchema> = {};\n\n  for (const name of schemaNames) {\n    const exportKey = `__fullSchema_${name}`;\n    const schema = finalExports[exportKey];\n\n    if (!schema || typeof schema !== \"object\") {\n      // Fall back to __schema_* exports for backward compatibility\n      const fallbackKey = `__schema_${name}`;\n      const fallbackSchema = finalExports[fallbackKey];\n\n      if (!fallbackSchema || typeof fallbackSchema !== \"object\") {\n        const availableExports = Object.keys(finalExports)\n          .filter((k) => k.startsWith(\"__fullSchema_\") || k.startsWith(\"__schema_\"))\n          .join(\", \");\n        return err({\n          code: \"SCHEMA_NOT_FOUND\",\n          message: `Full schema '${name}' not found in exports (tried ${exportKey}, ${fallbackKey}). Available: ${availableExports || \"(none)\"}`,\n          schemaLabel: name,\n          canonicalId: exportKey,\n        });\n      }\n\n      schemas[name] = fallbackSchema as AnyGraphqlSchema;\n      continue;\n    }\n\n    schemas[name] = schema as AnyGraphqlSchema;\n  }\n\n  return ok(schemas);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAyDA,MAAa,0BAA0B,aAAsF;CAC3H,MAAM,aAAa,IAAI,KAAsC;CAC7D,MAAMA,WAAqB,EAAE;AAE7B,MAAK,MAAM,CAAC,IAAI,YAAY,OAAO,QAAQ,SAAS,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