# GenerateContext

CLASS in `@skmtc/core 0.63.4`

The context of the generate phase, the second of the three phases.

The engine runs each generator over the parsed document and passes this
context to its `transform`. A generator uses it to:

- insert a projection: `insertModel`, `insertOperation`,
  `insertWebhook` and `insertNormalizedModel`. Each one makes the
  definition on the first call, uses that definition again after it, and adds
  the import to the file that needs it
- register imports and definitions in a file, with the `register` function
  of its language package. That function makes the file when it does not
  exist, then calls `register`, which takes only the language's import
  objects and throws when the file does not exist
- look up a model's schema: `resolveSchemaRefOnce`

## Signature

```ts
import { GenerateContext } from '@skmtc/core'

class GenerateContext implements GenerateContextType
```

## Examples

Insert a projection for each model:

```ts
transform({ context, ref, variant }) {
  context.insertModel(MyProjection, ref, { variant })
}
```

## Constructor

### constructor

```ts
constructor(args: ConstructorArgs)
```

## Properties

- `document` (SkmtcParsedDocument): Parsed source document, wrapped in `SkmtcParsedDocument`. Canonical representation; model and operation dispatch read through this.
- `settings` (ClientSettings | undefined): Client settings for customization (optional)
- `logger` (Logger): Logger instance for tracking generation progress
- `captureCurrentResult` ((result: ResultType, stackTrail: StackTrail) => void): Function to capture processing results at current stack position
- `toGeneratorConfigMap` (<EnrichmentType = undefined>() => GeneratorsMapContainer<EnrichmentType>): Function that returns the generator configuration map
- `pendingStack` (PendingDefinition[]): The pending models, outermost first: the last is the model whose projection constructor is running.
- `captureSink` (CaptureSink | undefined): The active attribution capture sink, or `undefined` outside the capture interval. Every `SnippetBase` instance's `toString` wrapper reads this; `RenderContext` opens/closes the interval by flipping the shared channel's `sink`.
- `capturesRender` (boolean): Whether this run has a capturing render: it was given a capture channel. A `SnippetBase` instance installs its `toString` wrapper only then.
- `currentSubjectTrail` (StackTrail | undefined): The trail of the subject whose variant is being generated, or `undefined` outside one. Log lines and the results the logger records are addressed by it.
- `inspectedFiles` (ReadonlyMap<string, FileBase>): Read-only view of every file generated so far, keyed by (normalized) export path. In a run with `onArtifact` it does not have the files that were given to the host. An **inspection / tooling** seam - NOT a coordination surface: generators must still register via `register` / `insert*`, and the storage stays `#`-private so nothing outside can mutate or re-bind it. Unlike `getFile` (which needs a path) this lets tooling *enumerate* the files map - e.g. a debugger visualiser snapshotting the in-progress state at a breakpoint. The `ReadonlyMap` type signals look-don't-touch.

## Methods

### readEnrichment

```ts
readEnrichment(segments: readonly string[]): unknown
```

The recording enrichment accessor - the single choke point every
enrichment lookup routes through (dispatch loops, the parse of a
subject's enrichments, the Drivers' peer-variant guards). Segments are
literal keys (`getPath` keeps dotted paths intact); the read is
recorded so the post-walk consumption audit can flag configured
entries no lookup ever touched.

### parseEnrichments

```ts
parseEnrichments<EnrichmentType>(
  args: ParseEnrichmentsArgs<EnrichmentType>
): EnrichmentType
```

Read the `{ subject, generator, stack }` enrichments of a generator and
parse them with `schema`. An entry's `toEnrichments` calls it: the entry
knows its id, its schema and where its kind of subject has its values.
Core does the same for each kind: it records the reads
(`readEnrichment`), reports each key the schema drops, and names
the place of each wrong value.

The `stack` scope is exempt from the check for dropped keys. All
generators share it and each one declares only the keys it reads, so a
key it does not know is not a typo.

Throws:

- `Error`: on a value of the wrong type. The check for dropped keys runs first, so a throw hides none of them.

### reportEnrichmentWarning

```ts
reportEnrichmentWarning(warning: EnrichmentWarning): void
```

