redashify 0.0.0 → 0.2.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,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Haihang Wang
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,169 @@
1
+ # redashify
2
+
3
+ [![npm](https://img.shields.io/npm/v/redashify)](https://www.npmjs.com/package/redashify)
4
+ [![license](https://img.shields.io/npm/l/redashify)](https://github.com/hangingahaw/redashify/blob/main/LICENSE)
5
+
6
+ Context-aware dash correction powered by LLMs.
7
+
8
+ Converts hyphens (`-`), double-hyphens (`--`), and triple-hyphens (`---`) to the typographically correct character — hyphen, en dash (`–`), or em dash (`—`) — based on surrounding context.
9
+
10
+ Unlike regex, redashify uses an LLM to determine the correct dash because the rules are too context-dependent for pattern matching alone. Only the dash contexts (not the full document) are sent to the LLM, making it token-efficient and privacy-conscious.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ npm install redashify
16
+ ```
17
+
18
+ ## Quick start
19
+
20
+ ```ts
21
+ import { redashify } from 'redashify'
22
+
23
+ const result = await redashify(
24
+ 'The court held--in a 5-4 decision--that pages 10-20 applied.',
25
+ { apiKey: process.env.OPENAI_API_KEY, provider: 'openai' }
26
+ )
27
+
28
+ result.text
29
+ // → 'The court held—in a 5-4 decision—that pages 10–20 applied.'
30
+
31
+ result.corrections
32
+ // → [{ position: 14, original: '--', replacement: '—', context: '...' }, ...]
33
+
34
+ result.unchanged
35
+ // → false
36
+ ```
37
+
38
+ ## Providers
39
+
40
+ Built-in support for any OpenAI-compatible API, plus a native Anthropic adapter.
41
+
42
+ | Provider | Default model | Notes |
43
+ |---|---|---|
44
+ | `openai` | `gpt-4o-mini` | |
45
+ | `anthropic` | `claude-haiku-4-5-20251001` | Native adapter (different API format) |
46
+ | `gemini` | `gemini-2.0-flash` | OpenAI-compatible endpoint |
47
+ | `groq` | `llama-3.3-70b-versatile` | |
48
+ | `together` | `meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo` | |
49
+ | `mistral` | `mistral-small-latest` | |
50
+ | `xai` | `grok-3-mini-fast` | |
51
+ | `deepseek` | `deepseek-chat` | |
52
+ | `openrouter` | *(none — must specify `model`)* | |
53
+
54
+ Override the default model:
55
+
56
+ ```ts
57
+ const result = await redashify(text, {
58
+ apiKey: process.env.OPENAI_API_KEY,
59
+ provider: 'openai',
60
+ model: 'gpt-4o',
61
+ })
62
+ ```
63
+
64
+ For unlisted providers that support the OpenAI chat completions format:
65
+
66
+ ```ts
67
+ const result = await redashify(text, {
68
+ apiKey: '...',
69
+ baseURL: 'https://my-provider.com/v1',
70
+ model: 'my-model',
71
+ })
72
+ ```
73
+
74
+ ### Custom LLM function
75
+
76
+ Bypass the built-in client entirely:
77
+
78
+ ```ts
79
+ const result = await redashify(text, {
80
+ llm: async (messages) => {
81
+ const res = await myLlmCall(messages)
82
+ return res.text
83
+ },
84
+ })
85
+ ```
86
+
87
+ ## Options
88
+
89
+ | Option | Type | Default | Description |
90
+ |---|---|---|---|
91
+ | `apiKey` | `string` | — | API key for the LLM provider |
92
+ | `provider` | `Provider` | — | Provider name (maps to base URL + default model) |
93
+ | `model` | `string` | *(per provider)* | Model name. Required if no provider default. |
94
+ | `baseURL` | `string` | — | Custom endpoint URL. Overrides provider mapping. |
95
+ | `llm` | `(messages) => Promise<string>` | — | Custom LLM function. Overrides apiKey/provider/model. |
96
+ | `rules` | `string` | `“”` | Custom rules prepended to the system prompt |
97
+ | `contextSize` | `number` | `50` | Characters of context on each side of a dash |
98
+ | `batchSize` | `number` | `50` | Maximum dashes per LLM call |
99
+
100
+ You must provide either `apiKey` (with `provider` or `model`) or `llm`.
101
+
102
+ ## Result
103
+
104
+ ```ts
105
+ interface RedashifyResult {
106
+ text: string // The corrected text
107
+ corrections: Array<{ // Only dashes that were changed
108
+ position: number // Index in original text
109
+ original: string // What was there (e.g. "--")
110
+ replacement: string // What it became (e.g. "—")
111
+ context: string // Surrounding snippet for audit
112
+ }>
113
+ unchanged: boolean // true if nothing was modified
114
+ }
115
+ ```
116
+
117
+ **No dashes in text:** LLM is not called. Returns immediately with `unchanged: true`.
118
+
119
+ **All dashes already correct:** LLM is called (correctness can’t be pre-judged), but `corrections` is empty and `unchanged` is `true`.
120
+
121
+ ## Custom rules
122
+
123
+ Pass domain-specific rules via the `rules` option. Works with [lexstyle](https://github.com/hangingahaw/lexstyle) for structured rule management:
124
+
125
+ ```ts
126
+ import { rules, serialize } from 'lexstyle'
127
+ import { redashify } from 'redashify'
128
+
129
+ const result = await redashify(text, {
130
+ apiKey: process.env.OPENAI_API_KEY,
131
+ provider: 'openai',
132
+ rules: serialize(rules, 'dashes'),
133
+ })
134
+ ```
135
+
136
+ Or pass rules as a plain string:
137
+
138
+ ```ts
139
+ const result = await redashify(text, {
140
+ apiKey: '...',
141
+ provider: 'openai',
142
+ rules: `Use en dashes for page ranges (e.g. pp. 45–67).
143
+ Use em dashes for parenthetical asides with no spaces.
144
+ Keep hyphens in compound modifiers and vote tallies (5-4).`,
145
+ })
146
+ ```
147
+
148
+ ## Design decisions
149
+
150
+ **LLM over regex.** Dash correction depends on semantic context — is “10-20” a range (en dash) or a compound modifier (hyphen)? Is “--” an em dash or a typo? Regex can’t answer these questions. An LLM can, given a few words of surrounding context.
151
+
152
+ **Privacy by design.** Only short context windows around each dash are sent to the LLM — never the full document. A 10,000-word document with 5 dashes sends ~5 small context snippets, regardless of document length.
153
+
154
+ **Batch validation.** Each batch response is validated against its expected IDs before merging. Cross-batch ID leakage or missing corrections are caught immediately, not silently swallowed.
155
+
156
+ **Robust response parsing.** LLM output is parsed via strict JSON first, with a hardened bracket-extraction fallback that skips stray brackets in preamble text. Every correction is validated for known dash characters and duplicate IDs.
157
+
158
+ ## Development
159
+
160
+ ```sh
161
+ npm install
162
+ npm test
163
+ npm run typecheck
164
+ npm run build # ESM + CJS + .d.ts
165
+ ```
166
+
167
+ ## License
168
+
169
+ Apache-2.0
package/dist/index.cjs ADDED
@@ -0,0 +1,244 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ VALID_DASHES: () => VALID_DASHES,
24
+ buildMessages: () => buildMessages,
25
+ extractDashes: () => extractDashes,
26
+ redashify: () => redashify
27
+ });
28
+ module.exports = __toCommonJS(index_exports);
29
+
30
+ // src/core.ts
31
+ var import_llm_client = require("@lexstyle/llm-client");
32
+
33
+ // src/extractor.ts
34
+ var DASH_RE = /---+|--|\u2014|\u2013|-/g;
35
+ function extractDashes(text, contextSize = 50) {
36
+ const results = [];
37
+ let match;
38
+ let id = 0;
39
+ DASH_RE.lastIndex = 0;
40
+ while ((match = DASH_RE.exec(text)) !== null) {
41
+ const start = match.index;
42
+ const end = start + match[0].length;
43
+ const bStart = Math.max(0, start - contextSize);
44
+ let before = text.slice(bStart, start);
45
+ if (bStart > 0) {
46
+ const idx = before.search(/\s/);
47
+ if (idx !== -1) {
48
+ before = before.slice(idx).trimStart();
49
+ }
50
+ }
51
+ const aEnd = Math.min(text.length, end + contextSize);
52
+ let after = text.slice(end, aEnd);
53
+ if (aEnd < text.length) {
54
+ const idx = after.search(/\s[^\s]*$/);
55
+ if (idx > 0) {
56
+ after = after.slice(0, idx);
57
+ }
58
+ }
59
+ results.push({ id: id++, original: match[0], before, after, start, end });
60
+ }
61
+ return results;
62
+ }
63
+
64
+ // src/prompt.ts
65
+ function buildMessages(contexts, rules) {
66
+ const ruleBlock = rules ? `
67
+ ${rules}
68
+ ` : "";
69
+ const system = `You are a typography expert. Your task is to determine the correct dash character for each occurrence.
70
+ ${ruleBlock}
71
+
72
+ For each dash below, return the correct Unicode character:
73
+ - (U+002D) hyphen
74
+ \u2013 (U+2013) en dash
75
+ \u2014 (U+2014) em dash
76
+
77
+ IMPORTANT: You must return exactly one entry for every id provided. Do not skip any.
78
+ Respond with ONLY a JSON array. No explanation, no markdown fences.
79
+ Format: [{"id":0,"dash":"-"},{"id":1,"dash":"\u2013"}]`;
80
+ const user = contexts.map((ctx) => `[${ctx.id}] \u201C${ctx.before}\u201D [${ctx.original}] \u201C${ctx.after}\u201D`).join("\n");
81
+ return [
82
+ { role: "system", content: system },
83
+ { role: "user", content: user }
84
+ ];
85
+ }
86
+
87
+ // src/types.ts
88
+ var VALID_DASHES = Object.freeze(["-", "\u2013", "\u2014"]);
89
+ var VALID_DASH_SET = new Set(VALID_DASHES);
90
+ function isValidDash(s) {
91
+ return VALID_DASH_SET.has(s);
92
+ }
93
+
94
+ // src/replacer.ts
95
+ function parseResponse(response) {
96
+ let cleaned = response.trim();
97
+ cleaned = cleaned.replace(/^```(?:json)?\s*\n?/i, "").replace(/\n?```\s*$/, "");
98
+ cleaned = cleaned.trim();
99
+ let parsed;
100
+ try {
101
+ const strict = JSON.parse(cleaned);
102
+ if (Array.isArray(strict)) {
103
+ parsed = strict;
104
+ }
105
+ } catch {
106
+ }
107
+ if (parsed === void 0) {
108
+ const end = cleaned.lastIndexOf("]");
109
+ if (end === -1) {
110
+ throw new Error(`Invalid LLM response: no JSON array found. Response: ${cleaned.slice(0, 200)}`);
111
+ }
112
+ for (let i = 0; i < end; i++) {
113
+ if (cleaned[i] !== "[") continue;
114
+ try {
115
+ const candidate = JSON.parse(cleaned.slice(i, end + 1));
116
+ if (Array.isArray(candidate)) {
117
+ parsed = candidate;
118
+ break;
119
+ }
120
+ } catch {
121
+ continue;
122
+ }
123
+ }
124
+ }
125
+ if (!Array.isArray(parsed)) {
126
+ throw new Error(
127
+ parsed === void 0 ? `Invalid LLM response: no JSON array found. Response: ${cleaned.slice(0, 200)}` : "LLM response is not a JSON array"
128
+ );
129
+ }
130
+ const seenIds = /* @__PURE__ */ new Set();
131
+ return parsed.map((item, idx) => {
132
+ const rec = item;
133
+ if (typeof rec !== "object" || rec === null || typeof rec.id !== "number" || typeof rec.dash !== "string") {
134
+ throw new Error(`Invalid correction at index ${idx}: ${JSON.stringify(item)}`);
135
+ }
136
+ const correction = { id: rec.id, dash: rec.dash };
137
+ if (!isValidDash(correction.dash)) {
138
+ throw new Error(
139
+ `Invalid dash character at index ${idx} (id ${correction.id}): got ${JSON.stringify(correction.dash)}, expected "-", "\\u2013", or "\\u2014"`
140
+ );
141
+ }
142
+ if (seenIds.has(correction.id)) {
143
+ throw new Error(`Duplicate correction id ${correction.id} at index ${idx}`);
144
+ }
145
+ seenIds.add(correction.id);
146
+ return { id: correction.id, dash: correction.dash };
147
+ });
148
+ }
149
+ function applyCorrections(text, contexts, corrections) {
150
+ const correctionMap = /* @__PURE__ */ new Map();
151
+ for (const c of corrections) {
152
+ correctionMap.set(c.id, c.dash);
153
+ }
154
+ const contextIds = new Set(contexts.map((c) => c.id));
155
+ for (const id of contextIds) {
156
+ if (!correctionMap.has(id)) {
157
+ throw new Error(`Missing correction for dash id ${id}`);
158
+ }
159
+ }
160
+ for (const id of correctionMap.keys()) {
161
+ if (!contextIds.has(id)) {
162
+ throw new Error(`Unknown correction id ${id}: no matching dash context`);
163
+ }
164
+ }
165
+ const changes = [];
166
+ for (const ctx of contexts) {
167
+ const replacement = correctionMap.get(ctx.id);
168
+ if (replacement !== ctx.original) {
169
+ changes.push({ context: ctx, replacement });
170
+ }
171
+ }
172
+ changes.sort((a, b) => b.context.start - a.context.start);
173
+ let result = text;
174
+ const appliedCorrections = [];
175
+ for (const { context: ctx, replacement } of changes) {
176
+ const snippetBefore = ctx.before.slice(-20);
177
+ const snippetAfter = ctx.after.slice(0, 20);
178
+ const contextSnippet = `${snippetBefore}[${ctx.original}\u2192${replacement}]${snippetAfter}`;
179
+ result = result.slice(0, ctx.start) + replacement + result.slice(ctx.end);
180
+ appliedCorrections.push({
181
+ position: ctx.start,
182
+ original: ctx.original,
183
+ replacement,
184
+ context: contextSnippet
185
+ });
186
+ }
187
+ appliedCorrections.reverse();
188
+ return { text: result, appliedCorrections };
189
+ }
190
+
191
+ // src/core.ts
192
+ function requireInt(value, name, min) {
193
+ if (!Number.isFinite(value) || value < min || Math.floor(value) !== value) {
194
+ throw new Error(`Invalid ${name}: ${value}. Must be a finite integer >= ${min}.`);
195
+ }
196
+ }
197
+ function validateBatchIds(corrections, expectedIds) {
198
+ for (const { id } of corrections) {
199
+ if (!expectedIds.has(id)) {
200
+ throw new Error(`LLM returned unexpected id ${id} (not in this batch)`);
201
+ }
202
+ }
203
+ for (const id of expectedIds) {
204
+ if (!corrections.some((c) => c.id === id)) {
205
+ throw new Error(`LLM missing correction for id ${id} in batch`);
206
+ }
207
+ }
208
+ }
209
+ async function redashify(text, options) {
210
+ if (!options || typeof options !== "object") {
211
+ throw new Error("redashify requires an options object with `apiKey` + `model`, `apiKey` + `provider`, or `llm`");
212
+ }
213
+ const batchSize = options.batchSize ?? 50;
214
+ requireInt(batchSize, "batchSize", 1);
215
+ const contextSize = options.contextSize ?? 50;
216
+ requireInt(contextSize, "contextSize", 0);
217
+ const llmFn = (0, import_llm_client.resolveLlm)(options, "redashify");
218
+ const contexts = extractDashes(text, contextSize);
219
+ if (contexts.length === 0) {
220
+ return { text, corrections: [], unchanged: true };
221
+ }
222
+ const allCorrections = [];
223
+ for (let i = 0; i < contexts.length; i += batchSize) {
224
+ const batch = contexts.slice(i, i + batchSize);
225
+ const messages = buildMessages(batch, options.rules);
226
+ const response = await llmFn(messages);
227
+ const corrections = parseResponse(response);
228
+ validateBatchIds(corrections, new Set(batch.map((ctx) => ctx.id)));
229
+ allCorrections.push(...corrections);
230
+ }
231
+ const { text: correctedText, appliedCorrections } = applyCorrections(text, contexts, allCorrections);
232
+ return {
233
+ text: correctedText,
234
+ corrections: appliedCorrections,
235
+ unchanged: appliedCorrections.length === 0
236
+ };
237
+ }
238
+ // Annotate the CommonJS export names for ESM import in node:
239
+ 0 && (module.exports = {
240
+ VALID_DASHES,
241
+ buildMessages,
242
+ extractDashes,
243
+ redashify
244
+ });
@@ -0,0 +1,82 @@
1
+ import { LlmOptions, Message } from '@lexstyle/llm-client';
2
+ export { Message, Provider } from '@lexstyle/llm-client';
3
+
4
+ /** The valid dash characters, exported for documentation/reference */
5
+ declare const VALID_DASHES: readonly ["-", "–", "—"];
6
+ /** A single valid dash character: hyphen, en dash, or em dash */
7
+ type DashChar = (typeof VALID_DASHES)[number];
8
+ /** Result of applying corrections to text */
9
+ interface ApplyResult {
10
+ text: string;
11
+ appliedCorrections: Correction[];
12
+ }
13
+ /** A dash occurrence extracted from the input text */
14
+ interface DashContext {
15
+ /** Unique identifier for this dash occurrence */
16
+ id: number;
17
+ /** The original dash string found (e.g. "-", "--", "---", "\u2013", "\u2014") */
18
+ original: string;
19
+ /** Text before the dash for context */
20
+ before: string;
21
+ /** Text after the dash for context */
22
+ after: string;
23
+ /** Start index in the original text */
24
+ start: number;
25
+ /** End index in the original text (exclusive) */
26
+ end: number;
27
+ }
28
+ /** A single correction applied to the text, for audit/review */
29
+ interface Correction {
30
+ /** Position in original text */
31
+ position: number;
32
+ /** The original dash string */
33
+ original: string;
34
+ /** The replacement dash character */
35
+ replacement: DashChar;
36
+ /** Surrounding context snippet */
37
+ context: string;
38
+ }
39
+ /** Result returned by redashify */
40
+ interface RedashifyResult {
41
+ /** The corrected text */
42
+ text: string;
43
+ /** List of corrections that were applied */
44
+ corrections: Correction[];
45
+ /** True if no changes were needed */
46
+ unchanged: boolean;
47
+ }
48
+ /** Options for redashify */
49
+ interface RedashifyOptions extends LlmOptions {
50
+ /** Characters of context on each side of a dash (default: 50) */
51
+ contextSize?: number;
52
+ /** Custom rules to prepend to the system prompt */
53
+ rules?: string;
54
+ /** Maximum dashes per LLM call (default: 50). Must be >= 1. */
55
+ batchSize?: number;
56
+ }
57
+
58
+ /**
59
+ * Correct dashes in text using an LLM.
60
+ *
61
+ * Architecture: extract dashes -> batch LLM calls -> replace.
62
+ * Only the dash contexts (not the full document) are sent to the LLM.
63
+ */
64
+ declare function redashify(text: string, options?: RedashifyOptions): Promise<RedashifyResult>;
65
+
66
+ /**
67
+ * Extract all dashes from text with surrounding context.
68
+ *
69
+ * Returns a DashContext for every dash occurrence, giving the LLM
70
+ * enough surrounding text to determine the correct replacement.
71
+ */
72
+ declare function extractDashes(text: string, contextSize?: number): DashContext[];
73
+
74
+ /**
75
+ * Build the messages array for a single LLM call.
76
+ *
77
+ * System prompt contains the rules (sent once).
78
+ * User prompt contains only the extracted dash contexts (compact).
79
+ */
80
+ declare function buildMessages(contexts: readonly DashContext[], rules?: string): Message[];
81
+
82
+ export { type ApplyResult, type Correction, type DashChar, type DashContext, type RedashifyOptions, type RedashifyResult, VALID_DASHES, buildMessages, extractDashes, redashify };
@@ -0,0 +1,82 @@
1
+ import { LlmOptions, Message } from '@lexstyle/llm-client';
2
+ export { Message, Provider } from '@lexstyle/llm-client';
3
+
4
+ /** The valid dash characters, exported for documentation/reference */
5
+ declare const VALID_DASHES: readonly ["-", "–", "—"];
6
+ /** A single valid dash character: hyphen, en dash, or em dash */
7
+ type DashChar = (typeof VALID_DASHES)[number];
8
+ /** Result of applying corrections to text */
9
+ interface ApplyResult {
10
+ text: string;
11
+ appliedCorrections: Correction[];
12
+ }
13
+ /** A dash occurrence extracted from the input text */
14
+ interface DashContext {
15
+ /** Unique identifier for this dash occurrence */
16
+ id: number;
17
+ /** The original dash string found (e.g. "-", "--", "---", "\u2013", "\u2014") */
18
+ original: string;
19
+ /** Text before the dash for context */
20
+ before: string;
21
+ /** Text after the dash for context */
22
+ after: string;
23
+ /** Start index in the original text */
24
+ start: number;
25
+ /** End index in the original text (exclusive) */
26
+ end: number;
27
+ }
28
+ /** A single correction applied to the text, for audit/review */
29
+ interface Correction {
30
+ /** Position in original text */
31
+ position: number;
32
+ /** The original dash string */
33
+ original: string;
34
+ /** The replacement dash character */
35
+ replacement: DashChar;
36
+ /** Surrounding context snippet */
37
+ context: string;
38
+ }
39
+ /** Result returned by redashify */
40
+ interface RedashifyResult {
41
+ /** The corrected text */
42
+ text: string;
43
+ /** List of corrections that were applied */
44
+ corrections: Correction[];
45
+ /** True if no changes were needed */
46
+ unchanged: boolean;
47
+ }
48
+ /** Options for redashify */
49
+ interface RedashifyOptions extends LlmOptions {
50
+ /** Characters of context on each side of a dash (default: 50) */
51
+ contextSize?: number;
52
+ /** Custom rules to prepend to the system prompt */
53
+ rules?: string;
54
+ /** Maximum dashes per LLM call (default: 50). Must be >= 1. */
55
+ batchSize?: number;
56
+ }
57
+
58
+ /**
59
+ * Correct dashes in text using an LLM.
60
+ *
61
+ * Architecture: extract dashes -> batch LLM calls -> replace.
62
+ * Only the dash contexts (not the full document) are sent to the LLM.
63
+ */
64
+ declare function redashify(text: string, options?: RedashifyOptions): Promise<RedashifyResult>;
65
+
66
+ /**
67
+ * Extract all dashes from text with surrounding context.
68
+ *
69
+ * Returns a DashContext for every dash occurrence, giving the LLM
70
+ * enough surrounding text to determine the correct replacement.
71
+ */
72
+ declare function extractDashes(text: string, contextSize?: number): DashContext[];
73
+
74
+ /**
75
+ * Build the messages array for a single LLM call.
76
+ *
77
+ * System prompt contains the rules (sent once).
78
+ * User prompt contains only the extracted dash contexts (compact).
79
+ */
80
+ declare function buildMessages(contexts: readonly DashContext[], rules?: string): Message[];
81
+
82
+ export { type ApplyResult, type Correction, type DashChar, type DashContext, type RedashifyOptions, type RedashifyResult, VALID_DASHES, buildMessages, extractDashes, redashify };
package/dist/index.js ADDED
@@ -0,0 +1,214 @@
1
+ // src/core.ts
2
+ import { resolveLlm } from "@lexstyle/llm-client";
3
+
4
+ // src/extractor.ts
5
+ var DASH_RE = /---+|--|\u2014|\u2013|-/g;
6
+ function extractDashes(text, contextSize = 50) {
7
+ const results = [];
8
+ let match;
9
+ let id = 0;
10
+ DASH_RE.lastIndex = 0;
11
+ while ((match = DASH_RE.exec(text)) !== null) {
12
+ const start = match.index;
13
+ const end = start + match[0].length;
14
+ const bStart = Math.max(0, start - contextSize);
15
+ let before = text.slice(bStart, start);
16
+ if (bStart > 0) {
17
+ const idx = before.search(/\s/);
18
+ if (idx !== -1) {
19
+ before = before.slice(idx).trimStart();
20
+ }
21
+ }
22
+ const aEnd = Math.min(text.length, end + contextSize);
23
+ let after = text.slice(end, aEnd);
24
+ if (aEnd < text.length) {
25
+ const idx = after.search(/\s[^\s]*$/);
26
+ if (idx > 0) {
27
+ after = after.slice(0, idx);
28
+ }
29
+ }
30
+ results.push({ id: id++, original: match[0], before, after, start, end });
31
+ }
32
+ return results;
33
+ }
34
+
35
+ // src/prompt.ts
36
+ function buildMessages(contexts, rules) {
37
+ const ruleBlock = rules ? `
38
+ ${rules}
39
+ ` : "";
40
+ const system = `You are a typography expert. Your task is to determine the correct dash character for each occurrence.
41
+ ${ruleBlock}
42
+
43
+ For each dash below, return the correct Unicode character:
44
+ - (U+002D) hyphen
45
+ \u2013 (U+2013) en dash
46
+ \u2014 (U+2014) em dash
47
+
48
+ IMPORTANT: You must return exactly one entry for every id provided. Do not skip any.
49
+ Respond with ONLY a JSON array. No explanation, no markdown fences.
50
+ Format: [{"id":0,"dash":"-"},{"id":1,"dash":"\u2013"}]`;
51
+ const user = contexts.map((ctx) => `[${ctx.id}] \u201C${ctx.before}\u201D [${ctx.original}] \u201C${ctx.after}\u201D`).join("\n");
52
+ return [
53
+ { role: "system", content: system },
54
+ { role: "user", content: user }
55
+ ];
56
+ }
57
+
58
+ // src/types.ts
59
+ var VALID_DASHES = Object.freeze(["-", "\u2013", "\u2014"]);
60
+ var VALID_DASH_SET = new Set(VALID_DASHES);
61
+ function isValidDash(s) {
62
+ return VALID_DASH_SET.has(s);
63
+ }
64
+
65
+ // src/replacer.ts
66
+ function parseResponse(response) {
67
+ let cleaned = response.trim();
68
+ cleaned = cleaned.replace(/^```(?:json)?\s*\n?/i, "").replace(/\n?```\s*$/, "");
69
+ cleaned = cleaned.trim();
70
+ let parsed;
71
+ try {
72
+ const strict = JSON.parse(cleaned);
73
+ if (Array.isArray(strict)) {
74
+ parsed = strict;
75
+ }
76
+ } catch {
77
+ }
78
+ if (parsed === void 0) {
79
+ const end = cleaned.lastIndexOf("]");
80
+ if (end === -1) {
81
+ throw new Error(`Invalid LLM response: no JSON array found. Response: ${cleaned.slice(0, 200)}`);
82
+ }
83
+ for (let i = 0; i < end; i++) {
84
+ if (cleaned[i] !== "[") continue;
85
+ try {
86
+ const candidate = JSON.parse(cleaned.slice(i, end + 1));
87
+ if (Array.isArray(candidate)) {
88
+ parsed = candidate;
89
+ break;
90
+ }
91
+ } catch {
92
+ continue;
93
+ }
94
+ }
95
+ }
96
+ if (!Array.isArray(parsed)) {
97
+ throw new Error(
98
+ parsed === void 0 ? `Invalid LLM response: no JSON array found. Response: ${cleaned.slice(0, 200)}` : "LLM response is not a JSON array"
99
+ );
100
+ }
101
+ const seenIds = /* @__PURE__ */ new Set();
102
+ return parsed.map((item, idx) => {
103
+ const rec = item;
104
+ if (typeof rec !== "object" || rec === null || typeof rec.id !== "number" || typeof rec.dash !== "string") {
105
+ throw new Error(`Invalid correction at index ${idx}: ${JSON.stringify(item)}`);
106
+ }
107
+ const correction = { id: rec.id, dash: rec.dash };
108
+ if (!isValidDash(correction.dash)) {
109
+ throw new Error(
110
+ `Invalid dash character at index ${idx} (id ${correction.id}): got ${JSON.stringify(correction.dash)}, expected "-", "\\u2013", or "\\u2014"`
111
+ );
112
+ }
113
+ if (seenIds.has(correction.id)) {
114
+ throw new Error(`Duplicate correction id ${correction.id} at index ${idx}`);
115
+ }
116
+ seenIds.add(correction.id);
117
+ return { id: correction.id, dash: correction.dash };
118
+ });
119
+ }
120
+ function applyCorrections(text, contexts, corrections) {
121
+ const correctionMap = /* @__PURE__ */ new Map();
122
+ for (const c of corrections) {
123
+ correctionMap.set(c.id, c.dash);
124
+ }
125
+ const contextIds = new Set(contexts.map((c) => c.id));
126
+ for (const id of contextIds) {
127
+ if (!correctionMap.has(id)) {
128
+ throw new Error(`Missing correction for dash id ${id}`);
129
+ }
130
+ }
131
+ for (const id of correctionMap.keys()) {
132
+ if (!contextIds.has(id)) {
133
+ throw new Error(`Unknown correction id ${id}: no matching dash context`);
134
+ }
135
+ }
136
+ const changes = [];
137
+ for (const ctx of contexts) {
138
+ const replacement = correctionMap.get(ctx.id);
139
+ if (replacement !== ctx.original) {
140
+ changes.push({ context: ctx, replacement });
141
+ }
142
+ }
143
+ changes.sort((a, b) => b.context.start - a.context.start);
144
+ let result = text;
145
+ const appliedCorrections = [];
146
+ for (const { context: ctx, replacement } of changes) {
147
+ const snippetBefore = ctx.before.slice(-20);
148
+ const snippetAfter = ctx.after.slice(0, 20);
149
+ const contextSnippet = `${snippetBefore}[${ctx.original}\u2192${replacement}]${snippetAfter}`;
150
+ result = result.slice(0, ctx.start) + replacement + result.slice(ctx.end);
151
+ appliedCorrections.push({
152
+ position: ctx.start,
153
+ original: ctx.original,
154
+ replacement,
155
+ context: contextSnippet
156
+ });
157
+ }
158
+ appliedCorrections.reverse();
159
+ return { text: result, appliedCorrections };
160
+ }
161
+
162
+ // src/core.ts
163
+ function requireInt(value, name, min) {
164
+ if (!Number.isFinite(value) || value < min || Math.floor(value) !== value) {
165
+ throw new Error(`Invalid ${name}: ${value}. Must be a finite integer >= ${min}.`);
166
+ }
167
+ }
168
+ function validateBatchIds(corrections, expectedIds) {
169
+ for (const { id } of corrections) {
170
+ if (!expectedIds.has(id)) {
171
+ throw new Error(`LLM returned unexpected id ${id} (not in this batch)`);
172
+ }
173
+ }
174
+ for (const id of expectedIds) {
175
+ if (!corrections.some((c) => c.id === id)) {
176
+ throw new Error(`LLM missing correction for id ${id} in batch`);
177
+ }
178
+ }
179
+ }
180
+ async function redashify(text, options) {
181
+ if (!options || typeof options !== "object") {
182
+ throw new Error("redashify requires an options object with `apiKey` + `model`, `apiKey` + `provider`, or `llm`");
183
+ }
184
+ const batchSize = options.batchSize ?? 50;
185
+ requireInt(batchSize, "batchSize", 1);
186
+ const contextSize = options.contextSize ?? 50;
187
+ requireInt(contextSize, "contextSize", 0);
188
+ const llmFn = resolveLlm(options, "redashify");
189
+ const contexts = extractDashes(text, contextSize);
190
+ if (contexts.length === 0) {
191
+ return { text, corrections: [], unchanged: true };
192
+ }
193
+ const allCorrections = [];
194
+ for (let i = 0; i < contexts.length; i += batchSize) {
195
+ const batch = contexts.slice(i, i + batchSize);
196
+ const messages = buildMessages(batch, options.rules);
197
+ const response = await llmFn(messages);
198
+ const corrections = parseResponse(response);
199
+ validateBatchIds(corrections, new Set(batch.map((ctx) => ctx.id)));
200
+ allCorrections.push(...corrections);
201
+ }
202
+ const { text: correctedText, appliedCorrections } = applyCorrections(text, contexts, allCorrections);
203
+ return {
204
+ text: correctedText,
205
+ corrections: appliedCorrections,
206
+ unchanged: appliedCorrections.length === 0
207
+ };
208
+ }
209
+ export {
210
+ VALID_DASHES,
211
+ buildMessages,
212
+ extractDashes,
213
+ redashify
214
+ };
package/package.json CHANGED
@@ -1,7 +1,64 @@
1
1
  {
2
2
  "name": "redashify",
3
- "version": "0.0.0",
3
+ "version": "0.2.0",
4
4
  "description": "Context-aware dash correction powered by LLMs",
5
- "main": "index.js",
6
- "license": "MIT"
5
+ "author": "Haihang Wang",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "sideEffects": false,
11
+ "exports": {
12
+ ".": {
13
+ "import": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "require": {
18
+ "types": "./dist/index.d.cts",
19
+ "default": "./dist/index.cjs"
20
+ }
21
+ }
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "scripts": {
27
+ "build": "tsup",
28
+ "test": "vitest run",
29
+ "test:watch": "vitest",
30
+ "typecheck": "tsc --noEmit",
31
+ "typecheck:test": "tsc --noEmit -p tsconfig.test.json",
32
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
33
+ },
34
+ "keywords": [
35
+ "typography",
36
+ "dash",
37
+ "em-dash",
38
+ "en-dash",
39
+ "hyphen",
40
+ "legal",
41
+ "smartypants",
42
+ "llm"
43
+ ],
44
+ "engines": {
45
+ "node": ">=18"
46
+ },
47
+ "license": "Apache-2.0",
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/hangingahaw/redashify.git"
51
+ },
52
+ "homepage": "https://github.com/hangingahaw/redashify#readme",
53
+ "bugs": {
54
+ "url": "https://github.com/hangingahaw/redashify/issues"
55
+ },
56
+ "dependencies": {
57
+ "@lexstyle/llm-client": "^0.1.0"
58
+ },
59
+ "devDependencies": {
60
+ "tsup": "^8.0.0",
61
+ "typescript": "^5.4.0",
62
+ "vitest": "^2.0.0"
63
+ }
7
64
  }
package/index.js DELETED
@@ -1 +0,0 @@
1
- module.exports = {};