@journey-to-code/symbology 0.2.0 → 0.3.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/README.md CHANGED
@@ -1,59 +1,102 @@
1
- # @journey-to-code/symbology
2
-
3
- Dependency-free QR and linear barcode encoding and decoding, with a Rust
4
- WebAssembly implementation and an optional Zubra-built custom element.
5
-
6
- ## Install
7
-
8
- ```sh
9
- npm install @journey-to-code/symbology
10
- ```
11
-
12
- The package includes the WebAssembly binary. Load it with no URL or pass an
13
- alternate source:
14
-
15
- ```js
16
- import { loadQr } from '@journey-to-code/symbology';
17
-
18
- const symbology = await loadQr();
19
- const code = symbology.encode('https://example.com');
20
- const svg = symbology.svg(code);
21
- ```
22
-
23
- `loadQr` also accepts WASM bytes, a `Response`, a `WebAssembly.Module`, or a
24
- URL. Encoding supports QR, Code 128, Code 39, and EAN-13. The decoder reads
25
- QR frames and linear-barcode scanlines or frames.
26
-
27
- ## Custom element
28
-
29
- Import the widget once from a JavaScript entry point that resolves npm
30
- package imports (for example, your bundler entry point):
31
-
32
- ```js
33
- import '@journey-to-code/symbology/symbology-code';
34
- ```
35
-
36
- Then use it in HTML:
37
-
38
- ```html
39
- <symbology-code format="qr" value="https://example.com"></symbology-code>
40
- ```
41
-
42
- The element offers a format picker, editable content, SVG preview, and
43
- download. `format` accepts `qr`, `code128`, `code39`, or `ean13`; `value`
44
- sets the initial content. It is authored in Zubra and distributed as a
45
- standalone custom element, so applications do not need Zubra or its runtime.
46
-
47
- ## Build from source
48
-
49
- Packing the package runs its build automatically. Building requires Rust with
50
- the `wasm32-unknown-unknown` target and Node.js 20 or newer:
51
-
52
- ```sh
53
- npm run build
54
- npm test
55
- ```
56
-
57
- Zubra is a development dependency used to compile
58
- [`components/symbology-code.zb`](./components/symbology-code.zb); it is not a
59
- runtime dependency of the published package.
1
+ # @journey-to-code/symbology
2
+
3
+ Dependency-free QR and linear barcode encoding and decoding, with a Rust
4
+ WebAssembly implementation and an optional Zubra-built custom element.
5
+
6
+ ## Install
7
+
8
+ ```sh
9
+ npm install @journey-to-code/symbology
10
+ ```
11
+
12
+ The package includes the WebAssembly binary. Load it with no URL or pass an
13
+ alternate source:
14
+
15
+ ```js
16
+ import { loadQr } from '@journey-to-code/symbology';
17
+
18
+ const symbology = await loadQr();
19
+ const code = symbology.encode('https://example.com');
20
+ const svg = symbology.svg(code);
21
+ ```
22
+
23
+ `loadQr` also accepts WASM bytes, a `Response`, a `WebAssembly.Module`, or a
24
+ URL. Encoding supports QR, Code 128, Code 39, and EAN-13. The decoder reads
25
+ QR frames and linear-barcode scanlines or frames.
26
+
27
+ ## Styled codes, logos, and LLM design
28
+
29
+ ```js
30
+ import { styledQr } from '@journey-to-code/symbology/style';
31
+
32
+ const { svg, report } = styledQr(symbology, 'https://example.com/jane', {
33
+ preset: 'liquid',
34
+ logo: { svg: logoMarkup, size: 0.22 },
35
+ frame: { text: 'SCAN ME' },
36
+ });
37
+ ```
38
+
39
+ Each result has been decoded back to the URL. `svg` is `null`, and
40
+ `report.errors` explains why, when it could not be verified.
41
+ `@journey-to-code/symbology/ai` adds `createDesigner()`, which lets an LLM
42
+ write the style for you (Anthropic, OpenAI, or any OpenAI-compatible API,
43
+ using plain `fetch`). The `symbology-mcp` binary exposes the same thing to
44
+ MCP clients. See the repository README for details.
45
+
46
+ ## Custom element
47
+
48
+ Import the widget once from a JavaScript entry point that resolves npm
49
+ package imports (for example, your bundler entry point):
50
+
51
+ ```js
52
+ import '@journey-to-code/symbology/symbology-code';
53
+ ```
54
+
55
+ Then use it in HTML:
56
+
57
+ ```html
58
+ <symbology-code format="qr" value="https://example.com"></symbology-code>
59
+ ```
60
+
61
+ The element offers a format picker, editable content, SVG preview, and
62
+ download. `format` accepts `qr`, `code128`, `code39`, or `ean13`; `value`
63
+ sets the initial content. It is authored in Zubra and distributed as a
64
+ standalone custom element, so applications do not need Zubra or its runtime.
65
+
66
+ For QR codes it can also draw a styled code with a logo. Like `styledQr()`,
67
+ it shows a design only after decoding it back; otherwise it explains what
68
+ to change:
69
+
70
+ ```html
71
+ <symbology-code
72
+ value="https://example.com/jane-doe"
73
+ preset="corporate"
74
+ logo="/images/logo.svg"
75
+ logo-size="0.22"
76
+ cta="SCAN FOR MY PORTFOLIO"
77
+ qr-style='{"colors": {"foreground": "#0b2545", "background": "#ffffff"}}'
78
+ ></symbology-code>
79
+ ```
80
+
81
+ | Attribute | |
82
+ | --- | --- |
83
+ | `preset` | `classic`, `corporate`, `minimal-dots`, `liquid`, `bars`, or `monochrome-print` |
84
+ | `logo` | An image URL (fetched and embedded) or data URI: SVG, PNG, JPEG, or WebP, up to 150 kB |
85
+ | `logo-size` | Logo width as a fraction of the code, 0.05 to 0.4 (default 0.22) |
86
+ | `cta` | Call-to-action text under the code, up to 32 characters |
87
+ | `qr-style` | A JSON style object merged over the preset (the `qrStyle` property takes an object) |
88
+ | `controls` | `full` (default) also lets visitors pick a style and upload a logo; `basic` hides those fields |
89
+
90
+ ## Build from source
91
+
92
+ Packing the package runs its build automatically. Building requires Rust with
93
+ the `wasm32-unknown-unknown` target and Node.js 20 or newer:
94
+
95
+ ```sh
96
+ npm run build
97
+ npm test
98
+ ```
99
+
100
+ Zubra is a development dependency used to compile
101
+ [`components/symbology-code.zb`](./components/symbology-code.zb); it is not a
102
+ runtime dependency of the published package.
package/ai.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ import type { Qr } from './qr.js';
2
+ import type { LogoStyle, QrStyle, StyleReport } from './style.js';
3
+
4
+ export class DesignError extends Error {
5
+ readonly attempts: Array<{ style?: QrStyle; errors?: string[]; warnings?: string[]; error?: string }>;
6
+ }
7
+
8
+ export interface DesignerOptions {
9
+ provider?: 'anthropic' | 'openai' | 'openai-compatible';
10
+ /** Your provider's model ID. Required. */
11
+ model: string;
12
+ apiKey?: string;
13
+ /** Required for openai-compatible; also routes calls through your own proxy. */
14
+ baseUrl?: string;
15
+ fetch?: typeof fetch;
16
+ headers?: Record<string, string>;
17
+ maxTokens?: number;
18
+ /** Model turns before giving up, 1 to 10. Default 3. */
19
+ maxAttempts?: number;
20
+ /** For the whole design. Default 60000. */
21
+ timeoutMs?: number;
22
+ jsonMode?: boolean;
23
+ /** Allow direct Anthropic calls from a browser. This exposes the key to the page. */
24
+ browser?: boolean;
25
+ qr?: Qr;
26
+ }
27
+
28
+ export interface GenerateOptions {
29
+ /** The URL to encode. */
30
+ data: string | Uint8Array;
31
+ prompt?: string;
32
+ brand?: { name?: string; colors?: string[] };
33
+ /** Your logo image; it always wins over anything the model proposes. */
34
+ logo?: LogoStyle;
35
+ /** Ask the model to draw a simple SVG mark when there is no logo. */
36
+ drawLogo?: boolean;
37
+ /** A style the model's proposal is layered over. */
38
+ base?: QrStyle;
39
+ signal?: AbortSignal;
40
+ }
41
+
42
+ export interface Designer {
43
+ readonly provider: string;
44
+ readonly model: string;
45
+ generate(options: GenerateOptions): Promise<{ svg: string; style: QrStyle; report: StyleReport; attempts: DesignError['attempts'] }>;
46
+ }
47
+
48
+ export function createDesigner(options: DesignerOptions): Designer;
49
+ export function extractJson(text: string): unknown;
50
+ export const toolDefinitions: {
51
+ anthropic: { name: string; description: string; input_schema: object };
52
+ openai: { type: 'function'; function: { name: string; description: string; parameters: object } };
53
+ jsonSchema: object;
54
+ };
55
+ export const styleSchema: object;
56
+ export const styleWithLogoSchema: object;
package/ai.js ADDED
@@ -0,0 +1,252 @@
1
+ // A language-model designer for styled QR codes, with no dependencies: plain fetch to Anthropic,
2
+ // OpenAI, or any OpenAI-compatible server (Ollama, OpenRouter, a company proxy).
3
+ //
4
+ // const designer = createDesigner({ provider: 'anthropic', apiKey, model: 'claude-…' });
5
+ // const { svg, style, report } = await designer.generate({ data: url, prompt: 'navy and gold' });
6
+ //
7
+ // The model only proposes a style. Every proposal is validated, drawn, and read back by the
8
+ // decoder (style.js); failures go back to the model with the reasons, up to `maxAttempts` times.
9
+ // A design that does not scan is never returned: `generate` throws DesignError instead.
10
+ //
11
+ // Keep API keys on a server. In a browser, point `baseUrl` at your own proxy instead.
12
+
13
+ import { loadQr } from './qr.js';
14
+ import { styleSchema, styleWithLogoSchema } from './schema.js';
15
+ import { styledQr, PRESETS } from './style.js';
16
+
17
+ export { styleSchema, styleWithLogoSchema };
18
+
19
+ export class DesignError extends Error {
20
+ constructor(message, { attempts = [], cause } = {}) {
21
+ super(message, cause ? { cause } : undefined);
22
+ this.name = 'DesignError';
23
+ /** Each attempt: `{ style, errors, warnings }`, or `{ error }` when the model's reply was unusable. */
24
+ this.attempts = attempts;
25
+ }
26
+ }
27
+
28
+ const PROVIDERS = {
29
+ anthropic: { baseUrl: 'https://api.anthropic.com/v1' },
30
+ openai: { baseUrl: 'https://api.openai.com/v1' },
31
+ 'openai-compatible': { baseUrl: null },
32
+ };
33
+
34
+ const DESCRIPTION =
35
+ 'Design a distinctive, scannable QR code for a URL (business cards, flyers, slides). Returns a style object for the Symbology renderer. ' +
36
+ 'Foreground colours must be clearly darker than a light, solid background; a centred logo is allowed only where error correction can recover it.';
37
+
38
+ /** Tool definitions for wiring the renderer into your own model calls (no API key needed here). */
39
+ export const toolDefinitions = {
40
+ /** For Anthropic's Messages API `tools` array. */
41
+ anthropic: { name: 'design_qr_code', description: DESCRIPTION, input_schema: stripMeta(styleSchema) },
42
+ /** For OpenAI's Chat Completions `tools` array. */
43
+ openai: { type: 'function', function: { name: 'design_qr_code', description: DESCRIPTION, parameters: stripMeta(styleSchema) } },
44
+ /** Plain JSON Schema, for anything else. */
45
+ jsonSchema: styleSchema,
46
+ };
47
+
48
+ function stripMeta(schema) {
49
+ const { $schema, $id, ...rest } = schema;
50
+ return rest;
51
+ }
52
+
53
+ const SYSTEM = [
54
+ 'You design QR codes that stay easy to scan. Reply with one JSON object only: a style matching the JSON Schema below. No prose, no code fences.',
55
+ 'Rules that keep codes scannable:',
56
+ '- The background is solid and light; every foreground, eyeFrame and eyeBall colour (and every gradient stop) is clearly darker, contrast 4:1 or more.',
57
+ '- Keep module scale at 0.85 or above for print. Leave level on auto and margin at 4 unless asked.',
58
+ '- A logo of 0.18 to 0.25 suits most URLs. If told the logo is too large, make it smaller.',
59
+ '- Use eye colours and shapes for personality; they are the safest place for accents.',
60
+ '- Set title to a short accessible description.',
61
+ `Presets you may start from: ${Object.keys(PRESETS).join(', ')}.`,
62
+ ].join('\n');
63
+
64
+ function userMessage({ data, prompt, brand, logo, drawLogo }) {
65
+ const lines = [`URL: ${new TextDecoder().decode(typeof data === 'string' ? new TextEncoder().encode(data) : data)}`];
66
+ if (prompt) lines.push(`Brief: ${String(prompt).slice(0, 2000)}`);
67
+ if (brand?.name) lines.push(`Brand name: ${String(brand.name).slice(0, 200)}`);
68
+ if (brand?.colors?.length) lines.push(`Brand colours: ${brand.colors.slice(0, 8).map(String).join(', ')}`);
69
+ if (logo) lines.push('The application supplies the logo image; choose only logo size, shape, padding and plate.');
70
+ else if (drawLogo) lines.push('Also draw a simple logo as logo.svg (flat paths, a viewBox, no <text>, under 8000 characters).');
71
+ else lines.push('There is no logo; omit the logo field.');
72
+ return lines.join('\n');
73
+ }
74
+
75
+ /** The first balanced JSON object in `text`, parsed, or an Error. */
76
+ export function extractJson(text) {
77
+ if (typeof text !== 'string') return new Error('the reply had no text');
78
+ const start = text.indexOf('{');
79
+ if (start < 0) return new Error('the reply contained no JSON object');
80
+ let depth = 0;
81
+ let inString = false;
82
+ for (let i = start; i < text.length; i++) {
83
+ const c = text[i];
84
+ if (inString) {
85
+ if (c === '\\') i++;
86
+ else if (c === '"') inString = false;
87
+ } else if (c === '"') inString = true;
88
+ else if (c === '{') depth++;
89
+ else if (c === '}' && --depth === 0) {
90
+ try {
91
+ return JSON.parse(text.slice(start, i + 1));
92
+ } catch (error) {
93
+ return new Error(`the reply's JSON did not parse: ${error.message}`);
94
+ }
95
+ }
96
+ }
97
+ return new Error('the reply\'s JSON object was not closed');
98
+ }
99
+
100
+ async function post(fetcher, url, headers, body, signal) {
101
+ const host = new URL(url).host;
102
+ let response;
103
+ try {
104
+ response = await fetcher(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body), signal });
105
+ } catch (cause) {
106
+ throw new DesignError(`could not reach ${host}: ${cause?.message ?? cause}`, { cause });
107
+ }
108
+ const text = await response.text();
109
+ if (!response.ok) {
110
+ let detail = text.slice(0, 300);
111
+ try {
112
+ detail = JSON.parse(text)?.error?.message ?? detail;
113
+ } catch {}
114
+ throw new DesignError(`${host} answered ${response.status}: ${detail}`);
115
+ }
116
+ try {
117
+ return JSON.parse(text);
118
+ } catch (cause) {
119
+ throw new DesignError(`${host} sent a reply that is not JSON`, { cause });
120
+ }
121
+ }
122
+
123
+ /** One model turn: the system prompt and conversation in, the reply text out. */
124
+ function chat({ provider, apiKey, model, baseUrl, fetch: fetcher, maxTokens, headers = {}, jsonMode, browser }) {
125
+ const root = String(baseUrl).replace(/\/+$/, '');
126
+ if (provider === 'anthropic') {
127
+ return async (system, messages, signal) => {
128
+ const reply = await post(
129
+ fetcher,
130
+ `${root}/messages`,
131
+ {
132
+ ...(apiKey ? { 'x-api-key': apiKey } : {}),
133
+ 'anthropic-version': '2023-06-01',
134
+ ...(browser ? { 'anthropic-dangerous-direct-browser-access': 'true' } : {}),
135
+ ...headers,
136
+ },
137
+ { model, max_tokens: maxTokens, system, messages },
138
+ signal,
139
+ );
140
+ return (reply.content ?? []).filter((part) => part.type === 'text').map((part) => part.text).join('');
141
+ };
142
+ }
143
+ return async (system, messages, signal) => {
144
+ const reply = await post(
145
+ fetcher,
146
+ `${root}/chat/completions`,
147
+ { ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}), ...headers },
148
+ {
149
+ model,
150
+ max_tokens: maxTokens,
151
+ messages: [{ role: 'system', content: system }, ...messages],
152
+ ...(jsonMode ? { response_format: { type: 'json_object' } } : {}),
153
+ },
154
+ signal,
155
+ );
156
+ return reply.choices?.[0]?.message?.content ?? '';
157
+ };
158
+ }
159
+
160
+ /** Layer the model's proposal over `base`, then put the caller's logo image back on top. */
161
+ function mergeStyle(base, proposal, logo, drawLogo) {
162
+ const style = { ...base, ...proposal };
163
+ for (const key of ['modules', 'eyes', 'colors', 'frame']) {
164
+ if (base[key] || proposal[key]) style[key] = { ...(base[key] ?? {}), ...(proposal[key] ?? {}) };
165
+ }
166
+ const placement = { ...(base.logo ?? {}), ...(proposal.logo ?? {}) };
167
+ delete placement.href;
168
+ if (logo) {
169
+ delete placement.svg;
170
+ style.logo = { ...placement, ...(logo.svg != null ? { svg: logo.svg } : { href: logo.href }) };
171
+ for (const key of ['size', 'shape', 'padding', 'plate']) if (logo[key] != null) style.logo[key] = logo[key];
172
+ } else if (drawLogo && placement.svg) {
173
+ style.logo = placement;
174
+ } else {
175
+ delete style.logo;
176
+ }
177
+ return style;
178
+ }
179
+
180
+ /**
181
+ * A designer bound to one model. Options: `provider` ('anthropic', 'openai', or
182
+ * 'openai-compatible'), `model` (required: your provider's model ID), `apiKey`, `baseUrl`
183
+ * (required for openai-compatible; also how to route through your own proxy), `fetch`,
184
+ * `headers`, `maxTokens` (default 2000), `maxAttempts` (default 3), `timeoutMs` (default 60000,
185
+ * for the whole design), `jsonMode` (OpenAI's response_format; default on for openai), `browser`
186
+ * (allow direct Anthropic calls from a page, which exposes the key), and `qr` (a `loadQr()`
187
+ * instance; loaded on first use otherwise).
188
+ */
189
+ export function createDesigner(options = {}) {
190
+ const { provider = 'anthropic', model, apiKey, maxAttempts = 3, timeoutMs = 60_000, maxTokens = 2000 } = options;
191
+ if (!Object.hasOwn(PROVIDERS, provider)) throw new TypeError(`createDesigner: provider must be one of ${Object.keys(PROVIDERS).join(', ')}`);
192
+ if (typeof model !== 'string' || !model) throw new TypeError("createDesigner: model is required (your provider's model ID)");
193
+ const baseUrl = options.baseUrl ?? PROVIDERS[provider].baseUrl;
194
+ if (!baseUrl) throw new TypeError('createDesigner: baseUrl is required for openai-compatible providers');
195
+ if (!apiKey && !options.baseUrl) throw new TypeError(`createDesigner: apiKey is required for ${provider} (or set baseUrl to a proxy that adds it)`);
196
+ if (!(Number.isInteger(maxAttempts) && maxAttempts >= 1 && maxAttempts <= 10)) throw new TypeError('createDesigner: maxAttempts must be 1 to 10');
197
+ const fetcher = options.fetch ?? globalThis.fetch;
198
+ if (typeof fetcher !== 'function') throw new TypeError('createDesigner: no fetch available; pass options.fetch');
199
+ const send = chat({
200
+ provider,
201
+ apiKey,
202
+ model,
203
+ baseUrl,
204
+ fetch: fetcher,
205
+ maxTokens,
206
+ headers: options.headers,
207
+ jsonMode: options.jsonMode ?? provider === 'openai',
208
+ browser: options.browser === true,
209
+ });
210
+ let qrPromise = options.qr ? Promise.resolve(options.qr) : null;
211
+
212
+ /**
213
+ * Design a code for `data` (the URL). `prompt` is the brief; `brand` may hold `name` and
214
+ * `colors`; `logo` is your image (`{ svg }` or `{ href }`, optionally with size, shape, padding,
215
+ * plate), which always wins over anything the model proposes; `drawLogo: true` asks the model
216
+ * for a simple SVG mark when you have none; `base` is a style the proposal is layered over.
217
+ * Resolves to `{ svg, style, report, attempts }`, or rejects with DesignError.
218
+ */
219
+ async function generate({ data, prompt = '', brand, logo, drawLogo = false, base = {}, signal } = {}) {
220
+ if (data == null || data === '') throw new TypeError('generate: data (the URL) is required');
221
+ const qr = await (qrPromise ??= loadQr());
222
+ const schema = drawLogo && !logo ? styleWithLogoSchema : styleSchema;
223
+ const system = `${SYSTEM}\n\nJSON Schema:\n${JSON.stringify(stripMeta(schema))}`;
224
+ const messages = [{ role: 'user', content: userMessage({ data, prompt, brand, logo, drawLogo }) }];
225
+ const attempts = [];
226
+ const timeout = AbortSignal.timeout(timeoutMs);
227
+ const abort = signal ? AbortSignal.any([signal, timeout]) : timeout;
228
+
229
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
230
+ const reply = await send(system, messages, abort);
231
+ messages.push({ role: 'assistant', content: reply || '(empty reply)' });
232
+ const proposal = extractJson(reply);
233
+ if (proposal instanceof Error || proposal === null || typeof proposal !== 'object' || Array.isArray(proposal)) {
234
+ const error = proposal instanceof Error ? proposal.message : 'the reply was not a JSON object';
235
+ attempts.push({ error });
236
+ messages.push({ role: 'user', content: `That could not be used: ${error}. Reply with one JSON object matching the schema.` });
237
+ continue;
238
+ }
239
+ const style = mergeStyle(base, proposal, logo, drawLogo);
240
+ const result = styledQr(qr, data, style);
241
+ attempts.push({ style, errors: result.report.errors, warnings: result.report.warnings });
242
+ if (result.report.ok) return { svg: result.svg, style, report: result.report, attempts };
243
+ messages.push({
244
+ role: 'user',
245
+ content: `That design was refused, so it was not drawn. Fix these and reply with the whole corrected JSON object:\n- ${result.report.errors.join('\n- ')}`,
246
+ });
247
+ }
248
+ throw new DesignError(`no scannable design after ${maxAttempts} attempt(s)`, { attempts });
249
+ }
250
+
251
+ return { generate, provider, model };
252
+ }
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ // The Symbology MCP server on stdio. See ../mcp.js.
3
+ import { serveStdio } from '../mcp.js';
4
+
5
+ serveStdio();