Add a warning to this run's enrichment audit (deduplicated).

### withSubjectTrail

```ts
withSubjectTrail<T>(stackTrail: StackTrail, fn: () => T): T
```

Runs `fn` with `currentSubjectTrail` set to `stackTrail`, and
restores the previous value afterwards.

### toSupportedSubjects

```ts
toSupportedSubjects(): SupportedSubjects
```

Evaluate each generator's `isSupported` over the parsed document's subjects
and report the subjects each generator supports - capability only, no
transform and no render. Operation generators report the operations their
`isSupported` accepts; model generators report the models theirs accepts
(a generator that declares no `isSupported` defaults to every subject).

### toEnrichmentDefaults

```ts
toEnrichmentDefaults(): EnrichmentDefaults
```

The seed enrichment values each configured generator derives from the
document - the *values* counterpart of `toSupportedSubjects`. For
every generator that advertises `toEnrichmentDefaults`, calls it over the
subjects the generator supports and keeps the non-`undefined` subject-scope
leaves, keyed by the `skmtc.config.json#settings.enrichments` routing:
`[id][path][method]['main']` for operations, `[id][refName]['main']` for
models. Seeding targets the `'main'` variant; a generator that advertises
no defaults (or whose every subject returns `undefined`) is omitted.

Like `toSupportedSubjects` it neither transforms nor renders, and is
defensive: a generator whose hook throws contributes nothing rather than
failing the whole pass.

### getFile

```ts
getFile(filePath: string): FileBase | undefined
```

Look up an already-registered file by path, or `undefined` if none
exists. In a run with `onArtifact`, a lookup of a file that was given
to the host throws. Neutral primitive: returns the abstract `FileBase` and never
constructs anything, so a (future) language-owned `register` can ask
"does this file exist yet?" without the engine knowing the language.
To create on a miss, add a file your language constructs with
`addFile` (`getFile(path) ?? addFile(lang.createFile(…))`).

`filePath` may be in any spelling. It is normalized only when it is no
key: a key is a normalized path. The file's own `path` is the key.

### getFileByWorkspacePath

```ts
getFileByWorkspacePath(path: WorkspacePath): FileBase | undefined
```

The file whose normalized path is `path`, or `undefined`. A normalized
path is a key as it is, so a miss is not normalized again, as it is in
`getFile`: there is no file there in any spelling.

### addFile

```ts
addFile<File extends FileBase>(file: File): File
```

Store a language-constructed file. The engine never constructs a
concrete (language) `File`; the language's `register` builds its own
`FileBase` subclass and hands it in here. Throws if a file already
exists at the (normalized) path. Sets `file.path` to that normalized
path, the file's key. Returns the stored file, so
get-or-create is a single expression at the call site
(`context.getFile(path) ?? context.addFile(new KtFile({ … }))`).

### registerJson

```ts
registerJson(args: RegisterJsonArgs): void
```

**Experimental.**

Registers JSON content for output to a file.

- `args`: Registration arguments with destination path and JSON content

### registerMarkdown

```ts
registerMarkdown(args: RegisterMarkdownArgs): void
```

**Experimental.**

Registers Markdown content for output to a file.

The Markdown counterpart of `registerJson` - create-or-replace, last
write wins. The `markdown` is any `Stringable` (typically a composed
snippet tree), rendered verbatim into a `MarkdownFile`.

### register

```ts
register(args: ContextRegisterArgs): void
```

Insert supplied `imports` and `definitions` into file at `destinationPath`.

If an import from a specified module already exists in the file, the
import names are appended to the existing import.

Definitions will only be added if there is not already a definition with
the same name in the file.

### insertOperation

```ts
insertOperation<V extends GeneratedValue, EnrichmentType = undefined, ProjectionOptions = undefined>(
  args: InsertOperationArgs<V, EnrichmentType, ProjectionOptions>
): Inserted<V, EnrichmentType>
```

Insert operation into the output file with path `destinationPath`.

Insert will perform the following steps:
Insert an operation definition into `destinationPath`.

Resolves identifier and export path from the projection, registers the
definition (or reuses a cached one), and stitches an import into
`destinationPath` if it differs from the projection's `exportPath`.

