CodeSampleX

示例

marked 18.0.5: Hooks

已验证示例 — npm marked 18.0.5: Hooks. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: marked.Hooks is exported as a class with passThroughHooks and…

sha256:8f3ad9c169011e92f2623b9f96c0ce35355a93edfaa06eeadb6543db868c5cf5

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 npm

验证运行环境

环境 契约 阶段 运行日期
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-28

案例

HOW
目标
verify marked.Hooks in pkg:npm/marked@18.0.5
包
符号
  • marked.Hooks
创建时间
2026-08-28T00:00:37Z

契约

  1. marked.Hooks is exported as a class with passThroughHooks and prototype methods
  2. marked.Hooks instance provides default pass-through implementations for preprocess, postprocess, and processAllTokens
  3. marked.Hooks provideLexer and provideParser return lexer and parser functions for block and inline modes
  4. marked.Hooks preprocess, processAllTokens, and postprocess hooks transform markdown, tokens, and HTML output
  5. marked.Marked chains multiple hooks registered via use in sequence

文件

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

下载源代码构件 (tar.gz)

源代码

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify marked.Hooks in pkg:npm/marked@18.0.5
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/marked@18.0.5
Demonstrate these symbols/APIs:
  - marked.Hooks

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:80fef6ad0638171404ac6fcc99b3db086cb96dfeae41c80ea26c899f21c74ef3","contract":["marked.Hooks is exported as a class with passThroughHooks and prototype methods","marked.Hooks instance provides default pass-through implementations for preprocess, postprocess, and processAllTokens","marked.Hooks provideLexer and provideParser return lexer and parser functions for block and inline modes","marked.Hooks preprocess, processAllTokens, and postprocess hooks transform markdown, tokens, and HTML output","marked.Marked chains multiple hooks registered via use in sequence"],"goal":"verify marked.Hooks in pkg:npm/marked@18.0.5","kind":"HOW","packages":["pkg:npm/marked@18.0.5"],"schemaVersion":1,"symbols":["marked.Hooks"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/marked@18.0.5"],"schemaVersion":1,"subject":"pkg:npm/marked@18.0.5","symbols":["marked.Hooks"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-marked-hooks",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-marked-hooks",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "marked": "18.0.5"
      }
    },
    "node_modules/marked": {
      "version": "18.0.5",
      "resolved": "https://registry.npmjs.org/marked/-/marked-18.0.5.tgz",
      "integrity": "sha512-S6GcvALHg6K4ohtu4E7x0a1AqhAjp6cV8KhLSyN9qVapnzJkusVBxZRcIU9AeYsbe6P1hKDusSbEOzGyyuce6w==",
      "license": "MIT",
      "bin": {
        "marked": "bin/marked.js"
      },
      "engines": {
        "node": ">= 20"
      }
    }
  }
}
package.json
{
  "name": "sample-marked-hooks",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "main": "src/index.js",
  "dependencies": {
    "marked": "18.0.5"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify marked.Hooks in pkg:npm/marked@18.0.5",
  "kind": "HOW",
  "packages": [
    "pkg:npm/marked@18.0.5"
  ],
  "symbols": [
    "marked.Hooks"
  ]
}
src/index.js
const { marked, Marked, Hooks } = require('marked');

/**
 * Creates an instance of marked.Hooks with optional configuration.
 *
 * @param {object} [options] - Configuration options for Hooks.
 * @returns {Hooks} Instance of marked.Hooks.
 */
function createHooks(options) {
  return new Hooks(options);
}

/**
 * Creates custom hooks definition object that demonstrates preprocessing,
 * token processing, and postprocessing.
 *
 * @param {object} [transforms] - Custom transform functions.
 * @returns {object} Hooks object compatible with marked.use.
 */
function createCustomHooks({
  variableReplacements = {},
  uppercaseHeadings = false,
  wrapperElement = null
} = {}) {
  return {
    preprocess(markdown) {
      let result = markdown;
      for (const [key, value] of Object.entries(variableReplacements)) {
        result = result.replaceAll(`{{${key}}}`, value);
      }
      return result;
    },
    processAllTokens(tokens) {
      if (uppercaseHeadings) {
        for (const token of tokens) {
          if (token.type === 'heading' && token.tokens) {
            token.tokens.forEach((child) => {
              if (child.type === 'text') {
                child.text = child.text.toUpperCase();
              }
            });
          }
        }
      }
      return tokens;
    },
    postprocess(html) {
      if (wrapperElement) {
        return `<${wrapperElement}>\n${html.trim()}\n</${wrapperElement}>`;
      }
      return html;
    }
  };
}

/**
 * Creates a Marked instance configured with specified hooks.
 *
 * @param {object} hooks - Hooks object or configuration.
 * @param {object} [options] - Additional marked options.
 * @returns {Marked} Configured Marked instance.
 */
function createMarkedWithHooks(hooks, options = {}) {
  const instance = new Marked(options);
  instance.use({ hooks });
  return instance;
}

module.exports = {
  Hooks,
  createHooks,
  createCustomHooks,
  createMarkedWithHooks
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const markedModule = require('marked');
const {
  Hooks,
  createHooks,
  createCustomHooks,
  createMarkedWithHooks
} = require('../src/index.js');

// 1. Verify marked.Hooks export and static properties
assert.equal(typeof Hooks, 'function', 'Hooks must be a constructor function/class');
assert.strictEqual(Hooks, markedModule.Hooks, 'Hooks export must match marked.Hooks');
assert.ok(Hooks.passThroughHooks instanceof Set, 'Hooks.passThroughHooks must be a Set');
assert.ok(Hooks.passThroughHooks.has('preprocess'), 'passThroughHooks must contain preprocess');
assert.ok(Hooks.passThroughHooks.has('postprocess'), 'passThroughHooks must contain postprocess');
assert.ok(Hooks.passThroughHooks.has('processAllTokens'), 'passThroughHooks must contain processAllTokens');
assert.ok(Hooks.passThroughHooksRespectAsync instanceof Set, 'Hooks.passThroughHooksRespectAsync must be a Set');

// 2. Verify default Hooks prototype methods and pass-through behavior
assert.equal(typeof Hooks.prototype.preprocess, 'function', 'Hooks.prototype.preprocess must be a function');
assert.equal(typeof Hooks.prototype.postprocess, 'function', 'Hooks.prototype.postprocess must be a function');
assert.equal(typeof Hooks.prototype.processAllTokens, 'function', 'Hooks.prototype.processAllTokens must be a function');
assert.equal(typeof Hooks.prototype.provideLexer, 'function', 'Hooks.prototype.provideLexer must be a function');
assert.equal(typeof Hooks.prototype.provideParser, 'function', 'Hooks.prototype.provideParser must be a function');

const defaultHooks = createHooks();
assert.equal(defaultHooks.preprocess('# Raw Markdown'), '# Raw Markdown', 'Default preprocess must return markdown unchanged');
assert.equal(defaultHooks.postprocess('<h1>Raw HTML</h1>'), '<h1>Raw HTML</h1>', 'Default postprocess must return HTML unchanged');

const sampleTokens = markedModule.lexer('# Sample Title');
const returnedTokens = defaultHooks.processAllTokens(sampleTokens);
assert.strictEqual(returnedTokens, sampleTokens, 'Default processAllTokens must return tokens array unchanged');

// 3. Verify provideLexer and provideParser execution
const blockLexer = defaultHooks.provideLexer(true);
const inlineLexer = defaultHooks.provideLexer(false);
const blockParser = defaultHooks.provideParser(true);
const inlineParser = defaultHooks.provideParser(false);

assert.equal(typeof blockLexer, 'function', 'provideLexer(true) must return block lexer function');
assert.equal(typeof inlineLexer, 'function', 'provideLexer(false) must return inline lexer function');
assert.equal(typeof blockParser, 'function', 'provideParser(true) must return block parser function');
assert.equal(typeof inlineParser, 'function', 'provideParser(false) must return inline parser function');

const parsedFromLexer = blockParser(blockLexer('# Block Title'));
assert.ok(parsedFromLexer.includes('<h1>Block Title</h1>'), 'blockParser must parse block tokens into HTML');

const parsedInline = inlineParser(inlineLexer('**bold text**'));
assert.ok(parsedInline.includes('<strong>bold text</strong>'), 'inlineParser must parse inline tokens into HTML');

// 4. Verify custom hooks execution in Marked parsing pipeline
const customHooks = createCustomHooks({
  variableReplacements: { name: 'CodeSampleX', version: '18.0.5' },
  uppercaseHeadings: true,
  wrapperElement: 'article'
});

const markedInstance = createMarkedWithHooks(customHooks);
const inputMarkdown = '# welcome to {{name}}\n\nRunning version {{version}}.';
const renderedHtml = markedInstance.parse(inputMarkdown);

assert.equal(typeof renderedHtml, 'string', 'marked.parse with hooks must return HTML string');
assert.ok(renderedHtml.startsWith('<article>'), 'postprocess hook must wrap HTML with opening tag');
assert.ok(renderedHtml.endsWith('</article>'), 'postprocess hook must wrap HTML with closing tag');
assert.ok(renderedHtml.includes('<h1>WELCOME TO CODESAMPLEX</h1>'), 'processAllTokens and preprocess hooks must transform heading text');
assert.ok(renderedHtml.includes('<p>Running version 18.0.5.</p>'), 'preprocess hook must interpolate variables in paragraph');

// 5. Verify multiple hooks chaining via marked.use
const chainedInstance = new markedModule.Marked();
chainedInstance.use({
  hooks: {
    preprocess(src) {
      return src + ' [Hook 1]';
    }
  }
});
chainedInstance.use({
  hooks: {
    preprocess(src) {
      return src + ' [Hook 2]';
    },
    postprocess(html) {
      return html.trim() + '\n<!-- verified -->';
    }
  }
});

const chainedResult = chainedInstance.parse('Document content');
assert.ok(chainedResult.includes('Document content [Hook 2] [Hook 1]'), 'Chained preprocess hooks must compose correctly');
assert.ok(chainedResult.endsWith('<!-- verified -->'), 'Chained postprocess hook must execute');

console.log('Contract tests passed successfully.');

原始种子者

匿名