@safran/core
Bu sayfa @safran/core paketinin başvurusudur: createSafran fabrika fonksiyonu, aldığı seçenekler, döndürdüğü Safran örneği ve alt API'lerinin her metodu; parametreleri, dönüş biçimleri, fırlattıkları hata kodları ve adlandırılmış varsayılanlarıyla. Bildirimler site derlenirken kaynak koddan alınır. Göreve dayalı anlatım için SDK kılavuzundan başlayın.
Eksiksiz bir örnek
Bu sayfadaki her örnek aynı bellek içi şirket üzerinde çalışır. createAcme(), @safran/kit/testing içindeki sahte (fake) bağlayıcılar üzerine gerçek bir Safran kurar; hiçbir çağrı ağa çıkmaz, diske yazılan tek şey geçici bir veri dizinidir.
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createSafran, type Safran } from "@safran/core";
import { FakeCodeHost, FakeCodeIndex, FakeDocSource, FakeTracker, fakePlugins } from "@safran/kit/testing";
const REFUND_SERVICE = `export function refundPartially(orderId: string, amount: number): Refund {
const order = loadOrder(orderId);
assertRefundable(order, amount);
return ledger.post({ orderId, amount, kind: "refund" });
}
`;
/** The acme story in memory: fake connectors, a fake index, and a temporary data directory. */
export async function createAcme(): Promise<Safran> {
const work = mkdtempSync(join(tmpdir(), "acme-"));
const paymentsApi = join(work, "payments-api");
mkdirSync(join(paymentsApi, "src/refund"), { recursive: true });
writeFileSync(join(paymentsApi, "src/refund/service.ts"), REFUND_SERVICE);
const jira = new FakeTracker({
id: "jira",
baseUrl: "https://jira.acme.example",
tickets: [
{
key: "PAY-1423",
title: "Kısmi iade işlemi İstanbul şubesinde başarısız oluyor",
type: "Bug",
status: "Done",
statusCategory: "done",
description: "Kısmi iade 500 hatası veriyor. Ayrıntı: https://jira.acme.example/wiki/spaces/PAY/pages/1/Refunds",
comments: [{ id: "1", author: { name: "Deniz" }, body: "Sadece İstanbul şubesinde tekrarlanıyor.", createdAt: "2026-03-02T09:00:00Z" }],
history: [{ at: "2026-03-04T10:00:00Z", field: "status", from: "In Progress", to: "Done" }],
},
{ key: "PAY-1500", title: "Refund webhook retries are not idempotent", type: "Bug", status: "In Progress", statusCategory: "in_progress" },
{ key: "PAY-1501", title: "Checkout basket total ignores the campaign discount", type: "Bug", status: "To Do", statusCategory: "todo" },
],
});
const azure = new FakeCodeHost({
id: "azure",
// An absolute path as clone URL is read in place, like a `local` host: no git involved.
repos: [{ name: "payments-api", cloneUrl: paymentsApi }],
pullRequests: [
{
id: "812",
repo: "payments-api",
title: "PAY-1423 fix partial refund rounding",
description: "",
sourceBranch: "bugfix/PAY-1423-partial-refund",
mergedAt: "2026-03-04T09:30:00Z",
linkedTicketKeys: [],
changedFiles: ["src/refund/service.ts", "src/refund/policy.ts"],
},
],
});
const wiki = new FakeDocSource({
id: "wiki",
origin: "https://jira.acme.example",
pages: { "https://jira.acme.example/wiki/spaces/PAY/pages/1/Refunds": { title: "Refunds", content: "Partial refunds are posted to the ledger." } },
});
const index = new FakeCodeIndex({
files: { "payments-api": { "src/refund/service.ts": REFUND_SERVICE } },
groups: { backend: ["payments-api", "ledger"] },
});
return createSafran({
profile: {
version: 1,
company: "acme",
languages: { tickets: "tr", code: "en" },
trackers: [{ id: "jira", type: "fake", projects: ["PAY", "MOB", "WEB"] }],
code: { hosts: [{ id: "azure", type: "fake" }], groups: { backend: ["payments-api", "ledger"] } },
docs: [{ id: "wiki", type: "fake" }],
teams: [{ name: "Payments", projects: ["PAY"], repos: ["payments-api", "ledger"] }],
glossary: [{ term: "İade", code: ["refund", "chargeback"] }],
conventions: ["Branch names start with the ticket key."],
embeddings: { type: "fake" },
},
builtinPlugins: false,
plugins: fakePlugins({ trackers: [jira], hosts: [azure], docs: [wiki] }),
index,
dataDir: join(work, "data"),
});
}Bu dosya yanında dururken aşağıdaki kod eksiksiz bir programdır: bir iş kaydını (ticket) okur, kayıttaki sözcüklerin işaret ettiği kodu bulur ve o kayıt için hangi pull request'in birleştirildiğini gösterir.
import { createAcme } from "./acme";
const safran = await createAcme();
try {
const ticket = await safran.tickets.get("PAY-1423");
console.log(ticket.title, ticket.statusCategory);
const { hits, effectiveQuery } = await safran.code.search("kısmi iade nerede yapılıyor", { groups: ["backend"] });
console.log(effectiveQuery); // "kısmi iade nerede yapılıyor refund chargeback"
for (const hit of hits) console.log(`${hit.repo} ${hit.path}:${hit.startLine}-${hit.endLine}`);
await safran.links.refresh({ since: "2026-01-01" });
for (const record of await safran.links.query({ ticket: "PAY-1423" })) {
console.log(record.repo, record.title, record.changedFiles);
}
} finally {
await safran.close();
}Gerçek bir projede profil bir dosyadır ve bağlayıcılar yerleşik olanlardır; kurulum tek satıra iner: await createSafran(), ./safran.yaml dosyasını okur. Ayrıntı için SDK kılavuzundaki createSafran sayfasına bakın.
Paketin dışa aktardıkları
| Dışa aktarım | Tür | Bölüm |
|---|---|---|
createSafran, SafranOptions, builtinPlugins | fabrika | createSafran |
Safran | arayüz | Safran örneği |
TicketsApi ve türleri | arayüz | safran.tickets |
CodeApi ve türleri | arayüz | safran.code |
DocsApi | arayüz | safran.docs |
ReposApi ve türleri | arayüz | safran.repos |
LinksApi ve türleri | arayüz | safran.links |
CompanyApi, Ownership | arayüz | safran.company |
PullsApi ve türleri | arayüz | safran.pulls |
WritesApi ve türleri | arayüz | safran.writes |
ToolPacksApi, RegisteredToolPack, toolNameCollisions | arayüz, fonksiyon | safran.toolPacks |
tokenExpiry, TokenExpiry | fonksiyon | Token süresi |
linkRole, LINK_ROLE_PHRASES | fonksiyon, sabit | tickets.linkedWork |
BatchError, SafranWarning | arayüz | Ortak sonuç biçimleri |
DEFAULT_*, LINKS_DB_FILE, LINKS_SCHEMA_VERSION | sabitler | Varsayılanlar |
createGlobMatcher, matchesGlob | fonksiyonlar | Glob eşleştirme |
@safran/core, çoğu kullanıcının ve eklenti yazarının alt paketlerden ihtiyaç duyduğu adları da yeniden dışa aktarır; çoğu zaman tek bir import yeter: @safran/kit paketinden SafranError, isSafranError, toSafranError, throwIfAborted, ERROR_CODES, defineTracker, defineCodeHost, defineDocSource, defineEmbedder, PluginRegistry, isSafranPlugin, parsePluginConfig, createHttpClient, envVarName, httpUrl, wrapUntrusted, silentLogger, TRACKER_CAPABILITIES, CODE_HOST_CAPABILITIES ve alan türleri (kit başvurusu, alan türleri); @safran/profile paketinden defineProfile, DEFAULT_PROFILE_FILE ile Profile, ProfileInput, Team, GlossaryEntry türleri (profil başvurusu). Sahte bağlayıcılar @safran/kit/testing içinde kalır.
createSafran
/**
* Builds a Safran instance: loads the profile, registers plugins and builds every connector.
* Nothing here touches the network; the code index and the embedder start on first use.
*/
export async function createSafran(options: SafranOptions = {}): Promise<Safran>;tanımlandığı yer: packages/core/src/create.ts
Profili yükleyip doğrular, eklentileri kaydeder ve profildeki her iş takip sistemini, kod barındırıcıyı ve doküman kaynağını kurar. Ağa hiç çıkmaz: bağlayıcılar karşı tarafa bağlanılmadan kurulur; embedding modeli (embedder) ve kod indeksi ilk kod çağrısında başlar. Bu yüzden yalnızca iş kayıtlarıyla çalışan bir program için ne çalışan bir embedding modeli ne de diskte bir indeks gerekir.
Dönüş değeri bir Safran örneğidir. İşiniz bitince kapatın (await safran.close() ya da await using).
Fırlattığı hatalar
| Kod | Ne zaman |
|---|---|
PROFILE_INVALID | Profil dosyası yok, geçerli YAML değil ya da şemaya uymuyor. details.problems her sorunu yoluyla birlikte listeler. |
FORBIDDEN | Profilde plugins: var ve allowProfilePlugins değeri false. |
PLUGIN_NOT_FOUND | plugins: altındaki bir modül içe aktarılamıyor ya da hiç eklenti dışa aktarmıyor; ya da bir girdi, kayıtlı hiçbir eklentinin sağlamadığı bir type adını kullanıyor. |
PLUGIN_CONFIG_INVALID | Bir bağlayıcı girdisi (ya da embeddings) eklentisinin yapılandırma şemasına uymuyor ya da girdiler farklı kodlarla başarısız oldu. |
INVALID_INPUT | Bir eklentinin kind:type çifti iki kez kaydedildi (plugins ile verilen ya da profilden yüklenen bir eklenti, kayıtlı olanla çakışıyor). |
AUTH_MISSING | Bir bağlayıcı kurulurken bir sır okudu ve ortam değişkeni tanımlı değil. |
INTERNAL | Bir eklenti, listelediği bir yeteneğin metodunu uygulamayan bir bağlayıcı kurdu. |
Fonksiyon hata fırlatmadan önce her bağlayıcı girdisini dener; böylece tek bir hata bütün yapılandırma sorunlarını birden bildirir: ileti sorunları satır satır listeler, details.problems aynı satırları taşır. Bütün sorunlar aynı kodu taşıyorsa o kod kullanılır; aksi hâlde hata PLUGIN_CONFIG_INVALID olur.
import { createSafran, isSafranError } from "@safran/core";
try {
await using safran = await createSafran({ profile: "/work/acme/safran.yaml" });
console.log(safran.profile.company, [...safran.trackers.keys()]);
} catch (error) {
if (isSafranError(error, "PROFILE_INVALID")) console.error(error.format());
else throw error;
}SafranOptions
/**
* Options for `createSafran`. Every field is optional: with none, Safran reads
* `./safran.yaml`, keeps its data in `./data` and uses the built-in plugins.
*
* Convention used throughout: `undefined` means "use the default", `false` means "off".
*/
export interface SafranOptions {
/**
* The company profile: a path to a YAML file, or the profile itself.
* Default: `safran.yaml` in the current directory.
*/
profile?: string | ProfileInput;
/** Where clones, the index and caches live. Default: `data` next to the profile file. */
dataDir?: string;
/** Extra plugins, registered next to the built-in ones. A type collision is an error. */
plugins?: SafranPlugin[];
/** `false` starts with an empty registry, so only `plugins` are available. Default: true. */
builtinPlugins?: boolean;
/** Overrides the embedder built from `profile.embeddings`. */
embedder?: Embedder;
/**
* Overrides the code index. `false` disables code search entirely (tickets-only use).
* An index passed in here is owned by the caller: `close()` does not close it, so one index
* can serve several instances. Only the index Safran opens itself is closed with it.
*/
index?: CodeIndex | false;
/** Environment used to resolve secrets. Default: `process.env`. */
env?: Record<string, string | undefined>;
/** Default: silent. */
logger?: Logger;
/** Default: the global `fetch`. */
fetch?: typeof fetch;
/**
* Whether modules listed under `plugins:` in the profile may be imported (which runs their
* code). Default: true. A caller that did not choose the profile itself (a CLI picking up
* `./safran.yaml` from the working directory) passes `false`; a profile that lists plugins then
* fails with FORBIDDEN instead of executing them.
*/
allowProfilePlugins?: boolean;
/**
* The hard switch for writes. `false` makes this instance read-only whatever the profile
* says: `writes.status()` reports them off, `preview` / `commit` / `execute` fail with
* FORBIDDEN, and a server built on the instance registers no write tool. Default: true, which
* grants nothing by itself: the profile's `writes` section still has to enable them. A caller
* that did not choose the profile itself (a CLI picking up `./safran.yaml`) passes `false`,
* for the reason it passes `allowProfilePlugins: false`.
*/
allowWrites?: boolean;
/**
* The instance's clock: confirmation-token expiry, audit times, index staleness. Default: the
* real one. A seam for tests and replays; nothing in a normal setup passes it.
*/
clock?: () => Date;
/**
* The in-memory answer cache of the work surface (`WorkCacheApi`): windows per kind of
* question, size bounds, per-source concurrency. `false` turns caching off. Default: on, with
* the `DEFAULT_WORK_CACHE_…` values.
*/
workCache?: WorkCacheOptions | false;
}tanımlandığı yer: packages/core/src/api.ts
Her alan isteğe bağlıdır. undefined "varsayılanı kullan", false ise "kapalı" demektir.
| Seçenek | Tür | Varsayılan | Anlamı |
|---|---|---|---|
profile | string | ProfileInput | geçerli dizindeki safran.yaml (DEFAULT_PROFILE_FILE) | Bir YAML profilinin yolu ya da nesne olarak profilin kendisi. Nesne de dosya gibi doğrulanır. |
dataDir | string | profil dosyasının yanındaki data; satır içi profilde ./data (DEFAULT_DATA_DIR) | Klonların, indeksin, bağlantı deposunun ve önbelleklerin durduğu yer. |
plugins | SafranPlugin[] | yok | Ek eklentiler; yerleşiklerden ve profildeki plugins: girdilerinden sonra kaydedilir. Zaten kayıtlı bir kind:type hatadır (INVALID_INPUT). |
builtinPlugins | boolean | true | false verilirse kayıt defteri boş başlar; yalnızca plugins ile profilin kendi eklentileri kullanılabilir. |
embedder | Embedder | ilk kullanımda profile.embeddings girdisinden kurulur | Yapılandırılmış olanın yerine geçen canlı bir embedding modeli. |
index | CodeIndex | false | ilk kullanımda <dataDir>/index altında açılan indeks | Canlı bir indeks ya da kod aramasını kapatmak için false. Dışarıdan verilen indeks çağıranındır: close() onu kapatmaz. |
env | Record<string, string | undefined> | process.env | Profilde adı geçen sırların (*_env alanları) çözüldüğü yer. |
logger | Logger | sessiz (silentLogger) | "Arama sırasında bir iş takip sistemi başarısız oldu" gibi uyarıları alır. |
fetch | typeof fetch | global fetch | Her bağlayıcıya verilen HTTP uygulaması. |
allowProfilePlugins | boolean | true | Profildeki plugins: modüllerinin içe aktarılıp aktarılamayacağı. Profili kendisi seçmemiş bir çağıran false verir. |
allowWrites | boolean | true | Yazma işlemleri için kesin anahtar. false ise writes.status() kapalı olduklarını bildirir, preview / commit / execute FORBIDDEN ile başarısız olur ve bu örnek üzerine kurulan sunucu hiçbir yazma aracı kaydetmez. true tek başına izin vermez; kararı profilin writes bölümü verir. Profili kendisi seçmemiş bir çağıran false verir. |
clock | () => Date | gerçek saat | Onay token'ının süresi, denetim zamanları ve indeksin eskiliği için kullanılır. Testlerin ve yeniden oynatmaların araya girebildiği nokta. |
workCache | WorkCacheOptions | false | açık, DEFAULT_WORK_CACHE_… değerleriyle | İş yüzeyinin bellek içi yanıt önbelleği: soru türüne göre süreler, boyut sınırları, kaynak başına eşzamanlılık. false önbelleği kapatır; eşzamanlılık sınırı ve hız sınırı beklemesi her iki durumda da açık kalır. |
Türlerin göstermediği notlar:
index: falseikensafran.codemetotlarının tümü verepos.syncçağrısının indeksleme yarısıUNSUPPORTEDfırlatır.repos.sync({ fetchOnly: true })çalışmaya devam eder.embedderya daindexverildiğinde profilinembeddingsgirdisi oluşturma sırasında doğrulanmaz; çünkü ondan bir şey kurulmayacaktır.plugins:altındaki göreli yollar profil dosyasının dizinine göre çözülür; satır içi profilde geçerli çalışma dizinine göre.
builtinPlugins
/** Every plugin that ships with Safran. */
export const builtinPlugins: SafranPlugin[] = [...builtinTrackers, ...builtinCodeHosts, ...builtinDocSources, ...builtinEmbedders];tanımlandığı yer: packages/core/src/create.ts
Safran ile gelen bütün iş takip sistemi, kod barındırıcı, doküman kaynağı ve embedding modeli eklentileri, tek bir dizide. builtinPlugins: false verilmedikçe kayıt defteri bununla başlar. Liste bağlayıcılara genel bakış sayfasındadır.
import { builtinPlugins } from "@safran/core";
for (const plugin of builtinPlugins) console.log(plugin.kind, plugin.type, plugin.description);Safran örneği
export interface Safran extends AsyncDisposable {
readonly profile: Profile;
/** Absolute path of the profile file, when it was loaded from disk. */
readonly profileFile: string | undefined;
readonly dataDir: string;
/**
* When this instance was created, by its own clock: read before the profile file is, so a
* profile edited later than this is one the instance may not have. What "since the server
* started" means for anything serving it.
*/
readonly startedAt: Date;
/**
* The instance's clock (`SafranOptions.clock`; the system clock by default), for callers that
* must agree with it on what "now" is: token expiry, index staleness, relative ages.
*/
readonly clock: () => Date;
/** Connectors by profile entry id. Built eagerly; building them does no network I/O. */
readonly trackers: ReadonlyMap<string, Tracker>;
readonly hosts: ReadonlyMap<string, CodeHost>;
readonly docSources: ReadonlyMap<string, DocSource>;
readonly tickets: TicketsApi;
readonly code: CodeApi;
readonly docs: DocsApi;
readonly repos: ReposApi;
readonly links: LinksApi;
readonly company: CompanyApi;
/** Live pull requests (wave 2). */
readonly pulls: PullsApi;
/** The guarded write framework (wave 2). Present on every instance; disabled unless the profile and `allowWrites` say otherwise. */
readonly writes: WritesApi;
/** Namespaced JSON records in `<dataDir>/safran.db`, for plugins and for Safran's own small state. Opened on first use. */
readonly store: StoreService;
readonly toolPacks: ToolPacksApi;
/** Boards with their columns and tickets (`work-api.ts`). */
readonly boards: BoardsApi;
/** Iterations: listings, tickets and the digest of one. */
readonly iterations: IterationsApi;
/** The ticket table, the home view, teams, epics, stand-up, and the cache they read through. */
readonly work: WorkApi;
/** Who "my work" means on this instance, and on what basis. */
readonly me: MeApi;
/**
* Stops the instance: later calls fail, calls still running are cancelled (they end with
* ABORTED; `repos.sync` and `links.refresh` return their report with `aborted: true`) and are
* waited for, then the index and every open handle are released. Nothing can open a handle
* afterwards. Safe to call more than once; never rejects because a running call failed.
*/
close(): Promise<void>;
}tanımlandığı yer: packages/core/src/api.ts
| Üye | Tür | Anlamı |
|---|---|---|
profile | Profile | Doğrulanmış profil; varsayılanlar uygulanmış. |
profileFile | string | undefined | Profil dosyasının mutlak yolu; satır içi profilde undefined. |
dataDir | string | Veri dizininin mutlak yolu. |
trackers | ReadonlyMap<string, Tracker> | Profil girdisi kimliğine göre iş takip sistemleri. |
hosts | ReadonlyMap<string, CodeHost> | Profil girdisi kimliğine göre kod barındırıcılar. |
docSources | ReadonlyMap<string, DocSource> | Profil girdisi kimliğine göre doküman kaynakları. |
startedAt | Date | Bu örneğin, kendi saatine göre oluşturulduğu an. Onu sunan her şey için "sunucu başladığından beri" ifadesi bu anı kasteder. |
clock | () => Date | Örneğin saati (SafranOptions.clock; varsayılan olarak sistem saati); "şimdi" konusunda onunla aynı fikirde olması gereken çağıranlar için: token süresi, indeksin eskiliği, göreli yaşlar. |
tickets | TicketsApi | Bütün iş takip sistemleri üzerinden iş kayıtları. |
code | CodeApi | Kod indeksi üzerinde arama, grep ve okuma. |
docs | DocsApi | İş kayıtlarının bağlantı verdiği sayfalar. |
repos | ReposApi | Repoları listeleme ve eşitleme. |
links | LinksApi | Birleştirilmiş pull request'lerden iş kaydı ↔ kod geçmişi. |
company | CompanyApi | Ekipler, sözlük, kurallar, sahiplik. |
pulls | PullsApi | Canlı pull request'ler. |
writes | WritesApi | Korumalı yazma çatısı. Her örnekte vardır; profil ve allowWrites aksini söylemedikçe kapalıdır. |
store | StoreService | <dataDir>/safran.db içindeki ad alanlı JSON kayıtları. İlk kullanımda açılır. |
toolPacks | ToolPacksApi | Profilin araç paketleri. |
close | () => Promise<void> | Örneği durdurur ve bütün tutamaçları bırakır. |
boards | BoardsApi | Sütunları ve iş kayıtlarıyla board'lar. |
iterations | IterationsApi | İterasyonlar: listeler, iş kayıtları ve tek bir iterasyonun özeti. |
work | WorkApi | İş kaydı tablosu, ana görünüm, ekipler, epic'ler, günlük özet ve bunların okurken kullandığı önbellek. |
me | MeApi | Bu örnekte "benim işim" ifadesinin kimi kastettiği ve neye dayandığı. |
Bağlayıcı haritaları @safran/kit sözleşmelerine doğrudan erişim verir (örneğin safran.trackers.get("jira")?.listProjects()). Bu yoldan yapılan çağrılar örneğin yaşam döngüsünün dışındadır: close() onları iptal etmez.
close
close(): Promise<void> — aynı zamanda [Symbol.asyncDispose]; yani await using çalışır.
Sırasıyla: yeni çağrılar reddedilir, süren çağrılar iptal edilir, örnek onların bitmesini bekler (en çok DEFAULT_CLOSE_GRACE_MS, 30 saniye), ardından Safran'ın kendi açtığı indeks ve bağlantı deposu bırakılır. Birden çok kez çağrılabilir ve süren bir çağrı başarısız oldu diye asla reddetmez.
close()sonrasında yapılan çağrıINVALID_INPUTfırlatır ("This Safran instance is closed").- O sırada süren çağrı
ABORTEDile biter.repos.syncvelinks.refreshhata fırlatmaz; raporlarınıaborted: trueile döndürür.
import { isSafranError } from "@safran/core";
import { createAcme } from "./acme";
const safran = await createAcme();
await safran.close();
await safran.close(); // safe: the second call returns the same promise
try {
await safran.tickets.get("PAY-1423");
} catch (error) {
if (isSafranError(error, "INVALID_INPUT")) console.log(error.message); // "This Safran instance is closed"
}Her yerde geçerli: hatalar ve iptal
Aşağıdaki bütün metotlar üç kuralı paylaşır; bu yüzden her "Fırlattığı hatalar" listesinde yinelenmezler:
- Bilerek üretilen her hata bir
SafranErrornesnesidir;error.codeüzerinden dallanın (hatalar). Bağlayıcı hataları, bağlayıcının ürettiği kodla yüzeye çıkar:AUTH_MISSING,AUTH_FAILED,NOT_FOUND,FORBIDDEN,RATE_LIMITED,UPSTREAM. - Her eşzamansız metot son seçenek argümanında
signal?: AbortSignalkabul eder ve sinyal tetiklendiğindeABORTEDile biter. Önceden tetiklenmiş bir sinyal, çağrıyı hiçbir bağlayıcıya ulaşmadan durdurur. close()sonrasında her metotINVALID_INPUTfırlatır.
safran.tickets
/**
* 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.
*
* `get` also fills `Ticket.designLinks` (kit `extractDesignLinks` over the description, the text
* fields and the web links); connectors do not. `search` with `createdSince` leaves out, with a
* warning, every tracker that lacks the `created-since` capability.
*/
export interface TicketsApi extends TicketDepthApi {
/** 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>;
}tanımlandığı yer: packages/core/src/api.ts
İş kaydı başvurusu (ref), bir insanın yapıştıracağı şeydir: bir anahtar (PAY-1423; iş takip sistemi izin veriyorsa büyük/küçük harfe duyarsız), bir kayıt URL'si, sisteme özgü bir kısa biçim ya da açık biçim <trackerId>:<ref> (jira:PAY-1423). Bir iş takip sisteminin isteğe bağlı metotları yetenekleriyle korunur: sistemin desteklemediği bir metodu çağırmak UNSUPPORTED fırlatır; ipucunda sistemin yetenekleri yazar.
tickets.resolve
resolve(ref: string): ResolvedTicketRef — eşzamanlı, çevrimdışı.
Bir başvurunun hangi iş takip sistemine ait olduğunu ve o sistemdeki kanonik anahtarı bulur. Biçimi birden çok sistem kabul ediyorsa, profilde projects listesi anahtarın projesini içeren sistem kazanır.
| Alan | Tür | Anlamı |
|---|---|---|
tracker | Tracker | Başvuruyu tanıyan bağlayıcı. |
key | string | O sistemdeki kanonik anahtar. |
Fırlattığı hatalar Boş başvuruda ve birden çok sistem eşleşip profil karar veremediğinde INVALID_INPUT (ipucu <trackerId>:<ref> biçimini gösterir); hiçbir sistem tanımadığında ya da adı verilen sistem tanımadığında NOT_FOUND.
import { createAcme } from "./acme";
const safran = await createAcme();
const { tracker, key } = safran.tickets.resolve("https://jira.acme.example/browse/PAY-1423");
console.log(tracker.id, key); // "jira" "PAY-1423"
await safran.close();tickets.get
get(ref: string, options?: CallOptions): Promise<Ticket>
Tek bir iş kaydını getirir. Dönüş değeri bir Ticket nesnesidir: açıklama Markdown'dır, fields sisteme özgü değerleri tutar.
Fırlattığı hatalar resolve ile aynıları; sistemde böyle bir kayıt yoksa NOT_FOUND.
import { isSafranError } from "@safran/core";
import { createAcme } from "./acme";
const safran = await createAcme();
try {
const ticket = await safran.tickets.get("pay-1423");
console.log(ticket.key, ticket.project, ticket.status, ticket.url);
} catch (error) {
if (isSafranError(error, "NOT_FOUND")) console.error(error.message, error.hint);
else throw error;
} finally {
await safran.close();
}tickets.comments
comments(ref: string, options?: PageOptions): Promise<Page<Comment>>
Yorumların bir sayfası. options.limit ve options.cursor ile sayfalanır; nextCursor değerini değiştirmeden geri verin (sayfalama). Varsayılan sayfa boyutu ve sıralama iş takip sistemine aittir.
Fırlattığı hatalar resolve ile aynıları; comments yeteneği yoksa UNSUPPORTED.
import { createAcme } from "./acme";
const safran = await createAcme();
let cursor: string | undefined;
do {
const page = await safran.tickets.comments("PAY-1423", { limit: 20, ...(cursor === undefined ? {} : { cursor }) });
for (const comment of page.items) console.log(comment.author?.name, comment.body);
cursor = page.nextCursor;
} while (cursor !== undefined);
await safran.close();tickets.attachments
attachments(ref: string, options?: CallOptions): Promise<Attachment[]>
Bir iş kaydının eklerini listeler: yalnızca üst veri, içerik yok.
Fırlattığı hatalar resolve ile aynıları; attachments yeteneği yoksa UNSUPPORTED.
tickets.attachment
attachment(ref: string, attachmentId: string, options?: CallOptions): Promise<AttachmentContent>
Tek bir eki indirir. data bir Uint8Array değeridir; mimeType ve filename iş takip sisteminin bildirdiği değerlerdir, doğrulanmaz.
Fırlattığı hatalar resolve ile aynıları; attachments yeteneği yoksa UNSUPPORTED; bilinmeyen ek kimliğinde NOT_FOUND.
import { createAcme } from "./acme";
const safran = await createAcme();
for (const attachment of await safran.tickets.attachments("PAY-1423")) {
const content = await safran.tickets.attachment("PAY-1423", attachment.id);
console.log(content.filename, content.mimeType, content.data.length);
}
await safran.close();tickets.links
links(ref: string, options?: CallOptions): Promise<TicketLink[]>
İş kaydının bağlantı verdiği diğer kayıtlar ve web sayfaları. kind: "web" türündeki bir bağlantının URL'si bir doküman kaynağına aitse docs.fetch ile okunabilir.
Fırlattığı hatalar resolve ile aynıları; links yeteneği yoksa UNSUPPORTED.
import { createAcme } from "./acme";
const safran = await createAcme();
for (const link of await safran.tickets.links("PAY-1423")) {
if (link.kind === "ticket") console.log(link.relation, link.ticket?.key);
else if (link.url !== undefined && safran.docs.canFetch(link.url)) console.log("readable page:", link.url);
}
await safran.close();tickets.history
history(ref: string, options?: PageOptions): Promise<Page<HistoryEntry>>
Alan değişikliklerinin (durum geçişleri, yeniden atama) bir sayfası.
Fırlattığı hatalar resolve ile aynıları; history yeteneği yoksa UNSUPPORTED.
import { createAcme } from "./acme";
const safran = await createAcme();
const { items } = await safran.tickets.history("PAY-1423");
for (const change of items) console.log(change.at, change.field, change.from, "→", change.to);
await safran.close();tickets.search
search(query: TicketSearchQuery, options?: TicketSearchOptions): Promise<TicketSearchResult>
Aramayı destekleyen bütün iş takip sistemlerinde arar ve yanıtları tek sayfada birleştirir. Sonucu kalan her sistem limit değerinden eşit pay alır; imleç (cursor) her birinin nerede kaldığını hatırlar. Filtreler TicketSearchQuery içindedir (text, projects, statusCategories, updatedSince, native).
TicketSearchOptions, PageOptions türünü (limit, cursor, signal) şununla genişletir:
| Seçenek | Tür | Varsayılan | Anlamı |
|---|---|---|---|
tracker | string | aramayı destekleyen bütün sistemler | Aramayı tek bir iş takip sistemi girdisinin kimliğiyle sınırlar. |
limit varsayılanı DEFAULT_TICKET_SEARCH_LIMIT (50) değeridir ve DEFAULT_MAX_TICKET_SEARCH_LIMIT (500) ile sınırlanır.
TicketSearchResult, TicketSummary & { tracker: string } öğelerinden oluşan bir Page nesnesidir (items, nextCursor?) ve şunu ekler:
| Alan | Tür | Anlamı |
|---|---|---|
warnings | SafranWarning[] | Sayfa bütün sistemleri kapsamadığında bulunur: başarısız olan (koduyla birlikte) ya da bu aramayı yapamadığı için dışarıda bırakılan (UNSUPPORTED) her sistem için bir girdi. |
Hangi sistemlere sorulur:
query.nativevarsa yalnızcanative-queryyeteneği olan sistemlere.query.projectsvarsa, profilde proje bildiren ve istenenlerden hiçbirine sahip olmayan sistemler atlanır. Bu, hepsinin atlanmasına yol açacaksa hepsine sorulur.- Başarısız olan sistem imleçten çıkarılır ve
warningsiçinde bildirilir; diğerlerinin öğeleri döndürülür.
Fırlattığı hatalar Bilinmeyen tracker, en az 1 olan bir tam sayı olmayan limit ya da başka bir aramaya ait imleç için INVALID_INPUT; yapılandırılmış hiçbir sistem aramayı (ya da yerel sorguları) desteklemiyorsa veya adı verilen sistem desteklemiyorsa UNSUPPORTED. Sorulan sistemlerin hepsi başarısız olursa çağrı hata fırlatır: tek başarısızlık varsa onun kendisini, birden çoksa ilk başarısızlığın kodunu taşıyan ve bütün iletileri listeleyen bir hatayı.
import { createAcme } from "./acme";
const safran = await createAcme();
const page = await safran.tickets.search({ text: "refund", projects: ["PAY"], statusCategories: ["todo", "in_progress"] }, { limit: 10 });
for (const item of page.items) console.log(item.tracker, item.key, item.title);
for (const warning of page.warnings ?? []) console.warn(warning.source, warning.code, warning.message);
if (page.nextCursor !== undefined) console.log("more results: pass cursor", page.nextCursor);
await safran.close();tickets.children
children(ref: string, options?: PageOptions): Promise<Page<TicketChild>>
Doğrudan alt kayıtlar; tek sayfa, her biri güncel durumu ve atananıyla. children yeteneği yoksa UNSUPPORTED fırlatır.
tickets.family
family(ref: string, options?: TicketFamilyOptions): Promise<TicketFamily>
Üst kayıt, doğrudan alt kayıtlar ve kardeşler; ilerleme sayılarıyla. Her iş takip sisteminde çalışır: sağlayamadığı parça ("children") unsupported içinde listelenir ve boş döner. limit, alt kayıtları ve kardeşleri ayrı ayrı sınırlar: varsayılan DEFAULT_FAMILY_LIMIT, en çok DEFAULT_MAX_FAMILY_LIMIT.
| Alan | Tür | Anlamı |
|---|---|---|
ticket | TicketSummary | İstenen iş kaydı. |
parent | TicketSummary | Kaydın üst kaydı yoksa bulunmaz. |
children | FamilyMember[] | Doğrudan alt kayıtlar; sistemin sırasıyla. |
childProgress | FamilyProgress | Döndürülen alt kayıtlar üzerinden sayılır; childrenTruncated yanlışsa kesindir. |
childrenTruncated | boolean | Kaydın limit değerinden fazla alt kaydı varsa doğrudur. |
siblings | FamilyMember[] | Üst kaydın diğer alt kayıtları. Üst kayıt yoksa boştur. |
siblingProgress | FamilyProgress | Döndürülen kardeşler artı bu kayıt üzerinden sayılır: üst kaydın ilerlemesi. |
siblingsTruncated | boolean | Üst kaydın limit değerinden fazla alt kaydı varsa doğrudur. |
unsupported | string[] | Sistemin sağlayamadığı parçalar. |
/** How many members are in each status category. `unknown`: the tracker gave no category. */
export interface FamilyProgress {
total: number;
todo: number;
inProgress: number;
done: number;
unknown: number;
}
export interface TicketFamilyOptions extends CallOptions {
/** Most children and most siblings returned (each). Default `DEFAULT_FAMILY_LIMIT`, max `DEFAULT_MAX_FAMILY_LIMIT`. */
limit?: number;
}tanımlandığı yer: packages/core/src/api.ts
tickets.linkedWork
linkedWork(ref: string, options?: LinkedWorkOptions): Promise<LinkedWork>
Bir iş kaydının bağlantıları; "başlayabilir miyim, başka ne okumalıyım" sorusu için özetlenmiş. Bağlı kayıtlar güncel durumları için yeniden okunur: en çok DEFAULT_LINKED_WORK_MAX_TICKETS tanesi, aynı anda DEFAULT_LINKED_WORK_CONCURRENCY tanesi. links yeteneği yoksa UNSUPPORTED, 0 ya da daha büyük bir tam sayı olmayan expandBodies için INVALID_INPUT fırlatır.
| Alan | Tür | Anlamı |
|---|---|---|
ticket | TicketSummary | İstenen iş kaydı. |
verdict | "blocked" | "not_blocked" | "unknown" | En az bir engelleyici bitmemişse blocked; her engelleyici bitmişse ya da hiç yoksa not_blocked; bir engelleyicinin durumu okunamadıysa unknown. |
reasons | string[] | Kararı belirleyen her engelleyici için bir satır. Yalnızca anahtarlar ve durum adları. |
unfinishedBlockers | LinkedTicket[] | Bitmemiş engelleyiciler; gövdesi olanlar başta. |
finishedBlockers | LinkedTicket[] | Bitmiş engelleyiciler. |
blocks | LinkedTicket[] | Bu kaydı bekleyen kayıtlar. |
related | LinkedTicket[] | Geri kalan her şey; yinelenenler dâhil (role hangisi olduğunu söyler). |
counterparts | CounterpartTicket[] | Aynı işin başka bir tarafına ait kayıtlar; bir bağlantıyla değil, tickets.title_prefixes ile bulunur. |
web | { relation, url, title? }[] | Sistemin verdiği hâliyle web bağlantıları. |
warnings | SafranWarning[] | Şu an okunamayan bağlı kayıtlar; bağlantı verileri yine de listelerdedir. |
unsupported | string[] | Sistemin sağlayamadığı parçalar. |
export interface LinkedTicket extends TicketSummary {
/** The relation as the tracker words it. */
relation: string;
role: LinkRole;
/** Current status category, read now (a link's own snapshot may be old). Absent when the ticket could not be read. */
statusCategory?: StatusCategory;
assignee?: Person;
/**
* The ticket's description (Markdown), cut to `bodyChars`. Present only for unfinished
* blockers and counterparts, at most `expandBodies` of them, blockers first.
*/
body?: string;
bodyTruncated?: boolean;
}
/** A ticket for the other side of the same feature, found through the profile's title prefixes, not through a link. */
export interface CounterpartTicket extends LinkedTicket {
/** The side its title prefix names (a key of `tickets.title_prefixes`). */
side: string;
}
/**
* What a link means for doing the work, decided from the tracker's relation wording:
* `blocker` (this ticket is blocked by / depends on it), `blocks` (it waits for this ticket),
* `duplicate`, `related` (everything else).
*/
export type LinkRole = "blocker" | "blocks" | "duplicate" | "related";
export interface LinkedWorkOptions extends CallOptions {
/** How many unfinished blockers and counterparts get their body. Default `DEFAULT_LINKED_WORK_BODIES` (3); 0 for none. */
expandBodies?: number;
/** Characters of each body. Default `DEFAULT_LINKED_WORK_BODY_CHARS`. */
bodyChars?: number;
/** Look for counterpart tickets. Default: true when the profile has `tickets.title_prefixes` and the tracker can search. */
counterparts?: boolean;
}tanımlandığı yer: packages/core/src/api.ts
linkRole(relation) ve LINK_ROLE_PHRASES, bir sistemin ilişki ifadesinden LinkRole değerine giden eşlemedir; bağlantıları kendisi sınıflandıran çağıranlar için dışa aktarılır.
/** The role of one relation, by `LINK_ROLE_PHRASES`. */
export function linkRole(relation: string): LinkRole;tanımlandığı yer: packages/core/src/ticket-depth.ts
tickets.changes
changes(ref: string, options?: TicketChangesOptions): Promise<TicketChanges>
Bir iş kaydına belli bir andan beri ne olduğu: bir HistoryDigest ve pencere içinde oluşturulan yorumlar. Sistemde ne history ne de comments varsa UNSUPPORTED; tarih, süre ya da last_status_change olmayan bir since için INVALID_INPUT fırlatır.
export interface TicketChangesOptions extends CallOptions {
/**
* Where the window starts: an ISO date or date-time, a duration back from now (`36h`, `3d`,
* `2w`), or `"last_status_change"` (everything since the ticket last changed status).
* Default: `"last_status_change"`.
*/
since?: string;
/** Clock, for durations and for the time in the current status. Default: now. */
now?: Date;
/** History entries read at most. Default `DEFAULT_CHANGES_HISTORY_LIMIT`. */
historyLimit?: number;
/** New comments returned at most. Default `DEFAULT_CHANGES_COMMENT_LIMIT`. */
commentLimit?: number;
}
/** "What happened to this ticket since …", in one answer. */
export interface TicketChanges {
ticket: TicketSummary;
/** Start of the window as an ISO time. Absent when it could not be determined (no status change on record): the digest then covers everything read. */
since?: string;
digest: HistoryDigest;
/** False when the history was longer than `historyLimit`: older entries were not read, so durations of early statuses may be missing. */
historyComplete: boolean;
/** Comments created inside the window, oldest first. */
comments: Comment[];
commentsTruncated: boolean;
/** Of "history", "comments": what the tracker cannot provide. */
unsupported: string[];
}tanımlandığı yer: packages/core/src/api.ts
tickets.worklogs ve tickets.time
worklogs(ref: string, options?: PageOptions): Promise<Page<Worklog>> · time(ref: string, options?: TicketTimeOptions): Promise<TicketTime>
worklogs, girilen çalışmaların tek sayfasıdır ve worklogs yeteneği yoksa UNSUPPORTED fırlatır. time, sistemin süre özetini, çalışma günlüklerini (en çok worklogLimit; varsayılan DEFAULT_TIME_WORKLOG_LIMIT) ve iterasyonları tek yanıtta toplar; bütün olarak hiçbir zaman UNSUPPORTED olmaz.
export interface TicketTimeOptions extends CallOptions {
/** Worklogs read at most. Default `DEFAULT_TIME_WORKLOG_LIMIT`. */
worklogLimit?: number;
}
/** Estimate, logged work and scheduling of one ticket, each part present when the tracker has it. */
export interface TicketTime {
ticket: TicketSummary;
tracking?: TimeTracking;
/** Oldest first. */
worklogs: Worklog[];
/** True when the ticket has more worklogs than were read; the sums below then cover only those read. */
worklogsTruncated: boolean;
/** Seconds logged per person, most first, over the worklogs read. */
loggedByPerson: { person: string; seconds: number }[];
/** Oldest first, current last. */
iterations: Iteration[];
/** Of "worklogs", "time-tracking", "iterations": what the tracker cannot provide. */
unsupported: string[];
}tanımlandığı yer: packages/core/src/api.ts
safran.code
export interface CodeApi {
search(query: string, options?: SafranCodeSearchOptions): Promise<CodeSearchResult>;
/** `GrepResult.byRepo` and `byRepoExact` are always present here: taken from the index when it counts, otherwise counted over `matches` (then exact only when `truncated` is false). */
grep(pattern: string, options?: SafranGrepOptions): Promise<GrepResult>;
/** The slice carries `indexedAt` and `stale` of its repository (the rule of `isIndexStale`), unless the index status cannot be read. */
readFile(repo: string, path: string, range?: { startLine?: number; endLine?: number }, options?: CallOptions): Promise<FileSlice>;
status(options?: CallOptions): Promise<IndexStatus>;
}tanımlandığı yer: packages/core/src/api.ts
Dört metot da ilk kullanımda açılan yerel kod indeksini okur. Yanıtlar kod barındırıcılardan değil, son repos.sync çalışmasından gelir.
Dördünde de ortak: örnek index: false ile oluşturulduysa UNSUPPORTED; indeks henüz yanıt veremiyorsa INDEX_NOT_READY (örneğin başka bir embedding modeliyle oluşturulmuştur; ipucu ne çalıştırılacağını söyler); diskteki indeks daha yeni bir sürümle yazıldıysa INCOMPATIBLE_DATA. İlk çağrı, embedding modelinin yapılandırma ya da bağlantı hatalarını da yüzeye çıkarabilir; çünkü model o anda kurulur.
code.search
search(query: string, options?: SafranCodeSearchOptions): Promise<CodeSearchResult>
Anlama ve sözcüklere göre sıralı arama. Sorgu indekse ulaşmadan önce, içinde bulunan sözlük terimleri kod tarafındaki karşılıklarını ekler (İade → refund, chargeback); sorguda zaten bulunan sözcükler ikinci kez eklenmez.
SafranCodeSearchOptions, CodeSearchOptions türünü (repos, groups, languages, kinds, pathPrefix, limit, mode, snippetLines, signal) şununla genişletir:
| Seçenek | Tür | Varsayılan | Anlamı |
|---|---|---|---|
expandGlossary | boolean | true | Sorguda bulunan sözlük terimlerinin kod tarafındaki sözcüklerini ekler. |
allGroups | string[] | yok | Yalnızca bu grupların hepsinde birden bulunan repolar (kesişim); groups ise birleşimdir. İkisi birlikte verilebilir. Bilinmeyen adlar INVALID_INPUT olur. |
| Alan | Tür | Anlamı |
|---|---|---|
hits | CodeHit[] | Sıralı sonuçlar. score yalnızca bu liste içinde karşılaştırılabilir. |
effectiveQuery | string | Sözlük genişletmesinden sonra indekse gerçekten gönderilen sorgu. |
glossary | GlossaryEntry[] | Devreye giren sözlük girdileri; hiçbiri girmediyse ya da expandGlossary değeri false ise boştur. |
byRepo | { repo: string; hits: number }[] | hits içindeki sonuçların repo başına sayısı; en çok olan başta. |
Kapsam kuralları: groups, profildeki code.groups üzerinden çözülür. Birden çok grup kapsamı genişletir (birleşim); groups ile birlikte verilen repos daraltır (kesişim). Hiçbir şeyle eşleşemeyecek bir kapsam, indekse sorulmadan boş sonuç döndürür.
Fırlattığı hatalar Profilin tanımlamadığı bir grup için (details.known tanımlı olanları listeler) ve indeksin reddettiği değerler için (geçersiz limit gibi) INVALID_INPUT.
import { createAcme } from "./acme";
const safran = await createAcme();
const result = await safran.code.search("kısmi iade nerede yapılıyor", { groups: ["backend"], limit: 5 });
console.log(result.effectiveQuery, result.glossary.map((entry) => entry.term));
for (const hit of result.hits) {
console.log(`${hit.repo} ${hit.path}:${hit.startLine}-${hit.endLine}`, hit.channels);
console.log(hit.snippet);
}
await safran.close();code.grep
grep(pattern: string, options?: SafranGrepOptions): Promise<GrepResult>
Tam eşleşme araması: düz bir string ya da regex: true ile bir düzenli ifade. Sıralı aramanın örneklem döndürdüğü yerde eksiksiz liste ve sayım için bunu kullanın. GrepOptions, aramayla aynı kapsam filtrelerini ve ek olarak caseSensitive, wholeWord, pathGlob, context, limit alanlarını alır.
Dönüş değeri bir GrepResult nesnesidir: matches, total (limit ötesindekiler dâhil bütün eşleşmeler), truncated ve bazı repolar tümüyle taranamadığında incomplete.
Fırlattığı hatalar Bilinmeyen grup ya da indeksin reddettiği bir kalıp veya seçenek (örneğin geçersiz bir düzenli ifade) için INVALID_INPUT.
import { createAcme } from "./acme";
const safran = await createAcme();
const result = await safran.code.grep("refundPartially", { repos: ["payments-api"], wholeWord: true, context: 1 });
console.log(`${result.matches.length} of ${result.total}`, result.truncated ? "(truncated)" : "");
for (const match of result.matches) console.log(`${match.repo} ${match.path}:${match.line}`, match.text);
await safran.close();code.readFile
readFile(repo: string, path: string, range?: { startLine?: number; endLine?: number }, options?: CallOptions): Promise<FileSlice>
İndekslenmiş bir repodan bir dosyayı ya da dosyanın bir satır aralığını okur. Satırlar 1'den başlar ve uçlar dâhildir. Aralık verilmezse indeks kendi varsayılanına kadar olan ilk satırları döndürür; FileSlice içindeki truncated ve totalLines devamı olup olmadığını söyler.
Fırlattığı hatalar İndekslenmemiş bir repo ya da repoda bulunmayan bir yol için NOT_FOUND; reponun dışına çıkan bir yol ya da anlamsız bir aralık için INVALID_INPUT.
import { createAcme } from "./acme";
const safran = await createAcme();
const slice = await safran.code.readFile("payments-api", "src/refund/service.ts", { startLine: 1, endLine: 3 });
console.log(`${slice.path}:${slice.startLine}-${slice.endLine} of ${slice.totalLines}`);
console.log(slice.content);
await safran.close();code.status
status(options?: CallOptions): Promise<IndexStatus>
İndeksin ne tuttuğu: embedding modelinin kimliği, indekslenmiş her repo için bir satır (dosya, parça sayısı, indexedAt) ve toplam parça sayısı. IndexStatus türüne bakın.
import { createAcme } from "./acme";
const safran = await createAcme();
const status = await safran.code.status();
console.log(status.embedder, status.chunks);
for (const repo of status.repos) console.log(repo.name, repo.files, repo.indexedAt ?? "never indexed");
await safran.close();safran.docs
/** Pages that tickets link to (wiki, specs), fetched through the profile's doc sources. */
export interface DocsApi {
/** Whether any configured source recognises the URL. Offline. */
canFetch(url: string): boolean;
/** Throws UNSUPPORTED when no doc source recognises the URL. Safran never fetches arbitrary URLs. */
fetch(url: string, options?: CallOptions): Promise<DocPage>;
}tanımlandığı yer: packages/core/src/api.ts
İş kayıtlarının bağlantı verdiği sayfalar. Safran bir URL'yi yalnızca profildeki bir doküman kaynağı sahiplendiğinde getirir; rastgele URL'leri asla getirmez.
docs.canFetch
canFetch(url: string): boolean — eşzamanlı, çevrimdışı.
Verilen string bir http(s) URL'si ise ve yapılandırılmış bir doküman kaynağı onu tanıyorsa true. Bozuk bir URL için hata fırlatmaz; false döndürür.
docs.fetch
fetch(url: string, options?: CallOptions): Promise<DocPage>
Sayfayı, URL'yi tanıyan ilk doküman kaynağı üzerinden getirir. DocPage içeriği Markdown'dır.
Fırlattığı hatalar String bir http(s) URL'si değilse INVALID_INPUT; hiçbir doküman kaynağı tanımıyorsa UNSUPPORTED (details.sources yapılandırılmış kimlikleri listeler); kaynaktan gelen NOT_FOUND ve FORBIDDEN (var olmayan bir sayfa, izin listesinin dışında bir alan).
import { createAcme } from "./acme";
const safran = await createAcme();
const url = "https://jira.acme.example/wiki/spaces/PAY/pages/1/Refunds";
if (safran.docs.canFetch(url)) {
const page = await safran.docs.fetch(url);
console.log(page.source, page.title, page.content.length);
}
await safran.close();safran.repos
export interface ReposApi {
/** Repos from every host, filtered by each host's include/exclude. */
list(options?: CallOptions & { refresh?: boolean; /** Ask each host for its remote heads to fill `behind` (one call per cloned repo). Default false. */ checkRemote?: boolean }): Promise<ManagedRepo[]>;
/**
* Problems of the most recent listing (by `list`, `get`, `sync` or a links refresh): hosts
* that could not list their repos (with the code of the failure), a host that lists one name
* twice (UPSTREAM), and a short name that exists on two hosts and how it was resolved
* (INVALID_INPUT: the name alone is ambiguous). Empty when the listing was complete and
* unambiguous, and before the first listing.
*/
warnings(): SafranWarning[];
/** Looks one up by short name. Throws NOT_FOUND with the closest names as a hint. */
get(name: string, options?: CallOptions): Promise<ManagedRepo>;
/**
* Clones or fetches working trees, then indexes what changed. Without `repos` it asks the
* hosts for their repos again instead of using the cached listing.
*
* Throws only before any work starts: NOT_FOUND for an unknown repo name, the listing error
* when no host can list its repos, UNSUPPORTED when indexing is asked for but off. From then on
* it always returns a report: a failing repo is a "failed" row, a cancelled run has
* `aborted: true`. Calls on one instance run one after the other; a repo another process is
* syncing is "skipped" with a `reason`.
*/
sync(options?: SyncOptions): Promise<SyncReport>;
}tanımlandığı yer: packages/core/src/api.ts
repos.list
list(options?: CallOptions & { refresh?: boolean; checkRemote?: boolean }): Promise<ManagedRepo[]>
Her kod barındırıcının, kendi include / exclude filtreinden sonra listelediği repolar. Liste örnek başına önbelleğe alınır; refresh: true barındırıcılara yeniden sorar. Bir barındırıcısı eksik kalan liste döndürülür ama önbelleğe alınmaz; sonraki çağrı o barındırıcıyı yeniden dener. Listeleme sorunları repos.warnings ile okunur.
ManagedRepo, RepoInfo türünü (name, fullName, defaultBranch, cloneUrl, …) şunlarla genişletir:
| Alan | Tür | Anlamı |
|---|---|---|
host | string | Kod barındırıcı girdisinin kimliği. |
groups | string[] | Reponun profilde ait olduğu gruplar. |
teams | string[] | Profilde repoya sahip olan ekiplerin adları. |
dir | string | Çalışma ağacının mutlak yolu. local barındırıcılarda kaynak dizinin kendisidir. |
cloned | boolean | Çalışma ağacının diskte bulunup bulunmadığı. |
head | string | Klonlanmışsa çalışma ağacının üzerinde durduğu commit. |
indexedAt | string | Son başarılı indeksleme çalışmasının ISO zamanı. Hiç indekslenmediyse, kod araması kapalıysa ve diskteki indeks açılamadıysa bulunmaz. Okunması asla indeks oluşturmaz ve embedding modeline çağrı yapmaz. |
indexedFiles | number | Bu reponun indeksteki dosya sayısı. Tam olarak indexedAt yokken bulunmaz. |
indexedChunks | number | Bu reponun indeksteki parça sayısı. Tam olarak indexedAt yokken bulunmaz. |
stale | boolean | Bu reponun indeksi DEFAULT_INDEX_STALE_AFTER_DAYS günden eskiyse ya da başka bir embedding modeliyle kurulduysa doğrudur. Hiç indekslenmediyse bulunmaz. |
behind | boolean | Barındırıcıdaki varsayılan dal çalışma ağacından farklı bir commit'teyse doğrudur. Yalnızca listeleme checkRemote ile istendiyse, barındırıcıda remote-head varsa ve repo klonlanmışsa bulunur; sorulamayan barındırıcı alanı boş bırakır ve bir uyarı ekler. |
Fırlattığı hatalar Hiçbir barındırıcı repolarını listeleyemediğinde listeleme hatası: tek başarısızlık varsa kendisi, birden çoksa ilk başarısızlığın kodunu ve her barındırıcının iletisini taşıyan bir hata.
import { createAcme } from "./acme";
const safran = await createAcme();
for (const repo of await safran.repos.list()) {
console.log(repo.host, repo.name, repo.groups, repo.teams, repo.cloned ? repo.dir : "not cloned", repo.indexedAt ?? "not indexed");
}
await safran.close();repos.warnings
warnings(): SafranWarning[] — eşzamanlı.
En son listelemenin (list, get, sync ya da bir bağlantı yenilemesi tarafından yapılan) sorunları: repolarını listeleyemeyen bir barındırıcı (hatanın koduyla), aynı adı iki kez listeleyen bir barındırıcı (UPSTREAM) ve iki barındırıcıda birden bulunan bir kısa ad ile nasıl çözüldüğü (INVALID_INPUT). Liste eksiksiz ve belirsizlik içermiyorsa, ayrıca ilk listelemeden önce boştur.
import { createAcme } from "./acme";
const safran = await createAcme();
const repos = await safran.repos.list({ refresh: true });
for (const warning of safran.repos.warnings()) console.warn(`${warning.source}: ${warning.code} ${warning.message}`);
console.log(repos.length);
await safran.close();repos.get
get(name: string, options?: CallOptions): Promise<ManagedRepo>
Bir repoyu kısa adıyla bulur. Tam eşleşme önceliklidir; yoksa büyük/küçük harfe duyarsız eşleşme, tek ise kabul edilir.
Fırlattığı hatalar NOT_FOUND; en yakın adlar ipucunda ("Did you mean: payments-api?", en çok DEFAULT_SUGGESTIONS adet) ve details.closest içinde yer alır.
import { isSafranError } from "@safran/core";
import { createAcme } from "./acme";
const safran = await createAcme();
try {
await safran.repos.get("payment-api");
} catch (error) {
if (isSafranError(error, "NOT_FOUND")) console.log(error.message, "→", error.hint);
}
await safran.close();repos.sync
sync(options?: SyncOptions): Promise<SyncReport>
Çalışma ağaçlarını <dataDir>/repos altına klonlar ya da günceller, ardından değişeni indeksler. local barındırıcının repoları yerinde okunur. repos verilmezse barındırıcılardan güncel bir liste ister. Aynı örnek üzerindeki çağrılar sırayla çalışır; başka bir sürecin eşitlemekte olduğu repo, bir reason ile birlikte skipped olarak bildirilir.
SyncOptions, CallOptions türünü (signal) şunlarla genişletir:
| Seçenek | Tür | Varsayılan | Anlamı |
|---|---|---|---|
repos | string[] | listelenen bütün repolar | Eşitlenecek repo adları. |
offline | boolean | false | Git fetch adımını atlar; diskte olanı indeksler. |
fetchOnly | boolean | false | Çalışma ağaçlarını günceller; indekslemez. |
onProgress | (progress: SyncProgress) => void | yok | Her repo aşamalarından geçerken çağrılır. |
| Alan | Tür | Anlamı |
|---|---|---|
repo | string | Repo adı. |
phase | "fetch" | "scan" | "chunk" | "embed" | "write" | fetch ya da indeksleme çalışmasının bir aşaması. |
done | number | Bu aşamada biten birim sayısı. |
total | number | Bu aşamadaki toplam birim sayısı. |
| Alan | Tür | Anlamı |
|---|---|---|
results | RepoSyncResult[] | Repo başına bir satır. |
durationMs | number | Çalışmanın toplam süresi. |
removed | string[] | Artık hiçbir barındırıcı listelemediği için indeksten çıkarılan repolar. Bunu yalnızca bütün barındırıcıların yanıt verdiği, bütün repoları kapsayan bir eşitleme yapar; o da yalnızca örneğin kendi açtığı indekste. |
aborted | boolean | Çalışma sinyalle ya da close() ile iptal edildiyse true. |
| Alan | Tür | Anlamı |
|---|---|---|
repo | string | Repo adı. |
status | "ok" | "failed" | "skipped" | Bu reponun sonucu. |
updated | boolean | Çalışma ağacının yeni bir commit'e geçip geçmediği. |
head | string | Çalışma ağacının üzerinde durduğu commit. |
index | IndexRepoResult | İndeksleme çalışmasının sayıları (IndexRepoResult). |
error | BatchError | status değeri "failed" ise bulunur. |
reason | string | status değeri, repoyu başka bir eşitleme tuttuğu için "skipped" ise bulunur. |
Fırlattığı hatalar Yalnızca iş başlamadan önce: bilinmeyen repo adları için NOT_FOUND (hepsi birden bildirilir), hiçbir barındırıcı repolarını listeleyemediğinde listeleme hatası, indeksleme istenip kod araması kapalıysa UNSUPPORTED. Bundan sonra her zaman rapor döndürür: başarısız repo bir "failed" satırıdır; iptal edilen çalışma aborted: true taşır, yarıda kalan ve sıra gelmeyen repolar "skipped" olur.
import { createAcme } from "./acme";
const safran = await createAcme();
const report = await safran.repos.sync({
repos: ["payments-api"],
onProgress: ({ repo, phase, done, total }) => console.log(repo, phase, `${done}/${total}`),
});
for (const result of report.results) {
if (result.status === "failed") console.error(result.repo, result.error?.code, result.error?.message, result.error?.hint);
else console.log(result.repo, result.status, result.index?.filesIndexed, result.reason ?? "");
}
if (report.aborted) console.log("cancelled; run it again to continue");
await safran.close();safran.links
/**
* History of finished work: which tickets changed which files. Built from merged pull
* requests, stored locally. It powers "what did similar tickets touch", team inference
* in discovery, and the evaluation golden set.
*/
export interface LinksApi {
/**
* Pulls merged PRs from the code hosts into the local store.
*
* Hosts are expected to list merged pull requests newest first, so a run stopped by
* `maxPerRepo` holds the newest ones; the next run skips what is stored and continues towards
* the horizon. Correctness does not depend on the order: a repo counts as complete only once a
* listing was read to its end.
*
* Throws only before any work starts (NOT_FOUND for an unknown repo, a listing error, an
* unreadable store). From then on it always returns a report: a failing repo is a "failed" row
* and a cancelled run has `aborted: true` with the repos not finished "skipped". Calls on one
* instance run one after the other.
*/
refresh(options?: LinkRefreshOptions): Promise<LinkRefreshReport>;
/**
* Recomputes the ticket keys of every stored record from its stored title, branch and
* description (host-native links are kept). No network call. Use it after the profile's
* project keys changed.
*/
relink(options?: RelinkOptions): Promise<RelinkReport>;
/** Records matching the query, newest first. Reads the local store only. */
query(query?: WorkQuery, options?: CallOptions): Promise<WorkRecord[]>;
/**
* The same records one page at a time: `limit` is the page size and `nextCursor` (present while
* more match) goes back as `WorkQuery.cursor`. A cursor made for other filters is INVALID_INPUT.
*/
queryPage(query?: WorkQuery, options?: CallOptions): Promise<Page<WorkRecord>>;
/** How many records match the query (`limit` is ignored). Reads the local store only. */
count(query?: WorkQuery, options?: CallOptions): Promise<number>;
/** Number of stored records and the time of the last refresh. */
status(options?: CallOptions): Promise<LinksStatus>;
}tanımlandığı yer: packages/core/src/api.ts
Bağlantı deposu, veri dizinindeki yerel bir SQLite dosyasıdır: safran.db (LINKS_DB_FILE). Bir kod barındırıcıya ulaşan tek metot refresh metodudur; diğerleri yerel depoyu okur ya da yeniden yazar. Daha yeni bir Safran'ın yazdığı depo ya da okunabilir bir veritabanı olmayan dosya, yeniden oluşturma ipucuyla birlikte INCOMPATIBLE_DATA fırlatır.
links.refresh
refresh(options?: LinkRefreshOptions): Promise<LinkRefreshReport>
Birleştirilmiş pull request'leri kod barındırıcılardan depoya çeker ve başlıklarında, dallarında, açıklamalarında iş kaydı anahtarlarını tanır (barındırıcının kendi iş kaydı bağlantıları da korunur). maxPerRepo nedeniyle duran bir çalışma en yeni pull request'leri tutar; sonraki çalışma ufka doğru devam eder.
LinkRefreshOptions, CallOptions türünü (signal) şunlarla genişletir:
| Seçenek | Tür | Varsayılan | Anlamı |
|---|---|---|---|
repos | string[] | listelenen bütün repolar | Yenilenecek repo adları. |
since | string | reponun önceki yenilemelerindeki ufuk; ilk yenilemede DEFAULT_LINKS_LOOKBACK_MONTHS (12) ay geriye | Saklanan geçmişin ulaşması gereken ISO tarihi. |
maxPerRepo | number | DEFAULT_LINKS_MAX_PER_REPO (500) | Tek çalışmada repo başına yeni saklanan pull request sayısının üst sınırı. |
projectKeys | string[] | profildeki trackers[].projects altındaki bütün projeler | İş kaydı anahtarlarını tanımak için kullanılan proje anahtarları. |
onProgress | (progress: { repo: string; fetched: number }) => void | yok | Bir reponun pull request'leri okundukça çağrılır. |
| Alan | Tür | Anlamı |
|---|---|---|
repos | LinkRefreshRepoResult[] | Repo başına bir satır. |
durationMs | number | Çalışmanın toplam süresi. |
aborted | boolean | Çalışma iptal edildiyse true. Bunun yerine asla hata fırlatılmaz. |
| Alan | Tür | Anlamı |
|---|---|---|
repo | string | Repo adı. |
status | "ok" | "failed" | "skipped" | "skipped": çalışma, bu repo tümüyle okunmadan iptal edildi; repodan hiçbir şey saklanmadı. |
fetched | number | Bu çalışmada depoya yazılan pull request'ler (yeniler ve yeniden görülen saklı olanlar). |
linked | number | Bunlardan kaçının en az bir iş kaydı anahtarı taşıdığı. |
truncated | boolean | maxPerRepo çalışmayı durdurduğu için bağlantı deposu bu repo için ufka kadar ulaşmıyorken true. |
error | BatchError | status değeri "failed" ise bulunur. pull-requests yeteneği olmayan barındırıcı, repolarını UNSUPPORTED ile başarısız kılar. |
Fırlattığı hatalar Yalnızca iş başlamadan önce: tarih olmayan bir since, en az 1 olan bir tam sayı olmayan maxPerRepo ya da boş olmayan string'lerden oluşmayan projectKeys için INVALID_INPUT; bilinmeyen repo için NOT_FOUND; listeleme hatası; okunamayan depo için INCOMPATIBLE_DATA. Çağrıdan önce tetiklenmiş bir sinyalde bile aborted: true taşıyan bir rapor döner.
import { createAcme } from "./acme";
const safran = await createAcme();
const report = await safran.links.refresh({ since: "2026-01-01", maxPerRepo: 200 });
for (const repo of report.repos) {
console.log(repo.repo, repo.status, `${repo.linked}/${repo.fetched} linked`, repo.truncated ? "run again to continue" : "");
if (repo.error) console.error(repo.error.code, repo.error.message);
}
await safran.close();links.relink
relink(options?: RelinkOptions): Promise<RelinkReport>
Saklanan her kaydın iş kaydı anahtarlarını, saklanan başlığından, dalından ve açıklamasından yeniden hesaplar. Ağ çağrısı yapmaz. Profilin proje anahtarları değiştikten sonra çalıştırın.
| Seçenek | Tür | Varsayılan | Anlamı |
|---|---|---|---|
projectKeys | string[] | profildeki trackers[].projects altındaki bütün projeler | LinkRefreshOptions içindekiyle aynı anlam. |
| Alan | Tür | Anlamı |
|---|---|---|
records | number | Bakılan saklı kayıt sayısı. |
linked | number | Sonrasında en az bir iş kaydı anahtarı taşıyan kayıtlar. |
changed | number | İş kaydı anahtarları öncekinden farklı olan kayıtlar. |
Fırlattığı hatalar Geçersiz projectKeys için INVALID_INPUT; iptal edildiğinde ABORTED (kayıtlar gruplar hâlinde yeniden yazılır; her biri ya eski ya yeni hâldedir).
import { createAcme } from "./acme";
const safran = await createAcme();
await safran.links.refresh();
const report = await safran.links.relink({ projectKeys: ["PAY", "MOB", "WEB", "OPS"] });
console.log(`${report.changed} of ${report.records} records changed; ${report.linked} linked`);
await safran.close();links.query
query(query?: WorkQuery, options?: CallOptions): Promise<WorkRecord[]>
Sorguyla eşleşen kayıtlar, en yeniden eskiye. Yalnızca yerel depoyu okur; boş depo boş dizi verir.
| Alan | Tür | Anlamı |
|---|---|---|
ticket | string | Kaydın ait olduğu iş kaydı anahtarı. |
repo | string | Repo adı. |
path | string | Repoya göreli dosya yolu; onu değiştiren kayıtlarla eşleşir. |
since | string | ISO tarihi; mergedAt için alt sınır (dâhil). |
until | string | ISO tarihi; mergedAt için üst sınır (hariç). |
limit | number | Yalnızca query kullanır. Varsayılan DEFAULT_WORK_QUERY_LIMIT (100); DEFAULT_MAX_WORK_QUERY_LIMIT ile sınırlanır. |
cursor | string | Aynı filtrelerle yapılan önceki queryPage çağrısının nextCursor değeri. Başka filtreler için üretilmiş bir imleç INVALID_INPUT olur. Yalnızca query ve queryPage kullanır. |
WorkRecord, PullRequest türünü (id, repo, title, description, url, author, sourceBranch, mergedAt, …) şunlarla genişletir:
| Alan | Tür | Anlamı |
|---|---|---|
host | string | Kod barındırıcı girdisinin kimliği. |
ticketKeys | string[] | Barındırıcının kendi bağlantıları ile başlıkta, dalda ve açıklamada tanınan anahtarlar. |
changedFiles | string[] | Pull request'in dokunduğu, repoya göreli yollar. |
Fırlattığı hatalar Tarih olmayan since / until ya da en az 1 olan bir tam sayı olmayan limit için INVALID_INPUT.
import { createAcme } from "./acme";
const safran = await createAcme();
await safran.links.refresh();
const forTicket = await safran.links.query({ ticket: "PAY-1423" });
const forFile = await safran.links.query({ repo: "payments-api", path: "src/refund/service.ts", since: "2026-01-01", limit: 20 });
for (const record of [...forTicket, ...forFile]) console.log(record.mergedAt, record.id, record.title, record.ticketKeys);
await safran.close();links.count
count(query?: WorkQuery, options?: CallOptions): Promise<number>
Sorguyla kaç kaydın eşleştiği. limit yok sayılır. Yalnızca yerel depoyu okur.
import { createAcme } from "./acme";
const safran = await createAcme();
await safran.links.refresh();
console.log(await safran.links.count({ repo: "payments-api" }), "merged pull requests stored for payments-api");
await safran.close();links.status
status(options?: CallOptions): Promise<LinksStatus>
| Alan | Tür | Anlamı |
|---|---|---|
records | number | Saklanan kayıt sayısı. |
linked | number | En az bir iş kaydı anahtarı taşıyan kayıtlar. |
refreshedAt | string | En az bir reponun başarılı olduğu son yenilemenin ISO zamanı. Öncesinde bulunmaz. |
incompleteRepos | string[] | Saklanan geçmişi henüz ufkuna ulaşmayan repolar. |
import { createAcme } from "./acme";
const safran = await createAcme();
const status = await safran.links.status();
console.log(status.records, status.linked, status.refreshedAt ?? "never refreshed", status.incompleteRepos);
await safran.close();safran.pulls
/**
* Live pull requests across every code host of the profile, with the conventions of
* `TicketsApi`. `ref` is whatever a person would paste: a pull request URL, the explicit form
* `<host id>:<repo>#<id>`, or `<repo>#<id>` when the repo name is unique across hosts
* (`!` is accepted for `#`). A host without the needed capability makes the call UNSUPPORTED,
* naming the host and its capabilities.
*/
export interface PullsApi {
/**
* Finds the host and repo a reference belongs to. NOT_FOUND when no host recognises it,
* INVALID_INPUT when several do (the hint shows the explicit form). Asynchronous, unlike
* `tickets.resolve`: the `<repo>#<id>` form needs the repo listing. It does not check that the
* pull request exists.
*/
resolve(ref: string, options?: CallOptions): Promise<ResolvedPullRequestRef>;
find(query: PullRequestFindQuery, options?: PullRequestFindOptions): Promise<PullRequestFindResult>;
/** One merged page over hosts and repos, roughly newest first. The cursor is opaque and belongs to the same options. */
list(options?: PullRequestListOptions): Promise<PullRequestListResult>;
get(ref: string, options?: CallOptions): Promise<LivePullRequest>;
changes(ref: string, options?: PageOptions): Promise<Page<PullRequestChange>>;
/** Needs `pr-diff`. */
diff(ref: string, options?: PullRequestDiffOptions): Promise<Page<PullRequestDiff>>;
/** Needs `pr-threads`. Group the result for display with kit `groupThreadsByFile`. */
threads(ref: string, options?: ReviewThreadQuery): Promise<Page<ReviewThread>>;
}tanımlandığı yer: packages/core/src/api.ts
Profildeki her kod barındırıcıda canlı pull request'ler. Pull request başvurusu (ref) bir pull request URL'si, açık biçim <host id>:<repo>#<id> ya da repo adı barındırıcılar arasında benzersizse <repo>#<id> olur (# yerine ! kabul edilir). Gereken yeteneği olmayan barındırıcı, adını ve yeteneklerini söyleyerek çağrıyı UNSUPPORTED yapar. Kılavuz ve eksiksiz bir örnek: pull request'ler.
| Metot | Döndürdüğü | Yetenek | Fırlattığı |
|---|---|---|---|
resolve(ref, options?) | ResolvedPullRequestRef | pull-requests-live | Hiçbir barındırıcı başvuruyu tanımazsa NOT_FOUND; boşsa ya da birkaç barındırıcı tanırsa INVALID_INPUT. Pull request'in var olup olmadığını denetlemez. |
find(query, options?) | PullRequestFindResult | pull-requests-live | url, ticket, branch alanlarından tam olarak biri verilmediyse ya da state bilinmiyorsa INVALID_INPUT; yapılandırılmış hiçbir barındırıcıda canlı pull request yoksa UNSUPPORTED. |
list(options?) | PullRequestListResult | pull-requests-live | Bilinmeyen barındırıcı, grup ya da durum, veya başka bir listelemeye ait imleç için INVALID_INPUT; bilinmeyen repo için NOT_FOUND; yapılandırılmış hiçbir barındırıcıda canlı pull request yoksa UNSUPPORTED. |
get(ref, options?) | LivePullRequest | pull-requests-live | Kimlik o repoda yoksa NOT_FOUND. |
changes(ref, options?) | Page<PullRequestChange> | pull-requests-live | |
diff(ref, options?) | Page<PullRequestDiff> | pr-diff | |
threads(ref, options?) | Page<ReviewThread> | pr-threads |
| Seçenek | Tür | Anlamı |
|---|---|---|
host | string | Tek bir kod barındırıcı girdisinin kimliğiyle sınırlar. Varsayılan: pull-requests-live yeteneği olan her barındırıcı. |
repos | string[] | Repo kısa adları. Varsayılan: yönetilen her repo. |
groups | string[] | Profildeki repo grupları (birleşim); kod aramasındaki gibi repos ile birleştirilir. |
PullRequestListQuery türünü genişletir (state, draft, author, reviewer, sourceBranch, targetBranch, createdSince, updatedSince, limit, cursor, signal). limit varsayılan olarak DEFAULT_PULL_REQUEST_LIST_LIMIT değerindedir ve DEFAULT_MAX_PULL_REQUEST_LIST_LIMIT ile sınırlanır.
| Alan | Tür | Anlamı |
|---|---|---|
matches | LivePullRequest[] | En yeni başta. Hiçbir şey eşleşmezse boştur: hata değil, yanıt. |
best | LivePullRequest | Sormadan okunacak eşleşme: tek eşleşme ya da birkaçı içindeki tek açık olan. Seçim açık değilse bulunmaz. |
truncated | boolean | limit değerinden (varsayılan DEFAULT_PULL_REQUEST_FIND_LIMIT) fazlası eşleştiyse doğrudur. |
warnings | SafranWarning[] | Başarısız olan ya da sorulamayan barındırıcılar. |
/**
* How to look for a pull request. Exactly one of `url`, `ticket`, `branch`:
* - `url`: a pull request link; at most one match.
* - `ticket`: a ticket reference; matches pull requests that carry its key (native link, title,
* branch, description), found among the live ones and, for merged work, in the link store.
* - `branch`: a source branch name (the branch of the working tree, usually).
*/
export type PullRequestFindQuery = ({ url: string } | { ticket: string } | { branch: string }) & {
/** Narrow `ticket` / `branch` lookups to these repos. */
repos?: string[];
/** Default: `all` for `url`, otherwise open first: open matches are returned alone when there are any, else merged and closed ones. */
state?: PullRequestState | "all";
};
export interface PullRequestFindOptions extends CallOptions {
/** Most matches returned. Default `DEFAULT_PULL_REQUEST_FIND_LIMIT`. */
limit?: number;
}
/**
* A pull request as it is now, with the code host entry it came from and every ticket key
* found for it: the host's native links plus keys recognised in the title, the source branch
* and the description (the same recognition the link store uses).
*/
export interface LivePullRequest extends PullRequestDetails {
host: string;
ticketKeys: string[];
}
export interface PullRequestListResult extends Page<LivePullRequest> {
/** One entry per host that failed, cannot list live pull requests, or cannot apply one of the filters; the others are still returned. */
warnings?: SafranWarning[];
}
export interface ResolvedPullRequestRef {
host: CodeHost;
/** Short repository name. */
repo: string;
id: string;
}tanımlandığı yer: packages/core/src/api.ts
safran.writes
/**
* The only way anything outside this machine is changed. Off by default.
*
* Order of the checks every method makes, each failing with the first that applies:
* 1. `allowWrites: false` → FORBIDDEN ("writes are turned off for this instance").
* 2. profile `writes.enabled` false → FORBIDDEN, hint naming `writes.enabled`.
* 3. the intent's kind not in `writes.allow` → FORBIDDEN, hint naming `writes.allow` and the kind.
* 4. the input (INVALID_INPUT: empty or over-long body, `line` without `path`, …).
* 5. the target (NOT_FOUND / INVALID_INPUT from resolving the reference).
* 6. the connector's `write:` capability → UNSUPPORTED naming the connector.
* A write is never a side effect of a read: nothing outside this interface calls a connector's
* `write:` method. If the audit row cannot be stored, nothing is sent.
*/
export interface WritesApi {
/** Offline. Never throws for "disabled": that is what it reports. */
status(): WritesStatus;
/** Checks 1–6, reads the target, records the preview and returns the token. Sends nothing. */
preview(intent: WriteIntent, options?: WriteCallOptions): Promise<WritePreview>;
/**
* Performs the write a preview described. CONFIRMATION_REQUIRED for a token that is unknown,
* expired or from another instance (the hint says to preview again); CONFLICT for one that was
* already used (the hint carries the URL of what it created) or whose target changed in a way
* that invalidates the preview. Checks 1–3 are made again: turning writes off between preview
* and commit wins. The token is spent the moment the request is sent, whatever the outcome: a
* failed commit needs a new preview, and a failure after the request left is reported as
* UPSTREAM with a hint that the write may have happened.
*/
commit(confirmationToken: string, options?: WriteCallOptions): Promise<WriteCommitResult>;
/**
* Preview and commit in one call, for code that already has its confirmation elsewhere (a
* script, a CI job). CONFIRMATION_REQUIRED while the profile has `writes.require_confirmation:
* true` (the default), with a hint naming that key. Audited like any other write.
*/
execute(intent: WriteIntent, options?: WriteCallOptions): Promise<WriteCommitResult>;
/** Audit rows, newest first. Reads the local store only; works while writes are disabled. */
log(query?: WriteLogQuery, options?: CallOptions): Promise<WriteAuditEntry[]>;
}tanımlandığı yer: packages/core/src/api.ts
Bu makinenin dışındaki herhangi bir şeyin değiştirilmesinin tek yolu. Her örnekte vardır; yalnızca profilin writes bölümü açtığında ve örnek allowWrites: false ile oluşturulmadığında açıktır, aksi hâlde kapalıdır. Kılavuz, denetimlerin sırası ve eksiksiz bir önizleme → onay örneği: yazma işlemleri.
| Metot | Döndürdüğü | Notlar |
|---|---|---|
status() | WritesStatus | Eşzamanlı ve çevrimdışıdır. "Kapalı" için asla hata fırlatmaz: bildirdiği şey budur. |
preview(intent, options?) | WritePreview | Bütün denetimleri yapar, hedefi okur, önizlemeyi kaydeder ve token'ı döndürür. Hiçbir şey göndermez. |
commit(confirmationToken, options?) | WriteCommitResult | Bir önizlemenin tanımladığı yazmayı gerçekleştirir. Bilinmeyen, süresi dolmuş ya da başka örneğe ait token için CONFIRMATION_REQUIRED; zaten kullanılmış token için CONFLICT. |
execute(intent, options?) | WriteCommitResult | Tek çağrıda önizleme ve onay. Profilde writes.require_confirmation: true iken CONFIRMATION_REQUIRED. |
log(query?, options?) | WriteAuditEntry[] | Denetim satırları; en yeni başta. Yalnızca yerel depo; yazma kapalıyken de çalışır. |
| Alan | Tür | Anlamı |
|---|---|---|
enabled | boolean | Yalnızca allowWrites yanlış değilse, profil writes.enabled: true diyorsa ve allow boş değilse doğrudur. |
allowed | WriteIntentKind[] | Bir önizlemenin şu an kabul edeceği türler: writes.allow eksi yapılandırılmış hiçbir bağlayıcının yapamadığı türler. Kapalıyken boştur. |
requireConfirmation | boolean | Profildeki writes.require_confirmation. |
reason | string | Kapalıyken: yazmayı neyin kapattığı; anahtarın adıyla. |
switch | WritesSwitch | Kapalıyken: buna karar veren anahtar; kod içindir. FORBIDDEN hatasındaki details.switch ile aynı adlar. |
/**
* Exactly what a commit would send, and the token that commits it. Making a preview reads the
* target (to prove it exists and to show its title) and changes nothing remote; it writes one
* `previewed` row to the audit log.
*/
export interface WritePreview {
kind: WriteIntentKind;
target: WriteTarget;
/** One line a person can confirm: `Add a comment to PAY-7 "Refund fails on partial capture"`. Contains the target's title: third-party text. */
description: string;
/** The title that will be sent (`ticket.create_child` only). */
title?: string;
/** The body that will be sent, character for character: the intent's Markdown plus the profile's marker. */
body: string;
/** True when `writes.marker` was appended to `body`. */
markerAdded: boolean;
/** `ticket.create_child`: resolved type and labels. `type` absent means the tracker's default child type. */
ticketType?: string;
labels?: string[];
/** `ticket.create_child`: existing children of the parent with a very similar title. Not a refusal; a reason to ask. */
possibleDuplicates?: TicketSummary[];
/** `pull_request.reply`: the comment being answered (first of the thread), cut. Third-party text. */
inReplyTo?: { author?: string; excerpt: string };
/**
* Opaque, unguessable, single use, valid until `expiresAt`, bound to this instance and to
* exactly this payload. Not a secret to protect from the user: its job is to prove that a
* preview happened and that what is committed is what was shown.
*/
confirmationToken: string;
/** ISO time; `DEFAULT_WRITE_CONFIRMATION_TTL_MS` after the preview. */
expiresAt: string;
}
/** What a write will touch, resolved from the intent's reference. */
export interface WriteTarget {
/** Profile entry id of the tracker or code host. */
source: string;
type: "ticket" | "pull_request";
/** Ticket key, or `<repo>#<id>`. For `ticket.create_child`: the PARENT. */
key: string;
url?: string;
/** Title of the ticket or pull request, read at preview time. Third-party text. */
title?: string;
/** For `pull_request.reply`: the thread, and for a line comment the position. */
threadId?: string;
path?: string;
line?: number;
}
/** A write that went through. */
export interface WriteCommitResult extends WriteResult {
kind: WriteIntentKind;
target: WriteTarget;
/** Id of the audit row. */
auditId: string;
}
/** One row of the audit log (`write_audit` in `<dataDir>/safran.db`). */
export interface WriteAuditEntry {
id: string;
/** ISO time of the last change of the row (the preview, then the commit or the failure). */
at: string;
kind: WriteIntentKind;
target: WriteTarget;
status: WriteAuditStatus;
/** SHA-256 (hex) of the body that was previewed, so a row can be matched to a posted text without storing it twice. */
bodySha256: string;
/** The body. Kept for `committed` and `failed` rows; a preview never committed keeps only the hash. */
body?: string;
/** For `committed`: what the connector reported. */
resultId?: string;
resultUrl?: string;
/** For `failed`. */
error?: BatchError;
/** Who asked, when the caller said so (`WriteCallOptions.client`): an MCP client name, "cli". */
client?: string;
}
export type WriteAuditStatus = "previewed" | "committed" | "failed";
export interface WriteLogQuery {
/** ISO date lower bound on `at` (inclusive). */
since?: string;
kinds?: WriteIntentKind[];
statuses?: WriteAuditStatus[];
/** Default `DEFAULT_WRITE_LOG_LIMIT`. */
limit?: number;
}
export interface WriteCallOptions extends CallOptions {
/** Recorded in the audit row. One line, no secrets. */
client?: string;
}tanımlandığı yer: packages/core/src/api.ts
safran.store
store: StoreService
<dataDir>/safran.db içindeki ad alanlı JSON kayıtları; eklentiler ve kendi küçük durumunuz için. namespace(name) tek bir ad alanı verir (aynı adla yapılan iki çağrı aynı kayıtları görür) ve ilk kullanıma kadar hiçbir şey açmaz; STORE_NAMESPACE_PATTERN ile eşleşmeyen bir ad için INVALID_INPUT fırlatır. Arayüzler ve sınırlar kit başvurusunda; kılavuz ise araç paketleri ve depo sayfasındadır.
safran.toolPacks
/**
* Tool packs are built with the connectors when the instance is created (no network I/O).
* Creation fails with PLUGIN_CONFIG_INVALID when a pack has no tools, a tool name is not
* snake_case, or two packs define the same tool name.
*/
export interface ToolPacksApi {
/** In profile order. Empty when the profile lists none. */
list(): RegisteredToolPack[];
/**
* Runs one tool by name with a fresh `ToolPackContext` (the instance's read services, the
* pack's store namespace, a signal that also fires on `close()`). NOT_FOUND for an unknown
* tool; FORBIDDEN for a tool that changes the outside world (`readOnly: false` and
* `openWorld: true`) while writes are disabled.
*/
call(tool: string, args: unknown, options?: ToolPackCallOptions): Promise<AgentToolOutput>;
}
/** A tool pack built from a `tool_packs` entry of the profile. */
export interface RegisteredToolPack {
/** Profile entry id; also the name of the pack's store namespace (kit `toolPackNamespace`). */
id: string;
/** Plugin type. */
type: string;
tools: readonly AgentTool[];
instructions?: string;
}
export interface ToolPackCallOptions extends CallOptions {
/**
* The wrapper handed to the handler as `ToolPackContext.untrusted`. A server that shows the
* result to a model passes its own (so the tag matches the rest of that result). Default: kit
* `wrapUntrusted` with a nonce made for this call.
*/
untrusted?: (text: string, source: string) => string;
}tanımlandığı yer: packages/core/src/api.ts
Profilin tool_packs listesinden kurulan araç paketleri. Örnek oluşturulurken bağlayıcılarla birlikte ve ağ G/Ç'si olmadan kurulurlar; bir paketin hiç aracı yoksa, bir araç adı snake_case değilse ya da iki paket aynı araç adını tanımlıyorsa oluşturma PLUGIN_CONFIG_INVALID ile başarısız olur.
| Metot | Döndürdüğü | Fırlattığı |
|---|---|---|
list() | RegisteredToolPack[]; profil sırasıyla | |
call(tool, args, options?) | AgentToolOutput | Bilinmeyen araç için NOT_FOUND; yazma kapalıyken dış dünyayı değiştiren araç için FORBIDDEN; şemasının reddettiği argümanlar için INVALID_INPUT; işleyici başarısız olursa ya da kendi çıktı şemasının reddettiği bir şey döndürürse INTERNAL. |
toolNameCollisions(packs, reserved?), birlikte kaydedilemeyecek araç adlarını listeler: iki paketin tanımladığı bir ad ve reserved içinde de bulunan bir ad. Bir sunucu, paketleri kaydetmeden önce onu kendi araç adlarıyla çağırır.
/**
* Tool names that cannot be registered together: a name two packs define, and a name that is
* also in `reserved` (the names a server keeps for its own tools). One entry per clash, in pack
* order. `createSafran` refuses a profile whose packs clash with each other; a server calls
* this with its own tool names before it registers the packs.
*/
export function toolNameCollisions(packs: readonly Pick<RegisteredToolPack, "id" | "tools">[], reserved: Iterable<string> = []): { tool: string; pack: string; with: string }[];tanımlandığı yer: packages/core/src/tool-packs.ts
Token süresi
/**
* Connector tokens that need attention, from the `token_expires` dates of the profile: expired
* ones first, then the soonest. Pure and offline; an entry without the key is never listed.
* An expired token otherwise shows up as every tool failing at once, so `safran doctor` and
* `get_server_info` show this, and `createSafran` logs it.
*/
export function tokenExpiry(profile: Profile, options: TokenExpiryOptions = {}): TokenExpiry[];
/** A connector entry whose token has expired, or will within the warning window. */
export interface TokenExpiry {
/** Profile entry id. */
source: string;
/** Which list of the profile the entry is in. */
kind: "tracker" | "code-host" | "doc-source";
/** The entry's `token_expires`, `YYYY-MM-DD`. The token works through the end of that day (UTC). */
expires: string;
/** Whole days left; 0 on the last day, negative once it has passed. */
daysLeft: number;
expired: boolean;
/** One line a person can act on. Holds no secret: the profile never does. */
message: string;
}
export interface TokenExpiryOptions {
/** Default: now. */
now?: Date;
/** Report tokens expiring within this many days. Default `DEFAULT_TOKEN_EXPIRY_WARNING_DAYS`. */
withinDays?: number;
}tanımlandığı yer: packages/core/src/token-expiry.ts
tokenExpiry(profile, options?), profildeki token_expires tarihlerinden, token'ının süresi dolmuş ya da withinDays (varsayılan DEFAULT_TOKEN_EXPIRY_WARNING_DAYS) gün içinde dolacak bağlayıcı girdilerini listeler: önce süresi dolanlar, sonra en yakın olanlar. Saftır ve çevrimdışıdır. createSafran aynı listeyi uyarı olarak günlüğe yazar.
safran.company
/** What the profile says about the company, in the shape agents ask for it. */
export interface CompanyApi {
teams(): Team[];
glossary(): GlossaryEntry[];
conventions(): string[];
/** Teams owning a repo or a tracker project. */
whoOwns(target: { repo: string } | { project: string }, options?: CallOptions): Promise<Ownership>;
/** Code-side words for the glossary terms found in the text. */
expand(text: string): string[];
}tanımlandığı yer: packages/core/src/api.ts
Profilin şirket hakkında söyledikleri. teams, glossary, conventions ve expand eşzamanlıdır ve yalnızca profili okur; profildeki metni işleten kişi yazmıştır ve güvenilir sayılır.
company.teams, company.glossary, company.conventions
teams(): Team[] · glossary(): GlossaryEntry[] · conventions(): string[]
Profilin ilgili bölümleri, varsayılanlar uygulanmış hâlde (profilde yoksa her biri boş dizidir). Girdi türleri profil başvurusunda yer alır.
import { createAcme } from "./acme";
const safran = await createAcme();
for (const team of safran.company.teams()) console.log(team.name, team.projects, team.repos, team.confidence ?? "declared");
for (const entry of safran.company.glossary()) console.log(entry.term, "→", entry.code.join(", "));
console.log(safran.company.conventions());
await safran.close();company.whoOwns
whoOwns(target: { repo: string } | { project: string }, options?: CallOptions): Promise<Ownership>
Bir repoya ya da bir iş takip projesine sahip olan ekipler. Repo için önce profile bakılır; hiçbir ekip repoyu bildirmiyorsa bağlantı deposu oy kullanır: reponun saklanan her kaydı (en yeni DEFAULT_OWNERSHIP_HISTORY_LIMIT, 500 adet), iş kayıtlarının projelerine sahip olan ekiplere birer oy verir ve en çok oyu alan ekipler döndürülür. Bir projenin sahipleri yalnızca bildirilebilir.
| Alan | Tür | Anlamı |
|---|---|---|
teams | Team[] | Sahip ekipler; hiçbir şey bilinmiyorsa boş. |
basis | "profile" | "history" | "none" | Bildirilmişse "profile", geçmiş işlerden çıkarılmışsa "history", yanıt yoksa "none". |
Fırlattığı hatalar Hedefte ne repo ne de project string'i varsa INVALID_INPUT.
import { createAcme } from "./acme";
const safran = await createAcme();
const byRepo = await safran.company.whoOwns({ repo: "payments-api" });
console.log(byRepo.basis, byRepo.teams.map((team) => team.name)); // "profile" ["Payments"]
const byProject = await safran.company.whoOwns({ project: "MOB" });
console.log(byProject.basis, byProject.teams.length); // "none" 0
await safran.close();company.expand
expand(text: string): string[]
Metinde bulunan sözlük terimlerinin kod tarafındaki sözcükleri, yinelemesiz. Örneğin profiline bağlanmış expandWithGlossary fonksiyonudur.
import { createAcme } from "./acme";
const safran = await createAcme();
console.log(safran.company.expand("Kısmi iade başarısız")); // ["refund", "chargeback"]
await safran.close();Ortak sonuç biçimleri
Toplu işlemler ve çok kaynaklı çağrılar başarısızlıkları fırlatmak yerine sonucun içinde taşır; böylece başarılı olan kısım kaybolmaz.
| Alan | Tür | Anlamı |
|---|---|---|
code | SafranErrorCode | Hata fırlatılsaydı SafranError nesnesinin taşıyacağı kodun aynısı. |
message | string | Neyin ters gittiği. |
hint | string | Yapılacak bir şey varsa, sırada ne yapılacağı. |
| Alan | Tür | Anlamı |
|---|---|---|
source | string | Uyarının ilgili olduğu iş takip sisteminin ya da kod barındırıcının profil girdisi kimliği. |
code | SafranErrorCode | O kaynağın yanıtta neden eksik olduğu ya da neyin belirsiz olduğu. |
message | string | Kaynağın adını veren tek cümle. |
BatchError, RepoSyncResult.error, LinkRefreshRepoResult.error ve WriteAuditEntry.error içinde; SafranWarning ise TicketSearchResult.warnings, repos.warnings(), LinkedWork.warnings ve pull request listelemelerinde görülür.
Varsayılanlar
@safran/core paketinin dışa aktardığı adlandırılmış sabitler. Gösterilen değerler kaynak koddan okunur.
/** Named defaults of `@safran/core`. Everything here is overridable per call or per instance. */
/** Directory name used next to the profile file (or in the cwd for inline profiles). */
export const DEFAULT_DATA_DIR = "data";
/** Total page size of `tickets.search` across all trackers. */
export const DEFAULT_TICKET_SEARCH_LIMIT = 50;
/** Largest `tickets.search` page; a larger `limit` is clamped. */
export const DEFAULT_MAX_TICKET_SEARCH_LIMIT = 500;
/**
* How long `close()` waits for cancelled calls to settle before it releases the handles anyway.
* A connector that ignores its signal must not keep the process from exiting.
*/
export const DEFAULT_CLOSE_GRACE_MS = 30_000;/** Clone / fetch budget. A cold shallow clone of a large monorepo over a slow VPN takes minutes. */
export const DEFAULT_GIT_NETWORK_TIMEOUT_MS = 10 * 60_000;
/** Budget for git commands that never leave the machine (rev-parse, checkout). */
export const DEFAULT_GIT_LOCAL_TIMEOUT_MS = 60_000;
/** How long a killed git gets to clean up after SIGTERM before SIGKILL. */
export const DEFAULT_GIT_KILL_GRACE_MS = 2_000;
/** Characters of git stderr kept in an error message. */
export const DEFAULT_GIT_ERROR_CHARS = 500;
/**
* Age after which a repo lock is taken over even though its process id is alive: the id may
* belong to an unrelated process by then. Far above any real sync of one repo.
*/
export const DEFAULT_REPO_LOCK_STALE_MS = 24 * 60 * 60_000;/** Merged pull requests newly stored per repo in one `links.refresh`. */
export const DEFAULT_LINKS_MAX_PER_REPO = 500;
/** How far back the first `links.refresh` of a repo looks. */
export const DEFAULT_LINKS_LOOKBACK_MONTHS = 12;
export const DEFAULT_LINKS_PAGE_SIZE = 100;
export const DEFAULT_WORK_QUERY_LIMIT = 100;
/** Largest `links.query` page; discovery and evaluation read the whole store in one call. */
export const DEFAULT_MAX_WORK_QUERY_LIMIT = 1_000_000;
/** Records of a repo read when ownership is inferred from history. */
export const DEFAULT_OWNERSHIP_HISTORY_LIMIT = 500;
/** Names offered in a "did you mean" hint. */
export const DEFAULT_SUGGESTIONS = 3;/**
* `<dataDir>/safran.db`: the one SQLite file behind the link store, the write audit log and the
* plugin store. One handle per instance, opened on first use and closed with the instance.
*/
export const LINKS_DB_FILE = "safran.db";
/** Version of the whole file. The name is historical: the link store was its first tenant. */
export const LINKS_SCHEMA_VERSION = 3;/** A repo whose index is older than this is reported `stale` on hits and in the repo list. */
export const DEFAULT_INDEX_STALE_AFTER_DAYS = 7;
/**
* What the score of a code hit in a `code.deprioritise` group is multiplied by before the list
* is re-sorted: such a hit must score a quarter higher than a hit elsewhere to keep its place.
* Not yet tuned with `safran eval retrieval`; with an empty `deprioritise` list ranking is
* untouched.
*/
export const DEFAULT_DEPRIORITISE_FACTOR = 0.8;
/** Remote heads asked for at once by `repos.list({ checkRemote: true })`. */
export const DEFAULT_REMOTE_HEAD_CONCURRENCY = 6;
/** A connector token that expires within this many days is reported by `tokenExpiry`. */
export const DEFAULT_TOKEN_EXPIRY_WARNING_DAYS = 14;
/** Pages a core method reads from a connector to gather one bounded answer (a family, a thread lookup); a connector that never ends its listing cannot hold a call forever. */
export const DEFAULT_MAX_CONNECTOR_PAGES = 50;/** Children and siblings returned by `tickets.family` (each). */
export const DEFAULT_FAMILY_LIMIT = 40;
export const DEFAULT_MAX_FAMILY_LIMIT = 200;
/** Unfinished blockers and counterparts whose body `tickets.linkedWork` includes. */
export const DEFAULT_LINKED_WORK_BODIES = 3;
export const DEFAULT_MAX_LINKED_WORK_BODIES = 10;
export const DEFAULT_LINKED_WORK_BODY_CHARS = 2_000;
export const DEFAULT_MAX_LINKED_WORK_BODY_CHARS = 20_000;
/** Linked tickets whose current status is read in one `tickets.linkedWork` call; the rest keep the link's snapshot. */
export const DEFAULT_LINKED_WORK_MAX_TICKETS = 50;
/** Linked tickets `tickets.linkedWork` reads at the same time. */
export const DEFAULT_LINKED_WORK_CONCURRENCY = 4;
/** Search results looked at when `tickets.linkedWork` looks for counterpart tickets. */
export const DEFAULT_COUNTERPART_SEARCH_LIMIT = 20;export const DEFAULT_TIME_WORKLOG_LIMIT = 200;
export const DEFAULT_MAX_TIME_WORKLOG_LIMIT = 5_000;
export const DEFAULT_CHANGES_HISTORY_LIMIT = 500;
export const DEFAULT_MAX_CHANGES_HISTORY_LIMIT = 5_000;
export const DEFAULT_CHANGES_COMMENT_LIMIT = 30;
export const DEFAULT_MAX_CHANGES_COMMENT_LIMIT = 500;
/** Comments `tickets.changes` reads to find the ones inside its window. */
export const DEFAULT_CHANGES_COMMENT_SCAN_LIMIT = 500;/** Page size of `pulls.list` across all hosts. */
export const DEFAULT_PULL_REQUEST_LIST_LIMIT = 20;
export const DEFAULT_MAX_PULL_REQUEST_LIST_LIMIT = 100;
export const DEFAULT_PULL_REQUEST_FIND_LIMIT = 10;
/**
* Pull requests `pulls.find` looks at per host (or per repo, when repos are named) for one
* lookup by ticket or branch. Older open pull requests than that are not found by ticket.
*/
export const DEFAULT_PULL_REQUEST_FIND_SCAN_LIMIT = 200;/** How long a confirmation token stays valid after its preview. */
export const DEFAULT_WRITE_CONFIRMATION_TTL_MS = 10 * 60_000;
/** Previews kept waiting at once; the oldest is dropped (its token then answers CONFIRMATION_REQUIRED). */
export const DEFAULT_WRITE_MAX_PENDING_PREVIEWS = 100;
export const DEFAULT_WRITE_LOG_LIMIT = 50;
export const DEFAULT_MAX_WRITE_LOG_LIMIT = 1_000;
/** Characters of a written body kept in an audit row (the SHA-256 always covers the whole body). */
export const DEFAULT_WRITE_AUDIT_BODY_CHARS = 2_000;
/** Characters of the comment a reply answers that a preview shows. */
export const DEFAULT_WRITE_REPLY_EXCERPT_CHARS = 300;
/** Existing children compared with a new child's title when a preview looks for duplicates. */
export const DEFAULT_WRITE_DUPLICATE_SCAN_LIMIT = 200;| Sabit | Kullanan |
|---|---|
DEFAULT_DATA_DIR | SafranOptions.dataDir |
DEFAULT_TICKET_SEARCH_LIMIT, DEFAULT_MAX_TICKET_SEARCH_LIMIT | tickets.search |
DEFAULT_CLOSE_GRACE_MS | close |
DEFAULT_GIT_NETWORK_TIMEOUT_MS, DEFAULT_GIT_LOCAL_TIMEOUT_MS, DEFAULT_GIT_KILL_GRACE_MS, DEFAULT_GIT_ERROR_CHARS | repos.sync içindeki git komutları |
DEFAULT_REPO_LOCK_STALE_MS | repos.sync içindeki repo başına kilit |
DEFAULT_LINKS_MAX_PER_REPO, DEFAULT_LINKS_LOOKBACK_MONTHS, DEFAULT_LINKS_PAGE_SIZE | links.refresh |
DEFAULT_WORK_QUERY_LIMIT, DEFAULT_MAX_WORK_QUERY_LIMIT | links.query |
DEFAULT_OWNERSHIP_HISTORY_LIMIT | company.whoOwns |
DEFAULT_SUGGESTIONS | "did you mean" ipuçları |
LINKS_DB_FILE, LINKS_SCHEMA_VERSION | <dataDir>/safran.db: bağlantı deposunun, yazma denetim günlüğünün ve eklenti deposunun arkasındaki tek SQLite dosyası. Adlar tarihseldir |
DEFAULT_INDEX_STALE_AFTER_DAYS | kod sonuçlarındaki ve repos.list içindeki stale |
DEFAULT_DEPRIORITISE_FACTOR | code.deprioritise grubundaki sonuçların sıralaması |
DEFAULT_REMOTE_HEAD_CONCURRENCY | repos.list({ checkRemote: true }) |
DEFAULT_TOKEN_EXPIRY_WARNING_DAYS | tokenExpiry |
DEFAULT_MAX_CONNECTOR_PAGES | sayfalı bir bağlayıcıdan sınırlı tek bir yanıt toplayan her core metodu |
DEFAULT_FAMILY_LIMIT, DEFAULT_MAX_FAMILY_LIMIT | tickets.family |
DEFAULT_LINKED_WORK_*, DEFAULT_MAX_LINKED_WORK_*, DEFAULT_COUNTERPART_SEARCH_LIMIT | tickets.linkedWork |
DEFAULT_TIME_WORKLOG_LIMIT, DEFAULT_MAX_TIME_WORKLOG_LIMIT | tickets.time |
DEFAULT_CHANGES_*, DEFAULT_MAX_CHANGES_* | tickets.changes |
DEFAULT_PULL_REQUEST_LIST_LIMIT, DEFAULT_MAX_PULL_REQUEST_LIST_LIMIT | pulls.list |
DEFAULT_PULL_REQUEST_FIND_LIMIT, DEFAULT_PULL_REQUEST_FIND_SCAN_LIMIT | pulls.find |
DEFAULT_WRITE_*, DEFAULT_MAX_WRITE_LOG_LIMIT | safran.writes |
Sabitler okunacak değerlerdir, anahtar değil: çağrı başına olanlar, onları kullanan metodun seçenekleriyle (limit, maxPerRepo, since) değiştirilir; git süre bütçelerinin, kilit yaşının ve kapanış bekleme süresinin bir seçeneği yoktur.
Glob eşleştirme
/**
* The small glob dialect of `include` / `exclude` in a code host entry:
* `*` is any run of characters, `?` is exactly one, everything else is literal.
* Matching is case-insensitive and always covers the whole name.
*
* Matched with two pointers and one remembered star instead of a regular expression: a pattern
* of several stars compiled to `.*.*.*` backtracks polynomially (six stars against a 200-character
* name took 74 s), and both the pattern and the names come from outside. Here the worst case is
* pattern length × name length.
*/
export function createGlobMatcher(pattern: string): (name: string) => boolean;
export function matchesGlob(name: string, pattern: string): boolean;tanımlandığı yer: packages/core/src/glob.ts
Kod barındırıcı girdisindeki include / exclude alanlarının lehçesi: * herhangi uzunlukta bir karakter dizisi, ? tam olarak bir karakterdir; geri kalan her şey olduğu gibi eşleşir. Eşleştirme büyük/küçük harfe duyarsızdır ve her zaman adın tamamını kapsar. createGlobMatcher bir kalıbı birçok ad için bir kez derler; matchesGlob tek seferlik biçimdir. Eşleştirici, kalıp ne olursa olsun kalıp uzunluğu × ad uzunluğu ile orantılı sürede çalışır.
import { createGlobMatcher, matchesGlob } from "@safran/core";
const isAcmeApp = createGlobMatcher("acme-*");
console.log(["acme-ios", "acme-android", "web-app"].filter(isAcmeApp)); // ["acme-ios", "acme-android"]
console.log(matchesGlob("Payments-API", "payments-???")); // true: case-insensitive, whole name
console.log(matchesGlob("payments-api-v2", "payments-api")); // false: no partial matchSık yapılan hatalar
- İletiye göre yakalamak. İletiler insanlar içindir ve değişebilir; sözleşme
codealanıdır.isSafranError(error, "NOT_FOUND")kullanın. repos.syncya dalinks.refreshçağrısının başarısız bir repo için hata fırlatmasını beklemek. Bunlar rapor döndürür. Satır başınastatus, raporda iseabortedalanına bakın.- Eşitlemeden önce kod aramak.
safran.codeyerel indeksten yanıt verir. Yeni bir veri dizininde öncerepos.sync()(ya dasafran sync) çalıştırın. - Bir arama imlecini farklı bir sorguyla yeniden kullanmak. İmleç, onu üreten sorguya ve seçeneklere aittir; başka her şey
INVALID_INPUTolur. close()çağrısını unutmak. İndeks ve bağlantı deposu dosya tutamaçları tutar.await usingya datry/finallykullanın.- Bir indeks verip
close()çağrısının onu kapatmasını beklemek.SafranOptions.indexile verilen indeks çağırana aittir.