Compare commits

...
15 Commits
Author SHA1 Message Date
haylan 982e1f8de1 Merge pull request 'Chore/apache 2.0 license' (#23) from chore/apache-2.0-license into main
Reviewed-on: #23
2026-10-04 10:27:12 +00:00
haylan d4613a6683 Merge branch 'main' into chore/apache-2.0-license
check / check (pull_request) Successful in 39s
2026-10-04 10:26:30 +00:00
haylan ed653057fd Merge pull request 'fix: use renamed repository name websearch in remote URLs and docs' (#22) from chore/fix-repo-name into main
Reviewed-on: #22
2026-10-04 10:26:14 +00:00
haylan 69c39c1658 Merge branch 'main' into chore/apache-2.0-license
check / check (pull_request) Successful in 1m4s
2026-10-04 10:25:24 +00:00
haylan 80887c4479 fix: use renamed repository name websearch in remote URLs and docs
check / check (pull_request) Successful in 37s
2026-10-04 12:24:40 +02:00
haylanandClaude Bot 5194c47375 chore: use standard Apache license header in NOTICE
check / check (pull_request) Successful in 1m5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 11:32:23 +02:00
haylanandClaude Bot 3b06927111 chore: add NOTICE file
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 11:31:34 +02:00
haylan 117b38ee2f Merge pull request 'chore: relicense from MIT to Apache License 2.0' (#20) from chore/apache-2.0-license into main 2026-10-04 09:31:31 +00:00
haylanandClaude Bot 120d3fd67c chore: relicense from MIT to Apache License 2.0
check / check (pull_request) Successful in 34s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 11:29:29 +02:00
haylan 2873c12547 Merge pull request 'docs: record registry install check and document the install steps' (#19) from docs/verify-registry-install into main
Reviewed-on: haylan/fastcrw-opencode-websarch#19
2026-10-03 19:02:24 +00:00
haylanandClaude Bot 68d22e28fe ci: use only the PACKAGE_TOKEN secret for releases
check / check (pull_request) Successful in 30s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-03 21:01:52 +02:00
haylanandClaude Bot 3a15c73e95 docs: update follow-ups after the root index.js decision
check / check (pull_request) Successful in 29s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-03 20:59:18 +02:00
haylanandClaude Bot ec0ee81cef docs: record registry install check and document the install steps
check / check (pull_request) Successful in 26s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-03 20:58:55 +02:00
haylan f16536fffd Merge pull request 'ci: tag the release commit and link the package to the repository' (#18) from ci/tag-and-link-release into main
Reviewed-on: haylan/fastcrw-opencode-websarch#18
2026-10-03 18:46:00 +00:00
haylanandClaude Bot 626ad4156d ci: tag the release commit and link the package to the repository
check / check (pull_request) Successful in 26s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-03 20:44:07 +02:00
10 changed files with 270 additions and 27 deletions

No files matched your search

+4 -2
View File
@@ -16,5 +16,7 @@ jobs:
- run: npm run build - run: npm run build
- run: node scripts/release.ts - run: node scripts/release.ts
env: env:
REGISTRY_URL: ${{ gitea.server_url }}/api/packages/${{ gitea.repository_owner }}/npm SERVER_URL: ${{ gitea.server_url }}
TOKEN: ${{ secrets.PACKAGE_TOKEN || secrets.GITHUB_TOKEN }} REPOSITORY: ${{ gitea.repository }}
SHA: ${{ gitea.sha }}
TOKEN: ${{ secrets.PACKAGE_TOKEN }}
+51
View File
@@ -0,0 +1,51 @@
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:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
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
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
+14
View File
@@ -0,0 +1,14 @@
Copyright 2026 Arthur Erlich
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.
+21 -5
View File
@@ -6,13 +6,21 @@ The plugin registers a search provider with id `fastcrw` and makes it the defaul
## Install ## Install
The package is published to the Gitea npm registry. Map the scope to it in your `.npmrc`: The package is published to the Gitea npm registry. Map the scope to it in your user-level `~/.npmrc`:
``` ```
@haylan:registry=https://git.arthurerlich.de/api/packages/haylan/npm/ @haylan:registry=https://git.arthurerlich.de/api/packages/haylan/npm/
``` ```
Then add the plugin to your `opencode.json`: It has to be the user-level file (or the equivalent `npm_config_@haylan:registry` environment variable): opencode installs plugins from its own cache folder and ignores a project-level `.npmrc`, and without the mapping it looks for the package on npmjs.com and fails with a 404.
Then install it with opencode, which also adds it to your config:
```bash
opencode plugin add @haylan/opencode-fastcrw
```
A plugin that is only listed in `opencode.json` is not installed automatically. Add your options to the entry that `plugin add` created:
```jsonc ```jsonc
{ {
@@ -25,7 +33,7 @@ Then add the plugin to your `opencode.json`:
} }
``` ```
Installing by name from the Gitea registry has not been verified end to end yet; see [docs/runtime-checks.md](docs/runtime-checks.md). Verified with 0.0.1 against opencode v2.0.22; see [docs/runtime-checks.md](docs/runtime-checks.md).
### Local build ### Local build
@@ -39,7 +47,7 @@ npm run build
opencode loads local plugins as directories, resolved by file path (`<dir>/server`, then `<dir>/index`), and ignores `package.json` `exports`, so this package cannot be pointed at directly. Use a small shim instead. Create `~/.config/opencode/plugins/fastcrw.js` (a `.js` or `.ts` file; `.mjs` is ignored) with: opencode loads local plugins as directories, resolved by file path (`<dir>/server`, then `<dir>/index`), and ignores `package.json` `exports`, so this package cannot be pointed at directly. Use a small shim instead. Create `~/.config/opencode/plugins/fastcrw.js` (a `.js` or `.ts` file; `.mjs` is ignored) with:
```js ```js
export { default } from "file:///ABSOLUTE/PATH/TO/fastcrw-opencode-websarch/dist/index.js" export { default } from "file:///ABSOLUTE/PATH/TO/fastcrw-opencode-websearch/dist/index.js"
``` ```
A drop-in file cannot receive plugin options, so configure the plugin with the environment variables below (`CRW_API_URL`, `CRW_API_KEY`). To use options instead, put the same line in an `index.js` inside a directory and reference that directory as `"package": "./that-dir"` (a relative path is resolved from the config file; `~` is not expanded). A drop-in file cannot receive plugin options, so configure the plugin with the environment variables below (`CRW_API_URL`, `CRW_API_KEY`). To use options instead, put the same line in an `index.js` inside a directory and reference that directory as `"package": "./that-dir"` (a relative path is resolved from the config file; `~` is not expanded).
@@ -82,4 +90,12 @@ npm run smoke -- "query" # one real search against CRW_API_URL (manual)
### Releasing ### Releasing
Releases are published by the manually started `release` workflow on Gitea Actions. It publishes the latest version heading in `CHANGELOG.md` (the repository keeps the dev version `0.0.0-dev` in `package.json`) and skips versions that already exist. To release: add a dated `## [x.y.z]` entry to `CHANGELOG.md`, merge it to `main`, then start the workflow. It needs a `PACKAGE_TOKEN` secret with `write:package` rights unless the job token already has them. Releases are published by the manually started `release` workflow on Gitea Actions. It reads the latest version heading in `CHANGELOG.md` (the repository keeps the dev version `0.0.0-dev` in `package.json`) and then:
1. publishes that version to the Gitea npm registry, unless it already exists;
2. tags the workflow's commit `v<version>`, unless the tag already exists;
3. links the package to this repository, unless it is already linked.
Every step skips itself when done, so starting the workflow again completes a release that only partly succeeded.
To release: add a dated `## [x.y.z]` entry to `CHANGELOG.md`, merge it to `main`, then start the workflow. It needs the `PACKAGE_TOKEN` repository secret, a token with `write:package` and `write:repository` rights.
+17 -5
View File
@@ -9,8 +9,8 @@ Results of the verification list in `docs/spec.md`. Run on 2026-10-03 against op
| 1 | Built-in providers removable or disableable | Done: not removable by a plugin, but never used as a fallback | | 1 | Built-in providers removable or disableable | Done: not removable by a plugin, but never used as a fallback |
| 2 | Throwing `setup` disables only this plugin | Done: yes, loudly | | 2 | Throwing `setup` disables only this plugin | Done: yes, loudly |
| 3 | Config `websearch.provider` vs `editor.default.set` | Done: config wins | | 3 | Config `websearch.provider` vs `editor.default.set` | Done: config wins |
| 4 | Install by name from the Gitea registry | Not run (needs a published release) | | 4 | Install by name from the Gitea registry | Done: works with a user-level scope mapping |
| 5 | Release job token has package-write rights | Not run (needs a release run) | | 5 | Release token has package-write rights | Done: the release uses the `PACKAGE_TOKEN` secret |
| 6 | `@opencode/plugin` install weight | Done | | 6 | `@opencode/plugin` install weight | Done |
| 7 | `npm run smoke` against the real fastCRW server | Done | | 7 | `npm run smoke` against the real fastCRW server | Done |
| 8 | Typings, `time` shape, 429 cooldown | Done: a 429 from our plugin triggers no cooldown | | 8 | Typings, `time` shape, 429 cooldown | Done: a 429 from our plugin triggers no cooldown |
@@ -46,6 +46,19 @@ With `baseURL: "nope"`, only this plugin ended up in state `failed`, with our me
Config `websearch.provider` wins over the plugin's `editor.default.set`: with the config set to `exa`, a query without a provider id went to Exa (and worked without a key, so the query left the machine). With the config unset or set to `fastcrw`, the plugin's provider was used. Consequence: do not set `websearch.provider` to anything else; setting it to `fastcrw` is harmless and explicit. Config `websearch.provider` wins over the plugin's `editor.default.set`: with the config set to `exa`, a query without a provider id went to Exa (and worked without a key, so the query left the machine). With the config unset or set to `fastcrw`, the plugin's provider was used. Consequence: do not set `websearch.provider` to anything else; setting it to `fastcrw` is harmless and explicit.
### 4. Install by name from the Gitea registry
Release 0.0.1 is in the registry, linked to this repository, with tag `v0.0.1` (workflow run succeeded). Verified in an isolated profile:
- `npm install @haylan/opencode-fastcrw` with the scoped `.npmrc` mapping works anonymously, and the installed package imports as plugin id `fastcrw.websearch`.
- `opencode plugin add @haylan/opencode-fastcrw` with the mapping set through `npm_config_@haylan:registry` installs it and adds `"@haylan/opencode-fastcrw"` to the config. Without the mapping it queries registry.npmjs.org and fails with a 404.
- opencode ignores a project-level `.npmrc` (it installs from its own cache folder), so the mapping must be in the user-level `~/.npmrc` or the environment.
- A `plugins` entry by name is **not** installed automatically on startup; only `plugin add` installs. After adding options to the entry and starting the server, a search without a provider id went to `fastcrw` and returned 3 results (`limit` 3) from the real server `http://crw.home`.
### 5. Release token
The release workflow succeeded with the `PACKAGE_TOKEN` repository secret (rights `write:package` and `write:repository`): publishing, tag creation and the package link all worked. Decision: that secret stays, and the workflow uses it alone; the untested job-token fallback was removed.
### 6. `@opencode/plugin` install weight ### 6. `@opencode/plugin` install weight
`npm install` of `@opencode/plugin@2.0.22` adds about 100 MB of transitive dependencies (mainly `effect`, OpenTelemetry, `@redis`). Its peers `solid-js`, `@opentui/core`, `@opentui/solid` and `@opencode/theme` are optional and not installed. Decision for the first release: keep it in `dependencies` as the docs say; revisit if install size matters. `npm install` of `@opencode/plugin@2.0.22` adds about 100 MB of transitive dependencies (mainly `effect`, OpenTelemetry, `@redis`). Its peers `solid-js`, `@opentui/core`, `@opentui/solid` and `@opencode/theme` are optional and not installed. Decision for the first release: keep it in `dependencies` as the docs say; revisit if install size matters.
@@ -60,10 +73,9 @@ From `@opencode/schema` 2.0.22: a result is `{ url: string, title?: string, cont
## Follow-ups this implies ## Follow-ups this implies
- **Local installs need a root `index.js`.** Add `index.js` (`export { default } from "./dist/index.js"`) to the package and `files`, so a config entry pointing at an unpacked package directory works as well as an npm-name install. The release script stages `package.json` and `dist/` only and would need to include it. - Decided against a root `index.js`: local testing uses a drop-in shim (see the README), and the package is installed by name through the registry.
- Update the README and spec examples: no `~` paths, and a directory (not a file) for local `plugins` entries. - Done: README install section and examples corrected (no `~` paths, directories only for local entries).
- Optional: decide whether the generic user-facing error is acceptable, since our detailed messages are not surfaced. - Optional: decide whether the generic user-facing error is acceptable, since our detailed messages are not surfaced.
- Still to verify after the first release: check 4 (install by name with a scoped `.npmrc`) and check 5 (job token package-write rights).
## Useful for later runs ## Useful for later runs
+2 -2
View File
@@ -1,6 +1,6 @@
# Spec: fastCRW websearch plugin for opencode v2 # Spec: fastCRW websearch plugin for opencode v2
Compiled from the closed tickets on the map ([Wayfinder map: fastCRW websearch plugin for opencode v2](https://git.arthurerlich.de/haylan/fastcrw-opencode-websarch/issues/1)). Detail lives in each ticket and in `docs/research/`. Vocabulary is defined in `CONTEXT.md`. Reference skills: `.claude/skills/opencode-v2-plugin`, `.claude/skills/fastcrw-search-api`. Compiled from the closed tickets on the map ([Wayfinder map: fastCRW websearch plugin for opencode v2](https://git.arthurerlich.de/haylan/fastcrw-opencode-websearch/issues/1)). Detail lives in each ticket and in `docs/research/`. Vocabulary is defined in `CONTEXT.md`. Reference skills: `.claude/skills/opencode-v2-plugin`, `.claude/skills/fastcrw-search-api`.
## Goal ## Goal
@@ -103,7 +103,7 @@ Run once on a real opencode v2 install; a failed check reopens the design as a n
2. Does a throwing `setup` disable only this plugin, not opencode startup? 2. Does a throwing `setup` disable only this plugin, not opencode startup?
3. Precedence of config `websearch.provider` vs `editor.default.set`. 3. Precedence of config `websearch.provider` vs `editor.default.set`.
4. Does install-by-name from the Gitea registry work with a scoped `.npmrc` (`@haylan:registry=...`)? Fallback: tarball or local path. 4. Does install-by-name from the Gitea registry work with a scoped `.npmrc` (`@haylan:registry=...`)? Fallback: tarball or local path.
5. Does the release workflow's job token have package-write rights? Fallback: a `write:package` secret. 5. Release token rights. Settled: the workflow uses a `PACKAGE_TOKEN` secret with `write:package` and `write:repository`; there is no job-token fallback.
6. Does `npm install` of `@opencode/plugin` drag in `solid-js` and the OpenTUI peers? If heavy, move it to `peerDependencies` plus `devDependencies`. 6. Does `npm install` of `@opencode/plugin` drag in `solid-js` and the OpenTUI peers? If heavy, move it to `peerDependencies` plus `devDependencies`.
7. `npm run smoke` against the real fastCRW server (`CRW_API_URL`/`CRW_API_KEY`): record the real response shape (`data[]` vs `data.results`). 7. `npm run smoke` against the real fastCRW server (`CRW_API_URL`/`CRW_API_KEY`): record the real response shape (`data[]` vs `data.results`).
8. Confirm the exact `@opencode/plugin` TypeScript types, the shape of `time`, and that a 429 status in an error message triggers opencode's provider cooldown. 8. Confirm the exact `@opencode/plugin` TypeScript types, the shape of `time`, and that a 429 status in an error message triggers opencode's provider cooldown.
+1 -1
View File
@@ -7,7 +7,7 @@
"": { "": {
"name": "@haylan/opencode-fastcrw", "name": "@haylan/opencode-fastcrw",
"version": "0.0.0-dev", "version": "0.0.0-dev",
"license": "MIT", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@opencode/plugin": "^2.0.22" "@opencode/plugin": "^2.0.22"
}, },
+2 -2
View File
@@ -24,9 +24,9 @@
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://git.arthurerlich.de/haylan/fastcrw-opencode-websarch.git" "url": "https://git.arthurerlich.de/haylan/fastcrw-opencode-websearch.git"
}, },
"license": "MIT", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@opencode/plugin": "^2.0.22" "@opencode/plugin": "^2.0.22"
}, },
+70 -9
View File
@@ -1,5 +1,8 @@
// Publishes the latest CHANGELOG.md version to a Gitea npm registry without `npm publish`. // Publishes the latest CHANGELOG.md version to a Gitea npm registry without `npm publish`, tags the
// Env: REGISTRY_URL (e.g. https://host/api/packages/<owner>/npm), TOKEN (needs write:package). // commit `v<version>` and links the package to this repository. Every step is idempotent, so a
// rerun repairs a release that is only partly done.
// Env: SERVER_URL, REPOSITORY (owner/repo), SHA (from the workflow), TOKEN (needs write:package
// and write:repository).
import { execFileSync } from "node:child_process" import { execFileSync } from "node:child_process"
import { createHash } from "node:crypto" import { createHash } from "node:crypto"
import { cpSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs" import { cpSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
@@ -43,10 +46,57 @@ export function publishBody(pkg: { name: string; version: string }, tarball: Buf
} }
} }
type Api = { base: string; headers: Record<string, string>; fetchFn?: typeof fetch }
async function call(api: Api, method: string, path: string, body?: object) {
return (api.fetchFn ?? fetch)(`${api.base}${path}`, {
method,
headers: { ...api.headers, "Content-Type": "application/json" },
body: body && JSON.stringify(body),
})
}
const fail = async (what: string, res: Response) =>
new Error(`${what} failed: ${res.status} ${await res.text()}`)
export async function ensureTag(api: Api, repo: string, version: string, sha: string) {
const tag = `v${version}`
const existing = await call(api, "GET", `/repos/${repo}/tags/${tag}`)
if (existing.ok) return "exists"
if (existing.status !== 404) throw await fail("tag lookup", existing)
const res = await call(api, "POST", `/repos/${repo}/tags`, {
tag_name: tag,
target: sha,
message: `Release ${version}`,
})
if (!res.ok) throw await fail("tag creation", res)
return "created"
}
export async function ensureLinked(
api: Api,
owner: string,
name: string,
version: string,
repoName: string,
) {
const pkg = `/packages/${owner}/npm/${encodeURIComponent(name)}`
const existing = await call(api, "GET", `${pkg}/${version}`)
if (!existing.ok) throw await fail("package lookup", existing)
if (((await existing.json()) as { repository?: unknown }).repository) return "already linked"
const res = await call(api, "POST", `${pkg}/-/link/${repoName}`)
if (!res.ok) throw await fail("package link", res)
return "linked"
}
async function main() { async function main() {
const registry = process.env.REGISTRY_URL?.replace(/\/+$/, "") const { SERVER_URL, REPOSITORY, SHA, TOKEN: token } = process.env
const token = process.env.TOKEN if (!SERVER_URL || !REPOSITORY || !SHA || !token) {
if (!registry || !token) throw new Error("REGISTRY_URL and TOKEN must be set") throw new Error("SERVER_URL, REPOSITORY, SHA and TOKEN must be set")
}
const [owner, repoName] = REPOSITORY.split("/")
const server = SERVER_URL.replace(/\/+$/, "")
const registry = `${server}/api/packages/${owner}/npm`
const version = latestVersion(readFileSync("CHANGELOG.md", "utf8")) const version = latestVersion(readFileSync("CHANGELOG.md", "utf8"))
// The version is rewritten in the staged copy only; the repo keeps its dev version. // The version is rewritten in the staged copy only; the repo keeps its dev version.
@@ -56,13 +106,24 @@ async function main() {
const existing = await fetch(url, { headers }) const existing = await fetch(url, { headers })
if (existing.ok && isPublished(await existing.json(), version)) { if (existing.ok && isPublished(await existing.json(), version)) {
console.log(`${pkg.name}@${version} is already published, skipping`) console.log(`${pkg.name}@${version} is already published, skipping publish`)
return } else if (!existing.ok && existing.status !== 404) {
}
if (!existing.ok && existing.status !== 404) {
throw new Error(`registry lookup failed: ${existing.status} ${await existing.text()}`) throw new Error(`registry lookup failed: ${existing.status} ${await existing.text()}`)
} else {
await publish(pkg, url, headers)
} }
const api = { base: `${server}/api/v1`, headers }
console.log(`tag v${version}: ${await ensureTag(api, REPOSITORY, version, SHA)}`)
console.log(`package link: ${await ensureLinked(api, owner, pkg.name, version, repoName)}`)
}
async function publish(
pkg: { name: string; version: string },
url: string,
headers: Record<string, string>,
) {
const { version } = pkg
rmSync(".release", { recursive: true, force: true }) rmSync(".release", { recursive: true, force: true })
mkdirSync(".release/package", { recursive: true }) mkdirSync(".release/package", { recursive: true })
writeFileSync(".release/package/package.json", JSON.stringify(pkg, null, 2)) writeFileSync(".release/package/package.json", JSON.stringify(pkg, null, 2))
+88 -1
View File
@@ -1,6 +1,13 @@
import assert from "node:assert/strict" import assert from "node:assert/strict"
import { test } from "node:test" import { test } from "node:test"
import { encodeName, isPublished, latestVersion, publishBody } from "../scripts/release.ts" import {
encodeName,
ensureLinked,
ensureTag,
isPublished,
latestVersion,
publishBody,
} from "../scripts/release.ts"
const changelog = (body: string) => `# Changelog\n\n${body}\n` const changelog = (body: string) => `# Changelog\n\n${body}\n`
@@ -42,3 +49,83 @@ test("publishBody builds the npm publish payload with the tarball attached", ()
assert.equal(body._attachments[file].data, tarball.toString("base64")) assert.equal(body._attachments[file].data, tarball.toString("base64"))
assert.equal(body._attachments[file].length, tarball.length) assert.equal(body._attachments[file].length, tarball.length)
}) })
// Fake Gitea API: each route answers with a status and optional JSON body; calls are recorded.
function fakeApi(routes: Record<string, [number, unknown?]>) {
const calls: string[] = []
const fetchFn = (async (url: string, init?: RequestInit) => {
const key = `${init?.method ?? "GET"} ${url.replace("https://git.test/api/v1", "")}`
calls.push(key + (init?.body ? ` ${init.body}` : ""))
const [status, body] = routes[key] ?? [500, { message: `unexpected ${key}` }]
return new Response(JSON.stringify(body ?? {}), { status })
}) as typeof fetch
return {
calls,
api: { base: "https://git.test/api/v1", headers: { Authorization: "Bearer t" }, fetchFn },
}
}
test("ensureTag creates the tag when it does not exist", async () => {
const { calls, api } = fakeApi({
"GET /repos/haylan/r/tags/v1.0.0": [404],
"POST /repos/haylan/r/tags": [201],
})
assert.equal(await ensureTag(api, "haylan/r", "1.0.0", "abc123"), "created")
assert.deepEqual(JSON.parse(calls[1].replace("POST /repos/haylan/r/tags ", "")), {
tag_name: "v1.0.0",
target: "abc123",
message: "Release 1.0.0",
})
})
test("ensureTag leaves an existing tag alone", async () => {
const { calls, api } = fakeApi({ "GET /repos/haylan/r/tags/v1.0.0": [200, { name: "v1.0.0" }] })
assert.equal(await ensureTag(api, "haylan/r", "1.0.0", "abc123"), "exists")
assert.equal(calls.length, 1)
})
test("ensureTag throws on an unexpected API answer", async () => {
const { api } = fakeApi({ "GET /repos/haylan/r/tags/v1.0.0": [403, { message: "no" }] })
await assert.rejects(ensureTag(api, "haylan/r", "1.0.0", "abc"), /403/)
})
const pkgPath = "/packages/haylan/npm/%40haylan%2Fopencode-fastcrw"
test("ensureLinked links an unlinked package to the repository", async () => {
const { calls, api } = fakeApi({
[`GET ${pkgPath}/1.0.0`]: [200, { repository: null }],
[`POST ${pkgPath}/-/link/r`]: [201],
})
assert.equal(
await ensureLinked(api, "haylan", "@haylan/opencode-fastcrw", "1.0.0", "r"),
"linked",
)
assert.equal(calls.length, 2)
})
test("ensureLinked skips a package that already has a repository", async () => {
const { calls, api } = fakeApi({
[`GET ${pkgPath}/1.0.0`]: [200, { repository: { full_name: "haylan/r" } }],
})
assert.equal(
await ensureLinked(api, "haylan", "@haylan/opencode-fastcrw", "1.0.0", "r"),
"already linked",
)
assert.equal(calls.length, 1)
})
test("ensureLinked throws when the package lookup or link fails", async () => {
const lookup = fakeApi({ [`GET ${pkgPath}/1.0.0`]: [404] })
await assert.rejects(
ensureLinked(lookup.api, "haylan", "@haylan/opencode-fastcrw", "1.0.0", "r"),
/404/,
)
const link = fakeApi({
[`GET ${pkgPath}/1.0.0`]: [200, {}],
[`POST ${pkgPath}/-/link/r`]: [403],
})
await assert.rejects(
ensureLinked(link.api, "haylan", "@haylan/opencode-fastcrw", "1.0.0", "r"),
/403/,
)
})