@hitch42/cli 0.1.0-beta.9 → 0.1.1-beta.10
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/dist/hitch.js +80 -103
- package/package.json +2 -2
package/dist/hitch.js
CHANGED
|
@@ -55,8 +55,8 @@ async function healCredentialStore(credentialsPath, source, store, unrecognizedC
|
|
|
55
55
|
console.error(unrecognizedCount === void 0 ? `hitch: reset unreadable credentials file (backup: ${backupPath}).` : unrecognizedCount === 0 ? `hitch: migrated credentials to per-organization storage (backup: ${backupPath}).` : `hitch: removed ${unrecognizedCount} unrecognized credential ${unrecognizedCount === 1 ? "entry" : "entries"} (backup: ${backupPath}).`);
|
|
56
56
|
return store;
|
|
57
57
|
}
|
|
58
|
-
async function readRawCredentialStore(
|
|
59
|
-
const { credentialsPath } = storePaths(
|
|
58
|
+
async function readRawCredentialStore() {
|
|
59
|
+
const { credentialsPath } = storePaths();
|
|
60
60
|
let source;
|
|
61
61
|
try {
|
|
62
62
|
source = await readFile(credentialsPath, "utf8");
|
|
@@ -123,9 +123,9 @@ function organizationInstanceUrl(instanceUrl, orgCode) {
|
|
|
123
123
|
url.hostname = [orgCode, ...labels.slice(1)].join(".");
|
|
124
124
|
return url.toString().replace(/\/$/, "");
|
|
125
125
|
}
|
|
126
|
-
function storePaths(
|
|
127
|
-
const env =
|
|
128
|
-
const home =
|
|
126
|
+
function storePaths() {
|
|
127
|
+
const env = process.env;
|
|
128
|
+
const home = homedir();
|
|
129
129
|
const configDir = join(env.XDG_CONFIG_HOME || join(home, ".config"), "hitch");
|
|
130
130
|
return {
|
|
131
131
|
configDir,
|
|
@@ -134,25 +134,25 @@ function storePaths(options = {}) {
|
|
|
134
134
|
credentialsPath: join(configDir, "credentials.json")
|
|
135
135
|
};
|
|
136
136
|
}
|
|
137
|
-
async function resolveInstanceUrl(override
|
|
137
|
+
async function resolveInstanceUrl(override) {
|
|
138
138
|
if (override !== void 0) return normalizeInstanceUrl(override);
|
|
139
|
-
const envInstanceUrl =
|
|
139
|
+
const envInstanceUrl = process.env.HITCH_API_URL;
|
|
140
140
|
if (envInstanceUrl !== void 0 && envInstanceUrl.length > 0) return normalizeInstanceUrl(envInstanceUrl);
|
|
141
|
-
const { configPath } = storePaths(
|
|
141
|
+
const { configPath } = storePaths();
|
|
142
142
|
const config = await readJson(configPath);
|
|
143
143
|
if (config === void 0) return DEFAULT_INSTANCE_URL;
|
|
144
144
|
if (!isObject$2(config) || config.instanceUrl !== void 0 && typeof config.instanceUrl !== "string") throw new Error(`${configPath}: expected { instanceUrl?: string }.`);
|
|
145
145
|
return normalizeInstanceUrl(config.instanceUrl ?? "https://app.hitch42.com");
|
|
146
146
|
}
|
|
147
|
-
async function readCredentialStore(
|
|
148
|
-
const store = await readRawCredentialStore(
|
|
147
|
+
async function readCredentialStore() {
|
|
148
|
+
const store = await readRawCredentialStore();
|
|
149
149
|
return { instances: Object.fromEntries(Object.entries(store.instances).map(([instanceUrl, credentialsByOrg]) => [instanceUrl, Object.fromEntries(Object.entries(credentialsByOrg).flatMap(([orgCode, value]) => {
|
|
150
150
|
const credentials = parseCredentials(value);
|
|
151
151
|
return credentials === void 0 ? [] : [[orgCode, credentials]];
|
|
152
152
|
}))])) };
|
|
153
153
|
}
|
|
154
|
-
function environmentAuth(
|
|
155
|
-
const apiKey =
|
|
154
|
+
function environmentAuth() {
|
|
155
|
+
const apiKey = process.env.HITCH_API_KEY;
|
|
156
156
|
return apiKey !== void 0 && apiKey.length > 0 ? {
|
|
157
157
|
accessToken: apiKey,
|
|
158
158
|
source: "environment"
|
|
@@ -176,12 +176,12 @@ function resolveStoredAuthForOrg(credentialsByOrg, orgCode) {
|
|
|
176
176
|
const apiKeyOrgs = Object.values(credentialsByOrg).filter((credentials) => credentials.type === "apiKey").map(({ orgCode: storedOrg }) => storedOrg).sort();
|
|
177
177
|
if (apiKeyOrgs.length > 0) throw new AuthenticationError(`Stored API ${apiKeyOrgs.length === 1 ? "key is" : "keys are"} scoped to ${apiKeyOrgs.map((storedOrg) => `"${storedOrg}"`).join(", ")}, not "${orgCode}".`);
|
|
178
178
|
}
|
|
179
|
-
async function resolveAuth(instanceUrl,
|
|
180
|
-
const auth = environmentAuth(
|
|
179
|
+
async function resolveAuth(instanceUrl, orgCode) {
|
|
180
|
+
const auth = environmentAuth();
|
|
181
181
|
if (auth !== void 0) return auth;
|
|
182
182
|
const normalizedUrl = normalizeInstanceUrl(instanceUrl);
|
|
183
|
-
const credentialsByOrg = (await readCredentialStore(
|
|
184
|
-
const selectedOrg = orgCode ??
|
|
183
|
+
const credentialsByOrg = (await readCredentialStore()).instances[normalizedUrl] ?? {};
|
|
184
|
+
const selectedOrg = orgCode ?? process.env.HITCH_DEFAULT_ORG;
|
|
185
185
|
if (selectedOrg !== void 0 && selectedOrg.length > 0) return resolveStoredAuthForOrg(credentialsByOrg, selectedOrg);
|
|
186
186
|
const orgCodes = Object.keys(credentialsByOrg).sort();
|
|
187
187
|
const soleOrg = orgCodes.at(0);
|
|
@@ -195,9 +195,9 @@ function rejectEnvironmentKey(response, auth) {
|
|
|
195
195
|
function bearerToken(credentials) {
|
|
196
196
|
return "apiKey" in credentials ? credentials.apiKey : credentials.accessToken;
|
|
197
197
|
}
|
|
198
|
-
async function setCredentials(instanceUrl, credentials
|
|
199
|
-
const paths = storePaths(
|
|
200
|
-
const store = await readRawCredentialStore(
|
|
198
|
+
async function setCredentials(instanceUrl, credentials) {
|
|
199
|
+
const paths = storePaths();
|
|
200
|
+
const store = await readRawCredentialStore();
|
|
201
201
|
const normalizedUrl = normalizeInstanceUrl(instanceUrl);
|
|
202
202
|
const credentialsByOrg = store.instances[normalizedUrl];
|
|
203
203
|
store.instances[normalizedUrl] = {
|
|
@@ -208,9 +208,9 @@ async function setCredentials(instanceUrl, credentials, options = {}) {
|
|
|
208
208
|
await writeFile(paths.credentialsPath, `${JSON.stringify(store, null, 2)}\n`, { mode: 384 });
|
|
209
209
|
await chmod(paths.credentialsPath, 384);
|
|
210
210
|
}
|
|
211
|
-
async function deleteCredentials(instanceUrl, orgCode
|
|
212
|
-
const paths = storePaths(
|
|
213
|
-
const store = await readRawCredentialStore(
|
|
211
|
+
async function deleteCredentials(instanceUrl, orgCode) {
|
|
212
|
+
const paths = storePaths();
|
|
213
|
+
const store = await readRawCredentialStore();
|
|
214
214
|
const normalizedUrl = normalizeInstanceUrl(instanceUrl);
|
|
215
215
|
if (orgCode === void 0) delete store.instances[normalizedUrl];
|
|
216
216
|
else {
|
|
@@ -232,17 +232,17 @@ function instanceSlug(instanceUrl) {
|
|
|
232
232
|
const url = new URL(normalizeInstanceUrl(instanceUrl));
|
|
233
233
|
return `${url.protocol.slice(0, -1)}-${url.host}${url.pathname}`.replace(/[^a-zA-Z0-9.-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
234
234
|
}
|
|
235
|
-
function instanceCacheDir(instanceUrl
|
|
236
|
-
return join(storePaths(
|
|
235
|
+
function instanceCacheDir(instanceUrl) {
|
|
236
|
+
return join(storePaths().cacheDir, instanceSlug(instanceUrl));
|
|
237
237
|
}
|
|
238
|
-
function contractCacheDir(instanceUrl, organizationId
|
|
239
|
-
return join(instanceCacheDir(instanceUrl
|
|
238
|
+
function contractCacheDir(instanceUrl, organizationId) {
|
|
239
|
+
return join(instanceCacheDir(instanceUrl), organizationId);
|
|
240
240
|
}
|
|
241
|
-
function adminContractCacheDir(instanceUrl, organizationId
|
|
242
|
-
return join(contractCacheDir(instanceUrl, organizationId
|
|
241
|
+
function adminContractCacheDir(instanceUrl, organizationId) {
|
|
242
|
+
return join(contractCacheDir(instanceUrl, organizationId), "admin");
|
|
243
243
|
}
|
|
244
|
-
async function deleteInstanceCache(instanceUrl
|
|
245
|
-
await rm(instanceCacheDir(instanceUrl
|
|
244
|
+
async function deleteInstanceCache(instanceUrl) {
|
|
245
|
+
await rm(instanceCacheDir(instanceUrl), {
|
|
246
246
|
recursive: true,
|
|
247
247
|
force: true
|
|
248
248
|
});
|
|
@@ -365,17 +365,17 @@ async function authWithOrganization(fetcher, instanceUrl, auth, expectedOrg) {
|
|
|
365
365
|
};
|
|
366
366
|
}
|
|
367
367
|
async function loginWithDevice(instanceUrl, options = {}) {
|
|
368
|
-
const fetcher =
|
|
369
|
-
const now =
|
|
368
|
+
const fetcher = globalThis.fetch;
|
|
369
|
+
const now = Date.now;
|
|
370
370
|
const { body, response } = await postJson(fetcher, `${instanceUrl}/api/auth/device/code`, { client_id: CLIENT_ID });
|
|
371
371
|
if (!response.ok) throw new AuthenticationError(typeof body.error_description === "string" ? body.error_description : `Could not start sign-in (${response.status}).`);
|
|
372
372
|
const device = parseDeviceCode(body);
|
|
373
373
|
const verificationUrl = options.expectedOrg === void 0 ? device.verification_uri_complete : `${device.verification_uri_complete}&org=${encodeURIComponent(options.expectedOrg)}`;
|
|
374
|
-
|
|
374
|
+
console.log(`Open ${verificationUrl} and confirm code ${device.user_code}.`);
|
|
375
375
|
if (!options.noBrowser) try {
|
|
376
|
-
|
|
376
|
+
defaultOpenUrl(verificationUrl);
|
|
377
377
|
} catch {}
|
|
378
|
-
const token = await pollForToken(fetcher, instanceUrl, device, now,
|
|
378
|
+
const token = await pollForToken(fetcher, instanceUrl, device, now, (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
|
|
379
379
|
const { body: organizationBody, response: organizationResponse } = await postJson(fetcher, `${instanceUrl}/api/auth/device/organization`, { device_code: device.device_code });
|
|
380
380
|
if (!organizationResponse.ok) throw new AuthenticationError("The sign-in did not resolve an organization.");
|
|
381
381
|
const organization = parseDeviceOrganization(organizationBody);
|
|
@@ -393,7 +393,7 @@ async function loginWithDevice(instanceUrl, options = {}) {
|
|
|
393
393
|
organizationId: organization.organizationId,
|
|
394
394
|
orgCode: organization.orgCode
|
|
395
395
|
};
|
|
396
|
-
await setCredentials(instanceUrl, credentials
|
|
396
|
+
await setCredentials(instanceUrl, credentials);
|
|
397
397
|
if (options.expectedOrg !== void 0 && organization.orgCode !== options.expectedOrg) throw new AuthenticationError(`logged in to "${organization.orgCode}" but this applet targets "${options.expectedOrg}" — confirm the right organization on the device page`);
|
|
398
398
|
return {
|
|
399
399
|
credentials,
|
|
@@ -520,7 +520,7 @@ function createBridgeRouter(contract, options) {
|
|
|
520
520
|
url: `${options.instanceUrl}/api`,
|
|
521
521
|
headers: { Authorization: `Bearer ${bearerToken(options.auth)}` },
|
|
522
522
|
fetch: async (request, init) => {
|
|
523
|
-
const response = await
|
|
523
|
+
const response = await globalThis.fetch(request, init);
|
|
524
524
|
if ("source" in options.auth) rejectEnvironmentKey(response, options.auth);
|
|
525
525
|
return response;
|
|
526
526
|
}
|
|
@@ -535,9 +535,9 @@ function createBridgeRouter(contract, options) {
|
|
|
535
535
|
const description = node["~orpc"].route.summary ?? node["~orpc"].route.description;
|
|
536
536
|
const procedure = os.meta(description ? { description } : {}).input(cliInputSchema(inputSchema)).handler(async ({ input }) => {
|
|
537
537
|
if (isDelete && !input.yes) {
|
|
538
|
-
if (
|
|
538
|
+
if (process.stdin.isTTY !== true) throw new Error("Refusing to delete without --yes in non-interactive mode.");
|
|
539
539
|
const values = Object.entries(input).filter(([key, value]) => key !== "yes" && value !== void 0).map(([key, value]) => `${key}=${String(value)}`).join(" ");
|
|
540
|
-
const answer = await
|
|
540
|
+
const answer = await defaultPrompt$1(`Confirm ${path.join(" ")}${values.length === 0 ? "" : ` ${values}`}? [y/N] `);
|
|
541
541
|
if (!["y", "yes"].includes(answer.trim().toLowerCase())) throw new Error("Aborted.");
|
|
542
542
|
}
|
|
543
543
|
const detailed = Object.fromEntries(sections.flatMap((section) => {
|
|
@@ -802,14 +802,14 @@ function objectCount(spec) {
|
|
|
802
802
|
return operation ? [operation.objectCode] : [];
|
|
803
803
|
}) : [])).size;
|
|
804
804
|
}
|
|
805
|
-
async function syncContractCache(instanceUrl, credentials
|
|
805
|
+
async function syncContractCache(instanceUrl, credentials) {
|
|
806
806
|
if (credentials.organizationId === void 0) throw new Error("Stored credentials do not include an organization. Run hitch login again.");
|
|
807
|
-
const response = await
|
|
807
|
+
const response = await globalThis.fetch(`${instanceUrl}/api/v1/openapi.json`, { headers: { Authorization: `Bearer ${bearerToken(credentials)}` } });
|
|
808
808
|
if ("source" in credentials) rejectEnvironmentKey(response, credentials);
|
|
809
809
|
if (!response.ok) throw new Error(`Failed to fetch the organization contract (${response.status} ${response.statusText}).`);
|
|
810
810
|
const prepared = prepareRecordSpec(await response.json());
|
|
811
811
|
const count = objectCount(prepared);
|
|
812
|
-
const outDir = contractCacheDir(instanceUrl, credentials.organizationId
|
|
812
|
+
const outDir = contractCacheDir(instanceUrl, credentials.organizationId);
|
|
813
813
|
await mkdir(outDir, { recursive: true });
|
|
814
814
|
await Promise.all((await readdir(outDir)).flatMap((name) => name === "admin" ? [] : [rm(resolve(outDir, name), {
|
|
815
815
|
recursive: true,
|
|
@@ -822,16 +822,16 @@ async function syncContractCache(instanceUrl, credentials, options = {}) {
|
|
|
822
822
|
}, null, 2)}\n`);
|
|
823
823
|
return count;
|
|
824
824
|
}
|
|
825
|
-
async function syncAdminContractCache(instanceUrl, credentials
|
|
825
|
+
async function syncAdminContractCache(instanceUrl, credentials) {
|
|
826
826
|
if (credentials.organizationId === void 0) throw new Error("Stored credentials do not include an organization. Run hitch login again.");
|
|
827
|
-
const outDir = adminContractCacheDir(instanceUrl, credentials.organizationId
|
|
827
|
+
const outDir = adminContractCacheDir(instanceUrl, credentials.organizationId);
|
|
828
828
|
let response;
|
|
829
829
|
try {
|
|
830
|
-
response = await
|
|
830
|
+
response = await globalThis.fetch(`${instanceUrl}/api/admin/v1/openapi.json`, { headers: { Authorization: `Bearer ${bearerToken(credentials)}` } });
|
|
831
831
|
if ("source" in credentials) rejectEnvironmentKey(response, credentials);
|
|
832
832
|
} catch (error) {
|
|
833
833
|
if (error instanceof AuthenticationError) throw error;
|
|
834
|
-
|
|
834
|
+
console.error(`Warning: failed to probe admin commands: ${error instanceof Error ? error.message : String(error)}`);
|
|
835
835
|
return false;
|
|
836
836
|
}
|
|
837
837
|
if (response.status === 401 || response.status === 403) {
|
|
@@ -842,7 +842,7 @@ async function syncAdminContractCache(instanceUrl, credentials, options = {}) {
|
|
|
842
842
|
return false;
|
|
843
843
|
}
|
|
844
844
|
if (!response.ok) {
|
|
845
|
-
|
|
845
|
+
console.error(`Warning: failed to probe admin commands (${response.status} ${response.statusText}).`);
|
|
846
846
|
return false;
|
|
847
847
|
}
|
|
848
848
|
const prepared = prepareAdminSpec(await response.json());
|
|
@@ -868,32 +868,31 @@ async function defaultPrompt(message) {
|
|
|
868
868
|
readline.close();
|
|
869
869
|
}
|
|
870
870
|
}
|
|
871
|
-
function rejectEnvironmentCredentialManagement(
|
|
872
|
-
if (
|
|
871
|
+
function rejectEnvironmentCredentialManagement() {
|
|
872
|
+
if (process.env.HITCH_API_KEY !== void 0) throw new AuthenticationError("HITCH_API_KEY is set — unset it to manage stored logins.");
|
|
873
873
|
}
|
|
874
874
|
function requireAuth(auth) {
|
|
875
875
|
if (auth === void 0) throw new NotLoggedInError("Not logged in. Run hitch login.");
|
|
876
876
|
return auth;
|
|
877
877
|
}
|
|
878
|
-
function createStaticRouter(activeInstanceUrl,
|
|
879
|
-
const fetcher =
|
|
880
|
-
const
|
|
881
|
-
const
|
|
882
|
-
const warn = dependencies.warn ?? console.error;
|
|
878
|
+
function createStaticRouter(activeInstanceUrl, selectedOrg) {
|
|
879
|
+
const fetcher = globalThis.fetch;
|
|
880
|
+
const print = console.log;
|
|
881
|
+
const warn = console.error;
|
|
883
882
|
return os.router({
|
|
884
883
|
login: os.meta({ description: "Sign in to a Hitch organization." }).input(z.object({
|
|
885
884
|
apiKey: z.union([z.string(), z.boolean()]).default(false).describe("Store an API key, prompting when no value is given"),
|
|
886
885
|
noBrowser: z.boolean().default(false).describe("Do not open a browser"),
|
|
887
886
|
instance: z.string().optional().describe("Hitch instance URL")
|
|
888
887
|
})).handler(async ({ input }) => {
|
|
889
|
-
rejectEnvironmentCredentialManagement(
|
|
888
|
+
rejectEnvironmentCredentialManagement();
|
|
890
889
|
if (input.apiKey !== false && input.noBrowser) throw new AuthenticationError("--api-key and --no-browser cannot be used together.");
|
|
891
|
-
const instanceUrl = input.instance === void 0 ? activeInstanceUrl : await resolveInstanceUrl(input.instance
|
|
890
|
+
const instanceUrl = input.instance === void 0 ? activeInstanceUrl : await resolveInstanceUrl(input.instance);
|
|
892
891
|
let me;
|
|
893
892
|
let membership;
|
|
894
893
|
let storedCredentials;
|
|
895
894
|
if (input.apiKey !== false) {
|
|
896
|
-
const apiKey = typeof input.apiKey === "string" ? input.apiKey : await
|
|
895
|
+
const apiKey = typeof input.apiKey === "string" ? input.apiKey : await defaultPrompt("Paste your API key: ");
|
|
897
896
|
if (apiKey.length === 0) throw new AuthenticationError("API key cannot be empty.");
|
|
898
897
|
me = await fetchMe(fetcher, instanceUrl, {
|
|
899
898
|
accessToken: apiKey,
|
|
@@ -912,37 +911,24 @@ function createStaticRouter(activeInstanceUrl, dependencies = {}, selectedOrg) {
|
|
|
912
911
|
organizationId: organization.id,
|
|
913
912
|
orgCode: organization.code
|
|
914
913
|
};
|
|
915
|
-
await setCredentials(instanceUrl, storedCredentials
|
|
914
|
+
await setCredentials(instanceUrl, storedCredentials);
|
|
916
915
|
} else {
|
|
917
916
|
const login = await loginWithDevice(instanceUrl, {
|
|
918
917
|
expectedOrg: selectedOrg,
|
|
919
|
-
|
|
920
|
-
noBrowser: input.noBrowser,
|
|
921
|
-
now,
|
|
922
|
-
openUrl: dependencies.openUrl,
|
|
923
|
-
print,
|
|
924
|
-
sleep: dependencies.sleep,
|
|
925
|
-
store: dependencies.store
|
|
918
|
+
noBrowser: input.noBrowser
|
|
926
919
|
});
|
|
927
920
|
me = login.me;
|
|
928
921
|
membership = login.membership;
|
|
929
922
|
storedCredentials = login.credentials;
|
|
930
923
|
}
|
|
931
924
|
const organizationUrl = organizationInstanceUrl(instanceUrl, storedCredentials.orgCode);
|
|
932
|
-
await syncContractCache(organizationUrl, storedCredentials
|
|
933
|
-
|
|
934
|
-
store: dependencies.store
|
|
935
|
-
});
|
|
936
|
-
await syncAdminContractCache(organizationUrl, storedCredentials, {
|
|
937
|
-
fetch: fetcher,
|
|
938
|
-
store: dependencies.store,
|
|
939
|
-
warn
|
|
940
|
-
});
|
|
925
|
+
await syncContractCache(organizationUrl, storedCredentials);
|
|
926
|
+
await syncAdminContractCache(organizationUrl, storedCredentials);
|
|
941
927
|
print(`Signed in as ${me.person.email} to ${membership.name}${storedCredentials.type === "apiKey" ? " (API key)" : ""}.`);
|
|
942
928
|
}),
|
|
943
929
|
logout: os.meta({ description: "Sign out and remove locally stored credentials." }).input(z.object({})).handler(async () => {
|
|
944
|
-
rejectEnvironmentCredentialManagement(
|
|
945
|
-
const credentials = Object.values((await readCredentialStore(
|
|
930
|
+
rejectEnvironmentCredentialManagement();
|
|
931
|
+
const credentials = Object.values((await readCredentialStore()).instances[normalizeInstanceUrl(activeInstanceUrl)] ?? {});
|
|
946
932
|
await Promise.all(credentials.filter((credential) => credential.type === "session").map(async (credential) => {
|
|
947
933
|
try {
|
|
948
934
|
const response = await fetcher(`${activeInstanceUrl}/api/auth/sign-out`, {
|
|
@@ -955,18 +941,18 @@ function createStaticRouter(activeInstanceUrl, dependencies = {}, selectedOrg) {
|
|
|
955
941
|
}
|
|
956
942
|
}));
|
|
957
943
|
const cacheUrls = [activeInstanceUrl, ...credentials.map((credential) => organizationInstanceUrl(activeInstanceUrl, credential.orgCode))];
|
|
958
|
-
await Promise.all([deleteCredentials(activeInstanceUrl
|
|
944
|
+
await Promise.all([deleteCredentials(activeInstanceUrl), ...[...new Set(cacheUrls)].map((url) => deleteInstanceCache(url))]);
|
|
959
945
|
print(`Logged out of ${activeInstanceUrl}.`);
|
|
960
946
|
}),
|
|
961
947
|
openapi: os.meta({ description: "Print the organization's OpenAPI spec as JSON (used by applet generate)" }).input(z.object({})).handler(async () => {
|
|
962
|
-
const auth = await authWithOrganization(fetcher, activeInstanceUrl, requireAuth(await resolveAuth(activeInstanceUrl,
|
|
948
|
+
const auth = await authWithOrganization(fetcher, activeInstanceUrl, requireAuth(await resolveAuth(activeInstanceUrl, selectedOrg)), selectedOrg);
|
|
963
949
|
const response = await fetcher(`${organizationInstanceUrl(activeInstanceUrl, auth.orgCode)}/api/v1/openapi.json`, { headers: { Authorization: `Bearer ${auth.accessToken}` } });
|
|
964
950
|
rejectEnvironmentKey(response, auth);
|
|
965
951
|
if (!response.ok) throw new AuthenticationError(`Failed to load the organization's OpenAPI spec (${response.status}).`);
|
|
966
952
|
process.stdout.write(`${JSON.stringify(await response.json(), null, 2)}\n`);
|
|
967
953
|
}),
|
|
968
954
|
whoami: os.meta({ description: "Show the current Hitch identity and organization." }).input(z.object({})).handler(async () => {
|
|
969
|
-
const auth = await authWithOrganization(fetcher, activeInstanceUrl, requireAuth(await resolveAuth(activeInstanceUrl,
|
|
955
|
+
const auth = await authWithOrganization(fetcher, activeInstanceUrl, requireAuth(await resolveAuth(activeInstanceUrl, selectedOrg)), selectedOrg);
|
|
970
956
|
const me = await fetchMe(fetcher, organizationInstanceUrl(activeInstanceUrl, auth.orgCode), auth);
|
|
971
957
|
const membership = me.memberships.find(({ orgId }) => orgId === auth.organizationId);
|
|
972
958
|
if (membership === void 0) throw new AuthenticationError(`The current identity is not a member of organization "${auth.orgCode}".`);
|
|
@@ -979,17 +965,10 @@ function createStaticRouter(activeInstanceUrl, dependencies = {}, selectedOrg) {
|
|
|
979
965
|
};
|
|
980
966
|
}),
|
|
981
967
|
sync: os.meta({ description: "Refresh the cached commands for the current organization." }).input(z.object({})).handler(async () => {
|
|
982
|
-
const auth = await authWithOrganization(fetcher, activeInstanceUrl, requireAuth(await resolveAuth(activeInstanceUrl,
|
|
968
|
+
const auth = await authWithOrganization(fetcher, activeInstanceUrl, requireAuth(await resolveAuth(activeInstanceUrl, selectedOrg)), selectedOrg);
|
|
983
969
|
const organizationUrl = organizationInstanceUrl(activeInstanceUrl, auth.orgCode);
|
|
984
|
-
const count = await syncContractCache(organizationUrl, auth
|
|
985
|
-
|
|
986
|
-
store: dependencies.store
|
|
987
|
-
});
|
|
988
|
-
await syncAdminContractCache(organizationUrl, auth, {
|
|
989
|
-
fetch: fetcher,
|
|
990
|
-
store: dependencies.store,
|
|
991
|
-
warn
|
|
992
|
-
});
|
|
970
|
+
const count = await syncContractCache(organizationUrl, auth);
|
|
971
|
+
await syncAdminContractCache(organizationUrl, auth);
|
|
993
972
|
print(`Synced ${count} object${count === 1 ? "" : "s"}.`);
|
|
994
973
|
})
|
|
995
974
|
});
|
|
@@ -1071,28 +1050,26 @@ async function loadContract(path, warn) {
|
|
|
1071
1050
|
if (module.contract === null || typeof module.contract !== "object") throw new Error(`${path}: generated contract export is missing.`);
|
|
1072
1051
|
return module.contract;
|
|
1073
1052
|
}
|
|
1074
|
-
async function buildRouter(
|
|
1075
|
-
const instanceUrl = await resolveInstanceUrl(
|
|
1076
|
-
const selectedOrg = resolveOrganization(options.orgCode, process.cwd(),
|
|
1077
|
-
const staticRouter = createStaticRouter(instanceUrl,
|
|
1053
|
+
async function buildRouter(options = {}) {
|
|
1054
|
+
const instanceUrl = await resolveInstanceUrl();
|
|
1055
|
+
const selectedOrg = resolveOrganization(options.orgCode, process.cwd(), process.env);
|
|
1056
|
+
const staticRouter = createStaticRouter(instanceUrl, selectedOrg);
|
|
1078
1057
|
if (options.staticOnly) return staticRouter;
|
|
1079
1058
|
let resolved;
|
|
1080
1059
|
try {
|
|
1081
|
-
resolved = await resolveAuth(instanceUrl,
|
|
1060
|
+
resolved = await resolveAuth(instanceUrl, selectedOrg);
|
|
1082
1061
|
} catch (error) {
|
|
1083
|
-
|
|
1062
|
+
console.error(`hitch: ${error instanceof Error ? error.message : String(error)}`);
|
|
1084
1063
|
return staticRouter;
|
|
1085
1064
|
}
|
|
1086
1065
|
if (resolved === void 0) return staticRouter;
|
|
1087
|
-
const auth = await authWithOrganization(
|
|
1088
|
-
const warn =
|
|
1066
|
+
const auth = await authWithOrganization(globalThis.fetch, instanceUrl, resolved, selectedOrg);
|
|
1067
|
+
const warn = console.error;
|
|
1089
1068
|
const organizationUrl = organizationInstanceUrl(instanceUrl, auth.orgCode);
|
|
1090
|
-
const [contract, adminContract] = await Promise.all([loadContract(resolve(contractCacheDir(organizationUrl, auth.organizationId
|
|
1069
|
+
const [contract, adminContract] = await Promise.all([loadContract(resolve(contractCacheDir(organizationUrl, auth.organizationId), "orpc.gen.ts"), warn), loadContract(resolve(adminContractCacheDir(organizationUrl, auth.organizationId), "orpc.gen.ts"), warn)]);
|
|
1091
1070
|
const bridgeOptions = {
|
|
1092
1071
|
instanceUrl: organizationUrl,
|
|
1093
|
-
auth
|
|
1094
|
-
fetch: dependencies.fetch,
|
|
1095
|
-
prompt: dependencies.prompt
|
|
1072
|
+
auth
|
|
1096
1073
|
};
|
|
1097
1074
|
const dynamicRouter = contract === void 0 ? {} : createBridgeRouter(contract, bridgeOptions);
|
|
1098
1075
|
const staticNamespaces = /* @__PURE__ */ new Set([...Object.keys(staticRouter), "admin"]);
|
|
@@ -1111,10 +1088,10 @@ async function buildRouter(dependencies = {}, options = {}) {
|
|
|
1111
1088
|
...staticRouter
|
|
1112
1089
|
});
|
|
1113
1090
|
}
|
|
1114
|
-
async function runCli(
|
|
1091
|
+
async function runCli(argv) {
|
|
1115
1092
|
const selected = extractOrganizationArg(argv ?? process.argv.slice(2));
|
|
1116
1093
|
const command = selected.argv.at(0);
|
|
1117
|
-
const router = await buildRouter(
|
|
1094
|
+
const router = await buildRouter({
|
|
1118
1095
|
orgCode: selected.orgCode,
|
|
1119
1096
|
staticOnly: [
|
|
1120
1097
|
"login",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hitch42/cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1-beta.10",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"bin": {
|
|
6
6
|
"hitch": "./dist/hitch.js"
|
|
@@ -29,6 +29,6 @@
|
|
|
29
29
|
"publishConfig": {
|
|
30
30
|
"access": "public",
|
|
31
31
|
"registry": "https://registry.npmjs.org",
|
|
32
|
-
"tag": "
|
|
32
|
+
"tag": "latest"
|
|
33
33
|
}
|
|
34
34
|
}
|