### Prefixes Option Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/configuration.md Example of how to configure custom prefixes. ```typescript const options = { prefixes: { ex: 'http://example.org/', foaf: 'http://xmlns.com/foaf/0.1/', schema: 'https://schema.org/' } }; // Output will use: // @prefix ex: . // @prefix foaf: . // @prefix schema: . ``` -------------------------------- ### ordered Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/configuration.md Example demonstrating deterministic output with ordered: true. ```typescript // Different input orders produce identical output const quads1 = [quad1, quad2, quad3]; const quads2 = [quad3, quad1, quad2]; const output1 = await write(quads1, { ordered: true }); const output2 = await write(quads2, { ordered: true }); console.log(output1 === output2); // true ``` -------------------------------- ### Compact Option Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/configuration.md Example demonstrating the effect of the 'compact' option. ```typescript // With compact: false (default) // Output: // @prefix ex: . // // ex:subject // ex:predicate ex:object . // With compact: true // Output: // @prefix ex: .ex:subject ex:predicate ex:object . const compact = await write(quads, { compact: true }); ``` -------------------------------- ### Format Option Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/configuration.md Examples of using the 'format' option for Turtle and N3. ```typescript // Turtle format (default) const ttl = await write(quads, { format: 'text/turtle' }); // Notation3 format const n3 = await write(quads, { format: 'text/n3' }); ``` -------------------------------- ### explicitBaseIRI Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/configuration.md Example demonstrating the effect of explicitBaseIRI. ```typescript // With explicitBaseIRI: false (default) // @prefix ex: . // ex:subject ex:predicate ex:object . // With explicitBaseIRI: true // @base . // @prefix ex: . // ex:subject ex:predicate ex:object . const result = await write(quads, { baseIri: 'http://example.org/base/', explicitBaseIRI: true }); ``` -------------------------------- ### Complete Options Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/configuration.md An example demonstrating how to configure all available options for the write function, including custom prefixes, base IRI, and output formatting. ```typescript import { write } from '@jeswr/pretty-turtle'; const options = { // Turtle format with all options format: 'text/turtle', // Custom prefixes prefixes: { ex: 'http://example.org/', foaf: 'http://xmlns.com/foaf/0.1/', schema: 'https://schema.org/' }, // Base IRI for relative resolution baseIri: 'http://example.org/base/', // Explicitly write @base directive explicitBaseIRI: true, // Compact single-line output compact: false, // Deterministic ordering ordered: true, // N3-specific options (only with format: 'text/n3') isImpliedBy: false }; const result = await write(quads, options); ``` -------------------------------- ### Serialize RDF data Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/INDEX.md Quick start example for serializing RDF data using the write function. ```typescript import { write } from '@jeswr/pretty-turtle'; const result = await write(quads); ``` -------------------------------- ### getObjectsOnce Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/VolitileStore.md Example demonstrating how to use getObjectsOnce to retrieve and remove objects for a subject-predicate pair. ```typescript const objects = store.getObjectsOnce(subject, predicate, graph); // Returns all objects for the subject-predicate pair // and removes those quads from the store ``` -------------------------------- ### Complete Example Source: https://github.com/jeswr/pretty-turtle/blob/main/README.md A complete example demonstrating the usage of various options for the write function. ```typescript import { write } from '@jeswr/pretty-turtle'; const str = await write(quads, { format: 'text/turtle', prefixes: { ex: "http://example.org/", foaf: "http://xmlns.com/foaf/0.1/" }, baseIri: "http://example.org/base/", explicitBaseIRI: true, compact: false, ordered: true }); ``` -------------------------------- ### Minimal Configuration Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/INDEX.md Example of minimal configuration for the write function. ```typescript await write(quads); ``` -------------------------------- ### Format Option Error Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/configuration.md Examples demonstrating error cases for the 'format' option. ```typescript // Throws: "Unsupported format: text/jsonld" await write(quads, { format: 'text/jsonld' }); // Throws: "More than one graph found" (in turtle mode) const multiGraphQuads = [ quad(s1, p1, o1, graph1), quad(s2, p2, o2, graph2) ]; await write(multiGraphQuads, { format: 'text/turtle' }); ``` -------------------------------- ### Complete Configuration Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/write.md An example showcasing a comprehensive configuration object for the write function. ```typescript const result = await write(quads, { format: 'text/turtle', prefixes: { ex: 'http://example.org/', foaf: 'http://xmlns.com/foaf/0.1/' }, baseIri: 'http://example.org/base/', explicitBaseIRI: true, compact: false, ordered: true }); ``` -------------------------------- ### With Prefixes Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/INDEX.md Example of configuring custom namespace prefixes for the write function. ```typescript await write(quads, { prefixes: { ex: 'http://example.org/' } }); ``` -------------------------------- ### isImpliedBy Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/configuration.md Example showing the use of isImpliedBy syntax for N3 implications. ```typescript // Without isImpliedBy (default) // { ?x a Person } => { ?x a Agent } . // With isImpliedBy: true // { ?x a Agent } <= { ?x a Person } . const result = await write(quads, { format: 'text/n3', isImpliedBy: true }); ``` -------------------------------- ### Method Chaining Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/Writer.md Demonstrates fluent method chaining with Writer methods. ```typescript writer .add('@prefix ex: .') .newLine(1) .add('ex:subject') .add(' ') .indent() .newLine(1) .add('ex:predicate ex:object .') .deindent(); ``` -------------------------------- ### VolitileStore Usage Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/VolitileStore.md Example demonstrating the instantiation and basic usage of VolitileStore, including retrieving and removing quads and objects. ```typescript import Store from '@jeswr/pretty-turtle/lib/volatile-store'; const quads = [ /* ... */ ]; const store = new Store(quads); // Get and remove triples with a specific predicate const typeQuads = store.getQuadsOnce( null, namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), null, defaultGraph() ); // Get and remove objects (useful for type values) const typeObjects = store.getObjectsOnce(subject, typePredicate, graph); // Store now has fewer quads console.log(store.size); // Decreased by the removed quads ``` -------------------------------- ### Full Configuration Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/INDEX.md Example of full configuration for the write function, including format, prefixes, base IRI, and ordering. ```typescript await write(quads, { format: 'text/turtle', prefixes: { ex: 'http://example.org/' }, baseIri: 'http://example.org/base/', explicitBaseIRI: true, compact: false, ordered: true }); ``` -------------------------------- ### baseIri Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/configuration.md Example of setting the baseIri option to resolve relative IRIs. ```typescript const result = await write(quads, { baseIri: 'http://example.org/base/', prefixes: { ex: 'http://example.org/base/ns/' } }); // An IRI like http://example.org/base/resource might be serialized as: // (relative to base) // or // ex:something (compressed with prefix if applicable) ``` -------------------------------- ### Usage Example for add Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/Writer.md Shows how to chain the add method to build a subject-predicate-object statement. ```typescript writer.add('ex:subject').add(' ').add('ex:predicate').add(' ').add('ex:object').add(' .'); ``` -------------------------------- ### Quad Usage Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/types.md Example demonstrating the usage of the Quad type with the `write` function. ```typescript import { write } from '@jeswr/pretty-turtle'; const quads: Quad[] = [ { subject: { termType: 'NamedNode', value: 'http://example.org/alice' }, predicate: { termType: 'NamedNode', value: 'http://xmlns.com/foaf/0.1/name' }, object: { termType: 'Literal', value: 'Alice', language: 'en', datatype: { termType: 'NamedNode', value: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#langString' } }, graph: { termType: 'DefaultGraph', value: '' } } ]; const result = await write(quads); ``` -------------------------------- ### With Prefixes Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/write.md Example of using the write function with custom prefix mappings for namespace compression. ```typescript const result = await write(quads, { prefixes: { ex: 'http://example.org/', foaf: 'http://xmlns.com/foaf/0.1/', rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' } }); ``` -------------------------------- ### Literal Examples Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/types.md Examples demonstrating how to represent plain strings, language-tagged strings, and typed literals. ```typescript // Plain string { termType: 'Literal', value: 'hello' } // Language-tagged string { termType: 'Literal', value: 'hello', language: 'en' } // Typed literal { termType: 'Literal', value: '42', datatype: { termType: 'NamedNode', value: 'http://www.w3.org/2001/XMLSchema#integer' } } ``` -------------------------------- ### Custom Prefixes Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/README.md Example demonstrating how to specify custom namespace prefixes during serialization. ```typescript const ttl = await write(quads, { prefixes: { ex: 'http://example.org/', foaf: 'http://xmlns.com/foaf/0.1/' } }); ``` -------------------------------- ### Usage Example for indent/deindent Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/Writer.md Demonstrates how to use indent and deindent methods for structured output. ```typescript writer.indent(); writer.add(' indented content'); writer.deindent(); ``` -------------------------------- ### Deterministic Ordered Output Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/write.md Example of enabling deterministic output ordering for consistent results. ```typescript const result = await write(quads, { ordered: true }); // Same input always produces identical output regardless of quad order ``` -------------------------------- ### Convert JSON-LD to Turtle Workflow Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/INDEX.md Example workflow demonstrating how to convert JSON-LD data to Turtle format using jsonld and pretty-turtle libraries. ```typescript import jsonld from 'jsonld'; import { write } from '@jeswr/pretty-turtle'; const quads = await jsonld.toRDF(jsonldData); const turtle = await write(quads); ``` -------------------------------- ### Unsupported Format Error Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/errors.md Demonstrates how the Unsupported Format Error is thrown when an invalid format is provided. ```typescript import { write } from '@jeswr/pretty-turtle'; // Throws: Error: Unsupported format: text/jsonld try { await write(quads, { format: 'text/jsonld' }); } catch (error) { console.error(error.message); // "Unsupported format: text/jsonld" } ``` -------------------------------- ### OTerm Usage Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/types.md Demonstrates using null as a wildcard in `store.getQuads` and `store.getSubjects`. ```typescript // Get all quads with any subject and predicate, with object 'Alice' store.getQuads(null, null, literalAlice, defaultGraph); // Get all subjects with predicate rdf:type store.getSubjects(null, rdfType, null); ``` -------------------------------- ### Deterministic Output Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/README.md Example showing how to ensure deterministic output by ordering quads. ```typescript const result1 = await write(quads1, { ordered: true }); const result2 = await write(quads2, { ordered: true }); // Same data = identical output regardless of input order ``` -------------------------------- ### Error Recovery Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/INDEX.md Example of how to catch and handle errors during the write operation. ```typescript try { const result = await write(quads, options); } catch (error) { console.error(error.message); // Handle specific error types } ``` -------------------------------- ### Basic Usage Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/README.md Example of basic usage for the write function. ```typescript import { write } from '@jeswr/pretty-turtle'; const quads = [ /* RDF/JS Quad array */ ]; const result = await write(quads); console.log(result); // Turtle-formatted RDF string ``` -------------------------------- ### escapeIRI Usage Examples Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/escape.md Examples demonstrating the usage of the escapeIRI function for IRIs with newlines, special characters, and base IRIs. ```typescript import { escapeIRI } from '@jeswr/pretty-turtle/lib/escape'; // IRI with newline escapeIRI('http://example.org/path\nwith\nnewlines'); // -> 'http://example.org/path\nwith\nnewlines' // IRI with special characters escapeIRI('http://example.org/resource"with"quotes'); // -> 'http://example.org/resource\"with\"quotes' // Base IRI escapeIRI('http://example.org/base/'); // -> 'http://example.org/base/' ``` -------------------------------- ### Compact Output Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/README.md Example of generating compact Turtle output with minimized whitespace. ```typescript const compact = await write(quads, { compact: true }); // Single line output, no newlines ``` -------------------------------- ### N3 Format with Implications Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/write.md Example of serializing to N3 format and enabling the use of log:isImpliedBy operator. ```typescript const result = await write(quads, { format: 'text/n3', isImpliedBy: true }); // Enables use of `<=` operator for log:isImpliedBy in N3 ``` -------------------------------- ### Working with Literals Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/types.md Example of a type guard function to check if a Term is an English Literal. ```typescript import type { Literal } from '@rdfjs/types'; function isEnglishLiteral(term: Term): term is Literal { return term.termType === 'Literal' && term.language === 'en'; } ``` -------------------------------- ### Usage Example for newLine Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/Writer.md Illustrates using newLine to add formatted line breaks with indentation. ```typescript writer.add('@prefix ex: .'); writer.newLine(2); // Two newlines with indentation writer.add('ex:subject ex:predicate ex:object .'); ``` -------------------------------- ### TTLWriter Usage Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/TTLWriter.md Demonstrates how to instantiate and use the TTLWriter class, typically done internally by the write() function. ```typescript import { TTLWriter } from '@jeswr/pretty-turtle/lib/ttlwriter'; import Store from '@jeswr/pretty-turtle/lib/volatile-store'; import Writer from '@jeswr/pretty-turtle/lib/writer'; const store = new Store(quads); const writer = new Writer({ write: console.log, end: () => {} }); const ttlWriter = new TTLWriter(store, writer, { ex: 'http://example.org/' }); await ttlWriter.write(); ``` -------------------------------- ### Example of Non-Default Graph in Nested Quad Error Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/errors.md This example demonstrates how to trigger and catch the 'Default graph expected on nested quads' error when serializing in N3 format with a nested quad having a non-default graph. ```typescript import { DataFactory } from 'n3'; import { write } from '@jeswr/pretty-turtle'; const df = new DataFactory(); // Create a nested quad with non-default graph const namedGraph = df.namedNode('http://example.org/graph1'); const nestedQuad = df.quad( df.namedNode('http://example.org/subject'), df.namedNode('http://example.org/predicate'), df.namedNode('http://example.org/object'), namedGraph // ERROR: Must be default graph ); // Use the nested quad as an object in an annotation const annotationQuad = df.quad( nestedQuad, // Nested quad as subject df.namedNode('http://example.org/isAnnotatedBy'), df.literal('Some annotation') ); // Throws: Error: Default graph expected on nested quads try { await write([annotationQuad], { format: 'text/n3' }); } catch (error) { console.error(error.message); } ``` -------------------------------- ### Notation3 with Rules Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/README.md Example of serializing to N3 format, enabling support for rules like 'implies' and 'isImpliedBy'. ```typescript const n3 = await write(quads, { format: 'text/n3', isImpliedBy: true }); // Supports rules: A => B and A <= B ``` -------------------------------- ### Error Handling Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/README.md Example demonstrating how to catch and handle errors during serialization. ```typescript try { const result = await write(quads, { format: 'text/turtle' }); } catch (error) { if (error.message.includes('Multiple')) { // Handle multiple graphs case } else if (error.message.includes('format')) { // Handle format error } } ``` -------------------------------- ### Enable Verbose Logging Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/errors.md This example demonstrates how to enable verbose logging when using the `write` function to help debug issues. It logs the input quads, options, and any errors encountered during the writing process. ```typescript import { write } from '@jeswr/pretty-turtle'; async function debugWrite(quads, options) { console.log('Input quads:', quads.length); console.log('Options:', JSON.stringify(options, null, 2)); try { const result = await write(quads, options); console.log('Success! Output length:', result.length); return result; } catch (error) { console.error('Error details:'); console.error(' Message:', error.message); console.error(' Stack:', error.stack); throw error; } } ``` -------------------------------- ### escapeStringRDF Usage Examples Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/escape.md Examples demonstrating the usage of the escapeStringRDF function for various scenarios including simple escaping, newlines, tabs, backslashes, and Unicode control characters. ```typescript import { escapeStringRDF } from '@jeswr/pretty-turtle/lib/escape'; // Simple escaping escapeStringRDF('Hello "world"'); // -> 'Hello \"world\"' // Newlines and tabs escapeStringRDF('Line 1\nLine 2\tTab'); // -> 'Line 1\nLine 2\tTab' // Backslashes escapeStringRDF('Path: C:\\Users'); // -> 'Path: C:\\\\Users' // Unicode control characters escapeStringRDF('Control Char'); // -> 'Control Char' ``` -------------------------------- ### Simple Serialization Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/README.md Basic example of serializing an array of quads to Turtle format. ```typescript import { write } from '@jeswr/pretty-turtle'; const quads = [ /* ... */ ]; const ttl = await write(quads); ``` -------------------------------- ### Creating Quads with DataFactory Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/types.md Example of creating RDF quads using the DataFactory from the n3 library. ```typescript import { DataFactory } from 'n3'; const df = new DataFactory(); const alice = df.namedNode('http://example.org/alice'); const name = df.namedNode('http://xmlns.com/foaf/0.1/name'); const aliceName = df.literal('Alice'); const quad = df.quad(alice, name, aliceName); ``` -------------------------------- ### Inspect Quad Structure Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/errors.md This example shows how to inspect the structure of quads to determine the appropriate serialization format. It checks for multiple graphs and nested quads, then uses this information to select the format for the `write` function. ```typescript function inspectQuads(quads) { const graphs = new Set(); const formats = new Set(); for (const quad of quads) { graphs.add(quad.graph.value || 'DEFAULT'); if (quad.subject.termType === 'Quad') { formats.add('nested-quads'); } } console.log('Quad count:', quads.length); console.log('Distinct graphs:', Array.from(graphs)); console.log('Uses nested quads:', formats.has('nested-quads')); return { multipleGraphs: graphs.size > 1, usesNestedQuads: formats.has('nested-quads') }; } // Use inspection to choose format const analysis = inspectQuads(quads); const format = analysis.multipleGraphs ? 'text/n3' : 'text/turtle'; const result = await write(quads, { format }); ``` -------------------------------- ### Usage with DataFactory (from n3) Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/EXPORTS.md Example demonstrating how to use Pretty Turtle with the DataFactory from the 'n3' library to create and write RDF quads. ```typescript import { write, type Options } from '@jeswr/pretty-turtle'; import { DataFactory } from 'n3'; import type { Quad } from '@rdfjs/types'; const df = new DataFactory(); const quads = [ df.quad( df.namedNode('http://example.org/alice'), df.namedNode('http://xmlns.com/foaf/0.1/name'), df.literal('Alice', 'en') ) ]; const result = await write(quads, { format: 'text/turtle' }); ``` -------------------------------- ### Format-Specific Error Handling Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/errors.md An example demonstrating how to handle errors specific to different RDF formats, including validation before calling the `write` function. ```typescript async function writeRDF(quads, userOptions) { try { // Validate format before processing if (userOptions.format && !['text/turtle', 'text/n3'].includes(userOptions.format)) { throw new Error(`Invalid format: ${userOptions.format}`); } return await write(quads, userOptions); } catch (error) { if (error.message.includes('Unsupported format')) { console.error('Format not supported. Use "text/turtle" or "text/n3"'); } else if (error.message.includes('More than one graph')) { console.error('Multiple graphs detected. Use format: "text/n3" or filter to single graph'); } else { console.error('Unknown error:', error.message); } throw error; } } ``` -------------------------------- ### Async Error Handling with Promise Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/errors.md An example showing how to handle errors asynchronously using Promise `.then()` and `.catch()` methods when calling the `write` function. ```typescript import { write } from '@jeswr/pretty-turtle'; write(quads, options) .then(result => { console.log('Serialization successful'); console.log(result); }) .catch(error => { console.error('Serialization failed:', error.message); }); ``` -------------------------------- ### Unicode Handling - Single Characters Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/escape.md Example showing how single Unicode control characters are escaped. ```typescript escapeStringRDF('A B'); // -> 'A B' ``` -------------------------------- ### Basic Try-Catch for Error Handling Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/errors.md A fundamental example of using a try-catch block to handle potential errors during the serialization process with the `write` function. ```typescript import { write } from '@jeswr/pretty-turtle'; try { const result = await write(quads, options); console.log(result); } catch (error) { console.error('Serialization failed:', error.message); } ``` -------------------------------- ### Multiple Graphs in Turtle Error Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/errors.md Illustrates the Multiple Graphs in Turtle Error when attempting to serialize multiple named graphs in Turtle format. ```typescript import { DataFactory } from 'n3'; import { write } from '@jeswr/pretty-turtle'; const df = new DataFactory(); // Create quads in different graphs const defaultGraph = df.defaultGraph(); const graph1 = df.namedNode('http://example.org/graph1'); const graph2 = df.namedNode('http://example.org/graph2'); const quads = [ df.quad( df.namedNode('http://example.org/alice'), df.namedNode('http://example.org/name'), df.literal('Alice'), graph1 // Named graph 1 ), df.quad( df.namedNode('http://example.org/bob'), df.namedNode('http://example.org/name'), df.literal('Bob'), graph2 // Named graph 2 ) ]; // Throws: Error: More than one graph found - can serialize in the default graph try { await write(quads, { format: 'text/turtle' }); } catch (error) { console.error(error.message); } ``` -------------------------------- ### Unicode Handling - Surrogate Pairs Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/escape.md Example showing how characters outside the BMP (surrogate pairs) are escaped. ```typescript // Emoji and other astral plane characters escapeStringRDF('Hello 😊'); // Properly escapes the emoji ``` -------------------------------- ### Solution for Non-Default Graph in Nested Quad Error Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/errors.md This example shows the corrected way to create nested quads, ensuring they use the default graph to avoid the 'Default graph expected on nested quads' error. ```typescript // Correct: nested quads use default graph const nestedQuad = df.quad( df.namedNode('http://example.org/subject'), df.namedNode('http://example.org/predicate'), df.namedNode('http://example.org/object'), df.defaultGraph() // Must be default graph ); const annotationQuad = df.quad( nestedQuad, df.namedNode('http://example.org/isAnnotatedBy'), df.literal('Some annotation'), df.defaultGraph() // Annotation is also in default graph ); const result = await write([annotationQuad], { format: 'text/n3' }); ``` -------------------------------- ### Validation Before Calling write() Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/errors.md This example illustrates performing validation checks on quads and options before calling the `write` function to prevent common errors, such as using multiple graphs with the Turtle format. ```typescript import { DataFactory } from 'n3'; import { write } from '@jeswr/pretty-turtle'; const df = new DataFactory(); function validateBeforeWrite(quads, options) { // Validate format if (options.format && !['text/turtle', 'text/n3'].includes(options.format)) { throw new Error(`Invalid format: ${options.format}`); } // Validate graphs for Turtle format if (options.format !== 'text/n3') { const graphs = new Set(); for (const quad of quads) { if (!quad.graph.equals(df.defaultGraph())) { graphs.add(quad.graph.value); } } if (graphs.size > 0) { throw new Error(`Turtle format only supports default graph. Found graphs: ${Array.from(graphs).join(', ')}`); } } return write(quads, options); } // Usage try { const result = await validateBeforeWrite(quads, options); } catch (error) { console.error(error.message); } ``` -------------------------------- ### Multiple Graphs in Turtle Error Solution: Merge Graphs Separately Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/errors.md Provides an example of serializing each named graph separately to Turtle format by filtering and mapping quads. ```typescript // Serialize each graph separately for (const graphName of ['graph1', 'graph2']) { const graphUri = `http://example.org/${graphName}`; const graphQuads = quads.filter(q => q.graph.value === graphUri); // Move to default graph const defaultGraphQuads = graphQuads.map(q => ({ ...q, graph: df.defaultGraph() })); const result = await write(defaultGraphQuads, { format: 'text/turtle' }); console.log(`Graph ${graphName}:\n${result}`); } ``` -------------------------------- ### Type Checking Example Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/types.md Example of a type guard function to check if a Term is a NamedNode. ```typescript import type { Quad, Term } from '@rdfjs/types'; function isNamedNode(term: Term): term is NamedNode { return term.termType === 'NamedNode'; } function processQuad(quad: Quad) { if (isNamedNode(quad.subject)) { console.log('Subject IRI:', quad.subject.value); } } ``` -------------------------------- ### Compact Output Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/write.md Shows how to enable compact output mode for reduced whitespace. ```typescript const result = await write(quads, { compact: true }); // Output with minimal whitespace ``` -------------------------------- ### Basic Usage Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/write.md Demonstrates the basic usage of the write function with an array of quads. ```typescript import { write } from '@jeswr/pretty-turtle'; const quads = [ // Array of RDF/JS Quad objects ]; const result = await write(quads); console.log(result); ``` -------------------------------- ### Constructor Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/Writer.md Initializes the Writer class with output callbacks and settings. ```typescript constructor(options: { write: (chunk: string, encoding: string, done?: Function) => void, end: (done?: Function) => void, compact?: boolean }) ``` -------------------------------- ### Create Reproducible RDF Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/INDEX.md Use the `ordered: true` option to ensure identical output for the same input. ```typescript const result = await write(quads, { ordered: true }); // Same input = identical output every time ``` -------------------------------- ### File Organization Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/MANIFEST.md Directory structure of the project's documentation files. ```bash /workspace/home/output/ ├── INDEX.md Navigation and learning path ├── README.md Project overview and architecture ├── EXPORTS.md Export index and imports ├── configuration.md Options interface reference ├── types.md Type definitions ├── errors.md Error reference and debugging ├── MANIFEST.md This file └── api-reference/ ├── write.md Main function documentation ├── TTLWriter.md Core writer class ├── Writer.md Output helper class ├── VolitileStore.md Store implementation └── escape.md Escape utilities ``` -------------------------------- ### Generate Compact Output Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/INDEX.md Use the `compact: true` option to generate compact output. ```typescript const result = await write(quads, { compact: true }); ``` -------------------------------- ### Base IRI with Explicit Declaration Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/write.md Demonstrates setting a base IRI and explicitly declaring it in the output. ```typescript const result = await write(quads, { baseIri: 'http://example.org/base/', explicitBaseIRI: true }); // Output includes: @base . ``` -------------------------------- ### Default Options Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/configuration.md Shows the default values for the configuration options when they are omitted. ```typescript { prefixes: {}, format: 'text/turtle', compact: false, isImpliedBy: false, baseIri: undefined, explicitBaseIRI: false, ordered: false } ``` -------------------------------- ### Built-in Default Prefixes Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/configuration.md The default prefixes used by pretty-turtle. ```typescript { rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', rdfs: 'http://www.w3.org/2000/01/rdf-schema#', owl: 'http://www.w3.org/2002/07/owl#', sh: 'http://www.w3.org/ns/shacl#', xsd: 'http://www.w3.org/2001/XMLSchema#', ex: 'http://example.com/ns#' } ``` -------------------------------- ### Main Exports Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/README.md Main entry point for RDF serialization. Async function that returns a promise resolving to serialized RDF string. ```typescript export { Options }; export async function write(quads: Quad[], options?: Options): Promise; ``` -------------------------------- ### Set Custom Prefixes Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/INDEX.md Provide a `prefixes` object to set custom prefixes for serialization. ```typescript const result = await write(quads, { prefixes: { schema: 'https://schema.org/', dc: 'http://purl.org/dc/elements/1.1/' } }); ``` -------------------------------- ### VolitileStore Constructor Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/VolitileStore.md Initializes the store with an array of quads. Inherited from n3 Store. ```typescript constructor(quads: Quad[]) ``` -------------------------------- ### Serialize Multiple Graphs Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/INDEX.md Use the `format: 'text/n3'` option to serialize multiple graphs in N3 format. ```typescript const result = await write(multiGraphQuads, { format: 'text/n3' }); ``` -------------------------------- ### Type Imports Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/types.md Shows how to import necessary types from '@rdfjs/types' and '@jeswr/pretty-turtle'. ```typescript // From @rdfjs/types import type { Quad, Term, NamedNode, BlankNode, Literal, DefaultGraph } from '@rdfjs/types'; // From pretty-turtle import { write, type Options } from '@jeswr/pretty-turtle'; ``` -------------------------------- ### Recommended Imports for Basic Usage Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/EXPORTS.md Imports for basic usage of the pretty-turtle library. ```typescript import { write, type Options } from '@jeswr/pretty-turtle'; import type { Quad } from '@rdfjs/types'; ``` -------------------------------- ### Format Option Source: https://github.com/jeswr/pretty-turtle/blob/main/README.md Convert RDF/JS quads into a Notation3 string using the format option. ```typescript // Convert RDF/JS quads into a Notation3 string const str = await write(quads, { format: 'text/n3' }); ``` -------------------------------- ### Unsupported Format Error Handling Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/errors.md Shows how to catch and handle the Unsupported Format Error by checking supported formats. ```typescript const supportedFormats = ['text/turtle', 'text/n3']; try { const result = await write(quads, { format: userFormat }); } catch (error) { if (error.message.includes('Unsupported format')) { console.error(`Format must be one of: ${supportedFormats.join(', ')}`); } } ``` -------------------------------- ### Serialization Flow Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/README.md Diagram illustrating the serialization flow. ```mermaid graph TD write(quads, options) subgraph "Steps" direction TB 1["1. Create VolitileStore from quads"] 2["2. Create Writer with output callbacks"] 3["3. Create TTLWriter with store, writer, and options"] 4["4. Call TTLWriter.write():\n - Write @base directive (if enabled)\n - Write @prefix declarations\n - Traverse graph subjects (NamedNodes first, then blank nodes)\n - For each subject, write predicates and objects\n - Apply blank node optimization and anonymization\n - Respect ordered option for deterministic output"] 5["5. Return accumulated string via Writer callback"] end write --> 1 --> 2 --> 3 --> 4 --> 5 --> "Promise" ``` -------------------------------- ### Prefixes Option Source: https://github.com/jeswr/pretty-turtle/blob/main/README.md Use the prefixes option to specify custom prefixes for compacting URIs. ```typescript const str = await write(quads, { prefixes: { ex: "http://example.org/", foaf: "http://xmlns.com/foaf/0.1/", schema: "https://schema.org/" } }); ``` -------------------------------- ### VolitileStore import Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/EXPORTS.md Store wrapper that removes quads as they are retrieved. Can be imported directly from its source file for advanced use cases. ```typescript import VolitileStore from '@jeswr/pretty-turtle/lib/volatile-store'; ``` -------------------------------- ### Multiple Graphs in Turtle Error Solution: Use N3 Format Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/errors.md Demonstrates using the N3 format to handle multiple graphs, which is supported by the N3 specification. ```typescript // N3 supports multiple graphs const result = await write(quads, { format: 'text/n3' }); ``` -------------------------------- ### Usage Source: https://github.com/jeswr/pretty-turtle/blob/main/README.md Convert RDF/JS quads into a pretty turtle string ```typescript import { write } from '@jeswr/pretty-turtle'; // Convert RDF/JS quads into a pretty turtle string const str = await write(quads); ``` -------------------------------- ### Options Interface Source: https://github.com/jeswr/pretty-turtle/blob/main/README.md Interface for configuration options for the write function. ```typescript interface Options { prefixes?: Record; format?: string; compact?: boolean; isImpliedBy?: boolean; baseIri?: string; explicitBaseIRI?: boolean; ordered?: boolean; } ``` -------------------------------- ### Compact Option Source: https://github.com/jeswr/pretty-turtle/blob/main/README.md Produce a more compact output by setting the compact option to true. ```typescript // Compact output const str = await write(quads, { compact: true }); ``` -------------------------------- ### Options Interface Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/README.md TypeScript interface defining the configuration options for the write() function. ```typescript interface Options { prefixes?: Record; // Namespace prefix mappings format?: string; // 'text/turtle' | 'text/n3' compact?: boolean; // Minimize whitespace isImpliedBy?: boolean; // Enable <= operator in N3 baseIri?: string; // Base IRI for relative URLs explicitBaseIRI?: boolean; // Write @base directive ordered?: boolean; // Deterministic output } ``` -------------------------------- ### write() function signature Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/EXPORTS.md Serializes an array of RDF/JS quads into Turtle or Notation3 syntax. ```typescript export async function write(quads: Quad[], options?: Options): Promise ``` -------------------------------- ### getObjectsOnce Method Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/VolitileStore.md Retrieves objects from quads matching the given subject and predicate, and removes those quads from the store. Equivalent to calling getQuadsOnce and mapping the results. ```typescript getObjectsOnce(s: OTerm, p: OTerm, g: OTerm): Quad_Object[] ``` -------------------------------- ### TTLWriter Constructor Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/TTLWriter.md The constructor for the TTLWriter class, which initializes the writer with a store, writer instance, and optional prefixes and options. ```typescript constructor( store: Store, writer: Writer, prefixes?: Record, options?: Options ) ``` -------------------------------- ### Writer import Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/EXPORTS.md Output buffer and indentation helper. Can be imported directly from its source file for advanced use cases. ```typescript import Writer from '@jeswr/pretty-turtle/lib/writer'; ``` -------------------------------- ### TTLWriter import Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/EXPORTS.md Core class implementing RDF serialization logic. Can be imported directly from its source file for advanced use cases. ```typescript import { TTLWriter, Options } from '@jeswr/pretty-turtle/lib/ttlwriter'; ``` -------------------------------- ### Base IRI Option Source: https://github.com/jeswr/pretty-turtle/blob/main/README.md Set the base IRI for the document using the baseIri option. ```typescript const str = await write(quads, { baseIri: "http://example.org/base/" }); ``` -------------------------------- ### Options interface Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/EXPORTS.md Configuration object controlling serialization behavior. ```typescript export interface Options { prefixes?: Record; format?: string; compact?: boolean; isImpliedBy?: boolean; baseIri?: string; explicitBaseIRI?: boolean; ordered?: boolean; } ``` -------------------------------- ### IsImpliedBy Option Source: https://github.com/jeswr/pretty-turtle/blob/main/README.md Opt in to using isImpliedBy syntax (<=) when in N3 mode. ```typescript const str = await write(quads, { format: 'text/n3', isImpliedBy: true }); ``` -------------------------------- ### TTLWriter write Method Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/TTLWriter.md The write method serializes all quads in the store to the output in Turtle/N3 format, handling directives and statements with specific behaviors for base, prefixes, subjects, blank nodes, and indentation. ```typescript async write(): Promise ``` -------------------------------- ### Advanced Usage Imports Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/EXPORTS.md Imports for advanced usage scenarios, including specific writer classes and escape functions. ```typescript import { write, type Options } from '@jeswr/pretty-turtle'; import { TTLWriter } from '@jeswr/pretty-turtle/lib/ttlwriter'; import Writer from '@jeswr/pretty-turtle/lib/writer'; import VolitileStore from '@jeswr/pretty-turtle/lib/volatile-store'; import { escapeStringRDF, escapeIRI } from '@jeswr/pretty-turtle/lib/escape'; import type { Quad, Term, NamedNode, BlankNode, Literal } from '@rdfjs/types'; ``` -------------------------------- ### VolitileStore Class Definition Source: https://github.com/jeswr/pretty-turtle/blob/main/_autodocs/api-reference/VolitileStore.md Extends the `Store` class from the n3 library, inheriting all standard Store methods with additions for volatile access patterns. ```typescript class VolitileStore extends Store ```