[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M793SNNTSN2EQA2ACDCGTYRT":3,"skill-same:01M793SNNTSN2EQA2ACDCGTYRT":58},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":35,"commitSha":36,"skillDirectory":37,"forksCount":38,"repositoryHtmlUrl":39,"repositoryHomepageUrl":6,"ownerHtmlUrl":40,"ownerBlogUrl":41,"ownerDescription":42,"updatedAt":43,"install":44,"resources":57},"01M793SNNTSN2EQA2ACDCGTYRT","obsidian-sdk-patterns",null,"Production-ready Obsidian plugin patterns: typed settings with migration,\nsafe vault operations, event auto-cleanup, workspace layout, metadata cache,\nand debounced file handlers. Use when hardening a plugin for release,\nrefactoring for reliability, or learning idiomatic Obsidian TypeScript.\nTrigger with \"obsidian patterns\", \"obsidian best practices\",\n\"obsidian production code\", \"idiomatic obsidian plugin\".","jukeyman\u002Fjukeyman-skills","jukeyman","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F142960420?v=4","01M78FR4Y3DHMMCBCC0GXXNB3F","RICK JEFFERSON","01M78FR4Z8RVQRAD31Y5J7V6EB",1,"MIT","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--obsidian-pack--obsidian-sdk-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: obsidian-sdk-patterns\ndescription: |\n  Production-ready Obsidian plugin patterns: typed settings with migration,\n  safe vault operations, event auto-cleanup, workspace layout, metadata cache,\n  and debounced file handlers. Use when hardening a plugin for release,\n  refactoring for reliability, or learning idiomatic Obsidian TypeScript.\n  Trigger with \"obsidian patterns\", \"obsidian best practices\",\n  \"obsidian production code\", \"idiomatic obsidian plugin\".\nallowed-tools: Read, Write, Edit, Grep\nversion: 2.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ncompatible-with: claude-code, codex, openclaw\ntags: [obsidian, patterns, production, typescript, best-practices]\n---\n\n# Obsidian SDK Patterns\n\n## Overview\n\nSix production patterns that prevent the most common Obsidian plugin bugs: lost\nsettings on upgrade, null-reference crashes on deleted files, memory leaks from\nunregistered events, stale metadata, and UI jank from rapid file changes. Each\npattern is self-contained and copy-pasteable.\n\n## Prerequisites\n\n- A working Obsidian plugin (see `obsidian-core-workflow-a`)\n- TypeScript strict mode enabled (`\"strictNullChecks\": true` in tsconfig)\n- Familiarity with `Plugin.onload()` \u002F `onunload()` lifecycle\n\n## Instructions\n\n### Step 1: Typed settings with versioned migration\n\nSettings break when you add or rename fields between releases. Version the\nsettings object and migrate on load so existing users keep their data.\n\n```typescript\n\u002F\u002F src\u002Fsettings.ts\ninterface PluginSettingsV1 {\n  apiKey: string;\n  interval: number;\n}\n\ninterface PluginSettingsV2 {\n  version: 2;\n  apiKey: string;\n  syncInterval: number;      \u002F\u002F renamed from \"interval\"\n  excludedFolders: string[]; \u002F\u002F new field\n  theme: \"default\" | \"minimal\";\n}\n\n\u002F\u002F Current version is always the latest\ntype PluginSettings = PluginSettingsV2;\n\nconst DEFAULTS: PluginSettings = {\n  version: 2,\n  apiKey: \"\",\n  syncInterval: 300,\n  excludedFolders: [],\n  theme: \"default\",\n};\n\nexport async function loadSettings(plugin: Plugin): Promise\u003CPluginSettings> {\n  const raw = (await plugin.loadData()) as any;\n  if (!raw) return { ...DEFAULTS };\n\n  \u002F\u002F Migrate v1 -> v2\n  if (!raw.version || raw.version \u003C 2) {\n    raw.version = 2;\n    if (raw.interval !== undefined) {\n      raw.syncInterval = raw.interval;\n      delete raw.interval;\n    }\n    raw.excludedFolders = raw.excludedFolders ?? [];\n    raw.theme = raw.theme ?? \"default\";\n    await plugin.saveData(raw);\n  }\n\n  \u002F\u002F Merge with defaults to pick up any newly added fields\n  return { ...DEFAULTS, ...raw };\n}\n```\n\nWhy: `Object.assign({}, DEFAULTS, raw)` handles new fields added in patch\nreleases. The explicit migration block handles renames and type changes between\nmajor versions.\n\n### Step 2: Safe vault operations (check-before-act)\n\nThe Vault API throws if you create a file that exists or read one that was\ndeleted between your check and your call. Wrap every operation.\n\n```typescript\n\u002F\u002F src\u002Fvault-helpers.ts\nimport { App, TFile, TFolder, TAbstractFile, normalizePath } from \"obsidian\";\n\nexport class VaultHelper {\n  constructor(private app: App) {}\n\n  \u002F** Read file content, return null if file doesn't exist *\u002F\n  async safeRead(path: string): Promise\u003Cstring | null> {\n    const file = this.app.vault.getAbstractFileByPath(normalizePath(path));\n    if (!(file instanceof TFile)) return null;\n    return this.app.vault.read(file);\n  }\n\n  \u002F** Create or overwrite a file. Creates parent folders as needed. *\u002F\n  async safeWrite(path: string, content: string): Promise\u003CTFile> {\n    const normalized = normalizePath(path);\n    await this.ensureParentFolder(normalized);\n\n    const existing = this.app.vault.getAbstractFileByPath(normalized);\n    if (existing instanceof TFile) {\n      await this.app.vault.modify(existing, content);\n      return existing;\n    }\n    return this.app.vault.create(normalized, content);\n  }\n\n  \u002F** Append content to a file. Creates the file if it doesn't exist. *\u002F\n  async safeAppend(path: string, content: string): Promise\u003Cvoid> {\n    const normalized = normalizePath(path);\n    const existing = this.app.vault.getAbstractFileByPath(normalized);\n    if (existing instanceof TFile) {\n      const current = await this.app.vault.read(existing);\n      await this.app.vault.modify(existing, current + content);\n    } else {\n      await this.ensureParentFolder(normalized);\n      await this.app.vault.create(normalized, content);\n    }\n  }\n\n  \u002F** Delete a file if it exists, moving to trash by default. *\u002F\n  async safeDelete(path: string, useTrash = true): Promise\u003Cboolean> {\n    const file = this.app.vault.getAbstractFileByPath(normalizePath(path));\n    if (!(file instanceof TFile)) return false;\n    if (useTrash) {\n      await this.app.vault.trash(file, false);\n    } else {\n      await this.app.vault.delete(file);\n    }\n    return true;\n  }\n\n  \u002F** Ensure a folder (and all parents) exist. *\u002F\n  private async ensureParentFolder(filePath: string): Promise\u003Cvoid> {\n    const parts = filePath.split(\"\u002F\");\n    parts.pop(); \u002F\u002F remove filename\n    let current = \"\";\n    for (const part of parts) {\n      current = current ? `${current}\u002F${part}` : part;\n      const existing = this.app.vault.getAbstractFileByPath(current);\n      if (!existing) {\n        await this.app.vault.createFolder(current);\n      }\n    }\n  }\n}\n```\n\n### Step 3: Event management with automatic cleanup\n\nEvery `this.registerEvent(...)` call in `onload()` is automatically cleaned up\nwhen the plugin unloads. Never use raw `addEventListener` or `app.vault.on()`\nwithout registering -- those leak.\n\n```typescript\nexport default class MyPlugin extends Plugin {\n  async onload() {\n    \u002F\u002F File events -- auto-cleaned on unload\n    this.registerEvent(\n      this.app.vault.on(\"create\", (file) => {\n        if (file instanceof TFile) this.onFileCreated(file);\n      })\n    );\n\n    this.registerEvent(\n      this.app.vault.on(\"delete\", (file) => {\n        if (file instanceof TFile) this.onFileDeleted(file);\n      })\n    );\n\n    this.registerEvent(\n      this.app.vault.on(\"rename\", (file, oldPath) => {\n        if (file instanceof TFile) this.onFileRenamed(file, oldPath);\n      })\n    );\n\n    \u002F\u002F Workspace events\n    this.registerEvent(\n      this.app.workspace.on(\"active-leaf-change\", (leaf) => {\n        this.onActiveLeafChange(leaf);\n      })\n    );\n\n    this.registerEvent(\n      this.app.workspace.on(\"layout-change\", () => {\n        this.onLayoutChange();\n      })\n    );\n\n    \u002F\u002F Periodic tasks -- also auto-cleaned\n    this.registerInterval(\n      window.setInterval(() => this.periodicSync(), 60_000)\n    );\n\n    \u002F\u002F DOM events -- use registerDomEvent for auto-cleanup\n    this.registerDomEvent(document, \"keydown\", (evt: KeyboardEvent) => {\n      if (evt.key === \"F5\") this.refreshData();\n    });\n  }\n\n  \u002F\u002F No cleanup code needed in onunload() -- all registered events\n  \u002F\u002F are automatically removed by the Plugin base class.\n}\n```\n\nAnti-pattern to avoid:\n```typescript\n\u002F\u002F BAD: leaks on plugin unload\nthis.app.vault.on(\"modify\", handler);\ndocument.addEventListener(\"click\", handler);\n\n\u002F\u002F GOOD: auto-cleaned\nthis.registerEvent(this.app.vault.on(\"modify\", handler));\nthis.registerDomEvent(document, \"click\", handler);\n```\n\n### Step 4: Workspace layout manipulation\n\nOpen files in specific panes, split views, and restore layout state.\n\n```typescript\nimport { MarkdownView, WorkspaceLeaf } from \"obsidian\";\n\nexport class WorkspaceHelper {\n  constructor(private app: App) {}\n\n  \u002F** Open a file in a new tab *\u002F\n  async openInNewTab(path: string): Promise\u003Cvoid> {\n    const file = this.app.vault.getAbstractFileByPath(path);\n    if (!(file instanceof TFile)) return;\n    const leaf = this.app.workspace.getLeaf(\"tab\");\n    await leaf.openFile(file);\n  }\n\n  \u002F** Open a file in a vertical split to the right *\u002F\n  async openInSplit(path: string): Promise\u003Cvoid> {\n    const file = this.app.vault.getAbstractFileByPath(path);\n    if (!(file instanceof TFile)) return;\n    const leaf = this.app.workspace.getLeaf(\"split\", \"vertical\");\n    await leaf.openFile(file);\n  }\n\n  \u002F** Get the currently active markdown file (or null) *\u002F\n  getActiveFile(): TFile | null {\n    const view = this.app.workspace.getActiveViewOfType(MarkdownView);\n    return view?.file ?? null;\n  }\n\n  \u002F** Iterate all open markdown leaves *\u002F\n  forEachOpenNote(callback: (file: TFile, leaf: WorkspaceLeaf) => void): void {\n    this.app.workspace.iterateAllLeaves((leaf) => {\n      if (leaf.view instanceof MarkdownView && leaf.view.file) {\n        callback(leaf.view.file, leaf);\n      }\n    });\n  }\n\n  \u002F** Pin\u002Funpin the active tab *\u002F\n  togglePin(): void {\n    const leaf = this.app.workspace.getLeaf();\n    if (leaf) {\n      const pinned = (leaf as any).pinned;\n      (leaf as any).setPinned(!pinned);\n    }\n  }\n}\n```\n\n### Step 5: Metadata cache for fast queries\n\n`metadataCache` is Obsidian's pre-parsed index of all vault files. It avoids\nreading file content for frontmatter, tags, links, and headings.\n\n```typescript\nimport { App, TFile, CachedMetadata } from \"obsidian\";\n\nexport class MetadataHelper {\n  constructor(private app: App) {}\n\n  \u002F** Get parsed metadata for a file (frontmatter, tags, links, headings) *\u002F\n  getCache(file: TFile): CachedMetadata | null {\n    return this.app.metadataCache.getFileCache(file);\n  }\n\n  \u002F** Get frontmatter value, returns undefined if missing *\u002F\n  getFrontmatterValue(file: TFile, key: string): any | undefined {\n    const cache = this.getCache(file);\n    return cache?.frontmatter?.[key];\n  }\n\n  \u002F** Find all files with a specific tag *\u002F\n  filesWithTag(tag: string): TFile[] {\n    const normalized = tag.startsWith(\"#\") ? tag : `#${tag}`;\n    return this.app.vault.getMarkdownFiles().filter((file) => {\n      const cache = this.getCache(file);\n      \u002F\u002F Tags in body\n      const bodyTags = cache?.tags?.map((t) => t.tag) ?? [];\n      \u002F\u002F Tags in frontmatter\n      const fmTags = (cache?.frontmatter?.tags ?? []).map((t: string) =>\n        t.startsWith(\"#\") ? t : `#${t}`\n      );\n      return [...bodyTags, ...fmTags].includes(normalized);\n    });\n  }\n\n  \u002F** Get all outgoing links from a file *\u002F\n  outgoingLinks(file: TFile): string[] {\n    const cache = this.getCache(file);\n    const links = cache?.links?.map((l) => l.link) ?? [];\n    const embeds = cache?.embeds?.map((e) => e.link) ?? [];\n    return [...new Set([...links, ...embeds])];\n  }\n\n  \u002F** Get files that link to this file (backlinks) *\u002F\n  backlinks(file: TFile): TFile[] {\n    const resolved = this.app.metadataCache.resolvedLinks;\n    const results: TFile[] = [];\n    for (const [sourcePath, targets] of Object.entries(resolved)) {\n      if (file.path in targets) {\n        const source = this.app.vault.getAbstractFileByPath(sourcePath);\n        if (source instanceof TFile) results.push(source);\n      }\n    }\n    return results;\n  }\n\n  \u002F** Wait for metadata cache to be fully indexed (useful on plugin load) *\u002F\n  onCacheReady(callback: () => void): void {\n    if (this.app.metadataCache.initialized) {\n      callback();\n    } else {\n      this.app.metadataCache.on(\"initialized\", callback);\n    }\n  }\n\n  \u002F** Listen for metadata changes on a specific file *\u002F\n  onFileMetadataChange(\n    plugin: Plugin,\n    filePath: string,\n    callback: (cache: CachedMetadata) => void\n  ): void {\n    plugin.registerEvent(\n      this.app.metadataCache.on(\"changed\", (file, _data, cache) => {\n        if (file.path === filePath) callback(cache);\n      })\n    );\n  }\n}\n```\n\n### Step 6: Debounced file modification handlers\n\nPlugins that react to file changes (auto-save, indexing, sync) fire too often\nwithout debouncing. Obsidian's vault `modify` event fires on every keystroke\nwhen live preview is active.\n\n```typescript\nimport { Plugin, TFile, debounce } from \"obsidian\";\n\nexport default class IndexerPlugin extends Plugin {\n  \u002F\u002F Debounce: wait 2s after last modification before processing\n  private processFile = debounce(\n    async (file: TFile) => {\n      console.log(`[Indexer] Processing ${file.path}`);\n      const content = await this.app.vault.read(file);\n      await this.updateIndex(file, content);\n    },\n    2000,\n    true  \u002F\u002F true = reset timer on each call (trailing edge)\n  );\n\n  async onload() {\n    this.registerEvent(\n      this.app.vault.on(\"modify\", (file) => {\n        if (file instanceof TFile && file.extension === \"md\") {\n          this.processFile(file);\n        }\n      })\n    );\n  }\n\n  private async updateIndex(file: TFile, content: string): Promise\u003Cvoid> {\n    \u002F\u002F Your indexing logic here -- runs at most once per 2s per file\n  }\n}\n```\n\nFor per-file debouncing (different timers for different files):\n\n```typescript\nprivate fileTimers = new Map\u003Cstring, ReturnType\u003Ctypeof setTimeout>>();\n\nprivate debouncedProcess(file: TFile, delayMs = 2000): void {\n  const existing = this.fileTimers.get(file.path);\n  if (existing) clearTimeout(existing);\n\n  this.fileTimers.set(\n    file.path,\n    setTimeout(async () => {\n      this.fileTimers.delete(file.path);\n      const content = await this.app.vault.read(file);\n      await this.updateIndex(file, content);\n    }, delayMs)\n  );\n}\n\n\u002F\u002F Clean up all timers on unload\nonunload() {\n  for (const timer of this.fileTimers.values()) {\n    clearTimeout(timer);\n  }\n  this.fileTimers.clear();\n}\n```\n\n## Output\n\nAfter applying these patterns:\n- Settings survive across plugin updates with automatic migration\n- File operations never crash on missing files or duplicate paths\n- All events auto-clean on plugin unload (zero memory leaks)\n- Workspace manipulation opens files in tabs, splits, or sidebar\n- Metadata cache provides instant tag\u002Flink\u002Ffrontmatter queries without reading files\n- File modification handlers are debounced to prevent UI jank and redundant work\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| Settings lost after update | No version field \u002F no migration | Add `version` to settings interface, migrate in `loadSettings` |\n| `null` file reference | File deleted between check and use | Always re-fetch with `getAbstractFileByPath` immediately before use |\n| Memory leak warning | Events registered without `registerEvent` | Wrap every `.on()` with `this.registerEvent()` |\n| Stale metadata | Cache not yet updated after `vault.modify` | Listen to `metadataCache.on('changed')` instead of reading immediately |\n| Plugin slows Obsidian | Processing every keystroke | Debounce `modify` handlers (2s+ delay) |\n| `createFolder` throws | Folder already exists | Check `getAbstractFileByPath` first |\n| `normalizePath` undefined | Forgot import | Import from `\"obsidian\"` |\n\n## Examples\n\n**Complete plugin using all patterns together:**\n```typescript\nimport { Plugin, TFile, debounce, normalizePath } from \"obsidian\";\nimport { loadSettings, PluginSettings } from \".\u002Fsettings\";\nimport { VaultHelper } from \".\u002Fvault-helpers\";\nimport { MetadataHelper } from \".\u002Fmetadata-helpers\";\n\nexport default class MyPlugin extends Plugin {\n  settings: PluginSettings;\n  vault: VaultHelper;\n  meta: MetadataHelper;\n\n  async onload() {\n    this.settings = await loadSettings(this);\n    this.vault = new VaultHelper(this.app);\n    this.meta = new MetadataHelper(this.app);\n\n    \u002F\u002F Debounced auto-index\n    const reindex = debounce(\n      (file: TFile) => this.indexFile(file), 2000, true\n    );\n    this.registerEvent(\n      this.app.vault.on(\"modify\", (f) => {\n        if (f instanceof TFile) reindex(f);\n      })\n    );\n  }\n\n  private async indexFile(file: TFile) {\n    const content = await this.vault.safeRead(file.path);\n    if (!content) return;\n    const tags = this.meta.filesWithTag(\"index\");\n    \u002F\u002F ... indexing logic\n  }\n}\n```\n\n## Resources\n- [Obsidian Plugin API](https:\u002F\u002Fdocs.obsidian.md\u002FReference\u002FTypeScript+API)\n- [Vault API](https:\u002F\u002Fdocs.obsidian.md\u002FReference\u002FTypeScript+API\u002FVault)\n- [MetadataCache API](https:\u002F\u002Fdocs.obsidian.md\u002FReference\u002FTypeScript+API\u002FMetadataCache)\n- [Plugin Guidelines](https:\u002F\u002Fdocs.obsidian.md\u002FPlugins\u002FReleasing\u002FPlugin+guidelines)\n\n## Next Steps\nDebug and test: `obsidian-local-dev-loop`. Common errors: `obsidian-common-errors`. Release: `obsidian-prod-checklist`.\n","# Obsidian SDK Patterns\n\n## Overview\n\nSix production patterns that prevent the most common Obsidian plugin bugs: lost\nsettings on upgrade, null-reference crashes on deleted files, memory leaks from\nunregistered events, stale metadata, and UI jank from rapid file changes. Each\npattern is self-contained and copy-pasteable.\n\n## Prerequisites\n\n- A working Obsidian plugin (see `obsidian-core-workflow-a`)\n- TypeScript strict mode enabled (`\"strictNullChecks\": true` in tsconfig)\n- Familiarity with `Plugin.onload()` \u002F `onunload()` lifecycle\n\n## Instructions\n\n### Step 1: Typed settings with versioned migration\n\nSettings break when you add or rename fields between releases. Version the\nsettings object and migrate on load so existing users keep their data.\n\n```typescript\n\u002F\u002F src\u002Fsettings.ts\ninterface PluginSettingsV1 {\n  apiKey: string;\n  interval: number;\n}\n\ninterface PluginSettingsV2 {\n  version: 2;\n  apiKey: string;\n  syncInterval: number;      \u002F\u002F renamed from \"interval\"\n  excludedFolders: string[]; \u002F\u002F new field\n  theme: \"default\" | \"minimal\";\n}\n\n\u002F\u002F Current version is always the latest\ntype PluginSettings = PluginSettingsV2;\n\nconst DEFAULTS: PluginSettings = {\n  version: 2,\n  apiKey: \"\",\n  syncInterval: 300,\n  excludedFolders: [],\n  theme: \"default\",\n};\n\nexport async function loadSettings(plugin: Plugin): Promise\u003CPluginSettings> {\n  const raw = (await plugin.loadData()) as any;\n  if (!raw) return { ...DEFAULTS };\n\n  \u002F\u002F Migrate v1 -> v2\n  if (!raw.version || raw.version \u003C 2) {\n    raw.version = 2;\n    if (raw.interval !== undefined) {\n      raw.syncInterval = raw.interval;\n      delete raw.interval;\n    }\n    raw.excludedFolders = raw.excludedFolders ?? [];\n    raw.theme = raw.theme ?? \"default\";\n    await plugin.saveData(raw);\n  }\n\n  \u002F\u002F Merge with defaults to pick up any newly added fields\n  return { ...DEFAULTS, ...raw };\n}\n```\n\nWhy: `Object.assign({}, DEFAULTS, raw)` handles new fields added in patch\nreleases. The explicit migration block handles renames and type changes between\nmajor versions.\n\n### Step 2: Safe vault operations (check-before-act)\n\nThe Vault API throws if you create a file that exists or read one that was\ndeleted between your check and your call. Wrap every operation.\n\n```typescript\n\u002F\u002F src\u002Fvault-helpers.ts\nimport { App, TFile, TFolder, TAbstractFile, normalizePath } from \"obsidian\";\n\nexport class VaultHelper {\n  constructor(private app: App) {}\n\n  \u002F** Read file content, return null if file doesn't exist *\u002F\n  async safeRead(path: string): Promise\u003Cstring | null> {\n    const file = this.app.vault.getAbstractFileByPath(normalizePath(path));\n    if (!(file instanceof TFile)) return null;\n    return this.app.vault.read(file);\n  }\n\n  \u002F** Create or overwrite a file. Creates parent folders as needed. *\u002F\n  async safeWrite(path: string, content: string): Promise\u003CTFile> {\n    const normalized = normalizePath(path);\n    await this.ensureParentFolder(normalized);\n\n    const existing = this.app.vault.getAbstractFileByPath(normalized);\n    if (existing instanceof TFile) {\n      await this.app.vault.modify(existing, content);\n      return existing;\n    }\n    return this.app.vault.create(normalized, content);\n  }\n\n  \u002F** Append content to a file. Creates the file if it doesn't exist. *\u002F\n  async safeAppend(path: string, content: string): Promise\u003Cvoid> {\n    const normalized = normalizePath(path);\n    const existing = this.app.vault.getAbstractFileByPath(normalized);\n    if (existing instanceof TFile) {\n      const current = await this.app.vault.read(existing);\n      await this.app.vault.modify(existing, current + content);\n    } else {\n      await this.ensureParentFolder(normalized);\n      await this.app.vault.create(normalized, content);\n    }\n  }\n\n  \u002F** Delete a file if it exists, moving to trash by default. *\u002F\n  async safeDelete(path: string, useTrash = true): Promise\u003Cboolean> {\n    const file = this.app.vault.getAbstractFileByPath(normalizePath(path));\n    if (!(file instanceof TFile)) return false;\n    if (useTrash) {\n      await this.app.vault.trash(file, false);\n    } else {\n      await this.app.vault.delete(file);\n    }\n    return true;\n  }\n\n  \u002F** Ensure a folder (and all parents) exist. *\u002F\n  private async ensureParentFolder(filePath: string): Promise\u003Cvoid> {\n    const parts = filePath.split(\"\u002F\");\n    parts.pop(); \u002F\u002F remove filename\n    let current = \"\";\n    for (const part of parts) {\n      current = current ? `${current}\u002F${part}` : part;\n      const existing = this.app.vault.getAbstractFileByPath(current);\n      if (!existing) {\n        await this.app.vault.createFolder(current);\n      }\n    }\n  }\n}\n```\n\n### Step 3: Event management with automatic cleanup\n\nEvery `this.registerEvent(...)` call in `onload()` is automatically cleaned up\nwhen the plugin unloads. Never use raw `addEventListener` or `app.vault.on()`\nwithout registering -- those leak.\n\n```typescript\nexport default class MyPlugin extends Plugin {\n  async onload() {\n    \u002F\u002F File events -- auto-cleaned on unload\n    this.registerEvent(\n      this.app.vault.on(\"create\", (file) => {\n        if (file instanceof TFile) this.onFileCreated(file);\n      })\n    );\n\n    this.registerEvent(\n      this.app.vault.on(\"delete\", (file) => {\n        if (file instanceof TFile) this.onFileDeleted(file);\n      })\n    );\n\n    this.registerEvent(\n      this.app.vault.on(\"rename\", (file, oldPath) => {\n        if (file instanceof TFile) this.onFileRenamed(file, oldPath);\n      })\n    );\n\n    \u002F\u002F Workspace events\n    this.registerEvent(\n      this.app.workspace.on(\"active-leaf-change\", (leaf) => {\n        this.onActiveLeafChange(leaf);\n      })\n    );\n\n    this.registerEvent(\n      this.app.workspace.on(\"layout-change\", () => {\n        this.onLayoutChange();\n      })\n    );\n\n    \u002F\u002F Periodic tasks -- also auto-cleaned\n    this.registerInterval(\n      window.setInterval(() => this.periodicSync(), 60_000)\n    );\n\n    \u002F\u002F DOM events -- use registerDomEvent for auto-cleanup\n    this.registerDomEvent(document, \"keydown\", (evt: KeyboardEvent) => {\n      if (evt.key === \"F5\") this.refreshData();\n    });\n  }\n\n  \u002F\u002F No cleanup code needed in onunload() -- all registered events\n  \u002F\u002F are automatically removed by the Plugin base class.\n}\n```\n\nAnti-pattern to avoid:\n```typescript\n\u002F\u002F BAD: leaks on plugin unload\nthis.app.vault.on(\"modify\", handler);\ndocument.addEventListener(\"click\", handler);\n\n\u002F\u002F GOOD: auto-cleaned\nthis.registerEvent(this.app.vault.on(\"modify\", handler));\nthis.registerDomEvent(document, \"click\", handler);\n```\n\n### Step 4: Workspace layout manipulation\n\nOpen files in specific panes, split views, and restore layout state.\n\n```typescript\nimport { MarkdownView, WorkspaceLeaf } from \"obsidian\";\n\nexport class WorkspaceHelper {\n  constructor(private app: App) {}\n\n  \u002F** Open a file in a new tab *\u002F\n  async openInNewTab(path: string): Promise\u003Cvoid> {\n    const file = this.app.vault.getAbstractFileByPath(path);\n    if (!(file instanceof TFile)) return;\n    const leaf = this.app.workspace.getLeaf(\"tab\");\n    await leaf.openFile(file);\n  }\n\n  \u002F** Open a file in a vertical split to the right *\u002F\n  async openInSplit(path: string): Promise\u003Cvoid> {\n    const file = this.app.vault.getAbstractFileByPath(path);\n    if (!(file instanceof TFile)) return;\n    const leaf = this.app.workspace.getLeaf(\"split\", \"vertical\");\n    await leaf.openFile(file);\n  }\n\n  \u002F** Get the currently active markdown file (or null) *\u002F\n  getActiveFile(): TFile | null {\n    const view = this.app.workspace.getActiveViewOfType(MarkdownView);\n    return view?.file ?? null;\n  }\n\n  \u002F** Iterate all open markdown leaves *\u002F\n  forEachOpenNote(callback: (file: TFile, leaf: WorkspaceLeaf) => void): void {\n    this.app.workspace.iterateAllLeaves((leaf) => {\n      if (leaf.view instanceof MarkdownView && leaf.view.file) {\n        callback(leaf.view.file, leaf);\n      }\n    });\n  }\n\n  \u002F** Pin\u002Funpin the active tab *\u002F\n  togglePin(): void {\n    const leaf = this.app.workspace.getLeaf();\n    if (leaf) {\n      const pinned = (leaf as any).pinned;\n      (leaf as any).setPinned(!pinned);\n    }\n  }\n}\n```\n\n### Step 5: Metadata cache for fast queries\n\n`metadataCache` is Obsidian's pre-parsed index of all vault files. It avoids\nreading file content for frontmatter, tags, links, and headings.\n\n```typescript\nimport { App, TFile, CachedMetadata } from \"obsidian\";\n\nexport class MetadataHelper {\n  constructor(private app: App) {}\n\n  \u002F** Get parsed metadata for a file (frontmatter, tags, links, headings) *\u002F\n  getCache(file: TFile): CachedMetadata | null {\n    return this.app.metadataCache.getFileCache(file);\n  }\n\n  \u002F** Get frontmatter value, returns undefined if missing *\u002F\n  getFrontmatterValue(file: TFile, key: string): any | undefined {\n    const cache = this.getCache(file);\n    return cache?.frontmatter?.[key];\n  }\n\n  \u002F** Find all files with a specific tag *\u002F\n  filesWithTag(tag: string): TFile[] {\n    const normalized = tag.startsWith(\"#\") ? tag : `#${tag}`;\n    return this.app.vault.getMarkdownFiles().filter((file) => {\n      const cache = this.getCache(file);\n      \u002F\u002F Tags in body\n      const bodyTags = cache?.tags?.map((t) => t.tag) ?? [];\n      \u002F\u002F Tags in frontmatter\n      const fmTags = (cache?.frontmatter?.tags ?? []).map((t: string) =>\n        t.startsWith(\"#\") ? t : `#${t}`\n      );\n      return [...bodyTags, ...fmTags].includes(normalized);\n    });\n  }\n\n  \u002F** Get all outgoing links from a file *\u002F\n  outgoingLinks(file: TFile): string[] {\n    const cache = this.getCache(file);\n    const links = cache?.links?.map((l) => l.link) ?? [];\n    const embeds = cache?.embeds?.map((e) => e.link) ?? [];\n    return [...new Set([...links, ...embeds])];\n  }\n\n  \u002F** Get files that link to this file (backlinks) *\u002F\n  backlinks(file: TFile): TFile[] {\n    const resolved = this.app.metadataCache.resolvedLinks;\n    const results: TFile[] = [];\n    for (const [sourcePath, targets] of Object.entries(resolved)) {\n      if (file.path in targets) {\n        const source = this.app.vault.getAbstractFileByPath(sourcePath);\n        if (source instanceof TFile) results.push(source);\n      }\n    }\n    return results;\n  }\n\n  \u002F** Wait for metadata cache to be fully indexed (useful on plugin load) *\u002F\n  onCacheReady(callback: () => void): void {\n    if (this.app.metadataCache.initialized) {\n      callback();\n    } else {\n      this.app.metadataCache.on(\"initialized\", callback);\n    }\n  }\n\n  \u002F** Listen for metadata changes on a specific file *\u002F\n  onFileMetadataChange(\n    plugin: Plugin,\n    filePath: string,\n    callback: (cache: CachedMetadata) => void\n  ): void {\n    plugin.registerEvent(\n      this.app.metadataCache.on(\"changed\", (file, _data, cache) => {\n        if (file.path === filePath) callback(cache);\n      })\n    );\n  }\n}\n```\n\n### Step 6: Debounced file modification handlers\n\nPlugins that react to file changes (auto-save, indexing, sync) fire too often\nwithout debouncing. Obsidian's vault `modify` event fires on every keystroke\nwhen live preview is active.\n\n```typescript\nimport { Plugin, TFile, debounce } from \"obsidian\";\n\nexport default class IndexerPlugin extends Plugin {\n  \u002F\u002F Debounce: wait 2s after last modification before processing\n  private processFile = debounce(\n    async (file: TFile) => {\n      console.log(`[Indexer] Processing ${file.path}`);\n      const content = await this.app.vault.read(file);\n      await this.updateIndex(file, content);\n    },\n    2000,\n    true  \u002F\u002F true = reset timer on each call (trailing edge)\n  );\n\n  async onload() {\n    this.registerEvent(\n      this.app.vault.on(\"modify\", (file) => {\n        if (file instanceof TFile && file.extension === \"md\") {\n          this.processFile(file);\n        }\n      })\n    );\n  }\n\n  private async updateIndex(file: TFile, content: string): Promise\u003Cvoid> {\n    \u002F\u002F Your indexing logic here -- runs at most once per 2s per file\n  }\n}\n```\n\nFor per-file debouncing (different timers for different files):\n\n```typescript\nprivate fileTimers = new Map\u003Cstring, ReturnType\u003Ctypeof setTimeout>>();\n\nprivate debouncedProcess(file: TFile, delayMs = 2000): void {\n  const existing = this.fileTimers.get(file.path);\n  if (existing) clearTimeout(existing);\n\n  this.fileTimers.set(\n    file.path,\n    setTimeout(async () => {\n      this.fileTimers.delete(file.path);\n      const content = await this.app.vault.read(file);\n      await this.updateIndex(file, content);\n    }, delayMs)\n  );\n}\n\n\u002F\u002F Clean up all timers on unload\nonunload() {\n  for (const timer of this.fileTimers.values()) {\n    clearTimeout(timer);\n  }\n  this.fileTimers.clear();\n}\n```\n\n## Output\n\nAfter applying these patterns:\n- Settings survive across plugin updates with automatic migration\n- File operations never crash on missing files or duplicate paths\n- All events auto-clean on plugin unload (zero memory leaks)\n- Workspace manipulation opens files in tabs, splits, or sidebar\n- Metadata cache provides instant tag\u002Flink\u002Ffrontmatter queries without reading files\n- File modification handlers are debounced to prevent UI jank and redundant work\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| Settings lost after update | No version field \u002F no migration | Add `version` to settings interface, migrate in `loadSettings` |\n| `null` file reference | File deleted between check and use | Always re-fetch with `getAbstractFileByPath` immediately before use |\n| Memory leak warning | Events registered without `registerEvent` | Wrap every `.on()` with `this.registerEvent()` |\n| Stale metadata | Cache not yet updated after `vault.modify` | Listen to `metadataCache.on('changed')` instead of reading immediately |\n| Plugin slows Obsidian | Processing every keystroke | Debounce `modify` handlers (2s+ delay) |\n| `createFolder` throws | Folder already exists | Check `getAbstractFileByPath` first |\n| `normalizePath` undefined | Forgot import | Import from `\"obsidian\"` |\n\n## Examples\n\n**Complete plugin using all patterns together:**\n```typescript\nimport { Plugin, TFile, debounce, normalizePath } from \"obsidian\";\nimport { loadSettings, PluginSettings } from \".\u002Fsettings\";\nimport { VaultHelper } from \".\u002Fvault-helpers\";\nimport { MetadataHelper } from \".\u002Fmetadata-helpers\";\n\nexport default class MyPlugin extends Plugin {\n  settings: PluginSettings;\n  vault: VaultHelper;\n  meta: MetadataHelper;\n\n  async onload() {\n    this.settings = await loadSettings(this);\n    this.vault = new VaultHelper(this.app);\n    this.meta = new MetadataHelper(this.app);\n\n    \u002F\u002F Debounced auto-index\n    const reindex = debounce(\n      (file: TFile) => this.indexFile(file), 2000, true\n    );\n    this.registerEvent(\n      this.app.vault.on(\"modify\", (f) => {\n        if (f instanceof TFile) reindex(f);\n      })\n    );\n  }\n\n  private async indexFile(file: TFile) {\n    const content = await this.vault.safeRead(file.path);\n    if (!content) return;\n    const tags = this.meta.filesWithTag(\"index\");\n    \u002F\u002F ... indexing logic\n  }\n}\n```\n\n## Resources\n- [Obsidian Plugin API](https:\u002F\u002Fdocs.obsidian.md\u002FReference\u002FTypeScript+API)\n- [Vault API](https:\u002F\u002Fdocs.obsidian.md\u002FReference\u002FTypeScript+API\u002FVault)\n- [MetadataCache API](https:\u002F\u002Fdocs.obsidian.md\u002FReference\u002FTypeScript+API\u002FMetadataCache)\n- [Plugin Guidelines](https:\u002F\u002Fdocs.obsidian.md\u002FPlugins\u002FReleasing\u002FPlugin+guidelines)\n\n## Next Steps\nDebug and test: `obsidian-local-dev-loop`. Common errors: `obsidian-common-errors`. Release: `obsidian-prod-checklist`.\n",{"name":5,"tags":24,"author":30,"license":15,"version":31,"description":32,"allowed-tools":33,"compatible-with":34},[25,26,27,28,29],"obsidian","patterns","production","typescript","best-practices","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","2.0.0","Production-ready Obsidian plugin patterns: typed settings with migration,\nsafe vault operations, event auto-cleanup, workspace layout, metadata cache,\nand debounced file handlers. Use when hardening a plugin for release,\nrefactoring for reliability, or learning idiomatic Obsidian TypeScript.\nTrigger with \"obsidian patterns\", \"obsidian best practices\",\n\"obsidian production code\", \"idiomatic obsidian plugin\".\n","Read, Write, Edit, Grep","claude-code, codex, openclaw","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--obsidian-pack--obsidian-sdk-patterns",0,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills","https:\u002F\u002Fgithub.com\u002Fjukeyman","https:\u002F\u002FRJBUSINESSSOLUTIONS.ORG","Credit and Finance Expert | Developer\r\n\r\nI'm Rick Jefferson, a seasoned credit and finance expert with over a decade of experience in financial literacy,","2026-07-13 07:03:29",{"source":8,"skillName":5,"commands":45,"prompt":55,"zipAvailable":56},[46,49,52],{"tool":47,"command":48},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill obsidian-sdk-patterns",{"tool":50,"command":51},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill obsidian-sdk-patterns",{"tool":53,"command":54},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill obsidian-sdk-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--obsidian-pack--obsidian-sdk-patterns\u002FSKILL.md",true,[],[59,66,73,80,87,95],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M79ANS2SM329NEP5ZCX106RR","zustand-store-creator","Create zustand store creator operations. Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like \"zustand store creator\", \"zustand creator\", \"zustand\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M79AMZKP4YDEZ7EHG1Y7PP74","zero-trust-config-helper","Configure with zero trust config helper operations. Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like \"zero trust config helper\", \"zero helper\", \"zero\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M79AMJSBCEJQNBTYNAHYN5HM","zapier-integration-helper","Assist with zapier integration helper operations. Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like \"zapier integration helper\", \"zapier helper\", \"zapier\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M79AHJZGVMARS13VFQYRR1MP","yaml-config-validator","Validate yaml config validator operations. Auto-activating skill for DevOps Basics.\nTriggers on: yaml config validator, yaml config validator\nPart of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like \"yaml config validator\", \"yaml validator\", \"yaml\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fyaml-config-validator\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":91,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M79AHGDZRN0020RDQSQDPAM8","xvary-stock-research","Thesis-driven equity analysis from public SEC EDGAR and market data; \u002Fanalyze, \u002Fscore, \u002Fcompare workflows with bundled Python tools (Claude Code, Cursor, Codex).","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M79AHCYJ9FV9RMHQ24HDRN33","xss-vulnerability-scanner","Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals.\nTriggers on: xss vulnerability scanner, xss vulnerability scanner\nPart of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like \"xss vulnerability scanner\", \"xss scanner\", \"xss\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxss-vulnerability-scanner\u002FSKILL.md",[],[]]