@ownkeyhq/cli 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 +32 -0
- package/LICENSE +21 -0
- package/dist/bin/ownkey.mjs +50 -0
- package/dist/src/args.d.ts +15 -0
- package/dist/src/args.js +160 -0
- package/dist/src/commands.d.ts +12 -0
- package/dist/src/commands.js +189 -0
- package/dist/src/context.d.ts +26 -0
- package/dist/src/context.js +22 -0
- package/dist/src/main.d.ts +3 -0
- package/dist/src/main.js +120 -0
- package/dist/src/output.d.ts +2 -0
- package/dist/src/output.js +55 -0
- package/package.json +34 -3
- package/README.md +0 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
- Breaking: `overview.summary` reports `valid_licenses.tier` on the eight-tier hosted ladder, `start`, `indie`, `grow`, `studio`, `pro`, `business`, `scale` and `scale_100k`. Above 100,000 valid licenses it reports `custom`, which replaces `above_scale`.
|
|
6
|
+
- `releases.storageUsage` reports the new `indie`, `studio`, `business` and `scale_100k` tiers in `tier`.
|
|
7
|
+
- Remove a product logo with `ownkey products remove-logo <product>`.
|
|
8
|
+
- Read what a connection supports in `capabilities`: new payments, renewals, and whether prices map by product or by price.
|
|
9
|
+
- List differences from a Lemon Squeezy reconciliation with `ownkey lemon-reconciliation list <connection>`.
|
|
10
|
+
- Count the records to check before switching from Lemon Squeezy with `ownkey imports lemonsqueezy readiness`, and link Ownkey customers to a Polar organization with `ownkey imports polar link-customers`.
|
|
11
|
+
- Apply a Polar discount with `--discount-id` and pass up to 5 attribution values with `--metadata` to `ownkey checkouts create-for-plan`.
|
|
12
|
+
- `ownkey releases remove-asset` removes a file from a yanked release without a replacement. A release that is not yanked still needs a newer stable release with a verified equivalent file.
|
|
13
|
+
- A repeated `ownkey licenses activate` on a site returns the site's current `instance_id`.
|
|
14
|
+
|
|
15
|
+
## 0.2.0
|
|
16
|
+
|
|
17
|
+
- Run the Ownkey CLI with `npx @ownkeyhq/cli`.
|
|
18
|
+
- Products now have an optional `install_instructions` field. The `kind` and `wp_slug` fields were removed.
|
|
19
|
+
- Use `licenses.list`, `payments.list`, `payments.get` and `customers.search` for seller support, and read the license state and renewal eligibility in the `state` and `renewal` fields of `licenses.get`.
|
|
20
|
+
- Read `periods[].origin` in `licenses.get` to see whether a payment, a person, or an EDD or Lemon Squeezy import created the period.
|
|
21
|
+
- Bundle download responses include `bundle_downloads[].source` to distinguish the bundle's own ZIP files from those of included products.
|
|
22
|
+
- Read one provider event with `providerEvents.get`.
|
|
23
|
+
- Link a match queue item to a license with `matchQueue.resolve`.
|
|
24
|
+
- Read a revenue and license summary with `overview.summary` and the items that need attention with `overview.attention`.
|
|
25
|
+
- Sort customers by their latest payment or renewal with `customers.list` and `sort=activity`. Customers without payments use their registration date.
|
|
26
|
+
- List saved EDD import jobs by source with `imports.edd.listJobs`. Lemon Squeezy import responses report progress and distinguish a skipped phase from a failure.
|
|
27
|
+
- Correct provider product and price IDs, replace the mapped plan, or remove a provider price mapping.
|
|
28
|
+
- Remove a brand logo with `ownkey brands remove-logo <brand>`.
|
|
29
|
+
|
|
30
|
+
## 0.1.0
|
|
31
|
+
|
|
32
|
+
- Install the Ownkey CLI from npm and sign in with `npx @ownkeyhq/cli login`.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Devoice LLC
|
|
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.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { createReadStream } from "node:fs";
|
|
4
|
+
import { chmod, mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
import { Readable } from "node:stream";
|
|
8
|
+
import { run } from "../src/main.js";
|
|
9
|
+
const env = process.env;
|
|
10
|
+
const configPath = env.OWNKEY_CONFIG ||
|
|
11
|
+
join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "ownkey", "config.json");
|
|
12
|
+
const io = {
|
|
13
|
+
stdout: (text) => process.stdout.write(text),
|
|
14
|
+
stderr: (text) => process.stderr.write(text),
|
|
15
|
+
env,
|
|
16
|
+
fetch: (input, init) => fetch(input, init),
|
|
17
|
+
async readConfig() {
|
|
18
|
+
let text;
|
|
19
|
+
try {
|
|
20
|
+
text = await readFile(configPath, "utf8");
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
if (error.code === "ENOENT")
|
|
24
|
+
return null;
|
|
25
|
+
throw error;
|
|
26
|
+
}
|
|
27
|
+
const config = JSON.parse(text);
|
|
28
|
+
if (typeof config?.url !== "string" || typeof config?.key !== "string") {
|
|
29
|
+
throw new Error(`${configPath} is not a JSON object with url and key`);
|
|
30
|
+
}
|
|
31
|
+
return { url: config.url, key: config.key };
|
|
32
|
+
},
|
|
33
|
+
async writeConfig(config) {
|
|
34
|
+
await mkdir(dirname(configPath), { recursive: true, mode: 0o700 });
|
|
35
|
+
await chmod(configPath, 0o600).catch(() => { });
|
|
36
|
+
await writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
|
37
|
+
},
|
|
38
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
39
|
+
async hashFile(path) {
|
|
40
|
+
const hash = createHash("sha256");
|
|
41
|
+
for await (const chunk of createReadStream(path))
|
|
42
|
+
hash.update(chunk);
|
|
43
|
+
return hash.digest("hex");
|
|
44
|
+
},
|
|
45
|
+
async openFile(path) {
|
|
46
|
+
const { size } = await stat(path);
|
|
47
|
+
return { stream: Readable.toWeb(createReadStream(path)), size };
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
process.exitCode = await run(process.argv.slice(2), io);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { JsonSchema } from "@ownkeyhq/sdk";
|
|
2
|
+
export declare class UsageError extends Error {
|
|
3
|
+
}
|
|
4
|
+
export interface Parsed {
|
|
5
|
+
raw: Record<string, string[]>;
|
|
6
|
+
positionals: string[];
|
|
7
|
+
json: boolean;
|
|
8
|
+
help: boolean;
|
|
9
|
+
}
|
|
10
|
+
export declare function flagOf(field: string): string;
|
|
11
|
+
export declare function types(schema: JsonSchema): Set<string>;
|
|
12
|
+
export declare function parse(args: string[], fields: Record<string, JsonSchema>): Parsed;
|
|
13
|
+
export declare function coerce(flag: string, raw: string[], schema: JsonSchema): unknown;
|
|
14
|
+
export declare function input(parsed: Parsed, fields: Record<string, JsonSchema>): Record<string, unknown>;
|
|
15
|
+
export declare function typeLabel(schema: JsonSchema): string;
|
package/dist/src/args.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
export class UsageError extends Error {
|
|
2
|
+
}
|
|
3
|
+
export function flagOf(field) {
|
|
4
|
+
return field.replaceAll("_", "-");
|
|
5
|
+
}
|
|
6
|
+
export function types(schema) {
|
|
7
|
+
const out = new Set();
|
|
8
|
+
if (typeof schema.type === "string")
|
|
9
|
+
out.add(schema.type);
|
|
10
|
+
for (const type of Array.isArray(schema.type) ? schema.type : [])
|
|
11
|
+
out.add(type);
|
|
12
|
+
for (const member of schema.anyOf ?? [])
|
|
13
|
+
for (const type of types(member))
|
|
14
|
+
out.add(type);
|
|
15
|
+
return out;
|
|
16
|
+
}
|
|
17
|
+
function member(schema, type) {
|
|
18
|
+
return schema.anyOf?.find((m) => types(m).has(type)) ?? schema;
|
|
19
|
+
}
|
|
20
|
+
function isSwitch(schema) {
|
|
21
|
+
const t = types(schema);
|
|
22
|
+
return t.has("boolean") && !t.has("string");
|
|
23
|
+
}
|
|
24
|
+
export function parse(args, fields) {
|
|
25
|
+
const parsed = { raw: {}, positionals: [], json: false, help: false };
|
|
26
|
+
for (let i = 0; i < args.length; i++) {
|
|
27
|
+
const arg = args[i];
|
|
28
|
+
if (arg === "--") {
|
|
29
|
+
parsed.positionals.push(...args.slice(i + 1));
|
|
30
|
+
break;
|
|
31
|
+
}
|
|
32
|
+
if (arg === "-h") {
|
|
33
|
+
parsed.help = true;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (!arg.startsWith("--")) {
|
|
37
|
+
parsed.positionals.push(arg);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
const eq = arg.indexOf("=");
|
|
41
|
+
const name = arg.slice(2, eq === -1 ? undefined : eq);
|
|
42
|
+
const inline = eq === -1 ? undefined : arg.slice(eq + 1);
|
|
43
|
+
if (name === "json" && inline === undefined) {
|
|
44
|
+
parsed.json = true;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (name === "help" && inline === undefined) {
|
|
48
|
+
parsed.help = true;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
const field = name.replaceAll("-", "_");
|
|
52
|
+
const schema = fields[field];
|
|
53
|
+
if (schema === undefined || name !== flagOf(field)) {
|
|
54
|
+
throw new UsageError(`unknown flag --${name}`);
|
|
55
|
+
}
|
|
56
|
+
let value = inline;
|
|
57
|
+
if (value === undefined) {
|
|
58
|
+
const next = args[i + 1];
|
|
59
|
+
if (isSwitch(schema)) {
|
|
60
|
+
value = next === "true" || next === "false" ? next : "true";
|
|
61
|
+
if (value === next)
|
|
62
|
+
i += 1;
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
if (next === undefined)
|
|
66
|
+
throw new UsageError(`--${name} needs a value`);
|
|
67
|
+
value = next;
|
|
68
|
+
i += 1;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
parsed.raw[field] = [...(parsed.raw[field] ?? []), value];
|
|
72
|
+
}
|
|
73
|
+
return parsed;
|
|
74
|
+
}
|
|
75
|
+
function json(flag, text) {
|
|
76
|
+
try {
|
|
77
|
+
return JSON.parse(text);
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
throw new UsageError(`--${flag} is not valid JSON`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export function coerce(flag, raw, schema) {
|
|
84
|
+
const t = types(schema);
|
|
85
|
+
const [first] = raw;
|
|
86
|
+
if (t.has("null") && raw.length === 1 && first === "null")
|
|
87
|
+
return null;
|
|
88
|
+
if (t.has("array")) {
|
|
89
|
+
if (raw.length === 1 && first?.startsWith("["))
|
|
90
|
+
return json(flag, first);
|
|
91
|
+
const items = member(schema, "array").items ?? {};
|
|
92
|
+
return raw
|
|
93
|
+
.flatMap((v) => v.split(","))
|
|
94
|
+
.filter((v) => v !== "")
|
|
95
|
+
.map((v) => coerce(flag, [v], items));
|
|
96
|
+
}
|
|
97
|
+
if (t.has("object")) {
|
|
98
|
+
if (raw.length === 1 && first?.startsWith("{"))
|
|
99
|
+
return json(flag, first);
|
|
100
|
+
const object = member(schema, "object");
|
|
101
|
+
const out = {};
|
|
102
|
+
for (const pair of raw) {
|
|
103
|
+
const at = pair.indexOf("=");
|
|
104
|
+
if (at < 1)
|
|
105
|
+
throw new UsageError(`--${flag} takes key=value or a JSON object`);
|
|
106
|
+
const key = pair.slice(0, at);
|
|
107
|
+
const values = object.properties?.[key] ??
|
|
108
|
+
(typeof object.additionalProperties === "object" ? object.additionalProperties : {});
|
|
109
|
+
out[key] = coerce(flag, [pair.slice(at + 1)], values);
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
if (first === undefined || raw.length > 1) {
|
|
114
|
+
throw new UsageError(`--${flag} takes one value`);
|
|
115
|
+
}
|
|
116
|
+
if (t.has("integer") || t.has("number")) {
|
|
117
|
+
const n = Number(first);
|
|
118
|
+
if (first.trim() !== "" && Number.isFinite(n))
|
|
119
|
+
return n;
|
|
120
|
+
if (!t.has("string"))
|
|
121
|
+
throw new UsageError(`--${flag} takes a number`);
|
|
122
|
+
}
|
|
123
|
+
if (t.has("boolean")) {
|
|
124
|
+
if (first === "true")
|
|
125
|
+
return true;
|
|
126
|
+
if (first === "false")
|
|
127
|
+
return false;
|
|
128
|
+
if (!t.has("string"))
|
|
129
|
+
throw new UsageError(`--${flag} takes true or false`);
|
|
130
|
+
}
|
|
131
|
+
if (t.size === 0) {
|
|
132
|
+
try {
|
|
133
|
+
return JSON.parse(first);
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return first;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return first;
|
|
140
|
+
}
|
|
141
|
+
export function input(parsed, fields) {
|
|
142
|
+
const out = {};
|
|
143
|
+
for (const [field, raw] of Object.entries(parsed.raw)) {
|
|
144
|
+
out[field] = coerce(flagOf(field), raw, fields[field] ?? {});
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
export function typeLabel(schema) {
|
|
149
|
+
if (schema.enum)
|
|
150
|
+
return schema.enum.join("|");
|
|
151
|
+
const t = types(schema);
|
|
152
|
+
if (t.has("array"))
|
|
153
|
+
return `${typeLabel(member(schema, "array").items ?? {})},...`;
|
|
154
|
+
if (t.has("object"))
|
|
155
|
+
return "key=value";
|
|
156
|
+
const named = [...t].filter((x) => x !== "null");
|
|
157
|
+
const choices = schema.anyOf?.flatMap((m) => m.enum ?? []);
|
|
158
|
+
const label = choices?.length ? choices.join("|") : named.join("|") || "value";
|
|
159
|
+
return t.has("null") ? `${label}|null` : label;
|
|
160
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type JsonSchema } from "@ownkeyhq/sdk";
|
|
2
|
+
import { type Parsed } from "./args.ts";
|
|
3
|
+
import { type Io } from "./context.ts";
|
|
4
|
+
export interface Command {
|
|
5
|
+
words: string[];
|
|
6
|
+
usage: string;
|
|
7
|
+
summary: string;
|
|
8
|
+
fields: Record<string, JsonSchema>;
|
|
9
|
+
required: string[];
|
|
10
|
+
run(parsed: Parsed, io: Io): Promise<number>;
|
|
11
|
+
}
|
|
12
|
+
export declare const commands: Command[];
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { createClient, OwnkeyError, putReleaseFile, releaseUploadRequestId, } from "@ownkeyhq/sdk";
|
|
2
|
+
import { input, UsageError } from "./args.js";
|
|
3
|
+
import { clientFor, defaultUrl, Failure, print } from "./context.js";
|
|
4
|
+
const string = { type: "string" };
|
|
5
|
+
function positionals(parsed, names) {
|
|
6
|
+
if (parsed.positionals.length !== names.length) {
|
|
7
|
+
throw new UsageError(`expected ${names.map((n) => `<${n}>`).join(" ")}`);
|
|
8
|
+
}
|
|
9
|
+
return parsed.positionals;
|
|
10
|
+
}
|
|
11
|
+
async function sha256(io, path) {
|
|
12
|
+
if (io.hashFile)
|
|
13
|
+
return io.hashFile(path);
|
|
14
|
+
const { stream, size } = await io.openFile(path);
|
|
15
|
+
if (size > 100_000_000) {
|
|
16
|
+
await stream.cancel();
|
|
17
|
+
throw new Failure("sha256_unavailable", "A streaming SHA-256 implementation is required for this file");
|
|
18
|
+
}
|
|
19
|
+
const chunks = [];
|
|
20
|
+
let length = 0;
|
|
21
|
+
for await (const chunk of stream) {
|
|
22
|
+
chunks.push(chunk);
|
|
23
|
+
length += chunk.length;
|
|
24
|
+
}
|
|
25
|
+
const bytes = new Uint8Array(length);
|
|
26
|
+
let at = 0;
|
|
27
|
+
for (const chunk of chunks) {
|
|
28
|
+
bytes.set(chunk, at);
|
|
29
|
+
at += chunk.length;
|
|
30
|
+
}
|
|
31
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
|
|
32
|
+
return [...digest].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
33
|
+
}
|
|
34
|
+
const login = {
|
|
35
|
+
words: ["login"],
|
|
36
|
+
usage: "login --key <key> [--url <url>]",
|
|
37
|
+
summary: "Check a secret key with the API and save it to the config file.",
|
|
38
|
+
fields: { key: string, url: string },
|
|
39
|
+
required: ["key"],
|
|
40
|
+
async run(parsed, io) {
|
|
41
|
+
positionals(parsed, []);
|
|
42
|
+
const { key = io.env.OWNKEY_API_KEY, url } = input(parsed, this.fields);
|
|
43
|
+
if (!key)
|
|
44
|
+
throw new UsageError("--key is required");
|
|
45
|
+
const baseUrl = url ?? (io.env.OWNKEY_API_URL || (await io.readConfig())?.url || defaultUrl);
|
|
46
|
+
await createClient({ baseUrl, key, fetch: io.fetch }).call("brands.list", {});
|
|
47
|
+
await io.writeConfig({ url: baseUrl, key });
|
|
48
|
+
io.stdout(`Logged in to ${baseUrl}. The key is saved.\n`);
|
|
49
|
+
return 0;
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
const push = {
|
|
53
|
+
words: ["releases", "push"],
|
|
54
|
+
usage: "releases push <product> <version> <file> [--plan-ids a,b] [--replaces <shared file>] [--channel beta]",
|
|
55
|
+
summary: "Upload a file to a product's version, creating the release when it is missing.",
|
|
56
|
+
fields: {
|
|
57
|
+
plan_ids: { type: "array", items: string },
|
|
58
|
+
replaces: string,
|
|
59
|
+
channel: { type: "string", enum: ["stable", "beta"] },
|
|
60
|
+
filename: string,
|
|
61
|
+
},
|
|
62
|
+
required: [],
|
|
63
|
+
async run(parsed, io) {
|
|
64
|
+
const [product, version, file] = positionals(parsed, ["product", "version", "file"]);
|
|
65
|
+
const flags = input(parsed, this.fields);
|
|
66
|
+
const client = await clientFor(io);
|
|
67
|
+
const local = await sha256(io, file);
|
|
68
|
+
const find = async () => (await client.call("releases.list", { product })).releases.find((r) => r.version === version);
|
|
69
|
+
let release = await find();
|
|
70
|
+
if (!release) {
|
|
71
|
+
try {
|
|
72
|
+
release = await client.call("releases.create", {
|
|
73
|
+
product,
|
|
74
|
+
version,
|
|
75
|
+
...(flags.channel ? { channel: flags.channel } : {}),
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
if (!(error instanceof OwnkeyError && error.status === 409))
|
|
80
|
+
throw error;
|
|
81
|
+
release = await find();
|
|
82
|
+
if (!release)
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const { stream, size } = await io.openFile(file);
|
|
87
|
+
const settings = {
|
|
88
|
+
release: release.id,
|
|
89
|
+
filename: flags.filename ?? file.split(/[\\/]/).pop(),
|
|
90
|
+
...(flags.plan_ids ? { plan_ids: [...new Set(flags.plan_ids)].sort() } : {}),
|
|
91
|
+
...(flags.replaces ? { replaces: flags.replaces } : {}),
|
|
92
|
+
};
|
|
93
|
+
const upload = { body: stream, length: size };
|
|
94
|
+
const asset = await (async () => {
|
|
95
|
+
if (size <= 100_000_000)
|
|
96
|
+
return client.call("releases.addAsset", settings, upload);
|
|
97
|
+
const intent = { ...settings, size, sha256: local };
|
|
98
|
+
const grant = await client.call("releases.prepareUpload", {
|
|
99
|
+
...intent,
|
|
100
|
+
request_id: await releaseUploadRequestId(intent),
|
|
101
|
+
});
|
|
102
|
+
if (grant.transfer)
|
|
103
|
+
await putReleaseFile(grant.transfer, upload, io.fetch);
|
|
104
|
+
return client.call("releases.confirmUpload", { release: release.id, asset: grant.asset_id });
|
|
105
|
+
})().finally(() => stream.cancel().catch(() => { }));
|
|
106
|
+
if (asset.sha256 !== local) {
|
|
107
|
+
throw new Failure("sha256_mismatch", `The server stored sha256 ${asset.sha256}, the local file has ${local}`);
|
|
108
|
+
}
|
|
109
|
+
print(io, asset, parsed.json);
|
|
110
|
+
return 0;
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
const maxCalls = 500;
|
|
114
|
+
const importParts = [
|
|
115
|
+
"catalog",
|
|
116
|
+
"files",
|
|
117
|
+
"customers",
|
|
118
|
+
"payments",
|
|
119
|
+
"subscriptions",
|
|
120
|
+
"licenses",
|
|
121
|
+
];
|
|
122
|
+
const importLemonSqueezy = {
|
|
123
|
+
words: ["import", "lemonsqueezy"],
|
|
124
|
+
usage: `import lemonsqueezy --connection <id> [--only ${importParts.join(",")}] [--rerun] [--dry-run]`,
|
|
125
|
+
summary: "Import a Lemon Squeezy store's catalog, files, customers, payments, subscriptions and keys, calling the API until done.",
|
|
126
|
+
fields: {
|
|
127
|
+
connection: string,
|
|
128
|
+
only: { type: "array", items: { type: "string", enum: [...importParts] } },
|
|
129
|
+
dry_run: { type: "boolean" },
|
|
130
|
+
rerun: { type: "boolean" },
|
|
131
|
+
products: { type: "object", additionalProperties: string },
|
|
132
|
+
},
|
|
133
|
+
required: ["connection"],
|
|
134
|
+
async run(parsed, io) {
|
|
135
|
+
positionals(parsed, []);
|
|
136
|
+
const flags = input(parsed, this.fields);
|
|
137
|
+
if (!flags.connection)
|
|
138
|
+
throw new UsageError("--connection is required");
|
|
139
|
+
const body = {
|
|
140
|
+
connection: flags.connection,
|
|
141
|
+
parts: [...(flags.only ?? importParts)],
|
|
142
|
+
...(flags.products ? { products: flags.products } : {}),
|
|
143
|
+
};
|
|
144
|
+
const client = await clientFor(io);
|
|
145
|
+
if (flags.dry_run) {
|
|
146
|
+
print(io, await client.call("imports.lemonsqueezy.plan", body), parsed.json);
|
|
147
|
+
return 0;
|
|
148
|
+
}
|
|
149
|
+
for (let call = 1; call <= maxCalls; call++) {
|
|
150
|
+
const result = await client.call("imports.lemonsqueezy.run", {
|
|
151
|
+
...body,
|
|
152
|
+
rerun: call === 1 && flags.rerun === true,
|
|
153
|
+
});
|
|
154
|
+
const progress = result.runs.map((r) => {
|
|
155
|
+
const counts = Object.entries(r.counts).map(([k, v]) => ` ${k}=${v}`);
|
|
156
|
+
return `${r.part} ${r.status}${counts.join("")}`;
|
|
157
|
+
});
|
|
158
|
+
io.stderr(`call ${call}: ${progress.join("; ")}\n`);
|
|
159
|
+
if (!result.done) {
|
|
160
|
+
if (result.wait_seconds !== null && result.wait_seconds > 0) {
|
|
161
|
+
io.stderr(`Lemon Squeezy asked to wait ${result.wait_seconds} s\n`);
|
|
162
|
+
await io.sleep(result.wait_seconds * 1000);
|
|
163
|
+
}
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
print(io, result.runs, parsed.json);
|
|
167
|
+
const failed = result.runs.filter((r) => r.status === "failed" || r.error !== null || (r.counts.files_failed ?? 0) > 0);
|
|
168
|
+
if (failed.length === 0)
|
|
169
|
+
return 0;
|
|
170
|
+
throw new Failure("import_failed", `${failed.map((r) => r.part).join(", ")} reported failures; run the command again with --rerun to retry`);
|
|
171
|
+
}
|
|
172
|
+
throw new Failure("not_done", `The import did not finish after ${maxCalls} calls; run the command again to continue`);
|
|
173
|
+
},
|
|
174
|
+
};
|
|
175
|
+
const uploadEdd = {
|
|
176
|
+
words: ["imports", "edd", "upload"],
|
|
177
|
+
usage: "imports edd upload <job> <file>",
|
|
178
|
+
summary: "Upload a private EDD snapshot and mapping envelope from a JSON file.",
|
|
179
|
+
fields: {},
|
|
180
|
+
required: [],
|
|
181
|
+
async run(parsed, io) {
|
|
182
|
+
const [job, file] = positionals(parsed, ["job", "file"]);
|
|
183
|
+
const client = await clientFor(io);
|
|
184
|
+
const { stream, size } = await io.openFile(file);
|
|
185
|
+
print(io, await client.call("imports.edd.upload", { job }, { body: stream, length: size }), parsed.json);
|
|
186
|
+
return 0;
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
export const commands = [login, push, importLemonSqueezy, uploadEdd];
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type Client, type Fetch } from "@ownkeyhq/sdk";
|
|
2
|
+
export interface Config {
|
|
3
|
+
url: string;
|
|
4
|
+
key: string;
|
|
5
|
+
}
|
|
6
|
+
export interface Io {
|
|
7
|
+
stdout(text: string): void;
|
|
8
|
+
stderr(text: string): void;
|
|
9
|
+
env: Record<string, string | undefined>;
|
|
10
|
+
fetch: Fetch;
|
|
11
|
+
readConfig(): Promise<Config | null>;
|
|
12
|
+
writeConfig(config: Config): Promise<void>;
|
|
13
|
+
hashFile?(path: string): Promise<string>;
|
|
14
|
+
openFile(path: string): Promise<{
|
|
15
|
+
stream: ReadableStream<Uint8Array>;
|
|
16
|
+
size: number;
|
|
17
|
+
}>;
|
|
18
|
+
sleep(ms: number): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
export declare const defaultUrl = "https://api.ownkey.dev";
|
|
21
|
+
export declare class Failure extends Error {
|
|
22
|
+
readonly code: string;
|
|
23
|
+
constructor(code: string, message: string);
|
|
24
|
+
}
|
|
25
|
+
export declare function clientFor(io: Io): Promise<Client>;
|
|
26
|
+
export declare function print(io: Io, value: unknown, json: boolean): void;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { createClient } from "@ownkeyhq/sdk";
|
|
2
|
+
import { render } from "./output.js";
|
|
3
|
+
export const defaultUrl = "https://api.ownkey.dev";
|
|
4
|
+
export class Failure extends Error {
|
|
5
|
+
code;
|
|
6
|
+
constructor(code, message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.code = code;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export async function clientFor(io) {
|
|
12
|
+
const config = await io.readConfig();
|
|
13
|
+
const key = io.env.OWNKEY_API_KEY || config?.key;
|
|
14
|
+
if (!key) {
|
|
15
|
+
throw new Failure("no_key", "No API key. Run ownkey login --key <key>, or set OWNKEY_API_KEY.");
|
|
16
|
+
}
|
|
17
|
+
const baseUrl = io.env.OWNKEY_API_URL || config?.url || defaultUrl;
|
|
18
|
+
return createClient({ baseUrl, key, fetch: io.fetch });
|
|
19
|
+
}
|
|
20
|
+
export function print(io, value, json) {
|
|
21
|
+
io.stdout(json ? `${JSON.stringify(value, null, 2)}\n` : render(value));
|
|
22
|
+
}
|
package/dist/src/main.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { OwnkeyError, operations } from "@ownkeyhq/sdk";
|
|
2
|
+
import { flagOf, input, parse, typeLabel, UsageError } from "./args.js";
|
|
3
|
+
import { commands } from "./commands.js";
|
|
4
|
+
import { clientFor, Failure, print } from "./context.js";
|
|
5
|
+
function kebab(word) {
|
|
6
|
+
return word.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
|
|
7
|
+
}
|
|
8
|
+
function generic(op) {
|
|
9
|
+
const params = op.pathParams.map((p) => `<${p}>`).join(" ");
|
|
10
|
+
const words = op.name.split(".").map(kebab);
|
|
11
|
+
return {
|
|
12
|
+
words,
|
|
13
|
+
usage: [...words, params].filter(Boolean).join(" "),
|
|
14
|
+
summary: op.summary,
|
|
15
|
+
fields: op.fields,
|
|
16
|
+
required: op.required,
|
|
17
|
+
async run(parsed, io) {
|
|
18
|
+
const body = input(parsed, op.fields);
|
|
19
|
+
const [param] = op.pathParams;
|
|
20
|
+
if (parsed.positionals.length > 0) {
|
|
21
|
+
const [first, extra] = parsed.positionals;
|
|
22
|
+
if (op.pathParams.length !== 1 || extra !== undefined || param === undefined) {
|
|
23
|
+
throw new UsageError(`unexpected argument "${extra ?? first}"`);
|
|
24
|
+
}
|
|
25
|
+
if (body[param] !== undefined)
|
|
26
|
+
throw new UsageError(`<${param}> is given twice`);
|
|
27
|
+
body[param] = first;
|
|
28
|
+
}
|
|
29
|
+
for (const p of op.pathParams) {
|
|
30
|
+
if (body[p] === undefined)
|
|
31
|
+
throw new UsageError(`<${p}> is required`);
|
|
32
|
+
}
|
|
33
|
+
if (op.upload || op.name === "releases.prepareUpload")
|
|
34
|
+
throw new UsageError("this sends a file: use ownkey releases push");
|
|
35
|
+
const client = await clientFor(io);
|
|
36
|
+
const call = client.call;
|
|
37
|
+
print(io, await call(op.name, body), parsed.json);
|
|
38
|
+
return 0;
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
const all = [
|
|
43
|
+
...commands,
|
|
44
|
+
...operations()
|
|
45
|
+
.filter((op) => op.scope !== "customer" && !commands.some((command) => command.words.join(".") === op.name))
|
|
46
|
+
.map(generic),
|
|
47
|
+
];
|
|
48
|
+
function find(argv) {
|
|
49
|
+
let best;
|
|
50
|
+
for (const command of all) {
|
|
51
|
+
const matches = command.words.every((word, i) => argv[i] === word);
|
|
52
|
+
if (matches && command.words.length > (best?.words.length ?? 0))
|
|
53
|
+
best = command;
|
|
54
|
+
}
|
|
55
|
+
return best;
|
|
56
|
+
}
|
|
57
|
+
function firstSentence(text) {
|
|
58
|
+
const end = text.indexOf(". ");
|
|
59
|
+
return end === -1 ? text : text.slice(0, end + 1);
|
|
60
|
+
}
|
|
61
|
+
function help() {
|
|
62
|
+
const width = Math.max(...all.map((c) => c.usage.length));
|
|
63
|
+
return [
|
|
64
|
+
"Usage: ownkey <command> [--flag value] [--json]",
|
|
65
|
+
"",
|
|
66
|
+
"Commands:",
|
|
67
|
+
...all.map((c) => ` ${c.usage.padEnd(width)} ${firstSentence(c.summary)}`),
|
|
68
|
+
"",
|
|
69
|
+
"Run ownkey <command> --help for its flags.",
|
|
70
|
+
"",
|
|
71
|
+
].join("\n");
|
|
72
|
+
}
|
|
73
|
+
function flagLine(field, schema, required) {
|
|
74
|
+
const type = typeLabel(schema);
|
|
75
|
+
return ` --${flagOf(field)} ${type === "boolean" ? "" : `<${type}>`}${required ? " (required)" : ""}`;
|
|
76
|
+
}
|
|
77
|
+
function commandHelp(command) {
|
|
78
|
+
const required = new Set(command.required);
|
|
79
|
+
return [
|
|
80
|
+
`Usage: ownkey ${command.usage}`,
|
|
81
|
+
"",
|
|
82
|
+
command.summary,
|
|
83
|
+
"",
|
|
84
|
+
"Flags:",
|
|
85
|
+
...Object.entries(command.fields).map(([f, s]) => flagLine(f, s, required.has(f))),
|
|
86
|
+
" --json print the JSON as returned",
|
|
87
|
+
"",
|
|
88
|
+
].join("\n");
|
|
89
|
+
}
|
|
90
|
+
export async function run(argv, io) {
|
|
91
|
+
try {
|
|
92
|
+
const [first] = argv;
|
|
93
|
+
if (first === undefined || first === "help" || first === "--help" || first === "-h") {
|
|
94
|
+
io.stdout(help());
|
|
95
|
+
return 0;
|
|
96
|
+
}
|
|
97
|
+
const command = find(argv);
|
|
98
|
+
if (!command) {
|
|
99
|
+
throw new UsageError(`unknown command "${argv.filter((a) => !a.startsWith("-")).join(" ")}"`);
|
|
100
|
+
}
|
|
101
|
+
const parsed = parse(argv.slice(command.words.length), command.fields);
|
|
102
|
+
if (parsed.help) {
|
|
103
|
+
io.stdout(commandHelp(command));
|
|
104
|
+
return 0;
|
|
105
|
+
}
|
|
106
|
+
return await command.run(parsed, io);
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
if (error instanceof UsageError) {
|
|
110
|
+
io.stderr(`usage: ${error.message}\nRun ownkey help for the commands.\n`);
|
|
111
|
+
return 2;
|
|
112
|
+
}
|
|
113
|
+
if (error instanceof OwnkeyError || error instanceof Failure) {
|
|
114
|
+
io.stderr(`error ${error.code}: ${error.message}\n`);
|
|
115
|
+
return 1;
|
|
116
|
+
}
|
|
117
|
+
io.stderr(`error failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
118
|
+
return 1;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
function isScalar(value) {
|
|
2
|
+
return value === null || typeof value !== "object";
|
|
3
|
+
}
|
|
4
|
+
export function compact(value) {
|
|
5
|
+
if (value === null || value === undefined)
|
|
6
|
+
return "-";
|
|
7
|
+
if (Array.isArray(value)) {
|
|
8
|
+
if (value.length === 0)
|
|
9
|
+
return "-";
|
|
10
|
+
return value.every(isScalar) ? value.map(compact).join(",") : `${value.length} items`;
|
|
11
|
+
}
|
|
12
|
+
if (typeof value === "object") {
|
|
13
|
+
const entries = Object.entries(value);
|
|
14
|
+
if (entries.length === 0)
|
|
15
|
+
return "-";
|
|
16
|
+
return entries.every(([, v]) => isScalar(v))
|
|
17
|
+
? entries.map(([k, v]) => `${k}=${compact(v)}`).join(" ")
|
|
18
|
+
: `${entries.length} fields`;
|
|
19
|
+
}
|
|
20
|
+
return String(value).replace(/\s*\n\s*/g, " ");
|
|
21
|
+
}
|
|
22
|
+
function lines(rows) {
|
|
23
|
+
const widths = rows[0]?.map((_, i) => Math.max(...rows.map((r) => (r[i] ?? "").length))) ?? [];
|
|
24
|
+
return rows
|
|
25
|
+
.map((r) => r
|
|
26
|
+
.map((cell, i) => cell.padEnd(widths[i] ?? 0))
|
|
27
|
+
.join(" ")
|
|
28
|
+
.trimEnd())
|
|
29
|
+
.map((line) => `${line}\n`)
|
|
30
|
+
.join("");
|
|
31
|
+
}
|
|
32
|
+
function table(items) {
|
|
33
|
+
if (!items.every((item) => typeof item === "object" && item !== null && !Array.isArray(item))) {
|
|
34
|
+
return items.map((item) => `${compact(item)}\n`).join("");
|
|
35
|
+
}
|
|
36
|
+
const columns = [];
|
|
37
|
+
for (const item of items) {
|
|
38
|
+
for (const key of Object.keys(item))
|
|
39
|
+
if (!columns.includes(key))
|
|
40
|
+
columns.push(key);
|
|
41
|
+
}
|
|
42
|
+
return lines([columns, ...items.map((item) => columns.map((c) => compact(item[c])))]);
|
|
43
|
+
}
|
|
44
|
+
export function render(value) {
|
|
45
|
+
if (Array.isArray(value))
|
|
46
|
+
return table(value);
|
|
47
|
+
if (typeof value !== "object" || value === null)
|
|
48
|
+
return `${compact(value)}\n`;
|
|
49
|
+
const entries = Object.entries(value);
|
|
50
|
+
const [only] = entries;
|
|
51
|
+
if (entries.length === 1 && only && Array.isArray(only[1])) {
|
|
52
|
+
return only[1].length === 0 ? `no ${only[0]}\n` : table(only[1]);
|
|
53
|
+
}
|
|
54
|
+
return lines(entries.map(([key, v]) => [key, compact(v)]));
|
|
55
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ownkeyhq/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"engines": {
|
|
7
|
+
"node": ">=22.16"
|
|
8
|
+
},
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/ownkeyhq/ownkey.git",
|
|
12
|
+
"directory": "packages/cli"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist/bin/ownkey.mjs",
|
|
16
|
+
"dist/src/*.js",
|
|
17
|
+
"dist/src/*.d.ts",
|
|
18
|
+
"CHANGELOG.md"
|
|
19
|
+
],
|
|
20
|
+
"bin": {
|
|
21
|
+
"ownkey": "./dist/bin/ownkey.mjs"
|
|
22
|
+
},
|
|
23
|
+
"exports": {
|
|
24
|
+
".": "./dist/src/main.js"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public",
|
|
28
|
+
"registry": "https://registry.npmjs.org/"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"@ownkeyhq/sdk": "0.3.0"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsc -p tsconfig.build.json",
|
|
35
|
+
"typecheck": "tsc -p tsconfig.json"
|
|
36
|
+
}
|
|
6
37
|
}
|
package/README.md
DELETED