# How to compose one generated file from several components

> Fill one generated TypeScript file from several features with jostraca's Fragment, Slot and Inject, and decide what happens when two features claim one slot.

Source: https://voxgig.com/howto/compose-generated-files-with-slots-and-fragments

- Audience: library-maintainer
- Level: intermediate
- Languages: typescript
- Verified: 2026-11-22
- Published: 2026-11-22

## Short answer

Write the file once as a jostraca Fragment over a template that stays valid TypeScript, with // <[SLOT:imports]> and // <[SLOT:methods]> markers in comments. Let each feature add Slot content through a small wrapper that merges imports and refuses a method name already taken, because jostraca concatenates two Slots of one name. Edit a hand-written file with Inject between markers.

---
## You will need

Node 22 or later, and a generator whose features write into one file. Verified 2026-11-22
against jostraca 0.42.0 with shape 12.2.5, TypeScript 5.9.3, Hey API 0.99.0 and NSwag 14.8.0.
Model values go into `Content` text as `$$path$$`. jostraca writes the value as it is, with no
escaping, and leaves a path the model lacks in the output unchanged.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Hey API entry file](https://heyapi.dev/docs/openapi/typescript/output#entry-file) | A TypeScript client whose plugins each own their files, joined by one `index.ts` | Each plugin writes its own files; a shared file beyond the entry needs the plugin API, still in development | Two features must add to the same class |
| [Hygen inject templates](https://github.com/jondot/hygen/blob/master/hygen.io/docs/templates.md#injection) | Small edits to files that already exist, one template per edit | An anchor found by a regular expression, so an edit elsewhere can move it | The file is generated whole each run |
| [jostraca Fragment, Slot and Inject](https://jostraca.org/docs/reference-components/#slot) | Features that each fill named regions of one generated file | Two Slots of one name are concatenated, so the clash rule is yours to write | A single feature writes the file |
| [NSwag ExtensionCode](https://github.com/RicoSuter/NSwag/wiki/TypeScriptClientGenerator) | Code added to a generated C# or TypeScript client class | One extension file, and of two bodies for one class only the last is kept | Several teams contribute to one class |
| [Nx generator Tree API](https://nx.dev/docs/reference/devkit/Tree) | Generators in an Nx workspace that read and rewrite files in a virtual tree | Every edit is code over file text, through the Tree's read and write methods | You are not in an Nx workspace |

Voxgig maintains jostraca, the subject of this page; the other four tools are not Voxgig's.

jostraca declares the whole file in one tree, so every contribution has a named place before
anything is written. Hygen and Nx edit a file where an anchor or your own code says, which
suits a file you did not generate. Hey API and NSwag offer one fixed seam each: an entry file
and an extension class.

## Mark the slots in a template that compiles

Put each marker in a comment and give the class a real name, so `tsc` can check the template
before it is used. A test type-checks it alone.

```ts title="tpl/client.ts"
// Generated from tpl/client.ts by the features in features.mjs. Edit those.
// <[SLOT:imports]>
export class ApiClient {
  constructor(readonly baseUrl: string) {}

  // <[SLOT:methods]>
}
```

The generator renames `ApiClient` with `Fragment`'s `replace` option. A `$$path$$` would not
do here, since `$$service.className$$Client` is not a TypeScript identifier.

## Fill the slots from each feature

jostraca puts every `Slot` with a matching name at the marker, concatenated in the order they
were emitted. That is the only behavior it offers for a shared slot, so the choice between
merging and failing goes in a wrapper.

```js title="parts.mjs"
    method(owner, text) {
      const declared = text.split('\n').map((l) => l.match(MEMBER)).filter(Boolean)
        .map(([, isStatic, name]) => (isStatic ? 'static ' : '') + name)
      if (declared.length === 0) throw new Error(`slot methods: ${owner} declares no member`)
      for (const [i, key] of declared.entries()) {
        if (methods.has(key)) {
          throw new Error(`slot methods: ${key}() from ${owner} is already there from ${methods.get(key)}`)
        }
        if (declared.indexOf(key) !== i) throw new Error(`slot methods: ${owner} declares ${key}() twice`)
      }
      for (const key of declared) methods.set(key, owner)
      // A plain function, not a cmp(): a Slot must be a direct child of the
      // Fragment, and a component wrapper would hide it.
      Slot({ name: 'methods' }, () => Content(text))
    },
```

The wrapper reads the member names from the source a feature hands it. A getter, a property or an
`async` method with a taken name stops the build before a file is written. A name that differs
only in case, or a static member beside an instance one, is a separate member to TypeScript and
passes. Imports are parsed and merged by name and module, whatever their spacing or quotes, and
one name imported from two modules is refused. `finish()` emits both slots even when no feature
used one, so no marker survives as text.

## Compose the file and inject the export

The generator fills the template from each feature in sorted order, then injects one export
line between two markers in `src/index.ts`, a file a person wrote.

```js title="generate.mjs"
          Fragment({ from: TEMPLATE, replace: { ApiClient: `${model.service.className}Client` } }, () => {
            const parts = slotParts()
            // Sorted, so reordering the model's list does not reorder the file.
            for (const f of [...model.features].sort()) FEATURES[f](parts)
            parts.finish()
            Object.assign(owners, parts.owners())
          })
        })
        Inject({ name: 'index.ts', markers: MARKERS }, () => {
          Line(`export { ${model.service.className}Client } from './client'`)
        })
```

`TEMPLATE` is an absolute path built from `import.meta.url`. A relative `from` resolves against
the output folder, and a test shows it failing with `ENOENT` there. `compose.mjs` runs the
generator in memory and prints both files.

```bash
node compose.mjs
```

```text output
--- src/client.ts
// Generated from tpl/client.ts by the features in features.mjs. Edit those.
import type { Call } from './transport'

export class ThingsClient {
  constructor(readonly baseUrl: string) {}

  async withToken<T>(call: (token: string) => Promise<T>, token: Call<string>): Promise<T> {
    return call(await token())
  }
  async withRetry<T>(call: Call<T>, attempts = 3): Promise<T> {
    for (let i = 1; ; i++) {
      try {
        return await call()
      } catch (err) {
        if (i >= attempts) throw err
        await new Promise((done) => setTimeout(done, 100 * i))
      }
    }
  }

}
--- src/index.ts
// Hand-written. The generator rewrites only the lines between the markers.
export { version } from './version'
// <generated-exports>
export { ThingsClient } from './client'
// </generated-exports>
--- 0 warnings
```

Both features asked for the `Call` import, and it appears once. `3` and `100` came from the
model through `$$retry.attempts$$` and `$$retry.delayMs$$`.

## Check it worked

Run the tests. They type-check the template and the output, reorder the features and the imports,
and feed the wrapper each clash it refuses. They also check what `$$path$$` writes,
run the generator twice over its own output, and hold the two generator runs below to their
records.

```bash
node --test compose.test.mjs generators.test.mjs
```

```text output
# tests 21
# suites 0
# pass 21
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

The second run leaves one `export { ThingsClient }` line in `src/index.ts`, because `Inject`
replaces what lies between the markers.

## When it goes wrong

`pitfall.mjs` reproduces four failures against the same template.

```bash
node pitfall.mjs
```

```text output
same method twice, raw Slots:   2 x withRetry, tsc exit 2
  client.ts(6,3): error TS2393: Duplicate function implementation.
same method twice, slotParts:   slot methods: withRetry() from retry-v2 is already there from retry
Slot inside a cmp():            jostraca: Fragment has non-Slot children, but tpl/client.ts contains no unnamed <[SLOT]> marker to receive them; their output would be silently discarded
no Slot at all:                 markers left: 2
slotParts, no feature:          markers left: 0
```

Two features add the same method. Raw `Slot`s write it twice, and `tsc` is the first to object.
Route methods through the wrapper so the clash stops generation instead.

A feature's methods vanish, or the build throws an error whose first sentence is the one `pitfall.mjs` printed,
with the template's full path. The `Slot` was emitted inside
a `cmp()` component, and the fragment reads its direct children only. Call features as plain
functions inside the `Fragment` body.[^1]

A marker is still in the output. No `Slot` matched it, and jostraca leaves an unmatched named
marker as text. In a comment that compiles and goes unnoticed, so emit every slot once.

`Inject` changes nothing. Its markers were not in the target file. jostraca leaves the file alone
and sends a warning to `log.debug`, so collect the warnings and fail on any.

A `$$retry.attempts$$` is still in the output. The model has no value at that path, and jostraca
writes the placeholder as it found it. Check the model before the tree, as `checkModel` does.

## Compose the client in Hey API and NSwag

Every file Hey API writes comes from a plugin, and an
[entry file](https://heyapi.dev/docs/openapi/typescript/output#entry-file), `index.ts`, joins them. A
plugin's `includeInEntry` option adds its exports there. NSwag copies the body of each class named
in `ExtendedClasses` from its
[`ExtensionCode`](https://github.com/RicoSuter/NSwag/wiki/TypeScriptClientGenerator) file into the
generated class. `generate.sh` ran both on the Bookshelf document. For NSwag it put the retry body and the auth
body in one extension file, once in each order.

```bash
node generators.mjs
```

```text output
Hey API entry file, generated/hey-api/index.ts, re-exports from 3 files:
  ./sdk.gen    6 names
  ./types.gen  17 names
  ./zod.gen    11 names
NSwag, extension code retry then auth: Client keeps withToken
NSwag, extension code auth then retry: Client keeps withRetry
```

NSwag answers the shared-slot question with last-wins and no warning, in either order. The
overwrite comes from NJsonSchema, the library NSwag 14.8.0 bundles: on its master branch the
[extension-code parser](https://github.com/RicoSuter/NJsonSchema/blob/master/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptExtensionCode.cs)
stores each extended class's body by class name (line 38). Merge the contributions into one
extension class yourself before you run it. NSwag 14.8.0 was the newest release on npm on the day. Hey API's entry file holds re-exports only, so
two features that must add to one generated class need a
[custom plugin](https://heyapi.dev/docs/openapi/typescript/plugins/custom), whose API its
documentation marks as in development.

## When not to do this

Do not build slots for a file one feature writes. A plain `File` with `Content` is shorter, and a
template with markers nobody fills is noise.

Do not choose jostraca to edit files your generator did not create. `Inject` needs markers a
person put in the file. A Hygen template's `before`, `after` and `skip_if` find an anchor in a file nobody
prepared, and an Nx generator can read and rewrite it through the Tree API.

Do not rely on concatenation order for anything that matters. jostraca emits `Slot`s in call
order, so sort the contributors or fix their order in one place.

If the shared file is the generated client itself, NSwag's extension class may be all the
composition you need while one team owns each class. Hey API's entry file suits features that can
each own a file. Both cost less than a component tree.

## Related how-tos

- [Generate a code section with code instead of a template](/howto/generate-a-code-section-with-a-component)

- [Check whether two generator runs produce identical output](/howto/check-two-generator-runs-are-identical)

- [Set an overwrite policy for a regenerated SDK](/howto/set-an-overwrite-policy-for-regeneration)

- [Find hand edits in a generated SDK before you regenerate](/howto/find-hand-edits-before-regenerating)

- [Choose a template engine for generating source code](/howto/choose-a-template-engine-for-generated-code)

## Last verified

Verified 2026-11-22 against Node 22.23.5, jostraca 0.42.0, shape 12.2.5 and TypeScript 5.9.3.
Every output block is what the command preceding it printed. Hey API 0.99.0 and NSwag 14.8.0,
on the ASP.NET Core 10 runtime, ran once in `generate.sh`, and the page reads what they wrote.
Hygen and Nx were not run; their rows come from their documentation, read on the same day.

[^1]: The [component reference](https://jostraca.org/docs/reference-components/#slot) lists
seven ways to wrap a marker in comment decoration, from `<!-- -->` to a bare indent, and calls
the list not exhaustive. It is more definite about the cmp() case: a `Slot` created
inside a custom component is not recognized as a slot, because the fragment inspects only its
direct children.