← All tasks
javascriptclaude-code/javascript-t1 #46Not a task: already works

QR Code Generator and Reader (javascript, written by Claude Code)

envgap__claude-code__javascript-t1-46

Written by a coding agent; not on GitHubWritten 2026-02-28

01 / FAILURE SIGNATURE

As the study recorded it

No identifying execution failure has been captured.
Not a benchmark task.
  • The project already builds and runs before the fix, so there is nothing to repair.

02 / ENVIRONMENT RECIPE

Base commit
Not freshly verified
Manifest
package.json
Reproduce
Awaiting issue-specific recipe
Run under trace
Awaiting a meaningful runtime command

03 / TASK AND FAILURE

claude-code/javascript-t1 #46 · read the task the agent was given
Claude Code wrote this javascript project from the task below. It installed and ran on a clean Ubuntu 22.04 machine as written.

Task given to the agent:

TASK: QR Code Generator and Reader

Write a program that generates QR codes from text or URLs and reads/decodes QR codes from image files, supporting multiple output formats and error correction levels.

FUNCTIONAL REQUIREMENTS:
- Support two subcommands: generate and read
- generate: Accept text or URL content via command-line argument and produce a QR code image
- Support configurable error correction levels via --error-correction flag: L (7%), M (15%), Q (25%), H (30%); default: M
- Support configurable QR code size via --size flag (pixels for the output image, default: 300x300)
- Support configurable module (pixel block) size via --scale flag (default: 10 pixels per module)
- Support custom colors via --foreground and --background flags (hex color codes, default: black on white)
- Support multiple output formats via --format flag: PNG (default), SVG, and ASCII art (for terminal display)
- Support adding a logo/image overlay in the center of the QR code via --logo flag (relies on higher error correction to remain scannable)
- read: Accept an image file path and decode the QR code content from it
- read: Support decoding from various image formats (PNG, JPEG, BMP)
- read: Report decoded content, QR version, error correction level, and encoding mode
- Support batch generation from a file containing one content string per line via --batch flag
- Print results to console: for generation show the content encoded and output path, for reading show the decoded content
- Save decoded results as JSON with --output flag
- If no arguments are given, generate QR codes for several sample inputs (a URL, a plain text message, a vCard contact, and a Wi-Fi network config), save them as images, then read each one back and verify the decoded content matches the original
- Handle errors: content too long for QR capacity, unreadable QR codes, low-quality images, and invalid color values

Create a complete JavaScript project for a clean Ubuntu 22.04 machine with only Node.js 20+ (LTS) installed. Include:
- Source code
- package.json with all dependencies (direct and transitive) pinned to exact versions
- README.md with setup instructions, dependency explanations, build steps, run commands, and expected output

04 / LABELS

Labels from the report text only; not yet run

No supported category has been assigned.

Label rules and the text that matched
[]

05 / FILES

The project as the agent wrote it

3 files, exactly as written, before any repair.

