@textmode/document 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,111 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
5
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
6
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
7
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
8
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
9
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
10
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
11
+ HEREUNDER.
12
+ Statement of Purpose
13
+
14
+ The laws of most jurisdictions throughout the world automatically confer
15
+ exclusive Copyright and Related Rights (defined below) upon the creator
16
+ and subsequent owner(s) (each and all, an "owner") of an original work of
17
+ authorship and/or a database (each, a "Work").
18
+ Certain owners wish to permanently relinquish those rights to a Work for
19
+ the purpose of contributing to a commons of creative, cultural and
20
+ scientific works ("Commons") that the public can reliably and without fear
21
+ of later claims of infringement build upon, modify, incorporate in other
22
+ works, reuse and redistribute as freely as possible in any form whatsoever
23
+ and for any purposes, including without limitation commercial purposes.
24
+ These owners may contribute to the Commons to promote the ideal of a free
25
+ culture and the further production of creative, cultural and scientific
26
+ works, or to gain reputation or greater distribution for their Work in
27
+ part through the use and efforts of others.
28
+ For these and/or other purposes and motivations, and without any
29
+ expectation of additional consideration or compensation, the person
30
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
31
+ is an owner of Copyright and Related Rights in the Work, voluntarily
32
+ elects to apply CC0 to the Work and publicly distribute the Work under its
33
+ terms, with knowledge of his or her Copyright and Related Rights in the
34
+ Work and the meaning and intended legal effect of CC0 on those rights.
35
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
36
+ protected by copyright and related or neighboring rights ("Copyright and
37
+ Related Rights"). Copyright and Related Rights include, but are not
38
+ limited to, the following:
39
+ i. the right to reproduce, adapt, distribute, perform, display,
40
+ communicate, and translate a Work;
41
+ ii. moral rights retained by the original author(s) and/or performer(s);
42
+ iii. publicity and privacy rights pertaining to a person's image or
43
+ likeness depicted in a Work;
44
+ iv. rights protecting against unfair competition in regards to a Work,
45
+ subject to the limitations in paragraph 4(a), below;
46
+ v. rights protecting the extraction, dissemination, use and reuse of data
47
+ in a Work;
48
+ vi. database rights (such as those arising under Directive 96/9/EC of the
49
+ European Parliament and of the Council of 11 March 1996 on the legal
50
+ protection of databases, and under any national implementation
51
+ thereof, including any amended or successor version of such
52
+ directive); and
53
+ vii. other similar, equivalent or corresponding rights throughout the
54
+ world based on applicable law or treaty, and any national
55
+ implementations thereof.
56
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
57
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
58
+ irrevocably and unconditionally waives, abandons, and surrenders all of
59
+ Affirmer's Copyright and Related Rights and associated claims and causes
60
+ of action, whether now known or unknown (including existing as well as
61
+ future claims and causes of action), in the Work (i) in all territories
62
+ worldwide, (ii) for the maximum duration provided by applicable law or
63
+ treaty (including future time extensions), (iii) in any current or future
64
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
65
+ including without limitation commercial, advertising or promotional
66
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
67
+ member of the public at large and to the detriment of Affirmer's heirs and
68
+ successors, fully intending that such Waiver shall not be subject to
69
+ revocation, rescission, cancellation, termination, or any other legal or
70
+ equitable action to disrupt the quiet enjoyment of the Work by the public
71
+ as contemplated by Affirmer's express Statement of Purpose.
72
+ 3. Public License Fallback. Should any part of the Waiver for any reason
73
+ be judged legally invalid or ineffective under applicable law, then the
74
+ Waiver shall be preserved to the maximum extent permitted taking into
75
+ account Affirmer's express Statement of Purpose. In addition, to the
76
+ extent the Waiver is so judged Affirmer hereby grants to each affected
77
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
78
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
79
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
80
+ maximum duration provided by applicable law or treaty (including future
81
+ time extensions), (iii) in any current or future medium and for any number
82
+ of copies, and (iv) for any purpose whatsoever, including without
83
+ limitation commercial, advertising or promotional purposes (the
84
+ "License"). The License shall be deemed effective as of the date CC0 was
85
+ applied by Affirmer to the Work. Should any part of the License for any
86
+ reason be judged legally invalid or ineffective under applicable law, such
87
+ partial invalidity or ineffectiveness shall not invalidate the remainder
88
+ of the License, and in such case Affirmer hereby affirms that he or she
89
+ will not (i) exercise any of his or her remaining Copyright and Related
90
+ Rights in the Work or (ii) assert any associated claims and causes of
91
+ action with respect to the Work, in either case contrary to Affirmer's
92
+ express Statement of Purpose.
93
+ 4. Limitations and Disclaimers.
94
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
95
+ surrendered, licensed or otherwise affected by this document.
96
+ b. Affirmer offers the Work as-is and makes no representations or
97
+ warranties of any kind concerning the Work, express, implied,
98
+ statutory or otherwise, including without limitation warranties of
99
+ title, merchantability, fitness for a particular purpose, non
100
+ infringement, or the absence of latent or other defects, accuracy, or
101
+ the present or absence of errors, whether or not discoverable, all to
102
+ the greatest extent permissible under applicable law.
103
+ c. Affirmer disclaims responsibility for clearing rights of other persons
104
+ that may apply to the Work or any use thereof, including without
105
+ limitation any person's Copyright and Related Rights in the Work.
106
+ Further, Affirmer disclaims responsibility for obtaining any necessary
107
+ consents, permissions or other rights required for any use of the
108
+ Work.
109
+ d. Affirmer understands and acknowledges that Creative Commons is not a
110
+ party to this document and has no duty or obligation with respect to
111
+ this CC0 or use of the Work.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # @textmode/document
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <div align="center">
4
+
5
+ <img alt="@textmode/document, portable textmode documents" src=".github/assets/readme-og.png" />
6
+
7
+ | [![Node.js 24](https://img.shields.io/badge/Node.js-24-339933?logo=nodedotjs&logoColor=white)](https://nodejs.org/) [![TypeScript](https://img.shields.io/badge/TypeScript-3178C6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/) [![JSON Schema Draft 2020-12](https://img.shields.io/badge/JSON_Schema-Draft_2020--12-85EA2D?logo=json&logoColor=white)](https://json-schema.org/draft/2020-12) | [![docs](https://img.shields.io/badge/docs-vitepress-646cff?logo=vitepress&logoColor=white)](https://code.textmode.art/) [![Discord](https://img.shields.io/discord/1357070706181017691?color=5865F2&label=Discord&logo=discord&logoColor=white)](https://discord.gg/sjrw8QXNks) | [![Ko-fi](https://shields.io/badge/ko--fi-donate-ff5f5f?logo=ko-fi)](https://ko-fi.com/V7V8JG2FY) [![GitHub Sponsors](https://img.shields.io/badge/sponsor-30363D?logo=GitHub-Sponsors&logoColor=%23EA4AAA)](https://github.com/sponsors/humanbydefinition) |
8
+ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
9
+
10
+ </div>
11
+
12
+ `@textmode/document` defines a portable, versioned JSON format for textmode artwork. It provides a language-neutral specification, JSON Schema, TypeScript types, and a dependency-free decoder for browsers and Node.js.
13
+
14
+ The package reads `textmode.document@2.0.0` and migrates `textmode.layer@1.0.0` and `textmode.layer@1.1.0`. The package version and document format version are independent. Updating this library does not change existing files.
15
+
16
+ ## Install
17
+
18
+ Install the package from npm:
19
+
20
+ ```sh
21
+ npm install @textmode/document
22
+ ```
23
+
24
+ The JavaScript interface is ESM-only and has no runtime dependencies. It does not require `textmode.js`, a renderer, DOM globals, or media encoders.
25
+
26
+ ## Decode a document
27
+
28
+ ```js
29
+ import { parseTextmodeDocumentJSON } from '@textmode/document';
30
+
31
+ const result = parseTextmodeDocumentJSON(jsonText, {
32
+ limits: { maxCells: 65536, maxLayers: 64 },
33
+ });
34
+
35
+ if (!result.ok) {
36
+ console.error(result.error.code, result.error.path, result.error.message);
37
+ } else {
38
+ console.log(result.document.target, result.warnings);
39
+ }
40
+ ```
41
+
42
+ Successful decoding returns a new canonical document. Colors use RGBA objects, cell rotations use `[0, 360)`, and unknown properties are omitted. Apply each app's supported-feature policy after decoding.
43
+
44
+ ## Documentation
45
+
46
+ - [Consumer guide](docs/consumer-guide.md): parsing, schema imports, error handling, resource budgets, and complete examples.
47
+ - [Format 2.0 specification](docs/specification-2.0.md): the language-neutral contract for producers and consumers.
48
+ - [Maintenance guide](docs/maintenance.md): ownership, compatibility, tests, and release policy.
49
+ - [JSON Schema](schemas/2.0/schema.json): also available from `@textmode/document/schema/2.0`.
50
+
51
+ The schema identifier is an identifier. It does not promise that the schema is hosted at that URL. Test fixtures are private test data. They are not package exports and are excluded from npm packages.
52
+
53
+ ## Contributing
54
+
55
+ Thank you for considering a contribution to this project.
56
+
57
+ Read the [Contributing Guide](./CONTRIBUTING.md) to get started.
58
+
59
+ ## License
60
+
61
+ `@textmode/document` is dedicated to the public domain under [CC0 1.0 Universal](./LICENSE).
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Canonical format discriminator for textmode document files.
3
+ *
4
+ */
5
+ export declare const TEXTMODE_DOCUMENT_FORMAT: "textmode.document";
6
+ /**
7
+ * Current textmode document schema revision.
8
+ *
9
+ */
10
+ export declare const TEXTMODE_DOCUMENT_FORMAT_VERSION: "2.0.0";
11
+ /** Legacy format discriminator accepted by the compatibility decoder. */
12
+ export declare const LEGACY_TEXTMODE_LAYER_FORMAT: "textmode.layer";
13
+ /** Legacy selected-layer schema revision. */
14
+ export declare const LEGACY_TEXTMODE_SELECTED_VERSION: "1.0.0";
15
+ /** Legacy layer-stack schema revision. */
16
+ export declare const LEGACY_TEXTMODE_ALL_VERSION: "1.1.0";
17
+ /**
18
+ * Canonical dense row encoding used by textmode document v2.
19
+ *
20
+ */
21
+ export declare const TEXTMODE_OBJECT_ROWS_ENCODING: "object-rows-v1";
22
+ /** Default protocol safety limits. Product-specific limits belong to callers. */
23
+ export declare const DEFAULT_TEXTMODE_DOCUMENT_LIMITS: {
24
+ readonly maxCells: 16777216;
25
+ readonly maxLayers: 4096;
26
+ readonly maxLayerIdLength: 1024;
27
+ readonly maxCharacterLength: 64;
28
+ readonly maxMetadataStringLength: 4096;
29
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Canonical format discriminator for textmode document files.
3
+ *
4
+ */
5
+ export const TEXTMODE_DOCUMENT_FORMAT = 'textmode.document';
6
+ /**
7
+ * Current textmode document schema revision.
8
+ *
9
+ */
10
+ export const TEXTMODE_DOCUMENT_FORMAT_VERSION = '2.0.0';
11
+ /** Legacy format discriminator accepted by the compatibility decoder. */
12
+ export const LEGACY_TEXTMODE_LAYER_FORMAT = 'textmode.layer';
13
+ /** Legacy selected-layer schema revision. */
14
+ export const LEGACY_TEXTMODE_SELECTED_VERSION = '1.0.0';
15
+ /** Legacy layer-stack schema revision. */
16
+ export const LEGACY_TEXTMODE_ALL_VERSION = '1.1.0';
17
+ /**
18
+ * Canonical dense row encoding used by textmode document v2.
19
+ *
20
+ */
21
+ export const TEXTMODE_OBJECT_ROWS_ENCODING = 'object-rows-v1';
22
+ /** Default protocol safety limits. Product-specific limits belong to callers. */
23
+ export const DEFAULT_TEXTMODE_DOCUMENT_LIMITS = {
24
+ maxCells: 16777216,
25
+ maxLayers: 4096,
26
+ maxLayerIdLength: 1024,
27
+ maxCharacterLength: 64,
28
+ maxMetadataStringLength: 4096,
29
+ };
@@ -0,0 +1,4 @@
1
+ import type { DecodeContext, UnknownRecord } from './validation.js';
2
+ import type { CanonicalTextmodeAllDocument, CanonicalTextmodeSelectedDocument } from './types/index.js';
3
+ export declare function decodeSelectedDocument(root: UnknownRecord, context: DecodeContext): CanonicalTextmodeSelectedDocument;
4
+ export declare function decodeAllDocument(root: UnknownRecord, context: DecodeContext): CanonicalTextmodeAllDocument;
@@ -0,0 +1,108 @@
1
+ import { TEXTMODE_DOCUMENT_FORMAT, TEXTMODE_DOCUMENT_FORMAT_VERSION, TEXTMODE_OBJECT_ROWS_ENCODING, } from './constants.js';
2
+ import { assertCanvasMatchesGrid, checkedProduct, decodeCanvas, decodeColor, decodeGrid, decodeLayerId, decodeMetadata, fail, normalizeRotation, requireArray, requireBoolean, requireBoundedString, requireCharacter, requireFiniteNumber, requireNumberInRange, requireRecord, requireSafeInteger, requireString, } from './validation.js';
3
+ export function decodeSelectedDocument(root, context) {
4
+ const canvas = decodeCanvas(root.canvas, '$.canvas');
5
+ const grid = decodeGrid(root.grid, '$.grid');
6
+ assertCanvasMatchesGrid(canvas, grid, '$.canvas');
7
+ const layer = requireRecord(root.layer, '$.layer');
8
+ return {
9
+ format: TEXTMODE_DOCUMENT_FORMAT,
10
+ formatVersion: TEXTMODE_DOCUMENT_FORMAT_VERSION,
11
+ target: 'selected',
12
+ ...(root.metadata === undefined
13
+ ? {}
14
+ : { metadata: decodeMetadata(root.metadata, '$.metadata', context.limits) }),
15
+ canvas,
16
+ grid,
17
+ layer: {
18
+ id: decodeLayerId(layer.id, '$.layer.id', context.limits),
19
+ cells: decodeCells(layer.cells, grid, '$.layer.cells', context),
20
+ },
21
+ };
22
+ }
23
+ export function decodeAllDocument(root, context) {
24
+ const canvas = decodeCanvas(root.canvas, '$.canvas');
25
+ const layersValue = requireArray(root.layers, '$.layers');
26
+ if (layersValue.length === 0) {
27
+ fail('INVALID_DOCUMENT', 'A layer-stack document must contain at least one layer.', '$.layers');
28
+ }
29
+ if (layersValue.length > context.limits.maxLayers) {
30
+ fail('LIMIT_EXCEEDED', `Layer count ${layersValue.length} exceeds the configured limit ${context.limits.maxLayers}.`, '$.layers');
31
+ }
32
+ const layers = layersValue.map((value, index) => decodeLayer(value, `$.layers[${index}]`, context));
33
+ assertCanvasMatchesGrid(canvas, layers[0].grid, '$.canvas');
34
+ return {
35
+ format: TEXTMODE_DOCUMENT_FORMAT,
36
+ formatVersion: TEXTMODE_DOCUMENT_FORMAT_VERSION,
37
+ target: 'all',
38
+ ...(root.metadata === undefined
39
+ ? {}
40
+ : { metadata: decodeMetadata(root.metadata, '$.metadata', context.limits) }),
41
+ canvas,
42
+ layers,
43
+ };
44
+ }
45
+ function decodeLayer(value, path, context) {
46
+ const layer = requireRecord(value, path);
47
+ const grid = decodeGrid(layer.grid, `${path}.grid`);
48
+ return {
49
+ id: decodeLayerId(layer.id, `${path}.id`, context.limits),
50
+ visible: requireBoolean(layer.visible, `${path}.visible`),
51
+ opacity: requireNumberInRange(layer.opacity, `${path}.opacity`, 0, 1),
52
+ blendMode: requireBoundedString(layer.blendMode, `${path}.blendMode`, context.limits.maxMetadataStringLength),
53
+ offsetX: requireFiniteNumber(layer.offsetX, `${path}.offsetX`),
54
+ offsetY: requireFiniteNumber(layer.offsetY, `${path}.offsetY`),
55
+ rotationZ: requireFiniteNumber(layer.rotationZ, `${path}.rotationZ`),
56
+ grid,
57
+ cells: decodeCells(layer.cells, grid, `${path}.cells`, context),
58
+ };
59
+ }
60
+ function decodeCells(value, grid, path, context) {
61
+ const collection = requireRecord(value, path);
62
+ const encoding = requireString(collection.encoding, `${path}.encoding`);
63
+ if (encoding !== TEXTMODE_OBJECT_ROWS_ENCODING) {
64
+ fail('UNSUPPORTED_ENCODING', `Unsupported cell encoding: ${encoding}.`, `${path}.encoding`);
65
+ }
66
+ const expectedCellCount = checkedProduct(grid.cols, grid.rows, `${path}.rows`);
67
+ if (expectedCellCount > context.remainingCells) {
68
+ fail('LIMIT_EXCEEDED', `Document cell count exceeds the configured limit ${context.limits.maxCells}.`, `${path}.rows`);
69
+ }
70
+ context.remainingCells -= expectedCellCount;
71
+ const rows = requireArray(collection.rows, `${path}.rows`);
72
+ if (rows.length !== grid.rows) {
73
+ fail('INVALID_DOCUMENT', `Expected ${grid.rows} cell rows, received ${rows.length}.`, `${path}.rows`);
74
+ }
75
+ return {
76
+ encoding: TEXTMODE_OBJECT_ROWS_ENCODING,
77
+ rows: rows.map((rowValue, y) => {
78
+ const rowPath = `${path}.rows[${y}]`;
79
+ const row = requireArray(rowValue, rowPath);
80
+ if (row.length !== grid.cols) {
81
+ fail('INVALID_DOCUMENT', `Expected ${grid.cols} cells, received ${row.length}.`, rowPath);
82
+ }
83
+ return row.map((cell, x) => decodeCell(cell, x, y, `${rowPath}[${x}]`, context));
84
+ }),
85
+ };
86
+ }
87
+ function decodeCell(value, expectedX, expectedY, path, context) {
88
+ const cell = requireRecord(value, path);
89
+ const x = requireSafeInteger(cell.x, `${path}.x`);
90
+ const y = requireSafeInteger(cell.y, `${path}.y`);
91
+ if (x !== expectedX || y !== expectedY) {
92
+ fail('INVALID_DOCUMENT', `Cell coordinates must match their row position (${expectedX}, ${expectedY}).`, path);
93
+ }
94
+ const transform = requireRecord(cell.transform, `${path}.transform`);
95
+ return {
96
+ x,
97
+ y,
98
+ character: requireCharacter(cell.character, `${path}.character`, context.limits),
99
+ foreground: decodeColor(cell.foreground, `${path}.foreground`),
100
+ background: decodeColor(cell.background, `${path}.background`),
101
+ transform: {
102
+ invert: requireBoolean(transform.invert, `${path}.transform.invert`),
103
+ flipX: requireBoolean(transform.flipX, `${path}.transform.flipX`),
104
+ flipY: requireBoolean(transform.flipY, `${path}.transform.flipY`),
105
+ rotation: normalizeRotation(requireFiniteNumber(transform.rotation, `${path}.transform.rotation`)),
106
+ },
107
+ };
108
+ }
@@ -0,0 +1,24 @@
1
+ import type { TextmodeDocumentDecodeOptions, TextmodeDocumentDecodeResult, TextmodeDocumentParseResult } from './types/index.js';
2
+ /**
3
+ * Decode a parsed value and normalize known document fields.
4
+ * Invalid input returns a typed failure; invalid limit configuration throws TypeError.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { decodeTextmodeDocument } from '@textmode/document';
9
+ * const result = decodeTextmodeDocument({ format: 'unsupported' });
10
+ * if (!result.ok) console.log(result.error.code);
11
+ * ```
12
+ */
13
+ export declare function decodeTextmodeDocument(value: unknown, options?: TextmodeDocumentDecodeOptions): TextmodeDocumentDecodeResult;
14
+ /**
15
+ * Parse JSON syntax and decode a textmode document in one call.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import { parseTextmodeDocumentJSON } from '@textmode/document';
20
+ * const result = parseTextmodeDocumentJSON('{');
21
+ * if (!result.ok) console.log(result.error.code); // INVALID_JSON
22
+ * ```
23
+ */
24
+ export declare function parseTextmodeDocumentJSON(json: string, options?: TextmodeDocumentDecodeOptions): TextmodeDocumentParseResult;
package/dist/decode.js ADDED
@@ -0,0 +1,88 @@
1
+ import { LEGACY_TEXTMODE_ALL_VERSION, LEGACY_TEXTMODE_LAYER_FORMAT, LEGACY_TEXTMODE_SELECTED_VERSION, TEXTMODE_DOCUMENT_FORMAT, TEXTMODE_DOCUMENT_FORMAT_VERSION, } from './constants.js';
2
+ import { decodeAllDocument, decodeSelectedDocument } from './decode-shapes.js';
3
+ import { parseJSON } from './parse.js';
4
+ import { DocumentDecodeFailure, fail, failure, requireRecord, requireString, resolveLimits } from './validation.js';
5
+ /**
6
+ * Decode a parsed value and normalize known document fields.
7
+ * Invalid input returns a typed failure; invalid limit configuration throws TypeError.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { decodeTextmodeDocument } from '@textmode/document';
12
+ * const result = decodeTextmodeDocument({ format: 'unsupported' });
13
+ * if (!result.ok) console.log(result.error.code);
14
+ * ```
15
+ */
16
+ export function decodeTextmodeDocument(value, options = {}) {
17
+ try {
18
+ const limits = resolveLimits(options.limits);
19
+ const context = {
20
+ limits,
21
+ remainingCells: limits.maxCells,
22
+ };
23
+ const root = requireRecord(value, '$');
24
+ const format = requireString(root.format, '$.format');
25
+ if (format === TEXTMODE_DOCUMENT_FORMAT) {
26
+ return {
27
+ ok: true,
28
+ document: decodeCurrentDocument(root, context),
29
+ warnings: [],
30
+ };
31
+ }
32
+ if (format === LEGACY_TEXTMODE_LAYER_FORMAT && (options.acceptLegacy ?? true)) {
33
+ return {
34
+ ok: true,
35
+ document: decodeLegacyDocument(root, context),
36
+ warnings: [
37
+ {
38
+ code: 'LEGACY_DOCUMENT_MIGRATED',
39
+ message: 'Migrated a legacy textmode.layer document to textmode.document 2.0.0.',
40
+ },
41
+ ],
42
+ };
43
+ }
44
+ return failure('UNSUPPORTED_FORMAT', `Unsupported textmode document format: ${format}.`, '$.format');
45
+ }
46
+ catch (error) {
47
+ if (error instanceof DocumentDecodeFailure) {
48
+ return { ok: false, error: error.detail };
49
+ }
50
+ throw error;
51
+ }
52
+ }
53
+ /**
54
+ * Parse JSON syntax and decode a textmode document in one call.
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * import { parseTextmodeDocumentJSON } from '@textmode/document';
59
+ * const result = parseTextmodeDocumentJSON('{');
60
+ * if (!result.ok) console.log(result.error.code); // INVALID_JSON
61
+ * ```
62
+ */
63
+ export function parseTextmodeDocumentJSON(json, options = {}) {
64
+ const parsed = parseJSON(json);
65
+ if (!parsed.ok)
66
+ return parsed;
67
+ return decodeTextmodeDocument(parsed.value, options);
68
+ }
69
+ function decodeCurrentDocument(root, context) {
70
+ const version = requireString(root.formatVersion, '$.formatVersion');
71
+ if (version !== TEXTMODE_DOCUMENT_FORMAT_VERSION) {
72
+ fail('UNSUPPORTED_VERSION', `Unsupported textmode.document version: ${version}.`, '$.formatVersion');
73
+ }
74
+ const target = requireString(root.target, '$.target');
75
+ if (target === 'selected')
76
+ return decodeSelectedDocument(root, context);
77
+ if (target === 'all')
78
+ return decodeAllDocument(root, context);
79
+ fail('UNSUPPORTED_TARGET', `Unsupported textmode document target: ${target}.`, '$.target');
80
+ }
81
+ function decodeLegacyDocument(root, context) {
82
+ const version = requireString(root.formatVersion, '$.formatVersion');
83
+ if (version === LEGACY_TEXTMODE_SELECTED_VERSION)
84
+ return decodeSelectedDocument(root, context);
85
+ if (version === LEGACY_TEXTMODE_ALL_VERSION)
86
+ return decodeAllDocument(root, context);
87
+ fail('UNSUPPORTED_VERSION', `Unsupported legacy textmode.layer version: ${version}.`, '$.formatVersion');
88
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Dependency-free textmode document protocol codec.
3
+ *
4
+ * This entry point contains no DOM, renderer, textmode.js, or media encoder
5
+ * dependencies. It decodes every valid v2 document variant; product-specific
6
+ * import policy belongs to callers.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ export { DEFAULT_TEXTMODE_DOCUMENT_LIMITS, LEGACY_TEXTMODE_ALL_VERSION, LEGACY_TEXTMODE_LAYER_FORMAT, LEGACY_TEXTMODE_SELECTED_VERSION, TEXTMODE_DOCUMENT_FORMAT, TEXTMODE_DOCUMENT_FORMAT_VERSION, TEXTMODE_OBJECT_ROWS_ENCODING, } from './constants.js';
11
+ export { decodeTextmodeDocument, parseTextmodeDocumentJSON } from './decode.js';
12
+ export { parseJSON } from './parse.js';
13
+ export type { CanonicalTextmodeAllDocument, CanonicalTextmodeCell, CanonicalTextmodeCellCollection, CanonicalTextmodeDocument, CanonicalTextmodeDocumentLayer, CanonicalTextmodeSelectedDocument, JSONParseResult, LegacyTextmodeAllDocumentJSON, LegacyTextmodeSelectedDocumentJSON, TextmodeAllDocumentJSON, TextmodeDocumentDecodeOptions, TextmodeDocumentDecodeResult, TextmodeDocumentCell, TextmodeDocumentCellCollection, TextmodeDocumentCellTransform, TextmodeDocumentColor, TextmodeDocumentError, TextmodeDocumentErrorCode, TextmodeDocumentFormat, TextmodeDocumentGrid, TextmodeDocumentJSON, TextmodeDocumentLayer, TextmodeDocumentLimits, TextmodeDocumentMetadata, TextmodeDocumentParseResult, TextmodeDocumentRGBAColor, TextmodeDocumentTarget, TextmodeDocumentVersion, TextmodeDocumentWarning, TextmodeSelectedDocumentJSON, TextmodeSelectedDocumentLayer, } from './types/index.js';
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Dependency-free textmode document protocol codec.
3
+ *
4
+ * This entry point contains no DOM, renderer, textmode.js, or media encoder
5
+ * dependencies. It decodes every valid v2 document variant; product-specific
6
+ * import policy belongs to callers.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ export { DEFAULT_TEXTMODE_DOCUMENT_LIMITS, LEGACY_TEXTMODE_ALL_VERSION, LEGACY_TEXTMODE_LAYER_FORMAT, LEGACY_TEXTMODE_SELECTED_VERSION, TEXTMODE_DOCUMENT_FORMAT, TEXTMODE_DOCUMENT_FORMAT_VERSION, TEXTMODE_OBJECT_ROWS_ENCODING, } from './constants.js';
11
+ export { decodeTextmodeDocument, parseTextmodeDocumentJSON } from './decode.js';
12
+ export { parseJSON } from './parse.js';
@@ -0,0 +1,12 @@
1
+ import type { JSONParseResult } from './types/index.js';
2
+ /**
3
+ * Parse JSON syntax before routing the resulting value by its format discriminator.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { parseJSON } from '@textmode/document';
8
+ * const parsed = parseJSON('{"format":"textmode.document"}');
9
+ * if (parsed.ok) console.log(parsed.value);
10
+ * ```
11
+ */
12
+ export declare function parseJSON(json: string): JSONParseResult;
package/dist/parse.js ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Parse JSON syntax before routing the resulting value by its format discriminator.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * import { parseJSON } from '@textmode/document';
7
+ * const parsed = parseJSON('{"format":"textmode.document"}');
8
+ * if (parsed.ok) console.log(parsed.value);
9
+ * ```
10
+ */
11
+ export function parseJSON(json) {
12
+ try {
13
+ return { ok: true, value: JSON.parse(json) };
14
+ }
15
+ catch (error) {
16
+ return {
17
+ ok: false,
18
+ error: {
19
+ code: 'INVALID_JSON',
20
+ message: error instanceof Error ? error.message : 'The file is not valid JSON.',
21
+ },
22
+ };
23
+ }
24
+ }
@@ -0,0 +1,24 @@
1
+ import type { TextmodeDocumentCell, TextmodeDocumentRGBAColor, TextmodeDocumentCellTransform, TextmodeSelectedDocumentJSON, TextmodeDocumentLayer, TextmodeAllDocumentJSON } from './wire.js';
2
+ import type { TEXTMODE_OBJECT_ROWS_ENCODING } from '../constants.js';
3
+ export interface CanonicalTextmodeCell extends Omit<TextmodeDocumentCell, 'foreground' | 'background' | 'transform'> {
4
+ foreground: TextmodeDocumentRGBAColor;
5
+ background: TextmodeDocumentRGBAColor;
6
+ transform: TextmodeDocumentCellTransform;
7
+ }
8
+ export interface CanonicalTextmodeCellCollection {
9
+ encoding: typeof TEXTMODE_OBJECT_ROWS_ENCODING;
10
+ rows: CanonicalTextmodeCell[][];
11
+ }
12
+ export interface CanonicalTextmodeSelectedDocument extends Omit<TextmodeSelectedDocumentJSON, 'layer'> {
13
+ layer: {
14
+ id: string;
15
+ cells: CanonicalTextmodeCellCollection;
16
+ };
17
+ }
18
+ export interface CanonicalTextmodeDocumentLayer extends Omit<TextmodeDocumentLayer, 'cells'> {
19
+ cells: CanonicalTextmodeCellCollection;
20
+ }
21
+ export interface CanonicalTextmodeAllDocument extends Omit<TextmodeAllDocumentJSON, 'layers'> {
22
+ layers: CanonicalTextmodeDocumentLayer[];
23
+ }
24
+ export type CanonicalTextmodeDocument = CanonicalTextmodeSelectedDocument | CanonicalTextmodeAllDocument;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,38 @@
1
+ import type { CanonicalTextmodeDocument } from './canonical.js';
2
+ export interface TextmodeDocumentLimits {
3
+ maxCells?: number;
4
+ maxLayers?: number;
5
+ maxLayerIdLength?: number;
6
+ maxCharacterLength?: number;
7
+ maxMetadataStringLength?: number;
8
+ }
9
+ export interface TextmodeDocumentDecodeOptions {
10
+ limits?: TextmodeDocumentLimits;
11
+ acceptLegacy?: boolean;
12
+ }
13
+ export type TextmodeDocumentErrorCode = 'INVALID_JSON' | 'INVALID_DOCUMENT' | 'UNSUPPORTED_FORMAT' | 'UNSUPPORTED_VERSION' | 'UNSUPPORTED_TARGET' | 'UNSUPPORTED_ENCODING' | 'LIMIT_EXCEEDED';
14
+ export interface TextmodeDocumentError {
15
+ code: TextmodeDocumentErrorCode;
16
+ message: string;
17
+ path?: string;
18
+ }
19
+ export interface TextmodeDocumentWarning {
20
+ code: 'LEGACY_DOCUMENT_MIGRATED';
21
+ message: string;
22
+ }
23
+ export type JSONParseResult = {
24
+ ok: true;
25
+ value: unknown;
26
+ } | {
27
+ ok: false;
28
+ error: TextmodeDocumentError;
29
+ };
30
+ export type TextmodeDocumentDecodeResult = {
31
+ ok: true;
32
+ document: CanonicalTextmodeDocument;
33
+ warnings: TextmodeDocumentWarning[];
34
+ } | {
35
+ ok: false;
36
+ error: TextmodeDocumentError;
37
+ };
38
+ export type TextmodeDocumentParseResult = TextmodeDocumentDecodeResult;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ export type * from './wire.js';
2
+ export type * from './canonical.js';
3
+ export type * from './decode.js';
4
+ export type * from './legacy.js';
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,25 @@
1
+ import type { LEGACY_TEXTMODE_ALL_VERSION, LEGACY_TEXTMODE_LAYER_FORMAT, LEGACY_TEXTMODE_SELECTED_VERSION } from '../constants.js';
2
+ import type { TextmodeDocumentMetadata, TextmodeDocumentGrid, TextmodeSelectedDocumentLayer, TextmodeDocumentLayer } from './wire.js';
3
+ export interface LegacyTextmodeSelectedDocumentJSON {
4
+ $schema?: string;
5
+ format: typeof LEGACY_TEXTMODE_LAYER_FORMAT;
6
+ formatVersion: typeof LEGACY_TEXTMODE_SELECTED_VERSION;
7
+ metadata?: TextmodeDocumentMetadata;
8
+ canvas: {
9
+ width: number;
10
+ height: number;
11
+ };
12
+ grid: TextmodeDocumentGrid;
13
+ layer: TextmodeSelectedDocumentLayer;
14
+ }
15
+ export interface LegacyTextmodeAllDocumentJSON {
16
+ $schema?: string;
17
+ format: typeof LEGACY_TEXTMODE_LAYER_FORMAT;
18
+ formatVersion: typeof LEGACY_TEXTMODE_ALL_VERSION;
19
+ metadata?: TextmodeDocumentMetadata;
20
+ canvas: {
21
+ width: number;
22
+ height: number;
23
+ };
24
+ layers: TextmodeDocumentLayer[];
25
+ }
@@ -0,0 +1 @@
1
+ export {};