Skip to content
safran

Type to search. Enter opens the first result.

    Reading tickets

    safran.tickets is one API over every tracker in the profile. You pass whatever a person would paste (a key, a URL, a tracker's short form); Safran finds the tracker it belongs to and returns the same neutral shapes whichever product is behind it. This page covers reading one ticket, the reference forms, paging, search across trackers and what happens when a tracker cannot do something.

    read-ticket.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    const ticket = await safran.tickets.get("PAY-1423");
    console.log(`${ticket.key}  ${ticket.title}`);
    console.log(`${ticket.type} · ${ticket.status} (${ticket.statusCategory}) · ${ticket.assignee?.name ?? "unassigned"}`);
    console.log(ticket.description);
    
    const comments = await safran.tickets.comments("PAY-1423", { limit: 20 });
    for (const comment of comments.items) {
      console.log(`- ${comment.author?.name ?? "unknown"}: ${comment.body}`);
    }
    
    for (const link of await safran.tickets.links("PAY-1423")) {
      if (link.kind === "ticket") console.log(`${link.relation} ${link.ticket?.key}  ${link.ticket?.title}`);
      else console.log(`${link.relation} ${link.url}${safran.docs.canFetch(link.url ?? "") ? "  (fetchable)" : ""}`);
    }
    $ bun read-ticket.ts
    PAY-1423  Kısmi iade işlemi İstanbul şubesinde başarısız oluyor
    Bug · Done (done) · Ayşe Yılmaz
    Müşteri kısmi iade istediğinde ödeme sağlayıcısı hata döndürüyor.
    
    Beklenen: iade tutarı sipariş tutarından küçükse işlem tamamlanmalı.
    - Ayşe Yılmaz: Sağlayıcı yanıtını inceledim, yuvarlama hatası görünüyor.
    - Çağrı Öztürk: Düzeltme canlıya alındı.
    blocks PAY-1500  Refund webhook retries are not idempotent
    mentioned in https://wiki.acme.test/refunds

    Three things to notice:

    • description and comment bodies are Markdown. Trackers that store rich formats convert them in the connector.
    • status is the tracker's own word (Done, Canlıda); statusCategory is the neutral todo, in_progress or done. Branch on the category.
    • A web link is a URL the ticket points at. docs.canFetch tells you offline whether a configured doc source can fetch it.

    References

    Every method takes a ref: a string in any form one of the profile's trackers recognises. Which forms exist is up to each connector (a key such as PAY-1423, the ticket's URL, a short form such as #412); the connector pages list them. Recognition is offline: it is a string match, not a lookup.

    tickets.resolve(ref) shows the routing without fetching anything. It returns the tracker and the canonical key:

    resolve.ts
    import { createSafran, isSafranError } from "@safran/core";
    
    await using safran = await createSafran();
    
    const { tracker, key } = safran.tickets.resolve("https://acme.atlassian.net/browse/pay-1423");
    console.log(tracker.id, key);
    console.log(safran.tickets.resolve("jira:PAY-1423").key);
    
    try {
      safran.tickets.resolve("OPS-7");
    } catch (error) {
      if (!isSafranError(error, "NOT_FOUND")) throw error;
      console.log(error.format());
    }
    $ bun resolve.ts
    jira PAY-1423
    PAY-1423
    No tracker recognises "OPS-7" as a ticket reference
    → Configured trackers: jira (PAY, MOB, WEB).

    The rules, in order:

    1. The reference is trimmed. An empty one is INVALID_INPUT.
    2. Explicit form <trackerId>:<ref>. When the part before the first colon is the id of a tracker in the profile, only that tracker is asked. If it does not recognise the rest, the error is NOT_FOUND. A URL is never read as this form (https: is not a tracker id).
    3. Otherwise every tracker is asked. No match is NOT_FOUND, with the configured trackers and their projects in the hint. One match wins.
    4. Several matches. The tracker whose profile entry lists the key's project under projects wins. If none or more than one does, the error is INVALID_INPUT and details.trackers holds the candidate ids; use the explicit form, or declare the project under one tracker.

    With two trackers that both use PROJECT-123 keys, declaring projects on each entry is what makes plain keys unambiguous. See multiple sources.

    The ticket methods

    MethodReturnsCapability needed
    get(ref, options?)Ticketnone: every tracker has it
    comments(ref, options?)Page<Comment>comments
    attachments(ref, options?)Attachment[]attachments
    attachment(ref, attachmentId, options?)AttachmentContentattachments
    links(ref, options?)TicketLink[]links
    history(ref, options?)Page<HistoryEntry>history
    search(query, options?)TicketSearchResultsearch
    resolve(ref)ResolvedTicketRefnone; synchronous and offline

    All of them except resolve accept a signal in their options (cancellation). A ticket that does not exist is NOT_FOUND from the tracker.

    /**
     * Ticket access across every tracker in the profile. `ref` is whatever a person would
     * paste: a key ("PAY-1423"), a URL, or a tracker-specific short form ("#412").
     * Methods a tracker does not support throw UNSUPPORTED.
     */
    export interface TicketsApi {
      /** Finds the tracker a reference belongs to. Throws NOT_FOUND when none recognises it. */
      resolve(ref: string): ResolvedTicketRef;
      get(ref: string, options?: CallOptions): Promise<Ticket>;
      comments(ref: string, options?: PageOptions): Promise<Page<Comment>>;
      attachments(ref: string, options?: CallOptions): Promise<Attachment[]>;
      attachment(ref: string, attachmentId: string, options?: CallOptions): Promise<AttachmentContent>;
      links(ref: string, options?: CallOptions): Promise<TicketLink[]>;
      history(ref: string, options?: PageOptions): Promise<Page<HistoryEntry>>;
      search(query: TicketSearchQuery, options?: TicketSearchOptions): Promise<TicketSearchResult>;
    }

    defined in packages/core/src/api.ts

    Comments and history

    Both are paged. limit is the page size and cursor continues where the previous page ended; the default page size is the connector's own. The rules for limit and cursors are the same everywhere and are described in pagination.

    all-comments.ts
    import { createSafran, type Comment } from "@safran/core";
    
    await using safran = await createSafran();
    
    const all: Comment[] = [];
    let cursor: string | undefined;
    do {
      const page = await safran.tickets.comments("PAY-1423", { limit: 50, ...(cursor === undefined ? {} : { cursor }) });
      all.push(...page.items);
      cursor = page.nextCursor;
    } while (cursor !== undefined);
    
    console.log(`${all.length} comments`);

    A HistoryEntry is one field change: at, field, and from / to as the tracker words them.

    Attachments

    attachments lists metadata; attachment downloads one by the id from that list and returns the same metadata plus data as a Uint8Array.

    attachments.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    const files = await safran.tickets.attachments("PAY-1423");
    for (const file of files) console.log(file.id, file.filename, file.mimeType, file.sizeBytes);
    
    const [first] = files;
    if (first) {
      const content = await safran.tickets.attachment("PAY-1423", first.id);
      await Bun.write(`/work/acme/tmp/${first.filename}`, content.data);
    }

    A TicketLink is either kind: "ticket" (another ticket, in ticket, as a TicketSummary) or kind: "web" (a remote link, in url and title). relation is the tracker's wording: blocks, is blocked by, child, relates to.

    Search across trackers

    tickets.search sends one neutral query to every tracker that can search and merges the answers into one page. Each item is a TicketSummary tagged with the tracker it came from.

    search-tickets.ts
    import { createSafran } from "@safran/core";
    
    await using safran = await createSafran();
    
    const result = await safran.tickets.search({ text: "refund", projects: ["PAY"], statusCategories: ["todo", "in_progress"] }, { limit: 20 });
    
    for (const item of result.items) console.log(`${item.tracker}  ${item.key}  [${item.status}]  ${item.title}`);
    for (const warning of result.warnings ?? []) console.warn(`${warning.source}: ${warning.code}: ${warning.message}`);
    if (result.nextCursor !== undefined) console.log("more results: pass nextCursor back as `cursor`");
    $ bun search-tickets.ts
    jira  PAY-1500  [In Progress]  Refund webhook retries are not idempotent

    The query

    FieldTypeMeaning
    textstringFree text matched against title and description. How it is matched (words, phrases, stemming) is the tracker's search.
    projectsstring[]Project keys. Also decides which trackers are asked (below).
    statusCategoriesStatusCategory[]Any of todo, in_progress, done.
    updatedSincestringISO date; only tickets updated at or after it.
    nativestringA query in the tracker's own language (JQL, WIQL, a hosted search syntax). Needs the native-query capability.

    The options

    OptionDefaultMeaning
    trackerevery tracker that can searchRestrict the search to one tracker entry id.
    limit50 (DEFAULT_TICKET_SEARCH_LIMIT)Total page size across all trackers. Above 500 it is clamped.
    cursornonenextCursor of the previous page, passed back with the same query and options.
    signalnoneCancels the search.

    Which trackers are asked

    • With tracker: only that one. An unknown id is INVALID_INPUT; a tracker without search (or without native-query when native is set) is UNSUPPORTED.
    • Without it: every tracker with the search capability. If none has it, the call throws UNSUPPORTED.
    • With native: only trackers with native-query. A native query is written for one product, so combine it with tracker.
    • With projects: a tracker whose profile entry declares its projects and has none of the wanted ones is not asked. A tracker that declares no projects is always asked.

    How a page is filled

    Each tracker that still has results gets an equal share of limit; a remainder goes to the trackers listed first in the profile. With limit: 20 and three trackers, the shares are 7, 7 and 6. A tracker that returns fewer than its share does not hand the rest to the others, so a page can be shorter than limit while nextCursor is still present. The end of the results is nextCursor === undefined, never a short page. With more trackers than limit, the ones beyond it wait in the cursor for a later page.

    Items are grouped by tracker in profile order. There is no cross-tracker ranking: scores of different products are not comparable.

    Warnings: a page that does not cover every tracker

    A search does not fail because one tracker did. warnings is present when the page leaves a tracker out, one entry per tracker:

    codeMeaning
    UNSUPPORTEDThe tracker cannot run this search (no search, or no native-query for a native query) and was not asked.
    any other codeThe tracker failed with that code (AUTH_FAILED, RATE_LIMITED, UPSTREAM, …). Its error message is in message.

    A failed tracker is dropped from the cursor, so later pages continue with the others instead of failing again. UNSUPPORTED warnings are repeated on every page of a paged search. When every asked tracker fails, the call throws: the single tracker's own error, or one error listing each tracker's message.

    export interface TicketSearchResult extends Page<TicketSummary & { tracker: string }> {
      /**
       * Present when the page does not cover every tracker: one entry per tracker that failed (with
       * the code of its failure) or was left out because it cannot run this search (UNSUPPORTED).
       * The items of the others are still returned.
       */
      warnings?: SafranWarning[];
    }
    
    /** Something that did not stop a call but made its answer incomplete or ambiguous. */
    export interface SafranWarning {
      /** Profile entry id of the tracker or code host the warning is about. */
      source: string;
      code: SafranErrorCode;
      message: string;
    }

    defined in packages/core/src/api.ts

    When a tracker cannot do it

    Optional features are capabilities. Calling a method the ticket's tracker does not support throws UNSUPPORTED with the tracker's capabilities in the hint and details.tracker / details.method for programs:

    capability-check.ts
    import { createSafran, isSafranError, type Attachment } from "@safran/core";
    
    await using safran = await createSafran();
    
    async function attachmentsOf(ref: string): Promise<Attachment[]> {
      // Check first when you can: no round trip, no exception.
      const { tracker } = safran.tickets.resolve(ref);
      if (!tracker.capabilities.has("attachments")) return [];
      return safran.tickets.attachments(ref);
    }
    
    try {
      console.log(await safran.tickets.history("PAY-1423"));
    } catch (error) {
      // Or catch: the code is stable, the message is for people.
      if (!isSafranError(error, "UNSUPPORTED")) throw error;
      console.log(error.format());
    }
    console.log((await attachmentsOf("PAY-1423")).length);

    What the built-in trackers support:

    Capabilityjiraazure-boardslineargithub-issues
    commentsyesyesyesyes
    attachmentsyesyesnono
    linksyesyesyesyes
    historyyesyesyesyes
    searchyesyesyesyes
    native-queryyesyesnoyes

    The domain types

    export interface Ticket extends TicketSummary {
      /** Id of the tracker entry in the profile this ticket came from. */
      tracker: string;
      url: string;
      /** Project / team / repository key the ticket belongs to. */
      project: string;
      /** Markdown. Rich formats (ADF, HTML) are converted by the tracker plugin. */
      description: string;
      priority?: string;
      labels: string[];
      assignee?: Person;
      reporter?: Person;
      parent?: TicketSummary;
      createdAt?: string;
      updatedAt?: string;
      resolvedAt?: string;
      /**
       * Tracker-specific extras that have no neutral home (story points, sprint, custom fields).
       * Keys are human-readable field names; values are JSON-serialisable.
       */
      fields: Record<string, unknown>;
    }
    
    /** Short reference to a ticket, as it appears in links, parents and search results. */
    export interface TicketSummary {
      key: string;
      title: string;
      url?: string;
      type?: string;
      status?: string;
      statusCategory?: StatusCategory;
    }
    
    export interface Person {
      id?: string;
      name: string;
      email?: string;
    }

    defined in packages/kit/src/types.ts

    fields holds what has no neutral home: story points, sprint, the custom fields a connector is configured to copy. Keys are the field names people see, not vendor ids.

    export interface Comment {
      id: string;
      author?: Person;
      /** Markdown. */
      body: string;
      createdAt?: string;
      updatedAt?: string;
    }
    
    export interface TicketLink {
      /** `ticket` points at another ticket; `web` is a remote link (wiki page, design file, PR). */
      kind: "ticket" | "web";
      /** Relation as the tracker words it: "blocks", "is blocked by", "child", "relates to", … */
      relation: string;
      ticket?: TicketSummary;
      url?: string;
      title?: string;
    }
    
    export interface HistoryEntry {
      at: string;
      author?: Person;
      field: string;
      from?: string;
      to?: string;
    }
    
    export interface Attachment {
      id: string;
      filename: string;
      mimeType?: string;
      sizeBytes?: number;
      createdAt?: string;
      author?: Person;
    }

    defined in packages/kit/src/types.ts

    export interface TicketSearchQuery {
      /** Free text matched against title and description. */
      text?: string;
      projects?: string[];
      statusCategories?: StatusCategory[];
      /** ISO date; only tickets updated at or after it. */
      updatedSince?: string;
      /** Tracker-native query (JQL, WIQL, GitHub search syntax). Needs the `native-query` capability. */
      native?: string;
    }
    
    export interface TicketSearchOptions extends PageOptions {
      /** Restrict to one tracker entry id. Default: every tracker that supports search. */
      tracker?: string;
    }

    defined in packages/kit/src/types.ts, packages/core/src/api.ts

    Common mistakes

    SymptomCause
    NOT_FOUND: No tracker recognises "…"The reference has no form any configured tracker accepts. Check the key's project against projects in the profile; the hint lists them.
    INVALID_INPUT: "…" could belong to several trackersTwo trackers accept the shape and the profile does not say who owns the project. Use <trackerId>:<ref> or declare projects.
    A page shorter than limit, treated as the last oneLoop until nextCursor is undefined.
    INVALID_INPUT: The search cursor does not belong to this searchThe cursor was passed with a different tracker, native or projects, which changes the set of trackers. Pass it with the same query and options.
    Results silently missing one trackerRead warnings. A search with one failing tracker still returns the others.