### insertWebhook

```ts
insertWebhook<V extends GeneratedValue, EnrichmentType = undefined, ProjectionOptions = undefined>(
  args: InsertWebhookArgs<V, EnrichmentType, ProjectionOptions>
): Inserted<V, EnrichmentType>
```

Insert a webhook's projection. Sibling of `insertOperation` for
the OAS 3.1 webhook subject - webhooks are OAS-only, so there is no
protocol discrimination.

### insertNormalizedModel

```ts
insertNormalizedModel<V extends GeneratedValue, Schema extends OasSchema | OasRef<'schema'> | OasVoid, EnrichmentType, ProjectionOptions = undefined>(
  projection: NormalizedModelProjection<V, EnrichmentType, ProjectionOptions>,
  args: InsertNormalizedModelArgs<Schema>,
  ...rest: ProjectionOptionsRest<InsertNormalizedModelOptions<ProjectionOptions>, ProjectionOptions>
): InsertNormalizedModelReturn<V, Schema>
```

Insert a normalized model: dispatch to `insertModel` when the schema
is a `$ref`, otherwise produce a one-off definition under `fallbackName`.

### insertModel

```ts
insertModel<V extends GeneratedValue, EnrichmentType, ProjectionOptions = undefined>(
  projection: ModelProjection<V, EnrichmentType, ProjectionOptions>,
  ref: RefParts,
  ...rest: ProjectionOptionsRest<InsertModelOptions<ProjectionOptions>, ProjectionOptions>
): Inserted<V, EnrichmentType>
```

Insert a model definition into `destinationPath`.

Resolves identifier and export path from the projection, registers the
definition (or reuses a cached one), and stitches an import into
`destinationPath` if it differs from the projection's `exportPath`.

### toOperationContentSettings

```ts
toOperationContentSettings<V extends GeneratedValue, EnrichmentType, ProjectionOptions>(
  settingsArgs: ToOperationSettingsArgs<V, EnrichmentType, ProjectionOptions>
): ContentSettings<EnrichmentType>
```

Build content settings for an operation projection: its enrichments,
from the `toEnrichments` of its generator's entry, and what its statics
`toIdentifierName`, `toIdentifierType` and `toExportPath` give for them.

### toWebhookContentSettings

```ts
toWebhookContentSettings<V extends GeneratedValue, EnrichmentType, ProjectionOptions>(
  args: ToWebhookSettingsArgs<V, EnrichmentType, ProjectionOptions>
): ContentSettings<EnrichmentType>
```

Build content settings for a webhook projection. Sibling of
`toOperationContentSettings`; webhooks are OAS-only, so there is no
protocol discrimination.

### toModelContentSettings

```ts
toModelContentSettings<V extends GeneratedValue, EnrichmentType, ProjectionOptions>(
  args: BuildModelSettingsArgs<V, EnrichmentType, ProjectionOptions>
): ContentSettings<EnrichmentType>
```

Build content settings for a model projection by calling its statics
`toIdentifierName` (pure, for the name) + `toIdentifierType`
(context-aware, for type/typeName/exported) and `toExportPath` with
the enrichments of the given `ref` and `variant`, from the
`toEnrichments` of its generator's entry. The full identifier is
assembled through the projection's language (`lang.toIdentifier`).

With no projection options, `toIdentifierName` and `toExportPath` are
asked once in a run for each projection, ref and variant.

### resolveSchemaRefOnce

```ts
resolveSchemaRefOnce(ref: RefParts): OasSchema | OasRef<'schema'>
```

Perform one lookup of a model's schema: a component by `refName`, or,
with a `refPath` other than `#/components/schemas`, the ref target the
parser kept under its whole pointer.

- `ref`: The model's ref; an `OasRef<'schema'>` fits as it is

Returns: Matching schema or ref

Throws:

- `DanglingRefError`: when no schema is found there

### findDefinition

```ts
findDefinition(args: FindDefinitionArgs): DefinitionBase | undefined
```

Check if definition name `name` in file with path `exportPath`
has already been created and registered.

Returns: Matching definition if found or `undefined` otherwise
