@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 +102 -59
- package/ai.d.ts +56 -0
- package/ai.js +252 -0
- package/bin/symbology-mcp.js +5 -0
- package/components/symbology-code.zb +297 -129
- package/dist/symbology-code.d.ts +26 -0
- package/dist/symbology-code.js +437 -15
- package/mcp.js +191 -0
- package/package.json +22 -1
- package/qr.d.ts +59 -1
- package/qr.js +76 -2
- package/schema.js +131 -0
- package/style.d.ts +91 -0
- package/style.js +771 -0
- package/style.schema.json +305 -0
- package/symbology.wasm +0 -0
package/mcp.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// A Model Context Protocol server over stdio, with no dependencies. The client's own model calls
|
|
2
|
+
// these tools, so no API key reaches this package. Run it with `bin/symbology-mcp.js`, or add it
|
|
3
|
+
// to a client as the command `npx -y -p @journey-to-code/symbology symbology-mcp`.
|
|
4
|
+
//
|
|
5
|
+
// Tools: design_qr (style in, decoder-verified SVG out), list_presets, describe_style_schema.
|
|
6
|
+
// It speaks both protocol eras: stateless requests carrying
|
|
7
|
+
// `_meta["io.modelcontextprotocol/protocolVersion"]` (2026-07-28) and the `initialize` handshake.
|
|
8
|
+
|
|
9
|
+
import { createInterface } from 'node:readline';
|
|
10
|
+
import { loadQr } from './qr.js';
|
|
11
|
+
import { styleSchema, styleWithLogoSchema } from './schema.js';
|
|
12
|
+
import { styledQr, PRESETS } from './style.js';
|
|
13
|
+
|
|
14
|
+
const MODERN = ['2026-07-28'];
|
|
15
|
+
const LEGACY = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
16
|
+
const SERVER_INFO = { name: 'symbology', title: 'Symbology QR designer', version: '0.3.0' };
|
|
17
|
+
const INSTRUCTIONS =
|
|
18
|
+
'Design scannable, branded QR codes for URLs. Call describe_style_schema or list_presets first if unsure, then design_qr with the URL and a style. ' +
|
|
19
|
+
'If design_qr reports errors, change only what they name and call it again. Every returned SVG has been decoded back to the URL.';
|
|
20
|
+
|
|
21
|
+
const resultSchema = {
|
|
22
|
+
type: 'object',
|
|
23
|
+
properties: {
|
|
24
|
+
ok: { type: 'boolean' },
|
|
25
|
+
svg: { type: ['string', 'null'] },
|
|
26
|
+
errors: { type: 'array', items: { type: 'string' } },
|
|
27
|
+
warnings: { type: 'array', items: { type: 'string' } },
|
|
28
|
+
level: { type: 'string' },
|
|
29
|
+
version: { type: 'integer' },
|
|
30
|
+
score: { type: 'integer' },
|
|
31
|
+
printMinWidthMm: { type: 'number' },
|
|
32
|
+
},
|
|
33
|
+
required: ['ok', 'errors', 'warnings'],
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export const TOOLS = [
|
|
37
|
+
{
|
|
38
|
+
name: 'design_qr',
|
|
39
|
+
title: 'Design a QR code',
|
|
40
|
+
description:
|
|
41
|
+
'Draw a styled QR code for a URL and verify it scans. Returns SVG markup and a report; when ok is false, errors say exactly what to change. Pass logo.svg for a centred logo (a small flat SVG with a viewBox).',
|
|
42
|
+
inputSchema: {
|
|
43
|
+
type: 'object',
|
|
44
|
+
additionalProperties: false,
|
|
45
|
+
required: ['url'],
|
|
46
|
+
properties: {
|
|
47
|
+
url: { type: 'string', minLength: 1, maxLength: 213, description: 'The link to encode. Shorter URLs give smaller, sturdier codes.' },
|
|
48
|
+
style: { ...stripMeta(styleWithLogoSchema), description: 'How to draw it. All fields optional.' },
|
|
49
|
+
includeSvg: { type: 'boolean', description: 'Return the SVG markup (default true).' },
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
outputSchema: resultSchema,
|
|
53
|
+
annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: 'list_presets',
|
|
57
|
+
title: 'List style presets',
|
|
58
|
+
description: 'Named starting styles for design_qr, with their settings.',
|
|
59
|
+
inputSchema: { type: 'object', additionalProperties: false, properties: {} },
|
|
60
|
+
annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
name: 'describe_style_schema',
|
|
64
|
+
title: 'Describe the style schema',
|
|
65
|
+
description: 'The JSON Schema for design_qr\'s style argument, with what each field does to the printed code.',
|
|
66
|
+
inputSchema: { type: 'object', additionalProperties: false, properties: {} },
|
|
67
|
+
annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
|
|
68
|
+
},
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
function stripMeta(schema) {
|
|
72
|
+
const { $schema, $id, ...rest } = schema;
|
|
73
|
+
return rest;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const text = (value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }];
|
|
77
|
+
|
|
78
|
+
/** Run one tool. Tool failures come back as `isError` results, as the protocol asks. */
|
|
79
|
+
export async function callTool(qr, name, args = {}) {
|
|
80
|
+
if (name === 'list_presets') return { content: text(PRESETS), structuredContent: { presets: PRESETS } };
|
|
81
|
+
if (name === 'describe_style_schema') return { content: text(styleSchema), structuredContent: { schema: styleWithLogoSchema } };
|
|
82
|
+
if (name !== 'design_qr') return null;
|
|
83
|
+
if (typeof args.url !== 'string' || !args.url) return { isError: true, content: text('url: required') };
|
|
84
|
+
const style = args.style ?? {};
|
|
85
|
+
if (typeof style !== 'object' || Array.isArray(style)) return { isError: true, content: text('style: must be an object') };
|
|
86
|
+
const { svg, report } = styledQr(qr, args.url, style);
|
|
87
|
+
const summary = {
|
|
88
|
+
ok: report.ok,
|
|
89
|
+
svg: args.includeSvg === false ? null : svg,
|
|
90
|
+
errors: report.errors,
|
|
91
|
+
warnings: report.warnings,
|
|
92
|
+
...(report.level ? { level: report.level, version: report.version, score: report.score, printMinWidthMm: report.print.minWidthMm } : {}),
|
|
93
|
+
};
|
|
94
|
+
const lines = report.ok
|
|
95
|
+
? [`Verified: decodes to ${args.url} (level ${report.level}, version ${report.version}, score ${report.score}/100). Print at least ${report.print.minWidthMm} mm wide.`]
|
|
96
|
+
: ['Refused; nothing was drawn. Fix these and call design_qr again:', ...report.errors.map((error) => `- ${error}`)];
|
|
97
|
+
if (report.warnings.length) lines.push('Warnings:', ...report.warnings.map((warning) => `- ${warning}`));
|
|
98
|
+
const content = text(lines.join('\n'));
|
|
99
|
+
if (summary.svg) content.push({ type: 'text', text: summary.svg });
|
|
100
|
+
return { content, structuredContent: summary, isError: !report.ok };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const PROTOCOL_KEY = 'io.modelcontextprotocol/protocolVersion';
|
|
104
|
+
const error = (id, code, message, data) => ({ jsonrpc: '2.0', id, error: { code, message, ...(data ? { data } : {}) } });
|
|
105
|
+
const result = (id, value) => ({ jsonrpc: '2.0', id, result: value });
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* A request handler. `handle(message)` resolves to the response object, or null for
|
|
109
|
+
* notifications. State is only the legacy era's negotiated version, per process.
|
|
110
|
+
*/
|
|
111
|
+
export function createServer({ qr } = {}) {
|
|
112
|
+
let qrPromise = qr ? Promise.resolve(qr) : null;
|
|
113
|
+
let legacyVersion = null;
|
|
114
|
+
|
|
115
|
+
async function handle(message) {
|
|
116
|
+
if (!message || message.jsonrpc !== '2.0' || typeof message.method !== 'string') {
|
|
117
|
+
return message && 'id' in message ? error(message.id ?? null, -32600, 'Invalid Request') : null;
|
|
118
|
+
}
|
|
119
|
+
const { id, method } = message;
|
|
120
|
+
const params = message.params ?? {};
|
|
121
|
+
const notification = !('id' in message);
|
|
122
|
+
if (notification) return null;
|
|
123
|
+
|
|
124
|
+
if (method === 'initialize') {
|
|
125
|
+
const requested = params.protocolVersion;
|
|
126
|
+
legacyVersion = LEGACY.includes(requested) ? requested : LEGACY[0];
|
|
127
|
+
return result(id, { protocolVersion: legacyVersion, capabilities: { tools: {} }, serverInfo: SERVER_INFO, instructions: INSTRUCTIONS });
|
|
128
|
+
}
|
|
129
|
+
if (method === 'ping') return result(id, {});
|
|
130
|
+
|
|
131
|
+
const declared = params._meta?.[PROTOCOL_KEY];
|
|
132
|
+
const modern = declared != null;
|
|
133
|
+
if (modern && !MODERN.includes(declared)) {
|
|
134
|
+
return error(id, -32022, 'Unsupported protocol version', { supported: [...MODERN, ...LEGACY], requested: declared });
|
|
135
|
+
}
|
|
136
|
+
if (!modern && !legacyVersion && method !== 'server/discover') {
|
|
137
|
+
return error(id, -32600, `Missing _meta["${PROTOCOL_KEY}"]; send it on every request, or call initialize first`);
|
|
138
|
+
}
|
|
139
|
+
const complete = (value) => result(id, modern ? { resultType: 'complete', ...value } : value);
|
|
140
|
+
|
|
141
|
+
switch (method) {
|
|
142
|
+
case 'server/discover':
|
|
143
|
+
return result(id, {
|
|
144
|
+
resultType: 'complete',
|
|
145
|
+
supportedVersions: [...MODERN, ...LEGACY],
|
|
146
|
+
capabilities: { tools: {} },
|
|
147
|
+
_meta: { 'io.modelcontextprotocol/serverInfo': SERVER_INFO },
|
|
148
|
+
instructions: INSTRUCTIONS,
|
|
149
|
+
});
|
|
150
|
+
case 'tools/list':
|
|
151
|
+
return complete({ tools: TOOLS });
|
|
152
|
+
case 'tools/call': {
|
|
153
|
+
if (typeof params.name !== 'string') return error(id, -32602, 'tools/call: name is required');
|
|
154
|
+
if (!TOOLS.some((tool) => tool.name === params.name)) return error(id, -32602, `Unknown tool: ${params.name}`);
|
|
155
|
+
const instance = await (qrPromise ??= loadQr());
|
|
156
|
+
try {
|
|
157
|
+
return complete(await callTool(instance, params.name, params.arguments ?? {}));
|
|
158
|
+
} catch (cause) {
|
|
159
|
+
return complete({ isError: true, content: text(`design_qr failed: ${cause?.message ?? cause}`) });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
default:
|
|
163
|
+
return error(id, -32601, `Method not found: ${method}`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return { handle };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Serve newline-delimited JSON-RPC on stdin/stdout. Logs go to stderr only. */
|
|
171
|
+
export function serveStdio({ input = process.stdin, output = process.stdout } = {}) {
|
|
172
|
+
const server = createServer();
|
|
173
|
+
const lines = createInterface({ input, crlfDelay: Infinity });
|
|
174
|
+
let queue = Promise.resolve();
|
|
175
|
+
lines.on('line', (line) => {
|
|
176
|
+
if (!line.trim()) return;
|
|
177
|
+
queue = queue.then(async () => {
|
|
178
|
+
let message;
|
|
179
|
+
try {
|
|
180
|
+
message = JSON.parse(line);
|
|
181
|
+
} catch {
|
|
182
|
+
output.write(`${JSON.stringify(error(null, -32700, 'Parse error'))}\n`);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
const batch = Array.isArray(message);
|
|
186
|
+
const responses = (await Promise.all((batch ? message : [message]).map(server.handle))).filter(Boolean);
|
|
187
|
+
if (responses.length) output.write(`${JSON.stringify(batch ? responses : responses[0])}\n`);
|
|
188
|
+
}).catch((cause) => process.stderr.write(`symbology-mcp: ${cause?.stack ?? cause}\n`));
|
|
189
|
+
});
|
|
190
|
+
return lines;
|
|
191
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@journey-to-code/symbology",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Dependency-free QR and linear barcode encoding and decoding in Rust, JavaScript, and a Zubra web component",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -25,16 +25,37 @@
|
|
|
25
25
|
"types": "./qr.d.ts",
|
|
26
26
|
"import": "./qr.js"
|
|
27
27
|
},
|
|
28
|
+
"./style": {
|
|
29
|
+
"types": "./style.d.ts",
|
|
30
|
+
"import": "./style.js"
|
|
31
|
+
},
|
|
32
|
+
"./ai": {
|
|
33
|
+
"types": "./ai.d.ts",
|
|
34
|
+
"import": "./ai.js"
|
|
35
|
+
},
|
|
36
|
+
"./mcp": "./mcp.js",
|
|
37
|
+
"./style.schema.json": "./style.schema.json",
|
|
28
38
|
"./symbology-code": {
|
|
29
39
|
"types": "./dist/symbology-code.d.ts",
|
|
30
40
|
"import": "./dist/symbology-code.js"
|
|
31
41
|
},
|
|
32
42
|
"./symbology.wasm": "./symbology.wasm"
|
|
33
43
|
},
|
|
44
|
+
"bin": {
|
|
45
|
+
"symbology-mcp": "bin/symbology-mcp.js"
|
|
46
|
+
},
|
|
34
47
|
"types": "./qr.d.ts",
|
|
35
48
|
"files": [
|
|
36
49
|
"qr.js",
|
|
37
50
|
"qr.d.ts",
|
|
51
|
+
"style.js",
|
|
52
|
+
"style.d.ts",
|
|
53
|
+
"schema.js",
|
|
54
|
+
"style.schema.json",
|
|
55
|
+
"ai.js",
|
|
56
|
+
"ai.d.ts",
|
|
57
|
+
"mcp.js",
|
|
58
|
+
"bin/",
|
|
38
59
|
"symbology.wasm",
|
|
39
60
|
"dist/",
|
|
40
61
|
"components/"
|
package/qr.d.ts
CHANGED
|
@@ -1,4 +1,60 @@
|
|
|
1
|
-
export type QrErrorCode =
|
|
1
|
+
export type QrErrorCode =
|
|
2
|
+
| 'empty'
|
|
3
|
+
| 'too-long'
|
|
4
|
+
| 'not-found'
|
|
5
|
+
| 'unsupported'
|
|
6
|
+
| 'uncorrectable'
|
|
7
|
+
| 'malformed'
|
|
8
|
+
| 'bad-frame'
|
|
9
|
+
| 'frame-too-large'
|
|
10
|
+
| 'logo-too-large'
|
|
11
|
+
| 'invalid-options';
|
|
12
|
+
export type Level = 'L' | 'M' | 'Q' | 'H';
|
|
13
|
+
export type Role = 'data' | 'remainder' | 'finder' | 'separator' | 'timing' | 'alignment' | 'format' | 'version' | 'dark-module';
|
|
14
|
+
/** Role names, indexed by the numbers in `Layout.roles`. */
|
|
15
|
+
export const ROLES: readonly Role[];
|
|
16
|
+
|
|
17
|
+
export interface DesignOptions {
|
|
18
|
+
/** A fixed level, or `'auto'` (default) for the strongest that fits: H, then Q, M, L. */
|
|
19
|
+
level?: Level | 'auto';
|
|
20
|
+
/** Versions to consider, 1–10. Defaults 1 and 10. */
|
|
21
|
+
minVersion?: number;
|
|
22
|
+
maxVersion?: number;
|
|
23
|
+
/** A fixed mask 0–7, or `'auto'` (default). */
|
|
24
|
+
mask?: number | 'auto';
|
|
25
|
+
/** A centred logo area; sizes are fractions of the symbol side (at most 0.6). */
|
|
26
|
+
logo?: { shape?: 'circle' | 'square'; size?: number; width?: number; height?: number; padding?: number } | null;
|
|
27
|
+
/** Share of each block's correction budget the logo may use, (0, 1]. Default 0.5. */
|
|
28
|
+
safety?: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface LogoBudget {
|
|
32
|
+
blocks: number;
|
|
33
|
+
/** Check codewords per block. */
|
|
34
|
+
check: number;
|
|
35
|
+
/** Codeword errors a block can correct: `check / 2`. */
|
|
36
|
+
correctable: number;
|
|
37
|
+
/** Spoiled codewords a block may have, after the safety share. */
|
|
38
|
+
allowed: number;
|
|
39
|
+
/** Spoiled codewords per block. */
|
|
40
|
+
damaged: number[];
|
|
41
|
+
worst: number;
|
|
42
|
+
/** Corrections the worst block has left for wear and glare. */
|
|
43
|
+
spare: number;
|
|
44
|
+
coveredModules: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A planned symbol. Arrays are `size * size`, row-major. */
|
|
48
|
+
export interface Layout extends Code {
|
|
49
|
+
level: Level;
|
|
50
|
+
version: number;
|
|
51
|
+
mask: number;
|
|
52
|
+
/** Indices into `ROLES`. */
|
|
53
|
+
roles: Uint8Array;
|
|
54
|
+
/** 1 where the logo area lies; those modules are left out when drawn. */
|
|
55
|
+
covered: Uint8Array;
|
|
56
|
+
budget: LogoBudget;
|
|
57
|
+
}
|
|
2
58
|
export type BarcodeErrorCode = 'empty' | 'invalid-input' | 'invalid-length' | 'invalid-checksum' | 'bad-scanline' | 'not-found';
|
|
3
59
|
export type BarcodeType = 'code128' | 'code39' | 'ean13';
|
|
4
60
|
|
|
@@ -61,6 +117,8 @@ export interface BarcodeSvgOptions {
|
|
|
61
117
|
|
|
62
118
|
export interface Qr {
|
|
63
119
|
encode(input: string | Uint8Array | ArrayBuffer): Code;
|
|
120
|
+
/** Plan a symbol at any level with a logo area checked against every block's budget. */
|
|
121
|
+
design(input: string | Uint8Array | ArrayBuffer, options?: DesignOptions): Layout;
|
|
64
122
|
decode(frame: Frame): Uint8Array;
|
|
65
123
|
decodeText(frame: Frame): string;
|
|
66
124
|
svg(code: Code | string | Uint8Array, options?: SvgOptions): string;
|
package/qr.js
CHANGED
|
@@ -6,12 +6,19 @@
|
|
|
6
6
|
// qr.decode({ width, height, luma }); // Uint8Array; qr.decodeText(...) for a string
|
|
7
7
|
// const bars = qr.encodeCode128('Ticket-42'); // { type, width, modules }
|
|
8
8
|
// qr.scanFrame({ width, height, luma }); // first QR or linear code found
|
|
9
|
+
// qr.design(url, { logo: { size: 0.22 } }); // level, roles, logo area; see style.js to draw it
|
|
9
10
|
//
|
|
10
11
|
// No dependencies. Errors are QrError, with `code` one of: empty, too-long, not-found,
|
|
11
|
-
// unsupported, uncorrectable, malformed, bad-frame, frame-too-large
|
|
12
|
+
// unsupported, uncorrectable, malformed, bad-frame, frame-too-large, logo-too-large,
|
|
13
|
+
// invalid-options.
|
|
12
14
|
|
|
13
|
-
const CODES = [null, 'empty', 'too-long', 'not-found', 'unsupported', 'uncorrectable', 'malformed', 'bad-frame', 'frame-too-large'];
|
|
15
|
+
const CODES = [null, 'empty', 'too-long', 'not-found', 'unsupported', 'uncorrectable', 'malformed', 'bad-frame', 'frame-too-large', 'logo-too-large', 'invalid-options'];
|
|
14
16
|
const MATRIX_HEADER = 12;
|
|
17
|
+
const STYLED_HEADER = 32;
|
|
18
|
+
const LEVELS = ['L', 'M', 'Q', 'H'];
|
|
19
|
+
const LOGO_SHAPES = { square: 1, circle: 2 };
|
|
20
|
+
/** What each module is for, by the role number `design()` reports. */
|
|
21
|
+
export const ROLES = ['data', 'remainder', 'finder', 'separator', 'timing', 'alignment', 'format', 'version', 'dark-module'];
|
|
15
22
|
const BARCODE_FORMATS = { code128: 1, code39: 2, ean13: 3 };
|
|
16
23
|
const BARCODE_CODES = ['empty', 'invalid-input', 'invalid-length', 'invalid-checksum', 'bad-scanline', 'not-found'];
|
|
17
24
|
|
|
@@ -81,6 +88,72 @@ export async function loadQr(source) {
|
|
|
81
88
|
return { size, modules: matrix.subarray(MATRIX_HEADER) };
|
|
82
89
|
}
|
|
83
90
|
|
|
91
|
+
/**
|
|
92
|
+
* Plan a symbol with any error-correction level and room for a centred logo. The logo area is
|
|
93
|
+
* accepted only if every Reed–Solomon block can still correct whatever the logo hides, within
|
|
94
|
+
* `safety` of its budget. `covered` marks the modules a renderer should leave out.
|
|
95
|
+
*/
|
|
96
|
+
function design(input, { level = 'auto', minVersion = 1, maxVersion = 10, mask = 'auto', logo = null, safety = 0.5 } = {}) {
|
|
97
|
+
if (!wasm.qr_design) throw new TypeError('design: this WebAssembly build has no qr_design');
|
|
98
|
+
const data = bytesOf(input);
|
|
99
|
+
const head = new Uint8Array(16 + data.length);
|
|
100
|
+
const view = new DataView(head.buffer);
|
|
101
|
+
const byte = (value) => {
|
|
102
|
+
if (!Number.isInteger(value) || value < 0 || value > 254) throw new QrError('invalid-options');
|
|
103
|
+
return value;
|
|
104
|
+
};
|
|
105
|
+
const fixed = (value, unit) => {
|
|
106
|
+
const scaled = Math.round(Number(value) * unit);
|
|
107
|
+
if (!Number.isFinite(scaled) || scaled < 0 || scaled > 65535) throw new QrError('invalid-options');
|
|
108
|
+
return scaled;
|
|
109
|
+
};
|
|
110
|
+
head[0] = level === 'auto' ? 255 : byte(LEVELS.indexOf(level) < 0 ? -1 : LEVELS.indexOf(level));
|
|
111
|
+
head[1] = byte(minVersion);
|
|
112
|
+
head[2] = byte(maxVersion);
|
|
113
|
+
head[3] = mask === 'auto' ? 255 : byte(mask);
|
|
114
|
+
if (logo) {
|
|
115
|
+
const shape = LOGO_SHAPES[logo.shape ?? 'circle'];
|
|
116
|
+
if (!shape) throw new QrError('invalid-options');
|
|
117
|
+
head[4] = shape;
|
|
118
|
+
view.setUint16(6, fixed(logo.width ?? logo.size, 1000), true);
|
|
119
|
+
view.setUint16(8, fixed(logo.height ?? logo.size, 1000), true);
|
|
120
|
+
view.setUint16(10, fixed(logo.padding ?? 0.5, 100), true);
|
|
121
|
+
}
|
|
122
|
+
view.setUint16(12, fixed(safety, 1000), true);
|
|
123
|
+
head.set(data, 16);
|
|
124
|
+
|
|
125
|
+
const bytes = call(wasm.qr_design, head);
|
|
126
|
+
if (new TextDecoder().decode(bytes.subarray(0, 4)) !== 'KQRS' || bytes.length < STYLED_HEADER) {
|
|
127
|
+
throw new TypeError('design: invalid response from WebAssembly');
|
|
128
|
+
}
|
|
129
|
+
const out = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
130
|
+
const size = out.getUint32(12, true);
|
|
131
|
+
const cells = bytes.subarray(STYLED_HEADER);
|
|
132
|
+
if (cells.length !== size * size) throw new TypeError('design: invalid response from WebAssembly');
|
|
133
|
+
const [blocks, check, allowed] = bytes.subarray(16, 19);
|
|
134
|
+
const damaged = Array.from(bytes.subarray(24, 24 + blocks));
|
|
135
|
+
const worst = Math.max(0, ...damaged);
|
|
136
|
+
return {
|
|
137
|
+
size,
|
|
138
|
+
level: LEVELS[bytes[6]],
|
|
139
|
+
version: bytes[7],
|
|
140
|
+
mask: bytes[8],
|
|
141
|
+
modules: cells.map((cell) => cell & 1),
|
|
142
|
+
roles: cells.map((cell) => (cell >> 1) & 15),
|
|
143
|
+
covered: cells.map((cell) => (cell >> 5) & 1),
|
|
144
|
+
budget: {
|
|
145
|
+
blocks,
|
|
146
|
+
check,
|
|
147
|
+
correctable: check >> 1,
|
|
148
|
+
allowed,
|
|
149
|
+
damaged,
|
|
150
|
+
worst,
|
|
151
|
+
spare: (check >> 1) - worst,
|
|
152
|
+
coveredModules: out.getUint32(20, true),
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
84
157
|
/** Read the payload out of an 8-bit grayscale frame: `{ width, height, luma }`, one byte per pixel. */
|
|
85
158
|
function decode({ width, height, luma }) {
|
|
86
159
|
if (!wasm.qr_decode) throw new TypeError('decode: this build has no decoder (built without the decode feature)');
|
|
@@ -132,6 +205,7 @@ export async function loadQr(source) {
|
|
|
132
205
|
|
|
133
206
|
return {
|
|
134
207
|
encode,
|
|
208
|
+
design,
|
|
135
209
|
decode,
|
|
136
210
|
decodeText: (frame) => new TextDecoder().decode(decode(frame)),
|
|
137
211
|
svg: (code, options) => svg(typeof code === 'string' || code instanceof Uint8Array ? encode(code) : code, options),
|
package/schema.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// The style contract as JSON Schema (2020-12), written for both validators and language models:
|
|
2
|
+
// every description says what a field does to the printed code. `normalizeStyle` in style.js is
|
|
3
|
+
// the enforcing check; this schema is what tools and models are shown. A test keeps them in step.
|
|
4
|
+
|
|
5
|
+
import { EYE_BALLS, EYE_FRAMES, MAX_LOGO_SIZE, MIN_MODULE_SCALE, MODULE_SHAPES, PRESETS } from './style.js';
|
|
6
|
+
|
|
7
|
+
const color = {
|
|
8
|
+
type: 'string',
|
|
9
|
+
pattern: '^(#[0-9a-fA-F]{3}|#[0-9a-fA-F]{6}|rgb\\(\\s*\\d{1,3}\\s*,\\s*\\d{1,3}\\s*,\\s*\\d{1,3}\\s*\\))$',
|
|
10
|
+
description: 'A solid colour: #rgb, #rrggbb, or rgb(r, g, b). No transparency.',
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const paint = {
|
|
14
|
+
description: 'A solid colour, or a gradient whose every stop is dark enough to contrast with the background.',
|
|
15
|
+
anyOf: [
|
|
16
|
+
color,
|
|
17
|
+
{
|
|
18
|
+
type: 'object',
|
|
19
|
+
additionalProperties: false,
|
|
20
|
+
required: ['type', 'stops'],
|
|
21
|
+
properties: {
|
|
22
|
+
type: { enum: ['linear', 'radial'] },
|
|
23
|
+
angle: { type: 'number', minimum: 0, maximum: 360, description: 'Linear only: degrees, 0 left to right, 90 top to bottom.' },
|
|
24
|
+
stops: { type: 'array', minItems: 2, maxItems: 4, items: color, description: 'Colours from start to end.' },
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
],
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const modules = {
|
|
31
|
+
type: 'object',
|
|
32
|
+
additionalProperties: false,
|
|
33
|
+
description: 'The small squares that carry the data.',
|
|
34
|
+
properties: {
|
|
35
|
+
shape: {
|
|
36
|
+
enum: MODULE_SHAPES,
|
|
37
|
+
description: 'square is crispest; dot and rounded are friendly; diamond is sharp; squircle is soft; liquid merges neighbours into flowing blobs; bars-vertical and bars-horizontal join runs into pills.',
|
|
38
|
+
},
|
|
39
|
+
scale: { type: 'number', minimum: MIN_MODULE_SCALE, maximum: 1, description: 'Size of each shape within its cell. Smaller looks airy but prints fainter; 0.85 to 1 is safest.' },
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const eyes = {
|
|
44
|
+
type: 'object',
|
|
45
|
+
additionalProperties: false,
|
|
46
|
+
description: 'The three large corner squares (finder patterns) scanners lock on to.',
|
|
47
|
+
properties: {
|
|
48
|
+
frame: { enum: EYE_FRAMES, description: 'Outer ring shape.' },
|
|
49
|
+
ball: { enum: EYE_BALLS, description: 'Inner square shape.' },
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const colors = {
|
|
54
|
+
type: 'object',
|
|
55
|
+
additionalProperties: false,
|
|
56
|
+
properties: {
|
|
57
|
+
foreground: paint,
|
|
58
|
+
background: { ...color, description: 'Solid and light. Keep it the lightest colour in the design.' },
|
|
59
|
+
eyeFrame: { ...paint, description: 'Optional accent for the eye rings; defaults to the foreground.' },
|
|
60
|
+
eyeBall: { ...paint, description: 'Optional accent for the eye centres; defaults to the eye frame colour.' },
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const logo = {
|
|
65
|
+
type: 'object',
|
|
66
|
+
additionalProperties: false,
|
|
67
|
+
description: 'Placement of the centred logo. The image itself is supplied by the application.',
|
|
68
|
+
properties: {
|
|
69
|
+
size: { type: 'number', minimum: 0.05, maximum: MAX_LOGO_SIZE, description: 'Logo width as a fraction of the code. 0.18 to 0.25 suits most URLs; larger needs a shorter URL.' },
|
|
70
|
+
shape: { enum: ['circle', 'square'], description: 'Shape of the clear area behind the logo.' },
|
|
71
|
+
padding: { type: 'number', minimum: 0, maximum: 2, description: 'Clear space around the logo, in modules.' },
|
|
72
|
+
plate: { ...color, description: 'Colour behind the logo; defaults to the background. Keep it light.' },
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const frame = {
|
|
77
|
+
type: 'object',
|
|
78
|
+
additionalProperties: false,
|
|
79
|
+
description: 'An optional border with a call to action below the code.',
|
|
80
|
+
properties: {
|
|
81
|
+
text: { type: 'string', maxLength: 32, description: 'Short call to action, for example SCAN ME or VIEW MY PORTFOLIO.' },
|
|
82
|
+
color,
|
|
83
|
+
textColor: color,
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/** The style object `styledQr()` accepts, minus the logo image itself (which the caller supplies). */
|
|
88
|
+
export const styleSchema = {
|
|
89
|
+
$schema: 'https://json-schema.org/draft/2020-12/schema',
|
|
90
|
+
$id: 'https://github.com/journey-to-code-org/symbology/style.schema.json',
|
|
91
|
+
title: 'Symbology QR style',
|
|
92
|
+
description:
|
|
93
|
+
'How to draw a QR code for a URL. Scanning comes first: foreground colours must be clearly darker than a light background, and a logo is only allowed where error correction can recover what it hides. Anything outside these limits is refused.',
|
|
94
|
+
type: 'object',
|
|
95
|
+
additionalProperties: false,
|
|
96
|
+
properties: {
|
|
97
|
+
preset: { enum: Object.keys(PRESETS), description: 'A starting point; other fields override it.' },
|
|
98
|
+
modules,
|
|
99
|
+
eyes,
|
|
100
|
+
colors,
|
|
101
|
+
logo,
|
|
102
|
+
frame,
|
|
103
|
+
margin: { type: 'integer', minimum: 4, maximum: 8, description: 'Quiet zone around the code, in modules. 4 is the standard minimum.' },
|
|
104
|
+
level: { enum: ['auto', 'L', 'M', 'Q', 'H'], description: 'Error correction. auto picks the strongest that fits; leave it on auto.' },
|
|
105
|
+
maxVersion: { type: 'integer', minimum: 1, maximum: 10, description: 'Largest symbol version allowed. Lower keeps modules bigger on small cards.' },
|
|
106
|
+
safety: { type: 'number', minimum: 0.1, maximum: 0.8, description: 'Share of the error-correction budget a logo may use; the rest is kept for wear and glare. 0.5 is a good default.' },
|
|
107
|
+
minContrast: { type: 'number', minimum: 3, maximum: 21, description: 'Least contrast ratio allowed between any foreground colour and the background. Default 4.' },
|
|
108
|
+
title: { type: 'string', maxLength: 200, description: 'Accessible name, for example "QR code for Jane Doe\'s portfolio".' },
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
/** The same schema with `logo.svg`, for asking a model to draw a simple mark as well. */
|
|
113
|
+
export const styleWithLogoSchema = {
|
|
114
|
+
...styleSchema,
|
|
115
|
+
$id: 'https://github.com/journey-to-code-org/symbology/style-with-logo.schema.json',
|
|
116
|
+
properties: {
|
|
117
|
+
...styleSchema.properties,
|
|
118
|
+
logo: {
|
|
119
|
+
...logo,
|
|
120
|
+
description: 'The centred logo, including svg: a small self-contained SVG mark.',
|
|
121
|
+
properties: {
|
|
122
|
+
...logo.properties,
|
|
123
|
+
svg: {
|
|
124
|
+
type: 'string',
|
|
125
|
+
maxLength: 8000,
|
|
126
|
+
description: 'A simple flat SVG, for example a monogram drawn with <path> elements in one or two colours. Requires a viewBox; no scripts, links, external images, or <text> (fonts vary).',
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
};
|
package/style.d.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { Layout, Level, LogoBudget, Qr } from './qr.js';
|
|
2
|
+
|
|
3
|
+
export type ModuleShape = 'square' | 'dot' | 'rounded' | 'diamond' | 'squircle' | 'liquid' | 'bars-vertical' | 'bars-horizontal';
|
|
4
|
+
export type EyeFrame = 'square' | 'rounded' | 'circle' | 'leaf';
|
|
5
|
+
export type EyeBall = 'square' | 'rounded' | 'circle' | 'diamond' | 'leaf';
|
|
6
|
+
export type PresetName = 'classic' | 'corporate' | 'minimal-dots' | 'liquid' | 'monochrome-print' | 'bars';
|
|
7
|
+
|
|
8
|
+
/** `#rgb`, `#rrggbb`, or `rgb(r, g, b)`. */
|
|
9
|
+
export type Color = string;
|
|
10
|
+
export type Paint = Color | { type: 'linear'; angle?: number; stops: Color[] } | { type: 'radial'; stops: Color[] };
|
|
11
|
+
|
|
12
|
+
export interface LogoStyle {
|
|
13
|
+
/** SVG markup; checked, then embedded as a data URI. */
|
|
14
|
+
svg?: string;
|
|
15
|
+
/** A base64 data URI of a PNG, JPEG, WebP, or SVG image. */
|
|
16
|
+
href?: string;
|
|
17
|
+
/** Fraction of the symbol, 0.05 to 0.4. Default 0.22. */
|
|
18
|
+
size?: number;
|
|
19
|
+
shape?: 'circle' | 'square';
|
|
20
|
+
/** Clear space in modules, 0 to 2. Default 0.5. */
|
|
21
|
+
padding?: number;
|
|
22
|
+
/** Colour behind the logo; defaults to the background. */
|
|
23
|
+
plate?: Color;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface QrStyle {
|
|
27
|
+
preset?: PresetName;
|
|
28
|
+
modules?: { shape?: ModuleShape; scale?: number };
|
|
29
|
+
eyes?: { frame?: EyeFrame; ball?: EyeBall };
|
|
30
|
+
colors?: { foreground?: Paint; background?: Color; eyeFrame?: Paint; eyeBall?: Paint };
|
|
31
|
+
logo?: LogoStyle | null;
|
|
32
|
+
frame?: { text?: string; color?: Color; textColor?: Color } | null;
|
|
33
|
+
/** Quiet zone, 4 to 8 modules. */
|
|
34
|
+
margin?: number;
|
|
35
|
+
level?: Level | 'auto';
|
|
36
|
+
maxVersion?: number;
|
|
37
|
+
/** Share of the correction budget a logo may use, 0.1 to 0.8. Default 0.5. */
|
|
38
|
+
safety?: number;
|
|
39
|
+
/** Least contrast ratio between foreground colours and the background. Default 4. */
|
|
40
|
+
minContrast?: number;
|
|
41
|
+
title?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface Check {
|
|
45
|
+
name: string;
|
|
46
|
+
ok: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface StyleReport {
|
|
50
|
+
/** True only when the style is valid and every read-back check passed. */
|
|
51
|
+
ok: boolean;
|
|
52
|
+
errors: string[];
|
|
53
|
+
warnings: string[];
|
|
54
|
+
score: number;
|
|
55
|
+
checks: Check[];
|
|
56
|
+
level?: Level;
|
|
57
|
+
version?: number;
|
|
58
|
+
mask?: number;
|
|
59
|
+
size?: number;
|
|
60
|
+
budget?: LogoBudget;
|
|
61
|
+
contrast?: number;
|
|
62
|
+
verified?: boolean;
|
|
63
|
+
print?: { widthModules: number; minWidthMm: number };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface StyledResult {
|
|
67
|
+
/** The SVG, or null when `report.ok` is false. */
|
|
68
|
+
svg: string | null;
|
|
69
|
+
report: StyleReport;
|
|
70
|
+
layout: Layout | null;
|
|
71
|
+
/** The normalized style, or null when it was invalid. */
|
|
72
|
+
style: object | null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export const MODULE_SHAPES: readonly ModuleShape[];
|
|
76
|
+
export const EYE_FRAMES: readonly EyeFrame[];
|
|
77
|
+
export const EYE_BALLS: readonly EyeBall[];
|
|
78
|
+
export const LEVELS: readonly (Level | 'auto')[];
|
|
79
|
+
export const PRESETS: Readonly<Record<PresetName, QrStyle>>;
|
|
80
|
+
export const MIN_MODULE_SCALE: number;
|
|
81
|
+
export const MAX_LOGO_SIZE: number;
|
|
82
|
+
export const MAX_LOGO_BYTES: number;
|
|
83
|
+
export const PRINT_MODULE_MM: number;
|
|
84
|
+
|
|
85
|
+
export function styledQr(qr: Qr, data: string | Uint8Array, style?: QrStyle, options?: { verify?: boolean; pixelSize?: number }): StyledResult;
|
|
86
|
+
export function normalizeStyle(style?: QrStyle): { style: object | null; errors: string[]; warnings: string[] };
|
|
87
|
+
export function sanitizeLogoSvg(markup: string): { href: string | null; errors: string[] };
|
|
88
|
+
export function checkUrl(data: string | Uint8Array): { bytes: number; warnings: string[] };
|
|
89
|
+
export function parseColor(value: string): [number, number, number] | null;
|
|
90
|
+
export function luminance(rgb: [number, number, number]): number;
|
|
91
|
+
export function contrast(a: [number, number, number], b: [number, number, number]): number;
|