adf

package module
v1.3.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 20, 2026 License: MIT Imports: 14 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

goldmark-adf

The release/v1 branch receives selective correctness and security fixes. It retains Go 1.25.6 compatibility with GOEXPERIMENT=jsonv2. New features are developed on v2.

A goldmark renderer that outputs Atlassian Document Format (ADF) JSON instead of HTML.

ADF is the native document format used by Atlassian products like Jira Cloud and Confluence Cloud.

Requirements

  • Go 1.25+
  • GOEXPERIMENT=jsonv2 environment variable (uses experimental encoding/json/v2)

Installation

go get github.com/ajbeck/goldmark-adf

Usage

Basic Conversion
package main

import (
    "bytes"
    "fmt"
    "log"

    "github.com/ajbeck/goldmark-adf"
)

func main() {
    // Using convenience function
    output, err := adf.Convert([]byte("# Hello World"))
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(output))

    // Using reusable instance
    md := adf.New()
    var buf bytes.Buffer
    if err := md.Convert([]byte("**Bold** text"), &buf); err != nil {
        log.Fatal(err)
    }
    fmt.Println(buf.String())
}
With GFM Extensions
// Enable tables, strikethrough, autolinks, and task lists
md := adf.NewWithGFM()

markdown := []byte(`| Name | Age |
| ---- | --- |
| Alice | 30 |

This has ~~strikethrough~~ text.`)

var buf bytes.Buffer
md.Convert(markdown, &buf)
With External Media Images

By default, images are converted to linked text. To render images as actual media in Atlassian products, enable external media:

md := adf.New(adf.WithExternalMedia(true))

markdown := []byte(`Check out this diagram:

![Architecture](https://example.com/diagram.png)

Pretty cool, right?`)

var buf bytes.Buffer
md.Convert(markdown, &buf)

This produces mediaSingle nodes that display images inline in Jira and Confluence.

You can also control image layout:

// Options: "center" (default), "wide", "full-width",
//          "wrap-left", "wrap-right", "align-start", "align-end"
md := adf.New(
    adf.WithExternalMedia(true),
    adf.WithImageLayout("wide"),
)

Building and Testing

# Build
GOEXPERIMENT=jsonv2 go build ./...

# Test
GOEXPERIMENT=jsonv2 go test ./...

Round-Trip with adf-to-markdown

This library is designed to work with adf-to-markdown for lossless ADF round-tripping:

ADF JSON --> adf-to-markdown --> Markdown --> goldmark-adf --> ADF JSON

adf-to-markdown converts ADF JSON to Markdown using custom syntax extensions for ADF-specific nodes (status badges, mentions, panels, etc.). goldmark-adf parses that Markdown — including the custom syntax — back into ADF JSON.

Use NewWithGFM() for round-trip workflows. It enables GFM parsing (tables, strikethrough, task lists) and registers the custom extension parsers:

md := adf.NewWithGFM(
    adf.WithExternalMedia(true), // ![alt](url) -> mediaSingle
)

var buf bytes.Buffer
if err := md.Convert(markdown, &buf); err != nil {
    log.Fatal(err)
}
// buf contains ADF JSON
Custom Extension Syntax

These extensions are parsed by NewWithGFM() and correspond to the output of adf-to-markdown:

Markdown Syntax ADF Node
[status:text|color] status
@[name](id) mention
[date:1234567890] date
{{placeholder text}} placeholder
[card:url] inlineCard / blockCard
[embed:url] embedCard
:shortcode: emoji
> [!WARNING] panel (GitHub alert syntax)
- [!] text / - [?] text decisionList / decisionItem
- [x] / - [ ] taskList / taskItem

For the full syntax specification and escaping rules, see the roundtrip-extensions.md document in adf-to-markdown.

Supported Markdown Features

Block Elements
  • Headings (1-6)
  • Paragraphs
  • Blockquotes
  • Panels (GitHub alert syntax: > [!NOTE], > [!WARNING], etc.)
  • Code blocks (fenced and indented)
  • Unordered lists
  • Ordered lists
  • Decision lists (- [!] / - [?])
  • Horizontal rules
