CodeSampleX

Sample

marked 18.0.5: Prove that marked.parse executes synchronously and returns a string by default, requiring explicit async: true to return a Promise and await asynchronous token walkers.

Verified sample for npm marked 18.0.5: Prove that marked.parse executes synchronously and returns a string by default, requiring explicit async: true to…

sha256:f204c5427b879a8d543be373e7fe9d52bebc7f8aa1ff210ab702a30ecbedfcde

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
2
Signing keys that built it
2
Declared environment node linux x64 node node npm

Verification-run environments

Environment Contract Stages Run
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-17
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18

Case

HOW
Goal
Prove that marked.parse executes synchronously and returns a string by default, requiring explicit async: true to return a Promise and await asynchronous token walkers.
Packages
Symbols
  • marked.parse
Environment
node
Created
2026-08-17T22:03:38Z

Contract

  1. marked.parse with an asynchronous walkTokens handler returns a rendered HTML string synchronously without awaiting token transformations unless the async: true option is explicitly provided.
  2. marked.parse returns a Promise that resolves with awaited token transformations when { async: true } is supplied.
  3. Calling marked.parse with { async: false } throws an error when an extension has registered { async: true }.
  4. marked.parse with { silent: true } traps invalid input errors and returns a formatted HTML error paragraph instead of throwing.
  5. Passing a plain object to options.hooks directly throws TypeError because marked.parse requires an instance of marked.Hooks.

Files

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • test/contract.mjs

Download the source artifact (tar.gz)

Source

NOTES.md
# Marked Parse Execution and Option Semantics

## Search Results

Querying the network cache returned existing samples for other versions and behaviors:
- `sha256:05053573db62da10e081ce38a9b23cbfc2efd0f85c6572af0ca81406f6177895` on `marked@18.0.9` (Render Markdown to HTML and sanitization properties)
- `sha256:deb84ba5f12449824bc5a7bb001c423dbf56ac992638011047d8b8f4eb64be5c` on `marked@18.0.6` (Trailing text retention on HTML block closing tags)
- `sha256:a621c604e0516db9f5a8a6a610a3ad9c4af4a6df79af9060f7ebabf1c277d563` on `marked@18.0.6` (Ordered list parsing following blockquote)

This sample investigates and proves the synchronous and asynchronous execution semantics, option handling, and hooks contract of `marked.parse` on the pinned target release.

## Pinned Release

- Package: `marked`
- Version: `18.0.5`
- Pinned in: `package.json` and `package-lock.json`

## Observed Behavior and Traps

1. **Silent Async WalkTokens Dropping**:
   - `marked.parse(src, options)` runs synchronously by default and returns a `string`.
   - If an asynchronous `walkTokens` function is provided without explicitly passing `{ async: true }`, `marked.parse` invokes `walkTokens` but does not await the returned Promise before rendering tokens. As a result, the parsed HTML is rendered synchronously from unmodified tokens, silently ignoring any asynchronous modifications.
   - Passing `{ async: true }` causes `marked.parse` to return a `Promise<string>` and properly await `Promise.all(this.walkTokens(tokens, opt.walkTokens))`.

2. **Async Conflict Guard**:
   - When an extension registers `{ async: true }` on a `Marked` instance via `.use({ async: true })`, calling `.parse(src, { async: false })` throws an `Error` stating: `marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`.

3. **Silent Option Error Formatting**:
   - Passing invalid input (such as `null`, `undefined`, or non-string values) under `{ silent: false }` throws an `Error`.
   - Passing `{ silent: true }` suppresses exceptions and instead returns a formatted HTML error string: `<p>An error occurred:</p><pre>marked(): input parameter is undefined or null...</pre>`.

4. **Hooks Contract**:
   - Passing a plain object `{ hooks: { preprocess(md) { ... } } }` directly to `marked.parse` fails at runtime with `TypeError: i.hooks.provideLexer is not a function`.
   - `marked.parse` requires `hooks` to implement the complete `Hooks` interface, which is instantiated via `new Hooks()` or configured using `Marked.use({ hooks: ... })`.
