Creating Custom Extensions
This guide covers building your own GLOST plugins for the v0.5+ processor API.
Plugin Basics
A plugin is an object implementing the Plugin interface:
interface Plugin {
id: string; // Unique identifier
name: string; // Human-readable name
description?: string; // What it does
// Processing methods (all optional)
transform?: (tree: GLOSTRoot) => GLOSTRoot | Promise<GLOSTRoot>;
visit?: { /* visitors */ };
enhanceMetadata?: (node: GLOSTWord) => Partial<GLOSTExtras> | void;
// Configuration
dependencies?: string[];
options?: Record<string, unknown>;
}Plugin Patterns
1. Metadata Enhancement
The simplest pattern - adds data to word nodes:
const WordCountPlugin: Plugin = {
id: "word-count",
name: "Word Character Count",
enhanceMetadata: (node) => {
const text = node.children
.map(c => c.value)
.join("");
return {
metadata: {
characterCount: text.length
}
};
}
};2. Visitor Pattern
Process specific node types:
const SentenceLengthPlugin: Plugin = {
id: "sentence-length",
name: "Sentence Length",
visit: {
sentence: (node) => {
const wordCount = node.children.filter(
c => c.type === "WordNode"
).length;
return {
...node,
extras: {
...node.extras,
wordCount
}
};
}
}
};3. Transform Pattern
Modify the entire tree structure:
const SortParagraphsPlugin: Plugin = {
id: "sort-paragraphs",
name: "Sort Paragraphs",
transform: (tree) => {
const sortedChildren = [...tree.children].sort((a, b) => {
// Custom sort logic
return 0;
});
return {
...tree,
children: sortedChildren
};
}
};4. Async Pattern
For fetching external data:
const DictionaryPlugin: Plugin = {
id: "dictionary-lookup",
name: "Dictionary Lookup",
visit: {
word: async (node) => {
const text = node.children.map(c => c.value).join("");
const response = await fetch(`/api/dictionary/${text}`);
const data = await response.json();
return {
...node,
extras: {
...node.extras,
definition: data.definition,
examples: data.examples
}
};
}
}
};Factory Pattern
Create configurable plugins with factory functions:
interface HighlightOptions {
minFrequency?: number;
highlightColor?: string;
}
function createHighlightPlugin(options: HighlightOptions = {}): Plugin {
const { minFrequency = 100, highlightColor = "yellow" } = options;
return {
id: "highlight-rare-words",
name: "Highlight Rare Words",
options,
enhanceMetadata: (node) => {
const frequency = node.extras?.metadata?.frequencyRank;
if (frequency && frequency > minFrequency) {
return {
metadata: {
highlight: true,
highlightColor
}
};
}
}
};
}
// Usage
const plugin = createHighlightPlugin({ minFrequency: 500 });Dependencies
Declare dependencies for ordering:
const AnalysisPlugin: Plugin = {
id: "analysis",
name: "Word Analysis",
dependencies: ["frequency", "difficulty"], // Runs after these
enhanceMetadata: (node) => {
// Can rely on frequency and difficulty data being present
const freq = node.extras?.frequency?.level;
const diff = node.extras?.difficulty?.level;
return {
metadata: {
studyPriority: calculatePriority(freq, diff)
}
};
}
};Registering Plugins
Global Registration
import { pluginRegistry } from '@glotblocks/glost';
// Single plugin
pluginRegistry.register(MyPlugin);
// Multiple plugins
pluginRegistry.registerAll([Plugin1, Plugin2, Plugin3]);Using Registered Extensions
import { processGLOST, getExtension } from '@glotblocks/glost-plugins';
// Get extension by ID
const frequencyExtension = getExtension("frequency");
const result = processGLOST(document, [frequencyExtension, MyExtension]);Error Handling
Plugins should handle errors gracefully:
const SafePlugin: Plugin = {
id: "safe-plugin",
name: "Safe Plugin",
visit: {
word: (node) => {
try {
// Processing that might fail
const result = riskyOperation(node);
return { ...node, extras: { ...node.extras, result } };
} catch (error) {
// Return undefined to leave node unchanged
console.warn("Plugin failed for word:", node);
return undefined;
}
}
}
};Testing Plugins
import { describe, it, expect } from 'vitest';
import { glost, createGLOSTWordNode, createSimpleDocument } from '@glotblocks/glost';
describe('MyPlugin', () => {
it('should add custom metadata', async () => {
const word = createGLOSTWordNode({
value: "test",
metadata: { partOfSpeech: "noun" }
});
const doc = createSimpleDocument([word], "en", "latin");
const result = processGLOST(doc, [MyExtension]);
const processedWord = result.children[0].children[0].children[0];
expect(processedWord.extras?.metadata?.myField).toBeDefined();
});
});Complete Example
import type { Plugin, GLOSTWord, GLOSTExtras } from '@glotblocks/glost';
import { getWordText } from '@glotblocks/glost';
interface ReadingTimeOptions {
wordsPerMinute?: number;
includeBreaks?: boolean;
}
export function createReadingTimePlugin(
options: ReadingTimeOptions = {}
): Plugin {
const { wordsPerMinute = 200, includeBreaks = true } = options;
let totalWords = 0;
let totalSentences = 0;
return {
id: "reading-time",
name: "Reading Time Calculator",
description: "Calculates estimated reading time for content",
options,
// Count words and sentences
visit: {
word: (node) => {
totalWords++;
return undefined; // Don't modify
},
sentence: (node) => {
totalSentences++;
return undefined;
}
},
// Add reading time to document
transform: (tree) => {
const minutes = totalWords / wordsPerMinute;
const breakTime = includeBreaks ? totalSentences * 0.5 / 60 : 0;
return {
...tree,
extras: {
...tree.extras,
readingTime: {
minutes: Math.ceil(minutes + breakTime),
wordCount: totalWords,
sentenceCount: totalSentences
}
}
};
}
};
}Using Custom Plugins
import { processGLOST } from '@glotblocks/glost-plugins';
import { createReadingTimeExtension } from './my-extensions';
const readingTime = createReadingTimeExtension({ wordsPerMinute: 180 });
const result = processGLOST(document, [readingTime, frequencyExtension]);
console.log(result.extras?.readingTime);
// { minutes: 5, wordCount: 850, sentenceCount: 42 }Best Practices
- Use unique IDs - Prefix with your namespace
- Return undefined for no-op - Don’t return the same node
- Handle missing data - Check for optional fields
- Keep plugins focused - One responsibility per plugin
- Document dependencies - Clearly state what data is required
- Test edge cases - Empty documents, missing fields
- Use factories - For configurable plugins
- Be async-aware - Async operations work automatically
Last updated on