From 5fb6946aa1d34b0b0490b47547a5bb9ddf78810d Mon Sep 17 00:00:00 2001 From: enricobuehler Date: Wed, 5 Aug 2026 19:17:02 +0200 Subject: [PATCH] feat: the Heroic library source MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The host's in-tree Heroic scanner, lifted out into its own installable plugin (design/library-scanner-plugins.md M5/WP5.2). One source covers all three of Heroic's backends — legendary (Epic), gog, nile (Amazon) — because that is how Heroic presents them and how the built-in scanner did. The package is a config schema, a detect, a scan and a watchDirs. The store claim, sync engine, __config surface, console registration and the detect/scan/parity/uninstall CLI verbs all come from @punktfunk/plugin-kit/library. Claiming the `heroic` store keeps the entry ids the built-in scanner produced (`heroic::`), so GameStream app ids, Moonlight pins, cached art and the operator's enabled/disabled state all survive the migration. Ported behaviours worth naming, each covered by a test: * a title counts as installed only if Heroic says so AND its install directory still exists. The second check is the workaround for Heroic's GOG is_installed bug (#2691), without which uninstalled games linger. * only http(s) art is emitted. A sideloaded title can carry a local file:// path, which — unlike a path this plugin resolved itself — is not one the host should proxy, and the client cannot fetch either. It degrades to the title card, as in-host. * both detect signals ride along: the install dir and the HEROIC_APP_NAME env marker. Heroic hands off to legendary/gogdl/nile, so the host never sees the game's own process any other way, and the env marker is what works under Proton (verified on-glass 2026-07-27). They are a union, so a Heroic version that stops setting it degrades rather than breaking. The launch VALUE and the `heroic` launch kind are unchanged — the host still owns turning `:` into a heroic://launch command, so this plugin never constructs a command line. Verified locally against the kit: tsc clean, biome clean, 5 tests, bundle builds, CLI runs (detect -> absent, scan -> 0 games). As with lutris: no lockfile and CI cannot be green until @punktfunk/plugin-kit@0.3.0 is published. The parity gate has NOT been run — that needs a box with Heroic installed. --- .gitea/workflows/ci.yml | 72 ++++++++++++++ .gitignore | 4 + LICENSE-APACHE | 201 ++++++++++++++++++++++++++++++++++++++++ LICENSE-MIT | 21 +++++ README.md | 81 ++++++++++++++++ biome.json | 51 ++++++++++ bunfig.toml | 4 + package.json | 50 ++++++++++ src/cli.ts | 10 ++ src/index.ts | 6 ++ src/plugin.ts | 157 +++++++++++++++++++++++++++++++ test/heroic.test.ts | 110 ++++++++++++++++++++++ tsconfig.json | 16 ++++ 13 files changed, 783 insertions(+) create mode 100644 .gitea/workflows/ci.yml create mode 100644 .gitignore create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 README.md create mode 100644 biome.json create mode 100644 bunfig.toml create mode 100644 package.json create mode 100644 src/cli.ts create mode 100644 src/index.ts create mode 100644 src/plugin.ts create mode 100644 test/heroic.test.ts create mode 100644 tsconfig.json diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..0b4540e --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,72 @@ +# CI for the lutris library source (Gitea Actions). +# build — install, lint, typecheck, unit tests, bundle. +# publish — npm publish to the Gitea registry on a `v*` tag. +# +# A library-source plugin is a SINGLE package (no contract, no UI — the console renders its +# settings from the schema the kit serves at /__config), so this is the short version of the +# playnite/rom-manager workflow. +# +# @punktfunk/* resolves from the Gitea registry via bunfig's scope map + REGISTRY_TOKEN; +# everything else (effect) comes from npm. +# +# NOT covered here, and it is the gate that actually matters: `punktfunk-plugin-lutris parity` +# against a host with Lutris installed. CI has no Lutris and no host, so parity is a release +# step run on a real box — see the README. +name: CI + +on: + push: + branches: [main] + tags: ['v*'] + pull_request: + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-24.04 + container: + image: oven/bun:1 + timeout-minutes: 10 + steps: + # oven/bun's slim base ships neither git nor a CA bundle — actions/checkout's HTTPS fetch needs both. + - name: Install git + CA certs + run: apt-get update && apt-get install -y --no-install-recommends ca-certificates git nodejs + - uses: actions/checkout@v4 + - name: Registry auth + env: + TOKEN: ${{ secrets.REGISTRY_TOKEN }} + run: | + test -n "$TOKEN" || { echo "REGISTRY_TOKEN secret is empty"; exit 1; } + printf '//git.unom.io/api/packages/unom/npm/:_authToken=%s\n' "$TOKEN" > "$HOME/.npmrc" + - name: Install + run: bun install --frozen-lockfile + - name: Lint & format + run: bunx biome check + - name: Typecheck + run: bunx tsc --noEmit + - name: Test + run: bun test + - name: Build + run: bun run build + + publish: + if: startsWith(github.ref, 'refs/tags/v') + needs: build + runs-on: ubuntu-24.04 + container: + image: oven/bun:1 + timeout-minutes: 10 + steps: + - name: Install git + CA certs + run: apt-get update && apt-get install -y --no-install-recommends ca-certificates git nodejs + - uses: actions/checkout@v4 + - name: Registry auth + env: + TOKEN: ${{ secrets.REGISTRY_TOKEN }} + run: | + test -n "$TOKEN" || { echo "REGISTRY_TOKEN secret is empty"; exit 1; } + printf '//git.unom.io/api/packages/unom/npm/:_authToken=%s\n' "$TOKEN" > "$HOME/.npmrc" + - name: Install + run: bun install --frozen-lockfile + - name: Publish + run: bun publish --access public diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7535211 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules +dist +*.log +.DS_Store diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..ce5770d --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative + Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 unom + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..f42d1f9 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 unom + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..dfdc591 --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +# @punktfunk/plugin-heroic + +Adds your installed **Heroic Games Launcher** titles to a Punktfunk host's library — Epic, GOG and +Amazon in one source, with their cover art, and with the session ending when you quit the game. + +Install it from the host's plugin store (**Library → Game sources → Add a source**), or: + +```sh +punktfunk-host plugins add heroic +``` + +Nothing to configure: it finds Heroic's config folder in the usual places (`$XDG_CONFIG_HOME/heroic`, +`~/.config/heroic`, Flatpak) and reads the library caches from there. If yours lives somewhere else, +set the path in **Library → Game sources → Heroic → Settings**. + +## What it replaces + +Punktfunk used to scan Heroic from inside the host. This plugin is that scanner, lifted out — so you +install it only if you use Heroic, and it can be updated without updating the host. + +It claims the `heroic` store, which means your games keep **exactly** the ids they had before +(`heroic:legendary:`): Moonlight pins, cached box art, and your enabled/disabled state all +carry over, and the host's built-in scanner switches itself off while this is installed. Remove the +plugin and the built-in comes straight back. + +## What gets listed + +Only titles Heroic reports as installed **and** whose install directory still exists — the second +check works around Heroic's GOG `is_installed` bug +([#2691](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher/issues/2691)), which otherwise +leaves uninstalled games sitting in your library. + +Art comes straight from Heroic's cached CDN URLs, so the client fetches it directly. A sideloaded +title whose art is a local `file://` path is listed without art rather than with a picture nothing +can load. + +## Commands + +```sh +punktfunk-plugin-heroic detect # is Heroic installed on this host? +punktfunk-plugin-heroic scan --preview # what WOULD be synced, as JSON (works with no host) +punktfunk-plugin-heroic uninstall # drop the games and release the store claim +``` + +## Parity — the release gate + +Unit tests pin the parsing. What actually has to hold is that this plugin reproduces the in-host +scanner it replaces, down to the ids — one that parses perfectly but emits a subtly different +`external_id` breaks every Moonlight pin on the host, and no unit test notices. + +So, on a box with Heroic installed, **before** installing this plugin: + +```sh +punktfunk-plugin-heroic parity --snapshot before.json # host still on its built-in scanner +punktfunk-plugin-heroic parity --compare before.json # offline; exits non-zero on any difference +``` + +`--compare` runs this plugin's own scan and diffs it: ids, titles, launch recipes, roles and +metadata exactly; art by **presence, not value**. + +Worth re-checking on-glass specifically: a game launched under **Proton**. Heroic hands off to +legendary/gogdl/nile, so the `HEROIC_APP_NAME` environment marker is what lets the host recognise +the running game and end the session when you quit it. + +Do not publish a version whose parity run is red. + +## Development + +```sh +bun install +bun run typecheck && bun test && bun run build +``` + +The framework — store claim, sync engine, `__config`, CLI verbs, and the launcher-file parsers — +lives in [`@punktfunk/plugin-kit/library`](https://git.unom.io/unom/punktfunk/src/branch/main/plugin-kit). +This package is the Heroic-specific part: find the config root, read the three `store_cache` +libraries, map entries. See `design/library-scanner-plugins.md` in the main repo. + +## License + +MIT OR Apache-2.0. diff --git a/biome.json b/biome.json new file mode 100644 index 0000000..db9e0f5 --- /dev/null +++ b/biome.json @@ -0,0 +1,51 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.5.6/schema.json", + "vcs": { + "enabled": true, + "clientKind": "git", + "useIgnoreFile": true + }, + "files": { + "ignoreUnknown": false, + "includes": ["**", "!dist", "!ui/dist", "!**/node_modules"] + }, + "formatter": { + "enabled": true, + "indentStyle": "tab" + }, + "css": { + "parser": { + "tailwindDirectives": true + } + }, + "assist": { + "actions": { + "source": { + "organizeImports": "on" + } + } + }, + "linter": { + "enabled": true, + "rules": { + "preset": "recommended", + "suspicious": { + "noArrayIndexKey": "off" + }, + "style": { + "noNonNullAssertion": "off" + }, + "a11y": { + "noLabelWithoutControl": "off" + }, + "correctness": { + "useExhaustiveDependencies": "warn" + } + } + }, + "javascript": { + "formatter": { + "quoteStyle": "double" + } + } +} diff --git a/bunfig.toml b/bunfig.toml new file mode 100644 index 0000000..c15a194 --- /dev/null +++ b/bunfig.toml @@ -0,0 +1,4 @@ +# Resolve the @punktfunk scope from the Gitea npm registry for the whole workspace. +[install.scopes] +"@punktfunk" = "https://git.unom.io/api/packages/unom/npm/" +"@unom" = "https://git.unom.io/api/packages/unom/npm/" diff --git a/package.json b/package.json new file mode 100644 index 0000000..9ea4dc5 --- /dev/null +++ b/package.json @@ -0,0 +1,50 @@ +{ + "name": "@punktfunk/plugin-heroic", + "version": "0.1.0", + "private": false, + "type": "module", + "description": "Punktfunk plugin: adds your installed Heroic Games Launcher titles (Epic, GOG, Amazon) to the host's library, with their cover art.", + "license": "MIT OR Apache-2.0", + "homepage": "https://git.unom.io/unom/punktfunk-plugin-heroic", + "repository": { + "type": "git", + "url": "https://git.unom.io/unom/punktfunk-plugin-heroic.git" + }, + "keywords": [ + "punktfunk", + "plugin", + "heroic", + "epic", + "gog", + "game-library", + "game-streaming" + ], + "main": "./dist/index.js", + "module": "./dist/index.js", + "bin": { + "punktfunk-plugin-heroic": "./dist/cli.js" + }, + "files": [ + "dist" + ], + "publishConfig": { + "registry": "https://git.unom.io/api/packages/unom/npm/" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "bun test", + "build": "bun build src/index.ts src/cli.ts --target=bun --outdir dist --external effect --external '@punktfunk/*'", + "prepublishOnly": "bun run build", + "check": "bunx biome check ." + }, + "dependencies": { + "@punktfunk/host": "^0.1.2", + "@punktfunk/plugin-kit": "^0.3.0", + "effect": "4.0.0-beta.99" + }, + "devDependencies": { + "@biomejs/biome": "^2.5.2", + "@types/bun": "^1.3.0", + "typescript": "^5.9.3" + } +} diff --git a/src/cli.ts b/src/cli.ts new file mode 100644 index 0000000..a89aadc --- /dev/null +++ b/src/cli.ts @@ -0,0 +1,10 @@ +#!/usr/bin/env bun +// `punktfunk-plugin-heroic ` — the ops surface. +// +// The verbs come from the kit: `detect` (is Heroic installed here?), `scan [--preview]` (what WOULD +// be synced, offline), `parity --snapshot|--compare` (prove this reproduces the host's built-in +// scanner), and `uninstall` (drop the games and release the store claim). `runPluginCli` exits the +// process itself, so there is nothing to await after it. +import { plugin } from "./plugin.js"; + +await plugin.cli(); diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..a609935 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,6 @@ +// The runner's entry point. It discovers plugins by their DEFAULT EXPORT, which must be the +// `PluginDef` — `defineLibraryPlugin` returns that as `.def` alongside the CLI entry, so the two +// entry points stay thin and the definition lives in one place (./plugin.ts). +import { plugin } from "./plugin.js"; + +export default plugin.def; diff --git a/src/plugin.ts b/src/plugin.ts new file mode 100644 index 0000000..77fe28c --- /dev/null +++ b/src/plugin.ts @@ -0,0 +1,157 @@ +// The Heroic library source: your installed Heroic Games Launcher titles, in the host's library. +// +// One source covers all three of Heroic's backends — legendary (Epic), gog, nile (Amazon) — because +// that is how Heroic itself presents them, and how the host's own scanner did. +// +// Everything below `scan` is Heroic-specific parsing. Everything else — claiming the `heroic` store +// so these entries keep the ids the host's own scanner gave them, the sync engine, the `__config` +// surface, the console registration, and the `detect` / `scan` / `parity` / `uninstall` CLI verbs — +// comes from `defineLibraryPlugin`. +// +// Ported from crates/punktfunk-host/src/library/heroic.rs. The launch VALUE (`:`) +// and the `heroic` launch kind are unchanged: the host still owns turning that into a +// `heroic://launch?…` command, so this plugin never constructs a command line. +import * as os from "node:os"; +import * as path from "node:path"; +import { + defineLibraryPlugin, + isDir, + readJsonCapped, +} from "@punktfunk/plugin-kit/library"; +import type { ProviderEntry } from "@punktfunk/plugin-kit/wire"; +import { Effect, Schema } from "effect"; + +const HeroicConfig = Schema.Struct({ + /** Where Heroic keeps its config, when it isn't in one of the standard places. */ + configRoot: Schema.optionalKey( + Schema.String.annotate({ + title: "Heroic config folder", + description: + "Absolute path to Heroic's config directory. Leave empty to find it automatically.", + }), + ), +}); + +/** Heroic's three backends: (store_cache file, runner id, the electron-store key holding games). */ +const RUNNERS = [ + { file: "legendary_library.json", runner: "legendary", key: "library" }, + { file: "gog_library.json", runner: "gog", key: "games" }, + { file: "nile_library.json", runner: "nile", key: "library" }, +] as const; + +/** Candidate Heroic config roots: XDG config dir, the classic path, Flatpak. */ +const rootCandidates = (): string[] => { + const out: string[] = []; + const xdg = process.env.XDG_CONFIG_HOME; + if (xdg) out.push(path.join(xdg, "heroic")); + const home = os.homedir(); + if (home) { + out.push(path.join(home, ".config/heroic")); + out.push( + path.join(home, ".var/app/com.heroicgameslauncher.hgl/config/heroic"), + ); + } + return out; +}; + +const findRoot = (cfg: { configRoot?: string }): string | undefined => + [...(cfg.configRoot ? [cfg.configRoot] : []), ...rootCandidates()].find( + isDir, + ); + +/** One entry in a runner's cached library array — only the fields we read. */ +interface HeroicGame { + app_name?: string; + title?: string; + is_installed?: boolean; + install?: { install_path?: string }; + art_square?: string; + art_cover?: string; + art_background?: string; + art_logo?: string; +} + +/** + * Only `http(s)` art is emitted. A sideloaded title can carry a local `file://` path here, and + * unlike a path this plugin resolved itself, Heroic's is not one the host should be asked to proxy + * — it may point anywhere, and the client can't fetch it either. Dropping it degrades to the title + * card, which is what the in-host scanner did. + */ +const httpArt = (v: string | undefined): string | undefined => + v && (v.startsWith("http://") || v.startsWith("https://")) ? v : undefined; + +/** The installed titles in one runner's `store_cache/*_library.json`. */ +export const runnerGames = ( + root: string, + file: string, + runner: string, + key: string, +): ProviderEntry[] => { + // A missing cache file is the normal "this backend is unused" case, not an error. + const doc = readJsonCapped>( + path.join(root, "store_cache", file), + // These caches carry every OWNED title with its art URLs, so they run large on a big + // account — well past the default manifest cap. + 32 * 1024 * 1024, + ); + const arr = doc?.[key]; + if (!Array.isArray(arr)) return []; + + const out: ProviderEntry[] = []; + for (const g of arr as HeroicGame[]) { + // The cache also lists owned-but-not-installed titles. + if (g.is_installed !== true) continue; + // Requiring the install dir to EXIST works around Heroic's gog `is_installed` bug (#2691), + // and the dir doubles as this title's detect signal. + const installPath = g.install?.install_path; + if (!installPath || !isDir(installPath)) continue; + const appName = g.app_name; + if (!appName) continue; + + out.push({ + // `:` — the host composes `heroic:`, byte-identical to what the + // built-in scanner produced. + external_id: `${runner}:${appName}`, + title: g.title || appName, + launch: { kind: "heroic", value: `${runner}:${appName}` }, + art: { + portrait: httpArt(g.art_square) ?? null, + header: httpArt(g.art_cover) ?? null, + hero: httpArt(g.art_background) ?? httpArt(g.art_cover) ?? null, + logo: httpArt(g.art_logo) ?? null, + }, + detect: { + install_dir: installPath, + // Heroic hands off to legendary/gogdl/nile, so the host never sees the game's own + // process any other way. The env marker is a second, cheap signal in the union — it is + // load-bearing under Proton, where the process tree tells you very little (verified + // on-glass 2026-07-27), and harmless on a Heroic version that doesn't set it. + env_marker: { key: "HEROIC_APP_NAME", value: appName }, + }, + platform: "PC", + }); + } + return out; +}; + +export const plugin = defineLibraryPlugin({ + // One string: plugin id, provider id, store claim, and the id of the built-in scanner this + // replaces — matching the package and repo names too. + name: "heroic", + configSchema: HeroicConfig, + + detect: (cfg) => Effect.sync(() => findRoot(cfg) !== undefined), + + scan: (cfg) => + Effect.sync(() => { + const root = findRoot(cfg); + if (!root) return []; + return RUNNERS.flatMap((r) => runnerGames(root, r.file, r.runner, r.key)); + }), + + // Heroic rewrites these caches when a game is installed or removed. + watchDirs: (cfg) => { + const root = findRoot(cfg); + return root ? [path.join(root, "store_cache")] : []; + }, +}); diff --git a/test/heroic.test.ts b/test/heroic.test.ts new file mode 100644 index 0000000..d99d1c5 --- /dev/null +++ b/test/heroic.test.ts @@ -0,0 +1,110 @@ +// The Heroic-specific half: which cached titles become entries, and what art survives. Everything +// else this plugin does is the kit's. The real end-to-end proof is +// `punktfunk-plugin-heroic parity --compare`, run on a box with Heroic actually installed. +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { runnerGames } from "../src/plugin.js"; + +// A throwaway Heroic config root with a real store_cache and real install dirs — the scan requires +// the install dir to EXIST, so a fixture of pure JSON would report nothing and pass vacuously. +let root: string; +let installed: string; + +beforeAll(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), "pf-heroic-")); + installed = path.join(root, "games", "Quail"); + fs.mkdirSync(installed, { recursive: true }); + fs.mkdirSync(path.join(root, "store_cache"), { recursive: true }); + fs.writeFileSync( + path.join(root, "store_cache", "legendary_library.json"), + JSON.stringify({ + library: [ + { + app_name: "Quail", + title: "Quail", + is_installed: true, + install: { install_path: installed }, + art_square: "https://cdn/quail_tall.jpg", + art_cover: "https://cdn/quail_wide.jpg", + // Sideloaded titles carry local paths here — the client cannot fetch them. + art_logo: "file:///home/u/logo.png", + }, + { app_name: "Owned", title: "Owned Only", is_installed: false }, + { + app_name: "Ghost", + title: "Uninstalled Underneath Us", + is_installed: true, + // Heroic's gog `is_installed` bug (#2691): flagged installed, directory long gone. + install: { install_path: path.join(root, "games", "gone") }, + }, + { + title: "No App Name", + is_installed: true, + install: { install_path: installed }, + }, + ], + }), + ); +}); + +afterAll(() => fs.rmSync(root, { recursive: true, force: true })); + +const scan = () => + runnerGames(root, "legendary_library.json", "legendary", "library"); + +/** The single surviving entry. Throws rather than returning undefined, so a regression that + * empties the scan fails loudly here instead of skipping every assertion below. */ +const only = () => { + const got = scan(); + if (got.length !== 1) throw new Error(`expected 1 entry, got ${got.length}`); + return got[0]!; +}; + +describe("heroic store_cache", () => { + test("keeps only installed titles whose install dir still exists", () => { + const got = scan(); + expect(got.map((e) => e.external_id)).toEqual(["legendary:Quail"]); + // Each exclusion is a distinct real case, so spell out why the other three are gone: + // not installed, installed-but-directory-gone (the #2691 workaround), and no app_name. + expect(got).toHaveLength(1); + }); + + test("the external id is :, which the host prefixes with the store", () => { + // This is the migration invariant: the host composes `heroic:legendary:Quail`, byte-identical + // to what the built-in scanner produced, so GameStream app ids and Moonlight pins survive. + const e = only(); + expect(e.external_id).toBe("legendary:Quail"); + expect(e.launch).toEqual({ kind: "heroic", value: "legendary:Quail" }); + }); + + test("only http(s) art survives; a sideloaded file:// path is dropped", () => { + const e = only(); + expect(e.art?.portrait).toBe("https://cdn/quail_tall.jpg"); + expect(e.art?.header).toBe("https://cdn/quail_wide.jpg"); + // No art_background in the fixture → hero falls back to the cover, as in-host. + expect(e.art?.hero).toBe("https://cdn/quail_wide.jpg"); + expect(e.art?.logo).toBeNull(); + }); + + test("carries both detect signals — the dir AND the env marker", () => { + // Heroic hands off to legendary/gogdl/nile, so the host never sees the game's own process + // any other way. The env marker is load-bearing under Proton specifically. + const e = only(); + expect(e.detect?.install_dir).toBe(installed); + expect(e.detect?.env_marker).toEqual({ + key: "HEROIC_APP_NAME", + value: "Quail", + }); + }); + + test("a missing or malformed cache is empty, not an error", () => { + // The normal "this backend is unused" case — two of the three files are usually absent. + expect(runnerGames(root, "gog_library.json", "gog", "games")).toEqual([]); + expect( + runnerGames(root, "legendary_library.json", "legendary", "nope"), + ).toEqual([]); + expect(runnerGames("/nope/not/here", "x.json", "gog", "games")).toEqual([]); + }); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..326d141 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2022"], + "strict": true, + "noUncheckedIndexedAccess": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true, + "noEmit": true, + "resolveJsonModule": true, + "types": ["bun"] + }, + "include": ["src", "test"] +}