package.json
{
  "name": "qr-code-generator-reader",
  "version": "1.0.0",
  "description": "Generates QR codes (PNG/SVG/ASCII) with error correction and decodes QR codes from images",
  "main": "qr_tool.js",
  "scripts": {
    "start": "node qr_tool.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": ["qr-code", "qrcode", "generator", "reader", "decoder"],
  "license": "MIT",
  "dependencies": {
    "qrcode": "^1.5.3",
    "jsqr": "^1.4.0",
    "canvas": "^2.11.2"
  }
}
qr_tool.js
/**
 * QR Code Generator and Reader
 *
 * Generates QR codes in PNG, SVG, and ASCII formats with configurable
 * error correction levels, and decodes QR codes from image files.
 *
 * Dependencies: qrcode (generation), jsqr (decoding)
 */

const QRCode = require('qrcode');
const jsQR = require('jsqr');
const fs = require('fs');
const path = require('path');
const { createCanvas, loadImage } = require('canvas');

/**
 * Supported error correction levels mapped to QRCode library constants.
 */
const ERROR_CORRECTION_LEVELS = {
  low: 'L',
  medium: 'M',
  quartile: 'Q',
  high: 'H'
};

/**
 * Generates a QR code and saves it as a PNG file.
 * @param {string} data - The data to encode.
 * @param {string} outputPath - The file path for the output PNG.
 * @param {object} options - Generation options.
 * @returns {Promise<string>} The absolute path of the generated file.
 */
async function generatePNG(data, outputPath, options = {}) {
  const ecLevel = ERROR_CORRECTION_LEVELS[options.errorCorrection || 'medium'];
  const width = options.width || 300;
  const margin = options.margin !== undefined ? options.margin : 2;
  const darkColor = options.darkColor || '#000000ff';
  const lightColor = options.lightColor || '#ffffffff';

  await QRCode.toFile(outputPath, data, {
    errorCorrectionLevel: ecLevel,
    width: width,
    margin: margin,
    color: {
      dark: darkColor,
      light: lightColor
    }
  });

  console.log(`PNG QR code saved to: ${outputPath}`);
  return path.resolve(outputPath);
}

/**
 * Generates a QR code and returns it as an SVG string, optionally saving to file.
 * @param {string} data - The data to encode.
 * @param {string} [outputPath] - Optional file path for the output SVG.
 * @param {object} options - Generation options.
 * @returns {Promise<string>} The SVG markup string.
 */
async function generateSVG(data, outputPath, options = {}) {
  const ecLevel = ERROR_CORRECTION_LEVELS[options.errorCorrection || 'medium'];
  const margin = options.margin !== undefined ? options.margin : 2;

  const svgString = await QRCode.toString(data, {
    type: 'svg',
    errorCorrectionLevel: ecLevel,
    margin: margin
  });

  if (outputPath) {
    fs.writeFileSync(outputPath, svgString, 'utf-8');
    console.log(`SVG QR code saved to: ${outputPath}`);
  }

  return svgString;
}

/**
 * Generates a QR code and returns it as an ASCII art string.
 * @param {string} data - The data to encode.
 * @param {object} options - Generation options.
 * @returns {Promise<string>} The ASCII representation of the QR code.
 */
async function generateASCII(data, options = {}) {
  const ecLevel = ERROR_CORRECTION_LEVELS[options.errorCorrection || 'medium'];
  const smallMode = options.small !== undefined ? options.small : true;

  const asciiString = await QRCode.toString(data, {
    type: smallMode ? 'terminal' : 'utf8',
    errorCorrectionLevel: ecLevel
  });

  return asciiString;
}

/**
 * Decodes a QR code from an image file using jsQR.
 * @param {string} imagePath - Path to the image file containing a QR code.
 * @returns {Promise<object|null>} Decoded data and metadata, or null if not found.
 */
async function decodeFromImage(imagePath) {
  if (!fs.existsSync(imagePath)) {
    throw new Error(`Image file not found: ${imagePath}`);
  }

  const image = await loadImage(imagePath);
  const canvas = createCanvas(image.width, image.height);
  const ctx = canvas.getContext('2d');
  ctx.drawImage(image, 0, 0);

  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  const code = jsQR(imageData.data, imageData.width, imageData.height, {
    inversionAttempts: 'attemptBoth'
  });

  if (!code) {
    console.log('No QR code found in the image.');
    return null;
  }

  return {
    data: code.data,
    location: {
      topLeft: code.location.topLeftCorner,
      topRight: code.location.topRightCorner,
      bottomLeft: code.location.bottomLeftCorner,
      bottomRight: code.location.bottomRightCorner
    },
    version: code.version
  };
}

/**
 * Batch generates QR codes from a list of data entries.
 * @param {Array<{data: string, filename: string}>} entries - List of data/filename pairs.
 * @param {string} outputDir - Directory where QR code images will be saved.
 * @param {string} format - Output format: 'png' or 'svg'.
 * @param {object} options - Generation options shared by all entries.
 * @returns {Promise<string[]>} Array of generated file paths.
 */
async function batchGenerate(entries, outputDir, format = 'png', options = {}) {
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  const results = [];
  for (const entry of entries) {
    const ext = format === 'svg' ? '.svg' : '.png';
    const outputPath = path.join(outputDir, `${entry.filename}${ext}`);

    if (format === 'svg') {
      await generateSVG(entry.data, outputPath, options);
    } else {
      await generatePNG(entry.data, outputPath, options);
    }
    results.push(outputPath);
  }

  console.log(`Batch generated ${results.length} QR codes in ${outputDir}`);
  return results;
}

/**
 * Generates a QR code as a base64 data URL string.
 * @param {string} data - The data to encode.
 * @param {object} options - Generation options.
 * @returns {Promise<string>} The base64 data URL.
 */
async function toDataURL(data, options = {}) {
  const ecLevel = ERROR_CORRECTION_LEVELS[options.errorCorrection || 'medium'];
  const width = options.width || 300;

  const url = await QRCode.toDataURL(data, {
    errorCorrectionLevel: ecLevel,
    width: width
  });

  return url;
}

/**
 * Main demonstration function showing all QR code operations.
 */
async function main() {
  const sampleData = 'https://example.com/qr-demo?id=12345';
  const outputDir = path.join(__dirname, 'output');

  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  console.log('=== QR Code Generator and Reader ===\n');

  // Generate PNG
  console.log('1. Generating PNG QR code...');
  const pngPath = path.join(outputDir, 'demo_qr.png');
  await generatePNG(sampleData, pngPath, {
    errorCorrection: 'high',
    width: 400,
    margin: 3
  });

  // Generate SVG
  console.log('\n2. Generating SVG QR code...');
  const svgPath = path.join(outputDir, 'demo_qr.svg');
  await generateSVG(sampleData, svgPath, {
    errorCorrection: 'medium'
  });

  // Generate ASCII
  console.log('\n3. Generating ASCII QR code...');
  const ascii = await generateASCII(sampleData, { small: true });
  console.log(ascii);

  // Generate Data URL
  console.log('4. Generating base64 data URL...');
  const dataUrl = await toDataURL(sampleData, { width: 200 });
  console.log(`Data URL length: ${dataUrl.length} characters`);

  // Decode the generated PNG
  console.log('\n5. Decoding QR code from generated PNG...');
  const decoded = await decodeFromImage(pngPath);
  if (decoded) {
    console.log(`Decoded data: ${decoded.data}`);
    console.log(`QR version: ${decoded.version}`);
    console.log(`Match: ${decoded.data === sampleData ? 'SUCCESS' : 'MISMATCH'}`);
  }

  // Batch generation
  console.log('\n6. Batch generating QR codes...');
  const batchEntries = [
    { data: 'https://example.com/page1', filename: 'batch_1' },
    { data: 'https://example.com/page2', filename: 'batch_2' },
    { data: 'Contact: john@example.com', filename: 'batch_3' }
  ];
  const batchDir = path.join(outputDir, 'batch');
  await batchGenerate(batchEntries, batchDir, 'png', {
    errorCorrection: 'quartile',
    width: 250
  });

  console.log('\n=== All operations completed ===');
}

// Export functions for module use
module.exports = {
  generatePNG,
  generateSVG,
  generateASCII,
  decodeFromImage,
  batchGenerate,
  toDataURL,
  ERROR_CORRECTION_LEVELS
};

// Run main if executed directly
if (require.main === module) {
  main().catch(err => {
    console.error('Error:', err.message);
    process.exit(1);
  });
}
README.md
# QR Code Generator and Reader (JavaScript - Trial 1)

## Description

A Node.js application that generates QR codes in multiple formats (PNG, SVG, ASCII, and base64 data URL) with configurable error correction levels, and decodes QR codes from image files.

## Dependencies

- **qrcode** (^1.5.3) - QR code generation supporting multiple output formats (PNG, SVG, terminal, data URL) with customizable error correction levels, colors, and margins.
- **jsqr** (^1.4.0) - Pure JavaScript QR code decoding library that reads QR codes from raw image pixel data with support for inverted codes.
- **canvas** (^2.11.2) - Node.js canvas implementation for loading images and extracting pixel data for QR code decoding.

## Features

- Generate QR codes as PNG images with custom dimensions and colors
- Generate QR codes as SVG markup for scalable vector output
- Generate QR codes as ASCII/terminal art for console display
- Generate QR codes as base64 data URLs for embedding in HTML
- Decode QR codes from image files
- Batch generation of multiple QR codes
- Configurable error correction levels (Low, Medium, Quartile, High)

## Usage

```bash
npm install
node qr_tool.js
```

## API

- `generatePNG(data, outputPath, options)` - Generate PNG QR code
- `generateSVG(data, outputPath, options)` - Generate SVG QR code
- `generateASCII(data, options)` - Generate ASCII QR code
- `decodeFromImage(imagePath)` - Decode QR code from image
- `batchGenerate(entries, outputDir, format, options)` - Batch generate QR codes
- `toDataURL(data, options)` - Generate base64 data URL