skmtc-generator

typescript

A reference of skmtc-generator 0.17.0

Reference

The TypeScript layer (@skmtc/lang-typescript)

What a generator that writes TypeScript takes from its lang package: base factories, TsSnippet, the register calls, identifier kinds, import forms, List and the helpers for strings from the document. Read the section for the work in hand.

1. Declaring the language

The declaration is the import graph — no lang config field exists. src/base.ts imports a factory; the returned class extends TsSnippet, which carries the static lang Drivers read pre-construction.

import { sanitizeIdentifier, toTsModelProjectionBase } from '@skmtc/lang-typescript'

export const MyBase = toTsModelProjectionBase<EnrichmentSchema>({
  id: denoJson.name,
  toIdentifierName({ ref }) { return sanitizeIdentifier(decapitalize(camelCase(ref.refName))) },
  toIdentifierType: () => ({ type: 'variable' }),
  toExportPath({ ref, enrichments, variant }) {
    const name = this.toIdentifierName({ ref, enrichments, variant })
    return `@/types/${name}.generated.ts`   // '@/' is basePath; always forward slashes
  },
  toEnrichmentSchema
})

The model statics receive the model's ref ({ refName, refPath }). refPath is #/components/schemas for a component, and the pointer before refName for a ref into a $defs entry, a property or #/paths/…. The example names by ref.refName alone; read ref.refPath too when your documents have two deep targets with one refName.

Factories: toTsModelProjectionBase, toTsOasOperationProjectionBase (+ webhook/GQL variants). Snippets extend TsSnippet directly. Casing helpers (camelCase, capitalize, decapitalize) and toEndpointName come from @skmtc/core. An export path is @/ plus a forward-slash path relative to basePath; write it as a template literal, never with a path-library join, which would use the host's separator (backslashes on Windows) inside generated import text.

The veneers take two type parameters: EnrichmentType and ProjectionOptions, the caller options a peer passes as { options } on an insert (engine.md, "Enrichments and options"). Declare the second to accept options; toIdentifierName / toExportPath then receive options and the instance stores it as this.options:

import { toTsModelProjectionBase } from '@skmtc/lang-typescript'

type ShapeOptions = { suffix: 'Input' | 'Output' }

export const MyBase = toTsModelProjectionBase<EnrichmentSchema, ShapeOptions>({
  id: denoJson.name,
  toIdentifierName({ ref, options }) { return `${camelCase(ref.refName)}${options.suffix}` },
  toIdentifierType: () => ({ type: 'variable' }),
  toExportPath({ ref, enrichments, variant, options }) {
    const name = this.toIdentifierName({ ref, enrichments, variant, options })
    return `@/types/${name}.generated.ts`
  },
  toEnrichmentSchema
})

Consuming a peer that declares options needs nothing from this layer: this.insertModel(Peer, ref, { options }).

A projection consumable by peers via insertNormalizedModel also needs two statics: schemaToValueFn (your router) and createIdentifier.

2. The three register shapes

CallerCallDestination
Projectionthis.register(args)its own export file
Projectionthis.registerInto(path, args)explicit file
Snippetthis.register({ ...args, destinationPath })required — snippets own no file

Free functions for transform-level code: register(context, args); defineAndRegister(context, { identifier, value, destinationPath }) — no cache check (pair with context.findDefinition for the accumulator get-or-create idiom). Args: { imports?: Record<module, ImportNameArg[]>, reExports?, definitions?, custom? }. register creates the file on first write and drops self-imports, so register imports unconditionally — per-leaf registration (every snippet needing z registers { zod: ['z'] }) is the correct pattern, and merging is idempotent. An imports key spelled from the workspace root (@/, ./, /) is an export path; any other key (zod, types/y.ts) is a module specifier, written as it is.

3. Identifier kinds

TypeScript output has five entity kinds — TsEntityType = 'variable' | 'type' | 'class' | 'interface' | 'namespace' — factories createVariable(name, { typeName? }), createType, createClass, createInterface, createNamespace. No 'function' kind: a generated function is a variable whose value renders as an arrow function. The engine's identifier type is an opaque string; isTsEntityType narrows it to the five above. ContentSettings.identifier is the neutral IdentifierBase; toTsIdentifier(identifier) narrows it back to the TsIdentifier a reExports entry needs (a barrel: registerInto(barrelPath, { reExports: { [exportPath]: [toTsIdentifier(settings.identifier)] } })).

toIdentifierType is one lever with three effects: declaration keyword; block form (class/interface/namespace take no = value;); and whether consumers import it type-only (type and interface do — this is what keeps consumers compiling under verbatimModuleSyntax/TS1484, and you get it by choosing the kind, never by writing import syntax). File dedup keys on keyword+name, so class Foo + namespace Foo coexist (declaration merging); first write wins per slot.

4. Emitted-import rules

