versimo 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/LICENSE +21 -0
- package/README.md +110 -2
- package/dist/bucket.d.ts +13 -0
- package/dist/bucket.js +60 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +59 -0
- package/dist/client.d.ts +31 -0
- package/dist/client.js +102 -0
- package/dist/deploy.d.ts +29 -0
- package/dist/deploy.js +29 -0
- package/dist/github/app-auth.d.ts +14 -0
- package/dist/github/app-auth.js +63 -0
- package/dist/github/client.d.ts +64 -0
- package/dist/github/client.js +127 -0
- package/dist/github/index.d.ts +4 -0
- package/dist/github/index.js +4 -0
- package/dist/github/tags.d.ts +20 -0
- package/dist/github/tags.js +56 -0
- package/dist/github/webhook.d.ts +5 -0
- package/dist/github/webhook.js +23 -0
- package/dist/health.d.ts +50 -0
- package/dist/health.js +68 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +12 -0
- package/dist/monitor.d.ts +67 -0
- package/dist/monitor.js +148 -0
- package/dist/posthog.d.ts +42 -0
- package/dist/posthog.js +96 -0
- package/dist/provider.d.ts +28 -0
- package/dist/provider.js +51 -0
- package/dist/resolve.d.ts +5 -0
- package/dist/resolve.js +22 -0
- package/dist/semver.d.ts +11 -0
- package/dist/semver.js +56 -0
- package/dist/transitions.d.ts +14 -0
- package/dist/transitions.js +51 -0
- package/dist/types.d.ts +51 -0
- package/dist/types.js +8 -0
- package/dist/validate.d.ts +6 -0
- package/dist/validate.js +79 -0
- package/docs/api.md +214 -0
- package/docs/concepts.md +65 -0
- package/docs/github-app.md +90 -0
- package/docs/health.md +76 -0
- package/docs/porting.md +130 -0
- package/docs/record-format.md +62 -0
- package/docs/usage.md +236 -0
- package/github-app/manifest.json +19 -0
- package/package.json +63 -4
- package/schema/examples/billing.json +15 -0
- package/schema/module-record.schema.json +50 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes are listed here. This project follows [semver](https://semver.org).
|
|
4
|
+
|
|
5
|
+
## 0.3.0
|
|
6
|
+
|
|
7
|
+
- Apps read their records from versimo.dev with the project's read key: `createClient({ source: 'https://versimo.dev/api/records/<read key>' })`
|
|
8
|
+
- `createDeployClient` and the `versimo` command change a project's modules from CI with its deploy key: `create`, `draft`, `rollout`, `promote`, `rollback`, `list`
|
|
9
|
+
- The app API signs in through Lucasia ID: endpoints and keys from discovery, a nonce, the ID token checked before a session starts, and the client secret sent as `client_secret_basic`
|
|
10
|
+
- PostHog flags drive next. `postHogRollout` reads the share on next for each module from the PostHog flag `versimo-<module>`, so a rollout change needs no deploy. Bucketing stays with Versimo, so users land on the same version in every language. No user data is sent to PostHog.
|
|
11
|
+
- `createClient` takes a `rollout` option that overrides the record's share
|
|
12
|
+
- Python (`PostHogRollout`) and Go (`NewPostHogRollout`) get the same
|
|
13
|
+
- `posthog` section in `spec/vectors.json`
|
|
14
|
+
- The app API writes each module's share to the project's own PostHog flag, so the slider on versimo.dev drives next. Connect with `PUT /api/projects/:id/posthog`. The personal key is sealed at rest
|
|
15
|
+
|
|
16
|
+
## 0.2.0
|
|
17
|
+
|
|
18
|
+
- Versimo for Python, Go, Kotlin and Swift, in `packages/`
|
|
19
|
+
- Shared language-neutral test vectors in `spec/vectors.json`, generated from the TypeScript code with `npm run spec:generate`
|
|
20
|
+
- `bucketFor` works on engines without `TextEncoder`, such as older React Native
|
|
21
|
+
- Docs for React Native and for porting to other languages
|
|
22
|
+
- A release workflow that publishes to npm with provenance
|
|
23
|
+
|
|
24
|
+
## 0.1.0
|
|
25
|
+
|
|
26
|
+
First release.
|
|
27
|
+
|
|
28
|
+
- Module record format and JSON Schema (2020-12)
|
|
29
|
+
- `resolveVersion` and `resolve` with deterministic bucketing
|
|
30
|
+
- `draftNext`, `promote`, `rollback` and `setRollout`, all pure, all logging history
|
|
31
|
+
- `validateRecord`, hand-written
|
|
32
|
+
- `createClient` with an in-memory cache, a TTL and stale-on-error
|
|
33
|
+
- `VersimoProvider`, OpenFeature compatible by structure
|
|
34
|
+
- Semver helpers
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lucasia Ltd
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,111 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Versimo
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A release model with no staging.
|
|
4
|
+
|
|
5
|
+
Every module of your product (billing, sign-in, search) has three versions: **last**, **current** and **next**. Next is user acceptance testing on live, behind a flag that reaches a percentage of your users. When next is good, you promote it. Next becomes current and current becomes last. If current fails its health checks, users go back to last on their own, and the fix ships as a semver patch.
|
|
6
|
+
|
|
7
|
+
Versimo is the small, dependency-free library that answers one question: which version of this module should this user get?
|
|
8
|
+
|
|
9
|
+
- Ports for TypeScript, Python, Go, Kotlin and Swift, all with zero runtime dependencies
|
|
10
|
+
- Node 20 and later, modern browsers and React Native
|
|
11
|
+
- Deterministic bucketing, so a user stays on the same version as the rollout grows
|
|
12
|
+
- Pure functions for promote, rollback, rollout and draft
|
|
13
|
+
- Health checks (error rate, latency, a custom URL) with automatic rollback, alerts and PostHog error tracking
|
|
14
|
+
- A hand-written record validator and a JSON Schema
|
|
15
|
+
- An OpenFeature compatible provider, with no OpenFeature import
|
|
16
|
+
|
|
17
|
+
Site: [versimo.dev](https://versimo.dev)
|
|
18
|
+
|
|
19
|
+
## Languages
|
|
20
|
+
|
|
21
|
+
Every port gives the same answer for the same record and user. They are checked against the same [test vectors](spec/vectors.json).
|
|
22
|
+
|
|
23
|
+
| Language | Package | Install | Docs |
|
|
24
|
+
| --- | --- | --- | --- |
|
|
25
|
+
| TypeScript and JavaScript, including React Native | Versimo for TypeScript | `npm install versimo` | This page |
|
|
26
|
+
| Python 3.10 and later | Versimo for Python | `pip install "git+https://github.com/luca-sia/versimo#subdirectory=packages/python"` | [packages/python](packages/python/README.md) |
|
|
27
|
+
| Go 1.22 and later | Versimo for Go | `go get github.com/luca-sia/versimo/packages/go` | [packages/go](packages/go/README.md) |
|
|
28
|
+
| Kotlin and Android | Versimo for Kotlin | Build from source with `gradle publishToMavenLocal`. Not on Maven Central or JitPack yet | [packages/kotlin](packages/kotlin/README.md) |
|
|
29
|
+
| Swift and iOS | Versimo for Swift | SwiftPM URL `https://github.com/luca-sia/versimo` | [packages/swift](packages/swift/README.md) |
|
|
30
|
+
|
|
31
|
+
Writing another port? See [docs/porting.md](docs/porting.md).
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
The rest of this page uses TypeScript.
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
npm install versimo
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The package is not on npm yet. Until it is published, install it from GitHub:
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
npm install github:luca-sia/versimo
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The install builds the package on your machine, so it needs a working `npm` and Node 20 or later.
|
|
48
|
+
|
|
49
|
+
## Quick start
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { createClient } from 'versimo';
|
|
53
|
+
|
|
54
|
+
const versimo = createClient({
|
|
55
|
+
source: 'https://config.example.com/versimo', // fetches /versimo/billing.json
|
|
56
|
+
ttlMs: 30_000,
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
const version = await versimo.version('billing', { userId: 'user-42' });
|
|
60
|
+
// "2.4.0" for most users, "2.5.0" for the share of users on next
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Load the version your code asks for. How you do that is up to you. It might be a dynamic import, a feature branch of a service, or a route to another deployment.
|
|
64
|
+
|
|
65
|
+
You can also work with a record directly:
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import { resolveVersion, draftNext, setRollout, promote } from 'versimo';
|
|
69
|
+
|
|
70
|
+
let record = await versimo.record('billing');
|
|
71
|
+
record = draftNext(record, '2.6.0', { by: 'alex' });
|
|
72
|
+
record = setRollout(record, 10, { by: 'alex' });
|
|
73
|
+
record = promote(record, { by: 'alex' });
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
These functions never change the record you pass in. They return a new one with a history entry. Saving it is your job.
|
|
77
|
+
|
|
78
|
+
## The record
|
|
79
|
+
|
|
80
|
+
```json
|
|
81
|
+
{
|
|
82
|
+
"module": "billing",
|
|
83
|
+
"last": "2.3.1",
|
|
84
|
+
"current": "2.4.0",
|
|
85
|
+
"next": "2.5.0",
|
|
86
|
+
"rollout": 10,
|
|
87
|
+
"healthy": true,
|
|
88
|
+
"updatedAt": "2026-03-12T09:30:00Z"
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
The full format is in [docs/record-format.md](docs/record-format.md). The JSON Schema is at [schema/module-record.schema.json](schema/module-record.schema.json).
|
|
93
|
+
|
|
94
|
+
## Docs
|
|
95
|
+
|
|
96
|
+
- [Concepts](docs/concepts.md): the model in plain words
|
|
97
|
+
- [Usage](docs/usage.md): server, browser, React, React Native, OpenFeature and PostHog
|
|
98
|
+
- [Health checks](docs/health.md): automatic rollback, alerts and PostHog
|
|
99
|
+
- [Porting](docs/porting.md): the algorithm and the test vectors, for new languages
|
|
100
|
+
- [Record format](docs/record-format.md)
|
|
101
|
+
- [API reference](docs/api.md)
|
|
102
|
+
- [GitHub app](docs/github-app.md): connect a repo, modules from tags, pull requests with auto merge
|
|
103
|
+
- [Contributing](CONTRIBUTING.md) and [Security](SECURITY.md)
|
|
104
|
+
|
|
105
|
+
## Licence
|
|
106
|
+
|
|
107
|
+
MIT. Copyright 2026 Lucasia Ltd.
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
Thinks with Lucasia.ai
|
package/dist/bucket.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* UTF-8 bytes of a string. Uses `TextEncoder` when the runtime has it.
|
|
3
|
+
* Older React Native engines do not, so there is a small fallback.
|
|
4
|
+
* A lone surrogate becomes U+FFFD, as `TextEncoder` does.
|
|
5
|
+
*/
|
|
6
|
+
export declare function utf8Bytes(text: string): Uint8Array;
|
|
7
|
+
/**
|
|
8
|
+
* Maps a module and user to a stable bucket from 0 to 99.
|
|
9
|
+
* FNV-1a over the UTF-8 bytes of `module`, a NUL byte and `userId`,
|
|
10
|
+
* then the murmur3 32-bit finaliser, then modulo 100.
|
|
11
|
+
* The steps are simple on purpose so other languages can port them.
|
|
12
|
+
*/
|
|
13
|
+
export declare function bucketFor(module: string, userId: string): number;
|
package/dist/bucket.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
let encoder;
|
|
2
|
+
/**
|
|
3
|
+
* UTF-8 bytes of a string. Uses `TextEncoder` when the runtime has it.
|
|
4
|
+
* Older React Native engines do not, so there is a small fallback.
|
|
5
|
+
* A lone surrogate becomes U+FFFD, as `TextEncoder` does.
|
|
6
|
+
*/
|
|
7
|
+
export function utf8Bytes(text) {
|
|
8
|
+
if (typeof TextEncoder !== 'undefined')
|
|
9
|
+
return (encoder ??= new TextEncoder()).encode(text);
|
|
10
|
+
const out = [];
|
|
11
|
+
for (let i = 0; i < text.length; i++) {
|
|
12
|
+
let cp = text.charCodeAt(i);
|
|
13
|
+
if (cp >= 0xd800 && cp <= 0xdbff) {
|
|
14
|
+
const low = text.charCodeAt(i + 1);
|
|
15
|
+
if (low >= 0xdc00 && low <= 0xdfff) {
|
|
16
|
+
cp = 0x10000 + ((cp - 0xd800) << 10) + (low - 0xdc00);
|
|
17
|
+
i++;
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
cp = 0xfffd;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
else if (cp >= 0xdc00 && cp <= 0xdfff) {
|
|
24
|
+
cp = 0xfffd;
|
|
25
|
+
}
|
|
26
|
+
if (cp < 0x80) {
|
|
27
|
+
out.push(cp);
|
|
28
|
+
}
|
|
29
|
+
else if (cp < 0x800) {
|
|
30
|
+
out.push(0xc0 | (cp >> 6), 0x80 | (cp & 0x3f));
|
|
31
|
+
}
|
|
32
|
+
else if (cp < 0x10000) {
|
|
33
|
+
out.push(0xe0 | (cp >> 12), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
out.push(0xf0 | (cp >> 18), 0x80 | ((cp >> 12) & 0x3f), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return Uint8Array.from(out);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Maps a module and user to a stable bucket from 0 to 99.
|
|
43
|
+
* FNV-1a over the UTF-8 bytes of `module`, a NUL byte and `userId`,
|
|
44
|
+
* then the murmur3 32-bit finaliser, then modulo 100.
|
|
45
|
+
* The steps are simple on purpose so other languages can port them.
|
|
46
|
+
*/
|
|
47
|
+
export function bucketFor(module, userId) {
|
|
48
|
+
const bytes = utf8Bytes(`${module}\u0000${userId}`);
|
|
49
|
+
let h = 0x811c9dc5;
|
|
50
|
+
for (const byte of bytes) {
|
|
51
|
+
h ^= byte;
|
|
52
|
+
h = Math.imul(h, 0x01000193);
|
|
53
|
+
}
|
|
54
|
+
h ^= h >>> 16;
|
|
55
|
+
h = Math.imul(h, 0x85ebca6b);
|
|
56
|
+
h ^= h >>> 13;
|
|
57
|
+
h = Math.imul(h, 0xc2b2ae35);
|
|
58
|
+
h ^= h >>> 16;
|
|
59
|
+
return (h >>> 0) % 100;
|
|
60
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createDeployClient } from './deploy.js';
|
|
3
|
+
const USAGE = `Usage: versimo <command> [args]
|
|
4
|
+
|
|
5
|
+
list
|
|
6
|
+
create <module> <current> [last]
|
|
7
|
+
draft <module> <version> [--patch]
|
|
8
|
+
rollout <module> <0-100>
|
|
9
|
+
promote <module>
|
|
10
|
+
rollback <module>
|
|
11
|
+
|
|
12
|
+
Needs VERSIMO_DEPLOY_KEY. VERSIMO_BASE defaults to https://versimo.dev.
|
|
13
|
+
`;
|
|
14
|
+
async function main(args) {
|
|
15
|
+
const [command, module, value, extra] = args;
|
|
16
|
+
const key = process.env.VERSIMO_DEPLOY_KEY;
|
|
17
|
+
if (!command || command === 'help' || command === '--help') {
|
|
18
|
+
process.stdout.write(USAGE);
|
|
19
|
+
return command ? 0 : 2;
|
|
20
|
+
}
|
|
21
|
+
if (!key) {
|
|
22
|
+
process.stderr.write('Set VERSIMO_DEPLOY_KEY to the project deploy key.\n');
|
|
23
|
+
return 2;
|
|
24
|
+
}
|
|
25
|
+
const versimo = createDeployClient({ key, base: process.env.VERSIMO_BASE });
|
|
26
|
+
const need = (v) => {
|
|
27
|
+
if (!v)
|
|
28
|
+
throw new Error(USAGE);
|
|
29
|
+
return v;
|
|
30
|
+
};
|
|
31
|
+
const out = (x) => process.stdout.write(`${JSON.stringify(x, null, 2)}\n`);
|
|
32
|
+
switch (command) {
|
|
33
|
+
case 'list':
|
|
34
|
+
out(await versimo.list());
|
|
35
|
+
return 0;
|
|
36
|
+
case 'create':
|
|
37
|
+
out(await versimo.create(need(module), need(value), extra));
|
|
38
|
+
return 0;
|
|
39
|
+
case 'draft':
|
|
40
|
+
out(await versimo.draft(need(module), need(value), { patch: extra === '--patch' }));
|
|
41
|
+
return 0;
|
|
42
|
+
case 'rollout':
|
|
43
|
+
out(await versimo.rollout(need(module), Number(need(value))));
|
|
44
|
+
return 0;
|
|
45
|
+
case 'promote':
|
|
46
|
+
out(await versimo.promote(need(module)));
|
|
47
|
+
return 0;
|
|
48
|
+
case 'rollback':
|
|
49
|
+
out(await versimo.rollback(need(module)));
|
|
50
|
+
return 0;
|
|
51
|
+
default:
|
|
52
|
+
process.stderr.write(USAGE);
|
|
53
|
+
return 2;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
main(process.argv.slice(2)).then((code) => (process.exitCode = code), (error) => {
|
|
57
|
+
process.stderr.write(`${error.message}\n`);
|
|
58
|
+
process.exitCode = 1;
|
|
59
|
+
});
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type Context, type ModuleRecord, type Resolution } from './types.js';
|
|
2
|
+
import type { RolloutFn } from './posthog.js';
|
|
3
|
+
export type SourceFn = (module: string) => ModuleRecord | null | undefined | Promise<ModuleRecord | null | undefined>;
|
|
4
|
+
export interface ClientOptions {
|
|
5
|
+
/**
|
|
6
|
+
* A function returning the record for a module, or a URL.
|
|
7
|
+
* A URL containing `{module}` has it replaced. Any other URL is a base
|
|
8
|
+
* and the client fetches `<base>/<module>.json`.
|
|
9
|
+
*/
|
|
10
|
+
source: SourceFn | string;
|
|
11
|
+
/** How long a record is cached, in milliseconds. Default 30000. */
|
|
12
|
+
ttlMs?: number;
|
|
13
|
+
/** Clock for the cache, in milliseconds. Mainly for tests. */
|
|
14
|
+
now?: () => number;
|
|
15
|
+
/** Fetch implementation for URL sources. Defaults to the global `fetch`. */
|
|
16
|
+
fetch?: typeof fetch;
|
|
17
|
+
/**
|
|
18
|
+
* Overrides the record's `rollout`, for example `postHogRollout(...)`.
|
|
19
|
+
* Only the share changes. Who lands on `next` is still decided by `bucketFor`.
|
|
20
|
+
* When it returns null or fails, the record's own rollout is used.
|
|
21
|
+
*/
|
|
22
|
+
rollout?: RolloutFn;
|
|
23
|
+
}
|
|
24
|
+
export interface VersimoClient {
|
|
25
|
+
record(module: string): Promise<ModuleRecord>;
|
|
26
|
+
resolve(module: string, ctx?: Context): Promise<Resolution>;
|
|
27
|
+
version(module: string, ctx?: Context): Promise<string>;
|
|
28
|
+
/** Drops one cached record, or all of them. */
|
|
29
|
+
clear(module?: string): void;
|
|
30
|
+
}
|
|
31
|
+
export declare function createClient(options: ClientOptions): VersimoClient;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { resolve } from './resolve.js';
|
|
2
|
+
import { validateRecord } from './validate.js';
|
|
3
|
+
import { VersimoError } from './types.js';
|
|
4
|
+
const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
5
|
+
function urlSource(url, fetchImpl) {
|
|
6
|
+
return async (module) => {
|
|
7
|
+
const f = fetchImpl ?? globalThis.fetch;
|
|
8
|
+
if (!f)
|
|
9
|
+
throw new VersimoError('SOURCE_ERROR', 'No fetch available. Pass the `fetch` option.');
|
|
10
|
+
const target = url.includes('{module}')
|
|
11
|
+
? url.replace('{module}', module)
|
|
12
|
+
: `${url.replace(/\/+$/, '')}/${module}.json`;
|
|
13
|
+
let res;
|
|
14
|
+
try {
|
|
15
|
+
res = await f(target);
|
|
16
|
+
}
|
|
17
|
+
catch (err) {
|
|
18
|
+
throw new VersimoError('SOURCE_ERROR', `Could not fetch ${target}: ${err.message}`);
|
|
19
|
+
}
|
|
20
|
+
if (res.status === 404)
|
|
21
|
+
return null;
|
|
22
|
+
if (!res.ok)
|
|
23
|
+
throw new VersimoError('SOURCE_ERROR', `Fetching ${target} returned ${res.status}`);
|
|
24
|
+
return (await res.json());
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export function createClient(options) {
|
|
28
|
+
const ttlMs = options.ttlMs ?? 30_000;
|
|
29
|
+
const now = options.now ?? Date.now;
|
|
30
|
+
const source = typeof options.source === 'string' ? urlSource(options.source, options.fetch) : options.source;
|
|
31
|
+
const cache = new Map();
|
|
32
|
+
const inflight = new Map();
|
|
33
|
+
async function load(module) {
|
|
34
|
+
const raw = await source(module);
|
|
35
|
+
if (raw === null || raw === undefined)
|
|
36
|
+
throw new VersimoError('NOT_FOUND', `No record for module "${module}"`);
|
|
37
|
+
const checked = validateRecord(raw);
|
|
38
|
+
if (!checked.ok) {
|
|
39
|
+
throw new VersimoError('INVALID_RECORD', `Invalid record for "${module}": ${checked.errors.join('; ')}`);
|
|
40
|
+
}
|
|
41
|
+
return raw;
|
|
42
|
+
}
|
|
43
|
+
async function withRollout(rec) {
|
|
44
|
+
if (!options.rollout)
|
|
45
|
+
return rec;
|
|
46
|
+
let share;
|
|
47
|
+
try {
|
|
48
|
+
share = await options.rollout(rec.module);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return rec;
|
|
52
|
+
}
|
|
53
|
+
if (typeof share !== 'number' || !Number.isInteger(share) || share < 0 || share > 100)
|
|
54
|
+
return rec;
|
|
55
|
+
return share === rec.rollout ? rec : { ...rec, rollout: share };
|
|
56
|
+
}
|
|
57
|
+
async function record(module) {
|
|
58
|
+
return withRollout(await stored(module));
|
|
59
|
+
}
|
|
60
|
+
async function stored(module) {
|
|
61
|
+
if (!SLUG.test(module))
|
|
62
|
+
throw new VersimoError('INVALID_INPUT', `Invalid module slug: ${JSON.stringify(module)}`);
|
|
63
|
+
const hit = cache.get(module);
|
|
64
|
+
if (hit && hit.expires > now())
|
|
65
|
+
return hit.record;
|
|
66
|
+
const pending = inflight.get(module);
|
|
67
|
+
if (pending)
|
|
68
|
+
return pending;
|
|
69
|
+
const p = load(module)
|
|
70
|
+
.then((rec) => {
|
|
71
|
+
cache.set(module, { record: rec, expires: now() + ttlMs });
|
|
72
|
+
return rec;
|
|
73
|
+
})
|
|
74
|
+
.catch((err) => {
|
|
75
|
+
const e = err instanceof VersimoError ? err : new VersimoError('SOURCE_ERROR', err.message);
|
|
76
|
+
// Serve the stale record when the source is down. A missing or invalid record is not hidden.
|
|
77
|
+
if (hit && e.code === 'SOURCE_ERROR') {
|
|
78
|
+
cache.set(module, { record: hit.record, expires: now() + ttlMs });
|
|
79
|
+
return hit.record;
|
|
80
|
+
}
|
|
81
|
+
throw e;
|
|
82
|
+
})
|
|
83
|
+
.finally(() => inflight.delete(module));
|
|
84
|
+
inflight.set(module, p);
|
|
85
|
+
return p;
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
record,
|
|
89
|
+
async resolve(module, ctx) {
|
|
90
|
+
return resolve(await record(module), ctx);
|
|
91
|
+
},
|
|
92
|
+
async version(module, ctx) {
|
|
93
|
+
return (await this.resolve(module, ctx)).version;
|
|
94
|
+
},
|
|
95
|
+
clear(module) {
|
|
96
|
+
if (module === undefined)
|
|
97
|
+
cache.clear();
|
|
98
|
+
else
|
|
99
|
+
cache.delete(module);
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
package/dist/deploy.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export interface DeployModule {
|
|
2
|
+
module: string;
|
|
3
|
+
last: string | null;
|
|
4
|
+
current: string;
|
|
5
|
+
next: string | null;
|
|
6
|
+
rollout: number;
|
|
7
|
+
healthy: boolean;
|
|
8
|
+
updatedAt: string;
|
|
9
|
+
}
|
|
10
|
+
export interface DeployClientOptions {
|
|
11
|
+
/** The project's deploy key from versimo.dev, `vdk_...`. Keep it in CI secrets only. */
|
|
12
|
+
key: string;
|
|
13
|
+
/** Default `https://versimo.dev`. */
|
|
14
|
+
base?: string;
|
|
15
|
+
/** Fetch implementation. Defaults to the global `fetch`. */
|
|
16
|
+
fetch?: typeof fetch;
|
|
17
|
+
}
|
|
18
|
+
export interface DeployClient {
|
|
19
|
+
list(): Promise<DeployModule[]>;
|
|
20
|
+
create(module: string, current: string, last?: string): Promise<DeployModule>;
|
|
21
|
+
draft(module: string, version: string, opts?: {
|
|
22
|
+
patch?: boolean;
|
|
23
|
+
}): Promise<DeployModule>;
|
|
24
|
+
rollout(module: string, share: number): Promise<DeployModule>;
|
|
25
|
+
promote(module: string): Promise<DeployModule>;
|
|
26
|
+
rollback(module: string): Promise<DeployModule>;
|
|
27
|
+
}
|
|
28
|
+
/** Changes a versimo.dev project's modules from CI, with its deploy key. */
|
|
29
|
+
export declare function createDeployClient(options: DeployClientOptions): DeployClient;
|
package/dist/deploy.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { VersimoError } from './types.js';
|
|
2
|
+
/** Changes a versimo.dev project's modules from CI, with its deploy key. */
|
|
3
|
+
export function createDeployClient(options) {
|
|
4
|
+
const base = `${(options.base ?? 'https://versimo.dev').replace(/\/+$/, '')}/api/deploy/modules`;
|
|
5
|
+
async function call(method, path, body) {
|
|
6
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
7
|
+
const res = await f(base + path, {
|
|
8
|
+
method,
|
|
9
|
+
headers: { authorization: `Bearer ${options.key}`, 'content-type': 'application/json' },
|
|
10
|
+
body: method === 'POST' ? JSON.stringify(body ?? {}) : undefined,
|
|
11
|
+
});
|
|
12
|
+
const data = (await res.json().catch(() => ({})));
|
|
13
|
+
if (!res.ok) {
|
|
14
|
+
const reason = typeof data.error === 'string' ? data.error : `HTTP ${res.status}`;
|
|
15
|
+
throw new VersimoError(res.status === 401 ? 'SOURCE_ERROR' : 'INVALID_INPUT', `Versimo refused: ${reason}`);
|
|
16
|
+
}
|
|
17
|
+
return data;
|
|
18
|
+
}
|
|
19
|
+
const one = async (path, body) => (await call('POST', path, body)).module;
|
|
20
|
+
const at = (module, action) => `/${encodeURIComponent(module)}/${action}`;
|
|
21
|
+
return {
|
|
22
|
+
list: async () => (await call('GET', '')).modules,
|
|
23
|
+
create: (module, current, last) => one('', { module, current, last }),
|
|
24
|
+
draft: (module, version, opts) => one(at(module, 'draft'), { version, patch: opts?.patch === true }),
|
|
25
|
+
rollout: (module, share) => one(at(module, 'rollout'), { rollout: share }),
|
|
26
|
+
promote: (module) => one(at(module, 'promote')),
|
|
27
|
+
rollback: (module) => one(at(module, 'rollback')),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface AppJwtOptions {
|
|
2
|
+
/** The GitHub App id (or its client id). */
|
|
3
|
+
appId: string | number;
|
|
4
|
+
/** The app's private key in PEM form. PKCS#1 and PKCS#8 both work. */
|
|
5
|
+
privateKey: string;
|
|
6
|
+
/** Clock, mainly for tests. Defaults to now. */
|
|
7
|
+
now?: Date | string | number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Signs the short lived JWT a GitHub App uses to ask for installation tokens.
|
|
11
|
+
* It is valid for nine minutes and backdated by one, as GitHub advises.
|
|
12
|
+
* Works anywhere WebCrypto does: Node 20, Cloudflare Workers and browsers.
|
|
13
|
+
*/
|
|
14
|
+
export declare function createAppJwt({ appId, privateKey, now }: AppJwtOptions): Promise<string>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
const encoder = new TextEncoder();
|
|
2
|
+
function base64url(bytes) {
|
|
3
|
+
let bin = '';
|
|
4
|
+
for (const b of bytes)
|
|
5
|
+
bin += String.fromCharCode(b);
|
|
6
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
7
|
+
}
|
|
8
|
+
function derLength(n) {
|
|
9
|
+
if (n < 0x80)
|
|
10
|
+
return [n];
|
|
11
|
+
const out = [];
|
|
12
|
+
while (n > 0) {
|
|
13
|
+
out.unshift(n & 0xff);
|
|
14
|
+
n >>= 8;
|
|
15
|
+
}
|
|
16
|
+
return [0x80 | out.length, ...out];
|
|
17
|
+
}
|
|
18
|
+
function der(tag, body) {
|
|
19
|
+
const len = derLength(body.length);
|
|
20
|
+
const out = new Uint8Array(1 + len.length + body.length);
|
|
21
|
+
out[0] = tag;
|
|
22
|
+
out.set(len, 1);
|
|
23
|
+
out.set(body, 1 + len.length);
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
function concat(...parts) {
|
|
27
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
28
|
+
let at = 0;
|
|
29
|
+
for (const p of parts) {
|
|
30
|
+
out.set(p, at);
|
|
31
|
+
at += p.length;
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
// AlgorithmIdentifier for rsaEncryption (1.2.840.113549.1.1.1) with NULL parameters.
|
|
36
|
+
const RSA_ALGORITHM = new Uint8Array([
|
|
37
|
+
0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00,
|
|
38
|
+
]);
|
|
39
|
+
/** Wraps a PKCS#1 RSA key, as GitHub hands it out, in PKCS#8, which WebCrypto needs. */
|
|
40
|
+
function pkcs1ToPkcs8(pkcs1) {
|
|
41
|
+
return der(0x30, concat(new Uint8Array([0x02, 0x01, 0x00]), RSA_ALGORITHM, der(0x04, pkcs1)));
|
|
42
|
+
}
|
|
43
|
+
function pemBody(pem) {
|
|
44
|
+
const m = /-----BEGIN (RSA )?PRIVATE KEY-----([\s\S]+?)-----END (RSA )?PRIVATE KEY-----/.exec(pem);
|
|
45
|
+
if (!m)
|
|
46
|
+
throw new TypeError('privateKey must be a PEM RSA private key');
|
|
47
|
+
const bin = atob(m[2].replace(/\s+/g, ''));
|
|
48
|
+
return { der: Uint8Array.from(bin, (c) => c.charCodeAt(0)), pkcs1: Boolean(m[1]) };
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Signs the short lived JWT a GitHub App uses to ask for installation tokens.
|
|
52
|
+
* It is valid for nine minutes and backdated by one, as GitHub advises.
|
|
53
|
+
* Works anywhere WebCrypto does: Node 20, Cloudflare Workers and browsers.
|
|
54
|
+
*/
|
|
55
|
+
export async function createAppJwt({ appId, privateKey, now = new Date() }) {
|
|
56
|
+
const { der: body, pkcs1 } = pemBody(privateKey);
|
|
57
|
+
const key = await crypto.subtle.importKey('pkcs8', new Uint8Array(pkcs1 ? pkcs1ToPkcs8(body) : body), { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['sign']);
|
|
58
|
+
const iat = Math.floor(new Date(now).getTime() / 1000) - 60;
|
|
59
|
+
const header = base64url(encoder.encode(JSON.stringify({ alg: 'RS256', typ: 'JWT' })));
|
|
60
|
+
const payload = base64url(encoder.encode(JSON.stringify({ iat, exp: iat + 600, iss: String(appId) })));
|
|
61
|
+
const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', key, encoder.encode(`${header}.${payload}`));
|
|
62
|
+
return `${header}.${payload}.${base64url(new Uint8Array(signature))}`;
|
|
63
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export interface GitHubOptions {
|
|
2
|
+
/** An installation token, or any token with the same rights. */
|
|
3
|
+
token: string;
|
|
4
|
+
/** Fetch implementation. Defaults to the global `fetch`. */
|
|
5
|
+
fetch?: typeof fetch;
|
|
6
|
+
/** REST base URL. Default https://api.github.com. */
|
|
7
|
+
apiUrl?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface FileChange {
|
|
10
|
+
path: string;
|
|
11
|
+
/** New UTF-8 content of the file. */
|
|
12
|
+
content: string;
|
|
13
|
+
}
|
|
14
|
+
export type MergeMethod = 'SQUASH' | 'MERGE' | 'REBASE';
|
|
15
|
+
export interface PullRequestInput {
|
|
16
|
+
owner: string;
|
|
17
|
+
repo: string;
|
|
18
|
+
/** New branch to create. It must not exist yet and must not be the base or the default branch. */
|
|
19
|
+
head: string;
|
|
20
|
+
/** Branch to merge into. Defaults to the repository's default branch. */
|
|
21
|
+
base?: string;
|
|
22
|
+
title: string;
|
|
23
|
+
body?: string;
|
|
24
|
+
/** Commit message. Defaults to the title. */
|
|
25
|
+
message?: string;
|
|
26
|
+
files: FileChange[];
|
|
27
|
+
/** Turn on auto merge once the PR is open. Default SQUASH. Pass false to leave it off. */
|
|
28
|
+
autoMerge?: MergeMethod | false;
|
|
29
|
+
}
|
|
30
|
+
export interface PullRequestResult {
|
|
31
|
+
number: number;
|
|
32
|
+
url: string;
|
|
33
|
+
head: string;
|
|
34
|
+
base: string;
|
|
35
|
+
/** True when auto merge was turned on. */
|
|
36
|
+
autoMerge: boolean;
|
|
37
|
+
/** Why auto merge could not be turned on, when it could not. */
|
|
38
|
+
autoMergeError?: string;
|
|
39
|
+
}
|
|
40
|
+
export interface GitHubClient {
|
|
41
|
+
/** Every tag name in the repository. */
|
|
42
|
+
listTags(owner: string, repo: string): Promise<string[]>;
|
|
43
|
+
/** Modules and their versions, read from `module/vX.Y.Z` tags, newest first. */
|
|
44
|
+
moduleVersions(owner: string, repo: string): Promise<Record<string, string[]>>;
|
|
45
|
+
/**
|
|
46
|
+
* Commits the files to a new branch and opens a pull request.
|
|
47
|
+
* This is the only write the client can make. It creates a new branch and
|
|
48
|
+
* never moves an existing one, so it cannot push to main.
|
|
49
|
+
*/
|
|
50
|
+
openPullRequest(input: PullRequestInput): Promise<PullRequestResult>;
|
|
51
|
+
}
|
|
52
|
+
export declare function createGitHub(opts: GitHubOptions): GitHubClient;
|
|
53
|
+
export interface InstallationTokenOptions {
|
|
54
|
+
/** A JWT from `createAppJwt`. */
|
|
55
|
+
jwt: string;
|
|
56
|
+
installationId: string | number;
|
|
57
|
+
fetch?: typeof fetch;
|
|
58
|
+
apiUrl?: string;
|
|
59
|
+
}
|
|
60
|
+
/** Swaps an app JWT for an installation token. Tokens last one hour. */
|
|
61
|
+
export declare function getInstallationToken(opts: InstallationTokenOptions): Promise<{
|
|
62
|
+
token: string;
|
|
63
|
+
expiresAt: string;
|
|
64
|
+
}>;
|