Inline Elements
  • Bold (**text**)
  • Italic (*text*)
  • Inline code (`code`)
  • Links ([text](url))
  • Images (converted to links by default, or external media with WithExternalMedia(true))
  • Hard breaks
  • Status badges ([status:text|color])
  • Mentions (@[name](id))
  • Dates ([date:timestamp])
  • Placeholders ({{text}})
  • Cards ([card:url], [embed:url])
  • Emoji (:shortcode:)
GFM Extensions (with NewWithGFM)
  • Tables
  • Strikethrough (~~text~~)
  • Autolinks
  • Task lists (- [x] / - [ ] as taskList / taskItem)

Schema Validation

The adfschema subpackage provides validation against the official Atlassian ADF JSON Schema:

import "github.com/ajbeck/goldmark-adf/adfschema"

if err := adfschema.Validate(jsonBytes); err != nil {
    log.Printf("Invalid ADF: %v", err)
}

Output Examples

Basic Markdown

Input:

# Hello World

This is **bold** text with a [link](https://example.com).

Output:

{
  "version": 1,
  "type": "doc",
  "content": [
    {
      "type": "heading",
      "attrs": { "level": 1 },
      "content": [
        { "type": "text", "text": "Hello World" }
      ]
    },
    {
      "type": "paragraph",
      "content": [
        { "type": "text", "text": "This is " },
        {
          "type": "text",
          "marks": [{ "type": "strong" }],
          "text": "bold"
        },
        { "type": "text", "text": " text with a " },
        {
          "type": "text",
          "marks": [{ "type": "link", "attrs": { "href": "https://example.com" } }],
          "text": "link"
        },
        { "type": "text", "text": "." }
      ]
    }
  ]
}
External Media Images

Input (with WithExternalMedia(true)):

Check this out:

![Diagram](https://example.com/diagram.png)

Output:

{
  "version": 1,
  "type": "doc",
  "content": [
    {
      "type": "paragraph",
      "content": [
        { "type": "text", "text": "Check this out:" }
      ]
    },
    {
      "type": "mediaSingle",
      "attrs": { "layout": "center" },
      "content": [
        {
          "type": "media",
          "attrs": {
            "type": "external",
            "url": "https://example.com/diagram.png",
            "alt": "Diagram"
          }
        }
      ]
    }
  ]
}

Documentation

ADF Resources

License

MIT

Documentation

Overview

Package adf provides a goldmark renderer for Atlassian Document Format (ADF).

This package implements a custom renderer for the goldmark Markdown parser that outputs ADF JSON instead of HTML. ADF is the native document format used by Atlassian products like Jira Cloud and Confluence Cloud.

Build Requirements

This package requires Go 1.25+ with the experimental json/v2 package:

GOEXPERIMENT=jsonv2 go build ./...
GOEXPERIMENT=jsonv2 go test ./...

Basic Usage

Use New to create a reusable goldmark instance:

md := adf.New()
var buf bytes.Buffer
if err := md.Convert([]byte("# Hello World"), &buf); err != nil {
    log.Fatal(err)
}
fmt.Println(buf.String())

With GFM Extensions

Use NewWithGFM to enable GitHub Flavored Markdown extensions including tables, strikethrough, autolinks, and task lists:

md := adf.NewWithGFM()

Convenience Functions

For simple one-off conversions, use Convert or ConvertWithGFM:

output, err := adf.Convert([]byte("# Hello"))
output, err := adf.ConvertWithGFM([]byte("| A | B |\n|---|---|"))

Configuration

The renderer can be configured using functional options:

md := adf.New(
    adf.WithTableLayout("wide"),
    adf.WithImageHandler(customHandler),
)

Schema Validation

The adfschema subpackage provides JSON Schema validation for ADF documents:

import "github.com/ajbeck/goldmark-adf/adfschema"

if err := adfschema.Validate(jsonBytes); err != nil {
    log.Printf("Invalid ADF: %v", err)
}

Supported Markdown Features

Block elements: headings, paragraphs, blockquotes, code blocks (fenced and indented), bullet lists, ordered lists, horizontal rules, and hard breaks.

Inline elements: bold, italic, inline code, links, and autolinks. Images are converted to links with the image URL.

GFM extensions (with NewWithGFM): tables, strikethrough, autolinks, and task lists (rendered as "[x]" or "[ ]" text prefixes).

Raw HTML is skipped as ADF does not support arbitrary HTML content.

Example

This example demonstrates basic Markdown to ADF conversion using the convenience function adf.Convert.

output, err := adf.Convert([]byte("Hello **world**"))
if err != nil {
	fmt.Println("Error:", err)
	return
}
fmt.Println(string(output))
Output:
{
  "version": 1,
  "type": "doc",
  "content": [
    {
      "type": "paragraph",
      "content": [
        {
          "type": "text",
          "text": "Hello "
        },
        {
          "type": "text",
          "marks": [
            {
              "type": "strong"
            }
          ],
          "text": "world"
        }
      ]
    }
  ]
}
Example (ReusableInstance)

This example demonstrates creating a reusable goldmark instance with adf.New. This approach is more efficient when converting multiple documents.

md := adf.New()
var buf bytes.Buffer

if err := md.Convert([]byte("# Title"), &buf); err != nil {
	fmt.Println("Error:", err)
	return
}
fmt.Println(buf.String())
Output:
{
  "version": 1,
  "type": "doc",
  "content": [
    {
      "type": "heading",
      "attrs": {
        "level": 1
      },
      "content": [
        {
          "type": "text",
          "text": "Title"
        }
      ]
    }
  ]
}
Example (WithGFM)

This example demonstrates GFM (GitHub Flavored Markdown) support with adf.NewWithGFM, which enables tables, strikethrough, autolinks, and task lists.

md := adf.NewWithGFM()
var buf bytes.Buffer

if err := md.Convert([]byte("Hello ~~world~~"), &buf); err != nil {
	fmt.Println("Error:", err)
	return
}
fmt.Println(buf.String())
Output:
{
  "version": 1,
  "type": "doc",
  "content": [
    {
      "type": "paragraph",
      "content": [
        {
          "type": "text",
          "text": "Hello "
        },
        {
          "type": "text",
          "marks": [
            {
              "type": "strike"
            }
          ],
          "text": "world"
        }
      ]
    }
  ]
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Convert

func Convert(source []byte) ([]byte, error)

Convert is a convenience function that converts Markdown to ADF JSON. It creates a new goldmark instance for each call, which is suitable for simple use cases. For better performance with multiple conversions, create a goldmark instance with New() and reuse it.

func ConvertWithGFM

func ConvertWithGFM(source []byte) ([]byte, error)

ConvertWithGFM is like Convert but with GFM extensions enabled.

func New

func New(opts ...Option) goldmark.Markdown

New creates a new goldmark.Markdown instance configured to output ADF JSON.

func NewRenderer

func NewRenderer(opts ...Option) renderer.NodeRenderer

NewRenderer creates a new ADF renderer with the given options.

func NewWithGFM

func NewWithGFM(opts ...Option) goldmark.Markdown

NewWithGFM creates a new goldmark.Markdown instance with GFM extensions enabled. This enables parsing of tables, strikethrough, autolinks, and task lists.

Types

type Config

type Config struct {
	// ImageHandler specifies how to handle image nodes.
	// By default, images are converted to links.
	ImageHandler ImageHandler

	// TableLayout specifies the default table layout.
	// Valid values: "default", "center", "wide", "full-width"
	TableLayout string

	// ExternalMedia enables external media image handling.
	// When true, images are rendered as mediaSingle nodes with external media.
	// When false (default), images are converted to text with link marks.
	ExternalMedia bool

	// ImageLayout specifies the default layout for mediaSingle nodes.
	// Valid values: "center", "wide", "full-width", "wrap-left", "wrap-right", "align-start", "align-end"
	// Defaults to "center" if not specified.
	ImageLayout string
}

Config holds configuration options for the ADF renderer.

func NewConfig

func NewConfig() Config

NewConfig creates a new Config with default values.

type Document

type Document struct {
	Version int    `json:"version"`
	Type    string `json:"type"`
	Content []Node `json:"content"`
}

Document represents the root ADF document node.

Every ADF document has a version (always 1), a type of "doc", and a content array containing the top-level block nodes. Use NewDocument to create a properly initialized Document.

func NewDocument

func NewDocument() *Document

NewDocument creates a new empty ADF document.

func (*Document) Marshal

func (d *Document) Marshal() ([]byte, error)

Marshal serializes the document to JSON.

func (*Document) MarshalIndent

func (d *Document) MarshalIndent(indent string) ([]byte, error)

MarshalIndent serializes the document to indented JSON.

type ImageHandler

type ImageHandler func(dest, alt, title string) *Node

ImageHandler is a function that handles image rendering.

type Mark

type Mark struct {
	Type  string         `json:"type"`
	Attrs map[string]any `json:"attrs,omitempty"`
}

Mark represents a mark applied to a text node.

Marks are used for inline formatting such as bold (NewStrongMark), italic (NewEmMark), code (NewCodeMark), strikethrough (NewStrikeMark), and links (NewLinkMark). Multiple marks can be applied to a single text node.

func NewCodeMark

func NewCodeMark() Mark

NewCodeMark creates an inline code mark.

func NewEmMark

func NewEmMark() Mark

NewEmMark creates an italic/emphasis mark.

func NewLinkMark

func NewLinkMark(href, title string) Mark

NewLinkMark creates a link mark with the given URL and optional title.

func NewStrikeMark

func NewStrikeMark() Mark

NewStrikeMark creates a strikethrough mark.

func NewStrongMark

func NewStrongMark() Mark

NewStrongMark creates a bold/strong mark.

func NewSubSupMark

func NewSubSupMark(subType string) Mark

NewSubSupMark creates a subscript or superscript mark. subType should be "sub" or "sup".

func NewTextColorMark

func NewTextColorMark(color string) Mark

NewTextColorMark creates a text color mark with a hex color code.

func NewUnderlineMark

func NewUnderlineMark() Mark

NewUnderlineMark creates an underline mark.

type Node

type Node struct {
	Type    string         `json:"type"`
	Attrs   map[string]any `json:"attrs,omitempty"`
	Content []Node         `json:"content,omitempty"`
	Marks   []Mark         `json:"marks,omitempty"`
	Text    string         `json:"text,omitempty"`
}

Node represents an ADF node. It uses a flexible structure that can represent any node type in ADF, including block nodes (paragraph, heading, codeBlock), inline nodes (hardBreak), and text nodes.

Block and inline nodes use the Content field to hold child nodes. Text nodes use the Text field for their content and may have Marks applied. The Attrs field holds type-specific attributes like heading level or link href.

Use the constructor functions (e.g., NewParagraph, NewHeading, NewText) to create properly initialized nodes.

func NewBlockCardNode

func NewBlockCardNode(url string) *Node

NewBlockCardNode creates a new blockCard node.

func NewBlockquote

func NewBlockquote() *Node

NewBlockquote creates a new blockquote node.

func NewBulletList

func NewBulletList() *Node

NewBulletList creates a new unordered list node.

func NewCaption

func NewCaption() *Node

NewCaption creates a new caption node for use within mediaSingle.

func NewCodeBlock

func NewCodeBlock(language string) *Node

NewCodeBlock creates a new code block node with an optional language.

func NewDateNode

func NewDateNode(timestamp string) *Node

NewDateNode creates a new date inline node.

func NewDecisionItemNode

func NewDecisionItemNode(state string) *Node

NewDecisionItem creates a new decisionItem node.

func NewDecisionListNode

func NewDecisionListNode() *Node

NewDecisionList creates a new decisionList node.

func NewEmbedCardNode

func NewEmbedCardNode(url string) *Node

NewEmbedCardNode creates a new embedCard node.

func NewEmojiNode

func NewEmojiNode(shortName string) *Node

NewEmojiNode creates a new emoji inline node.

func NewExternalMedia

func NewExternalMedia(url, alt string) *Node

NewExternalMedia creates a new media node for external URLs.

func NewHardBreak

func NewHardBreak() *Node

NewHardBreak creates a new hard break node.

func NewHeading

func NewHeading(level int) *Node

NewHeading creates a new heading node with the specified level (1-6).

func NewInlineCardNode

func NewInlineCardNode(url string) *Node

NewInlineCardNode creates a new inlineCard node.

func NewListItem

func NewListItem() *Node

NewListItem creates a new list item node.

func NewMediaSingle

func NewMediaSingle(layout string) *Node

NewMediaSingle creates a new mediaSingle container node with the specified layout. Valid layouts: "center", "wide", "full-width", "wrap-left", "wrap-right", "align-start", "align-end"

func NewMentionNode

func NewMentionNode(id, displayName string) *Node

NewMentionNode creates a new mention inline node.

func NewOrderedList

func NewOrderedList(start int) *Node

NewOrderedList creates a new ordered list node with an optional start number.

func NewPanelNode

func NewPanelNode(panelType string) *Node

NewPanel creates a new panel block node.

func NewParagraph

func NewParagraph() *Node

NewParagraph creates a new paragraph node.

func NewPlaceholderNode

func NewPlaceholderNode(text string) *Node

NewPlaceholderNode creates a new placeholder inline node.

func NewRule

func NewRule() *Node

NewRule creates a new horizontal rule node.

func NewStatusNode

func NewStatusNode(text, color string) *Node

NewStatus creates a new status inline node.

func NewTable

func NewTable() *Node

NewTable creates a new table node.

func NewTableCell

func NewTableCell() *Node

NewTableCell creates a new table cell node.

func NewTableHeader

func NewTableHeader() *Node

NewTableHeader creates a new table header cell node.

func NewTableRow

func NewTableRow() *Node

NewTableRow creates a new table row node.

func NewTaskItem

func NewTaskItem(state string) *Node

NewTaskItem creates a new taskItem node.

func NewTaskList

func NewTaskList() *Node

NewTaskList creates a new taskList node.

func NewText

func NewText(text string) *Node

NewText creates a new text node with the given content.

func NewTextWithMarks

func NewTextWithMarks(text string, marks []Mark) *Node

NewTextWithMarks creates a new text node with marks.

func (*Node) AppendChild

func (n *Node) AppendChild(child Node)

AppendChild appends a child node to this node's content.

func (*Node) AppendMark

func (n *Node) AppendMark(mark Mark)

AppendMark appends a mark to this node's marks.

type Option

type Option interface {
	SetADFOption(*Config)
}

Option is a functional option for configuring the ADF renderer.

func WithExternalMedia

func WithExternalMedia(enabled bool) Option

WithExternalMedia enables or disables external media image handling. When enabled, images are rendered as mediaSingle nodes containing external media. When disabled (default), images are converted to text with link marks.

func WithImageHandler

func WithImageHandler(handler ImageHandler) Option

WithImageHandler sets a custom image handler.

func WithImageLayout

func WithImageLayout(layout string) Option

WithImageLayout sets the default layout for mediaSingle nodes. Valid values: "center", "wide", "full-width", "wrap-left", "wrap-right", "align-start", "align-end" Defaults to "center" if not specified.

func WithTableLayout

func WithTableLayout(layout string) Option

WithTableLayout sets the default table layout. Valid values: "default", "center", "wide", "full-width"

type Renderer

type Renderer struct {
	// contains filtered or unexported fields
}

Renderer is a goldmark renderer.NodeRenderer that outputs Atlassian Document Format (ADF) JSON.

The Renderer maintains internal state during the AST walk, using a node stack to track the current position in the ADF document tree and a mark stack to accumulate active text marks (bold, italic, links, etc.). This state is reset for each new document.

Use NewRenderer to create a Renderer, or use the higher-level New and NewWithGFM functions which configure a complete goldmark instance.

func (*Renderer) RegisterFuncs

func (r *Renderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer)

RegisterFuncs implements renderer.NodeRenderer.

Directories

Path Synopsis
Package adfschema provides JSON Schema validation for Atlassian Document Format.
Package adfschema provides JSON Schema validation for Atlassian Document Format.
Package astext defines AST node types for ADF round-trip markdown extensions.
Package astext defines AST node types for ADF round-trip markdown extensions.
Command migrate-schema normalizes the vendored ADF schema to draft-07.
Command migrate-schema normalizes the vendored ADF schema to draft-07.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址