Concise forms per module: ['z'] (named), [{ default: 'invariant' }] (aliased/default), [{ name: 'User', type: 'type' }] (type-only). Sharp edge: only type: 'type' triggers type-only in the concise form — type: 'interface' does NOT; tag interfaces type: 'type'. Register against @/… export paths, where @/ is the workspace root. At render TsFile re-keys each module through settings.packages: same package → @/ from that package's root; another package → the innermost root's moduleName; no root → as written. A package file that imports a workspace-root path under no root throws at render.

A module loaded on demand is a snippet, not an import: new TsDynamicImport({ context, module, destinationPath }) renders import('<module>') where it stands, with the module re-keyed as a header import in that file would be. Do not also import that module in the file's header (the module would load at startup after all); a type-only header import is fine.

5. Composition helpers

All are Stringable, and all join at render.

  • List is for a real list: items of one kind, in a number the document sets (properties, parameters, entries, steps). Use it in place of array.join over producers. A fixed set of different parts is a template over named fields (producers.md, rule 5). List.toObject/toArray/toParams/toLines/toKeyValue, List.fromKeys(record).toObject(fn), new List(values, { separator, bookends, skipEmpty }). Build a List in the constructor: the lint rule skmtc/tostring-purity reports new List(…) in toString(). A List leaves out an item that is undefined. It keeps an item that renders '', and skipEmpty acts on an empty list only.
  • FunctionParameter({ typeDefinition, destructure, required, skipEmpty }) — one object, four readings: toString() (declaration), toInbound() (call site), toPropertyList() (the variables), hasProperty(name). Destructured, a property whose name cannot be a variable is renamed with toParameterVariable: {'user-id': userId, export: exportValue}.
  • toPathTemplate('/users/{id}') → /users/${id}, the body of a template literal: static text is escaped, and {user-id} gives ${userId}, or ${params['user-id']} with 'params' as the second argument. toPathParams → /users/:id; PathParams bundles type + parameter + template.
  • keyValues, withDescription, handleKey, handlePropertyName; TsClass/TsHeritage for class syntax (TsHeritage registers its own heritage imports).

6. Sanitizing emitted names

A string from the schema (a model name, a property name, a description, a pattern) can hold any character: a.b, count(), a"b, a line break. Each place it lands in TypeScript has one helper. Never quote, escape or hand-roll keyword lists yourself:

Where the string landsHelper
a binding name (export const <name>, a type, a class)sanitizeIdentifier(name) inside toIdentifierName, and on a fallbackName built from schema text (default → defaultValue, 2fa → _2fa). A TsIdentifier stores the name as given, so the name you return is the name peers insert and findDefinition finds.
the variable of an operation parametertoParameterVariable(name) (user-id → userId, export → exportValue): the name FunctionParameter and toPathTemplate use.
an object keyhandleKey(key): quotes it only when needed
a property accesshandlePropertyName(name, parent)
a destructured property that is not a parametersanitizePropertyName(name): a rename pair when needed
a string literaltoStringLiteral(value), never '${value}' or "${value}"
a JSDoc commentwithDescription(value, { description }): escapes */
a regex that matches exact textescapeRegExpText(text)
a regex for any string except some namestoAnyStringExceptPattern({ names })
a regex literal in codetoRegExpLiteral(source, flags?)

toRegExpLiteral throws a SyntaxError on a pattern or flags that are not valid JavaScript ((?i), a trailing \, 'gg'). A throw fails the whole run, so where you read pattern from a document, catch it, leave that check out, and say so in the output with withDescription (gen-effect-schema's EffectString does this).

Sanitizing is lossy: default and defaultValue give one binding. In one file the second insert throws Registered definition mismatch, naming both schemas, and the run fails.

7. Files

Render order: custom banner → re-exports → imports → definitions; first-wins per definition slot makes output order-independent. Definitions render in the order they were added, a model's when its constructor returned, so a const lands after the models it refers to. You almost never construct TsFile/TsImport/TsDefinition yourself — register and the Drivers do.

8. What a field holds

// Wrong: the field holds rendered text. The `z` import is not registered, and a ref is not reused.
this.properties[key] = `z.string().optional()`
// Right: the field holds a producer. Its imports register, and the cache sees it.
this.properties[key] = toMyValue({ schema: propSchema, required, destinationPath, context })

A field can hold a plain string that is a fact: an identifier name, an export path, a module specifier, a literal, the name of a peer's definition. Read a peer's name from the result of the insert: definition.identifier.name from insertNormalizedModel, or .toName() from the Inserted handle of insertModel. Modifiers (applyModifiers) run in toString(), and never build a stored field.

9. TypeScript pitfalls

SymptomFix
TS1484 in consumersIdentifier kind type/interface; concise imports need type: 'type'
Interface import emitted as valueTag it type: 'type' (known concise-form gap)
TS7022/7024 on recursive schemasSet settings.identifier.typeName (e.g. z.ZodType<X>) post-construction; the name stays stable
Provenance holes under some nodestoString must be a prototype method, never an arrow field
Doubled ?/modifiersOne owner: apply modifiers once, at the leaf's render