@bazariodev/typecase
v0.1.0
Published
Language lookup, syntax tokens, JSON formatting, and JSON container checks.
Maintainers
Readme
@bazariodev/typecase
Prepare source text for display and identify JSON objects and arrays. Use the core with any JavaScript client. The application selects the languages, styles, and limits.
Install
npm install @bazariodev/[email protected]Use this command after 0.1.0 publication. Before publication, use these Bazario workspace commands to build a local tarball:
pnpm --filter @bazariodev/typecase build
pnpm --filter @bazariodev/typecase pack --pack-destination "$PWD"In the application, install the tarball by its path:
npm install /path/to/bazariodev-typecase-0.1.0.tgzInstall react 18 or 19 to use /react. Install lowlight 3 to use /lowlight. Install
highlight.js ~11.11.0 when the application imports its grammars.
Usage
Highlight JSON with a tokenizer that loads on demand.
import { Highlighter } from '@bazariodev/typecase/highlight';
const highlighter = new Highlighter({
loaders: {
json: async () => {
const [{ createTokenizer }, { default: grammar }] = await Promise.all([
import('@bazariodev/typecase/lowlight'),
import('highlight.js/lib/languages/json'),
]);
return createTokenizer('json', grammar);
},
},
});
const source = '{"ready":true}';
const result = await highlighter.highlight(source, 'json');To load XML, SQL, or CSS, use the language ID and grammar module from this table in the same loader pattern.
| Language ID | Highlight.js grammar module |
| --- | --- |
| xml | highlight.js/lib/languages/xml |
| sql | highlight.js/lib/languages/sql |
| css | highlight.js/lib/languages/css |
Show the source while the tokenizer loads. Render each token as literal text. Render plain
tokens as text nodes. Use kind to style the other tokens. For a text result, show
result.text. MDN createTextNode()
Behavior
- The application gets the extension from the display filename. It checks file byte limits and owns layout, labels, and controls. Use the source for Copy and the original file for Download.
- Tokens can span lines. Join their text to get the source exactly, including tabs and line
endings. Tokens from
Highlighter.highlightare mutable. Atextresult contains the full source. - A highlight call can load a tokenizer when its arguments are valid, its ID has a loader, and
the source is within
maxInputLength. Concurrent calls share the load for that ID. The highlighter keeps a successful load, even if tokenization fails. The next eligible call retries a failed load. The browser can keep a failed module import. - JSON formatting changes only whitespace outside strings. It keeps key order, duplicate keys,
number spelling, and escapes. Formatted text uses LF and has no outer whitespace. The result
is
unchangedif the only differences are outer whitespace or line endings. - Load optional entries where you use them. Show the source if an entry fails to load. Use the
default outgoing extension if the JSON check returns
false, the entry fails to load, or the application has no canonical extension for JSON.
API
| Entry | Export | Result |
| --- | --- | --- |
| Root | LANGUAGES | Built-in language definitions. |
| Root | new LanguageRegistry(definitions) | get(id), fromExtension(extension), and fromLabel(label) return a definition or undefined. |
| /highlight | new Highlighter(options) | highlight(source, languageId) resolves to { kind: 'tokens', tokens } or { kind: 'text', text, reason }. |
| /lowlight | createTokenizer(name, grammar) | A tokenizer that joins adjacent tokens of the same kind before it counts them. |
| /json | formatJson(source, options?) | { kind: 'formatted', text } for a layout change. Otherwise, { kind: 'original', text, reason }. |
| /json | isJsonContainer(source) | true for a complete JSON object or array. Otherwise, false. |
| /react | useHighlight(highlighter, source, languageId) | A read-only result, or undefined while inputs are missing or the call is pending. |
| /web-components | defineCodeElement() | Registers <typecase-code> and returns its constructor. |
In createTokenizer, use the Highlight.js registration name that the grammar expects. This
name can differ from the Typecase language ID. The adapter checks that Lowlight registered this
name and throws TypeError if it did not. Each tokenizer registers one grammar. An embedded
language without a registered grammar stays plain text. maxInputLength limits grammar input.
Lowlight builds its tree before maxTokens limits token output.
Client adapters
Both adapters take an object with highlight(source, languageId). The method returns a promise
for a core result. A null or undefined input pauses highlighting. An empty source string is
valid. Each adapter ignores results for earlier inputs.
Call useHighlight(highlighter, source, languageId) at the top level of a React client component.
Pass a language ID from a supported file extension or a labeled fence. Pass undefined for prose.
Do not call the hook conditionally. Render the source until the hook returns a result. The hook
throws a rejection for the current inputs during render so a React error boundary can catch it.
Create the highlighter once outside the component or in useMemo or a lazy state initializer.
When the highlighter, source, and language ID have values, a new highlighter object on each render
starts a new call after each result. The hook then never returns a result. Reuse a stable
highlighter while its settings match. The hook keeps at most 16 entries for each highlighter. Each
entry uses the exact source and language ID. The hook shares a pending call and a read-only token
result across remounts. A cached token, limit, or unsupported result is available on the first
render after remount. A later request can retry an unavailable result or a rejected call. Reuse
ends after entry eviction. If all callers unmount before dispatch, the hook skips the call. React
results and their tokens are read-only.
Call defineCodeElement() in browser startup. Repeat calls from the same module return the
same constructor. A different definition for the same tag raises NotSupportedError.
Set the element's highlighter, source, and languageId properties. The element batches
changes and starts highlighting while connected. It reuses a pending call or token result for
the same inputs. It applies a result for the current inputs even while detached. It shows the
source while it waits. A new connection retries a current unavailable result or rejected call.
If the current call rejects, it keeps the source. It calls reportError only while connected.
The element renders plain tokens as text nodes. Style them through <code>. Use [data-kind]
for the spans of other kinds. For repeated Web Component or Angular highlighting, the application
can supply a stable caching wrapper with the same async method. Key cached token results by source,
language ID, and highlighter. Bound the cache. Treat cached tokens as read-only.
In Angular, call highlighter.highlight(source, languageId) from ngOnChanges. Store the
current result in a signal that the template reads. Ignore late results after an input change
or ngOnDestroy. Angular lifecycle, Angular signals
Languages
A definition has an id and can have extension, extensions, and labels. Set extension
to the canonical outgoing extension without a dot. Put alternate extensions in extensions.
For a label-only language, supply at least one label and omit both extension fields. Find this
definition by ID or label.
IDs match exactly. Labels and extensions match without case. Extension lookup accepts the
canonical extension and aliases with or without a leading dot. Duplicate IDs or keys that
name two languages in one lookup table cause TypeError. The registry copies and freezes its
definitions and alias arrays. The built-in definitions and their alias arrays are frozen.
| Definition | ID | Canonical extension | Extra extension | Extra label |
| --- | --- | --- | --- | --- |
| LANGUAGES.JSON | json | json | | |
| LANGUAGES.XML | xml | xml | | |
| LANGUAGES.YAML | yaml | yaml | yml | yml |
| LANGUAGES.JAVA | java | java | | |
| LANGUAGES.JAVASCRIPT | javascript | js | | js |
| LANGUAGES.TYPESCRIPT | typescript | ts | | ts |
| LANGUAGES.PYTHON | python | py | | py |
| LANGUAGES.SQL | sql | sql | | |
| LANGUAGES.CSS | css | css | | |
Each built-in definition accepts its ID as a label. Add product extensions as needed.
import { LanguageRegistry, LANGUAGES } from '@bazariodev/typecase';
const registry = new LanguageRegistry([{ ...LANGUAGES.YAML, extensions: ['yml', 'config'] }]);
const language = registry.fromExtension('.CONFIG');Settings
| Operation | Settings | Defaults |
| --- | --- | --- |
| Highlight | Set loaders by language ID. Limits apply per highlighter. | maxInputLength 65,536 and maxTokens 10,000. |
| Format JSON | Set indent to 'tab' or an integer from 1 to 8. | Two spaces. maxInputLength 65,536 and maxOutputLength 262,144. |
Set length and token limits to positive safe integers. Lengths count UTF-16 code units. The
length or token count can equal its limit. Check your source length before calling
isJsonContainer. It validates the full string after a check for an opening { or [.
MDN String.length
A loader takes no arguments and returns a synchronous tokenizer or a promise for one. Use
() => myTokenizer for a custom tokenizer. A load fails if it produces a value other than a
function. A call to tokenize(source, { maxTokens }) gives a fresh list of { text, kind }
tokens. Each token has nonempty text. Empty source gives []. If the token limit prevents a
complete result, the tokenizer returns null. Use highlight for the input check and text
fallback. Token kinds are plain, comment, keyword, string, number, literal,
operator, punctuation, name, and type.
Errors
Invalid arguments or settings cause TypeError. This includes a missing { maxTokens }
argument. A number outside its allowed integer range causes RangeError. With invalid
arguments, highlight rejects its promise.
If JSON.parse throws for a string, isJsonContainer returns false. The parser's nesting
limit can vary by engine.
The registry raises TypeError for extensions without extension. It also raises TypeError
if a definition has neither extension nor a label, an empty extension or label, or a dot in
any extension.
| Result | Reason | Condition |
| --- | --- | --- |
| Highlight text | unsupported | No loader for the ID. This takes precedence over the input limit. |
| Highlight text | limit | Input or token count exceeds its limit, or the tokenizer returns null. |
| Highlight text | unavailable | The loader or tokenizer fails or returns an invalid value. Each token needs a nonempty string for text and a known kind. Joined token text must equal the source. |
| JSON original | invalid | The source is within the input limit and JSON.parse throws. This includes empty text, whitespace-only text, and a leading U+FEFF. |
| JSON original | limit | Input or output exceeds its length limit. |
| JSON original | unchanged | The formatted text equals the source after removal of outer whitespace and conversion of line endings to LF. This includes valid scalars within both length limits. The result contains the source as received. |
TypeScript
Each entry has ESM and CommonJS declarations. Root, /highlight, /json, and /lowlight do not
need DOM types. Use DOM types with /web-components.
License
MIT.