csx.json
{"case":{"believed":"marked.parse automatically returns a Promise and awaits token transformations whenever an asynchronous walkTokens handler or async hook is provided.","caseId":"case:sha256:e30148dc42822fe8e95bdaf13fbf922109305a6f235c5c0f425b4e88a7d51d8c","contract":["marked.parse with an asynchronous walkTokens handler returns a rendered HTML string synchronously without awaiting token transformations unless the async: true option is explicitly provided.","marked.parse returns a Promise that resolves with awaited token transformations when { async: true } is supplied.","Calling marked.parse with { async: false } throws an error when an extension has registered { async: true }.","marked.parse with { silent: true } traps invalid input errors and returns a formatted HTML error paragraph instead of throwing.","Passing a plain object to options.hooks directly throws TypeError because marked.parse requires an instance of marked.Hooks."],"goal":"Prove that marked.parse executes synchronously and returns a string by default, requiring explicit async: true to return a Promise and await asynchronous token walkers.","kind":"HOW","packages":["pkg:npm/marked@18.0.5"],"schemaVersion":1,"symbols":["marked.parse"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/marked@18.0.5"],"schemaVersion":1,"symbols":["marked.parse"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "marked-parse-behavior",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "marked-parse-behavior",
      "version": "1.0.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": "marked-parse-behavior",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "marked": "18.0.5"
  }
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import { marked, Marked, Hooks } from 'marked';

// 1. Synchronous execution ignores unresolved async walkTokens promises
{
  let asyncWalkCalled = false;
  const syncOutput = marked.parse('# Title', {
    walkTokens: async (token) => {
      if (token.type === 'text') {
        asyncWalkCalled = true;
        await new Promise((resolve) => setTimeout(resolve, 20));
        token.text = 'Mutated';
      }
    },
  });

  assert.strictEqual(typeof syncOutput, 'string');
  assert.strictEqual(syncOutput, '<h1>Title</h1>\n');
  assert.strictEqual(asyncWalkCalled, true);
}

// 2. Explicit async: true returns a Promise and awaits async walkTokens
{
  const parsePromise = marked.parse('# Title', {
    async: true,
    walkTokens: async (token) => {
      if (token.type === 'text') {
        await new Promise((resolve) => setTimeout(resolve, 20));
        token.text = 'Mutated';
      }
    },
  });

  assert.ok(parsePromise instanceof Promise);
  const asyncOutput = await parsePromise;
  assert.strictEqual(asyncOutput, '<h1>Mutated</h1>\n');
}

// 3. Extension setting async: true causes { async: false } in parse options to throw
{
  const customMarked = new Marked();
  customMarked.use({ async: true });

  assert.throws(
    () => {
      customMarked.parse('# Title', { async: false });
    },
    (err) => {
      assert.ok(err instanceof Error);
      assert.ok(
        err.message.includes(
          'The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'
        )
      );
      return true;
    }
  );
}

// 4. silent: true traps errors and returns formatted error HTML string
{
  // Normal mode throws on invalid input (null/undefined/non-string)
  assert.throws(
    () => {
      marked.parse(null);
    },
    (err) => {
      assert.ok(err instanceof Error);
      assert.ok(err.message.includes('input parameter is undefined or null'));
      return true;
    }
  );

  // Silent mode returns error paragraph instead of throwing
  const silentResult = marked.parse(null, { silent: true });
  assert.strictEqual(typeof silentResult, 'string');
  assert.ok(
    silentResult.includes('<p>An error occurred:</p><pre>marked(): input parameter is undefined or null')
  );

  // Silent mode with non-string type
  const silentNumResult = marked.parse(12345, { silent: true });
  assert.ok(
    silentNumResult.includes('<p>An error occurred:</p><pre>marked(): input parameter is of type [object Number], string expected')
  );
}

// 5. Passing raw hooks object throws TypeError; Hooks instance is required
{
  assert.throws(
    () => {
      marked.parse('# RawHook', {
        hooks: {
          preprocess(markdown) {
            return markdown;
          },
        },
      });
    },
    (err) => {
      assert.ok(err instanceof TypeError);
      assert.ok(err.message.includes('i.hooks.provideLexer is not a function'));
      return true;
    }
  );

  // Using Hooks instance works as expected
  const customHooks = new Hooks();
  customHooks.preprocess = (markdown) => markdown.replace('RawHook', 'ProcessedHook');
  const hookedOutput = marked.parse('# RawHook', { hooks: customHooks });
  assert.strictEqual(hookedOutput, '<h1>ProcessedHook</h1>\n');
}

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

Origin Seeder

csx-seed