@shop-on/theme-cli 0.10.0 → 0.11.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.
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env node
2
+ import { commonErrors } from "./errors.mjs";
3
+ import { ORPCError, createORPCClient, isORPCErrorJson, mapEventIterator } from "@orpc/client";
4
+ import { RPCLink } from "@orpc/client/fetch";
5
+ // ../contract-kit/src/client.ts
6
+ const BROWSER_TIMEOUT_MS = 3e4;
7
+ const MAX_RETRY_AFTER_SECONDS = 86400;
8
+ /** What an RPC mount answers with: JSON, an event stream, or a form when the output holds files. */
9
+ const RPC_CONTENT_TYPES = [
10
+ "application/json",
11
+ "text/event-stream",
12
+ "multipart/form-data"
13
+ ];
14
+ /** The fields of oRPC's JSON answer; an output of nothing is `{}`. */
15
+ const ENVELOPE_FIELDS = /* @__PURE__ */ new Set([
16
+ "json",
17
+ "meta",
18
+ "maps"
19
+ ]);
20
+ /** The longest wait a timer holds. */
21
+ const MAX_TIMEOUT_MS = 2 ** 31 - 1;
22
+ function assertTimeout(ms) {
23
+ if (!Number.isInteger(ms) || ms <= 0 || ms > MAX_TIMEOUT_MS) throw new TypeError(`timeoutMs is a whole number of milliseconds, 1 to ${MAX_TIMEOUT_MS}`);
24
+ return ms;
25
+ }
26
+ /** What the caller's own `headers()` threw: its failure, not the service's. */
27
+ var CallerFailure = class {
28
+ thrown;
29
+ constructor(thrown) {
30
+ this.thrown = thrown;
31
+ }
32
+ };
33
+ function createRpcClient(audience, credentials, options) {
34
+ const timeoutMs = options.timeoutMs ?? (typeof globalThis.document === "undefined" ? void 0 : BROWSER_TIMEOUT_MS);
35
+ if (timeoutMs === void 0) throw new TypeError(`a ${audience} client made on a server needs \`timeoutMs\``);
36
+ assertTimeout(timeoutMs);
37
+ const send = options.fetch ?? ((request) => fetch(request));
38
+ const link = new RPCLink({
39
+ url: `${options.baseUrl.replace(/\/$/, "")}/rpc/${audience}`,
40
+ headers: async ({ context }) => {
41
+ const headers = { ...await Promise.resolve().then(() => options.headers?.()).catch((thrown) => {
42
+ throw new CallerFailure(thrown);
43
+ }) };
44
+ if (context.idempotencyKey !== void 0) headers["idempotency-key"] = context.idempotencyKey;
45
+ return headers;
46
+ },
47
+ fetch: async (request, init) => screen(await send(new Request(request, {
48
+ ...init,
49
+ credentials
50
+ }))),
51
+ interceptors: [async ({ next, ...call }) => {
52
+ const ms = call.context.timeoutMs === void 0 ? timeoutMs : assertTimeout(call.context.timeoutMs);
53
+ const deadline = new AbortController();
54
+ const timer = setTimeout(() => deadline.abort(), ms);
55
+ const caller = call.signal;
56
+ try {
57
+ const output = await next({
58
+ ...call,
59
+ signal: caller ? AbortSignal.any([caller, deadline.signal]) : deadline.signal
60
+ });
61
+ if (!isAsyncIterable(output)) return output;
62
+ return mapEventIterator(output, {
63
+ value: async (value) => value,
64
+ error: async (error) => caller?.aborted ? error : toContractError(error)
65
+ });
66
+ } catch (error) {
67
+ if (caller?.aborted) throw error;
68
+ if (error instanceof CallerFailure) throw error.thrown;
69
+ if (deadline.signal.aborted) throw contractError("DEADLINE_EXCEEDED", { deadlineMs: ms });
70
+ throw toContractError(error);
71
+ } finally {
72
+ clearTimeout(timer);
73
+ }
74
+ }]
75
+ });
76
+ return createORPCClient(link);
77
+ }
78
+ function contractError(code, data) {
79
+ return new ORPCError(code, {
80
+ status: commonErrors[code].status,
81
+ data,
82
+ defined: true
83
+ });
84
+ }
85
+ function isCommonCode(code) {
86
+ return Object.hasOwn(commonErrors, code);
87
+ }
88
+ /**
89
+ * The service's own error: one a procedure declares (oRPC marks it
90
+ * defined), or a common code with its params, as the edge sends them.
91
+ */
92
+ function isServiceError(error) {
93
+ if (error.defined) return true;
94
+ if (!isCommonCode(error.code)) return false;
95
+ const entry = commonErrors[error.code];
96
+ return error.status === entry.status && entry.data.safeParse(error.data).success;
97
+ }
98
+ /**
99
+ * Turns an answer that is not the service's into the contract's error before
100
+ * oRPC reads it: a redirect, and an error status whose body is not one of
101
+ * the service's errors (a proxy's page, a path an older deploy lacks).
102
+ */
103
+ async function screen(response) {
104
+ if (response.type === "opaqueredirect" || response.status === 0) throw contractError("UNAVAILABLE", {});
105
+ if (response.status >= 300 && response.status < 400) throw contractError("UNAVAILABLE", { status: response.status });
106
+ if (response.status < 400) {
107
+ const type = response.headers.get("content-type");
108
+ if (type === null) return response;
109
+ if (!RPC_CONTENT_TYPES.some((rpc) => type.startsWith(rpc))) throw contractError("UNAVAILABLE", { status: response.status });
110
+ if (type.startsWith("application/json") && !isEnvelope(await response.clone().text())) throw contractError("UNAVAILABLE", { status: response.status });
111
+ return response;
112
+ }
113
+ const body = await response.clone().text().then((text) => JSON.parse(text)).catch(() => void 0);
114
+ const error = typeof body === "object" && body !== null ? body.json : null;
115
+ if (isORPCErrorJson(error) && isServiceError(error)) return response;
116
+ throw byStatus(response.status, response.headers.get("retry-after"));
117
+ }
118
+ /** Whether a JSON body is oRPC's answer. One that does not parse is left for oRPC to refuse. */
119
+ function isEnvelope(text) {
120
+ if (text === "") return true;
121
+ let body;
122
+ try {
123
+ body = JSON.parse(text);
124
+ } catch {
125
+ return true;
126
+ }
127
+ return typeof body === "object" && body !== null && !Array.isArray(body) && Object.keys(body).every((field) => ENVELOPE_FIELDS.has(field));
128
+ }
129
+ function byStatus(status, retryAfter) {
130
+ if (status === 429) return contractError("RATE_LIMITED", { retryAfterSeconds: retryAfterSeconds(retryAfter) });
131
+ if (status === 408 || status === 504) return contractError("DEADLINE_EXCEEDED", {});
132
+ return contractError("UNAVAILABLE", { status });
133
+ }
134
+ /** `Retry-After` in seconds or as an HTTP date; anything else is the default wait. */
135
+ function retryAfterSeconds(header, now = Date.now()) {
136
+ const value = header?.trim() ?? "";
137
+ let seconds = NaN;
138
+ if (/^\d+$/.test(value)) seconds = Number(value);
139
+ else if (value.endsWith("GMT")) seconds = Math.ceil((Date.parse(value) - now) / 1e3);
140
+ if (Number.isNaN(seconds)) return 60;
141
+ return Math.min(Math.max(seconds, 0), MAX_RETRY_AFTER_SECONDS);
142
+ }
143
+ /** Any failure as the contract's error; the service's own pass through, marked defined. */
144
+ function toContractError(error) {
145
+ if (!(error instanceof ORPCError)) return contractError("UNAVAILABLE", {});
146
+ if (!isServiceError(error)) return byStatus(error.status, null);
147
+ if (error.defined) return error;
148
+ return new ORPCError(error.code, {
149
+ status: error.status,
150
+ data: error.data,
151
+ defined: true
152
+ });
153
+ }
154
+ function isAsyncIterable(value) {
155
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
156
+ }
157
+ export { createRpcClient, retryAfterSeconds };
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env node
2
+ import { z } from "zod";
3
+ // ../contract-kit/src/errors.ts
4
+ const validationIssue = z.object({
5
+ /** Where in the input: keys and array indexes from the root. */
6
+ path: z.array(z.union([z.string(), z.int()])),
7
+ /** The zod issue code (`too_small`, `invalid_type`, …) or a procedure's own. */
8
+ code: z.string(),
9
+ /** What the translation needs: `minimum`, `maximum`, `expected`, `format`… */
10
+ params: z.record(z.string(), z.union([
11
+ z.string(),
12
+ z.number(),
13
+ z.boolean()
14
+ ]))
15
+ });
16
+ const commonErrors = {
17
+ UNAUTHENTICATED: {
18
+ status: 401,
19
+ data: z.object({ reason: z.enum([
20
+ "missing",
21
+ "invalid",
22
+ "expired",
23
+ "revoked"
24
+ ]) })
25
+ },
26
+ PERMISSION_DENIED: {
27
+ status: 403,
28
+ data: z.object({ permission: z.string() })
29
+ },
30
+ NOT_FOUND: {
31
+ status: 404,
32
+ data: z.object({
33
+ resource: z.string(),
34
+ id: z.string().optional()
35
+ })
36
+ },
37
+ CONFLICT: {
38
+ status: 409,
39
+ data: z.object({
40
+ resource: z.string(),
41
+ field: z.string().optional()
42
+ })
43
+ },
44
+ PRECONDITION_FAILED: {
45
+ status: 412,
46
+ data: z.object({
47
+ condition: z.string(),
48
+ /** What stands in the way, by name and how many (an amount for money): only a condition that counts says. */
49
+ categories: z.record(z.string(), z.int()).optional()
50
+ })
51
+ },
52
+ /** The request's body is larger than its mount reads: the edge refuses it before any procedure runs. */
53
+ PAYLOAD_TOO_LARGE: {
54
+ status: 413,
55
+ data: z.object({ limitBytes: z.int().positive() })
56
+ },
57
+ VALIDATION_FAILED: {
58
+ status: 422,
59
+ data: z.object({ issues: z.array(validationIssue).min(1) })
60
+ },
61
+ RATE_LIMITED: {
62
+ status: 429,
63
+ data: z.object({ retryAfterSeconds: z.int().nonnegative() })
64
+ },
65
+ /**
66
+ * The service did not answer in the contract's shape: it could not be
67
+ * reached, or something in front of it answered instead (a proxy's page,
68
+ * a redirect, an older deploy without the procedure). Retry later. The
69
+ * client raises it (`./client`); `status` is the HTTP status that came
70
+ * back, for a log, absent when nothing did.
71
+ */
72
+ UNAVAILABLE: {
73
+ status: 503,
74
+ data: z.object({ status: z.int().optional() })
75
+ },
76
+ /** The call ran past its deadline, the client's own or the server's. */
77
+ DEADLINE_EXCEEDED: {
78
+ status: 504,
79
+ data: z.object({ deadlineMs: z.int().positive().optional() })
80
+ }
81
+ };
82
+ export { commonErrors };
package/dist/index.mjs CHANGED
@@ -7,14 +7,14 @@ import { runInit } from "./theme/init.mjs";
7
7
  import { runMcp } from "./theme/mcp.mjs";
8
8
  import { runPack } from "./theme/pack.mjs";
9
9
  import { runSource } from "./theme/source.mjs";
10
- //#region src/index.ts
10
+ // src/index.ts
11
11
  const USAGE = `usage: shop-on <command>
12
12
 
13
13
  login log in to your store (opens the browser)
14
14
  theme init <dir> scaffold a theme with its .env filled in
15
15
  theme dev run this theme in the hosted theme editor
16
16
  theme mcp serve the theme editor's tools to Claude Code (stdio)
17
- theme credentials revoke <client-id> revoke a dev storefront credential
17
+ theme credentials revoke <id> revoke a dev storefront credential (sfc_…)
18
18
  theme audit measure this theme against the quality bar
19
19
  theme pack pack the built theme into its version tarball
20
20
  theme source pack the theme's source for a developer-portal submission
@@ -34,5 +34,4 @@ else {
34
34
  (help ? console.log : console.error)(USAGE);
35
35
  process.exitCode = help ? 0 : 2;
36
36
  }
37
- //#endregion
38
37
  export {};
package/dist/login.mjs CHANGED
@@ -4,7 +4,7 @@ import { defaultConfigDir } from "./auth/credentials.mjs";
4
4
  import { login, resolveApiUrl } from "./auth/oauth.mjs";
5
5
  import { openUrl } from "./open-url.mjs";
6
6
  import { parseArgs } from "node:util";
7
- //#region src/login.ts
7
+ // src/login.ts
8
8
  const LOGIN_USAGE = `usage: shop-on login [--api <url>]
9
9
 
10
10
  --api <url> the Shop-On api to log in to (default: $SHOP_ON_API_URL, else production)`;
@@ -45,5 +45,4 @@ async function runLogin({ argv, io = processIo, configDir = defaultConfigDir(),
45
45
  io.out(`Logged in to ${apiUrl}. Theme commands act on the store you picked.`);
46
46
  return 0;
47
47
  }
48
- //#endregion
49
48
  export { LOGIN_USAGE, runLogin };
package/dist/open-url.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from "node:child_process";
3
- //#region src/open-url.ts
3
+ // src/open-url.ts
4
4
  /**
5
5
  * Opens `url` in the default browser, without waiting. On a machine with no
6
6
  * browser it does nothing: every caller also prints the URL.
@@ -14,5 +14,4 @@ function openUrl(url) {
14
14
  child.on("error", () => {});
15
15
  child.unref();
16
16
  }
17
- //#endregion
18
17
  export { openUrl };
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from "node:child_process";
3
- //#region src/theme/build.ts
3
+ // src/theme/build.ts
4
4
  /** Runs the theme's `pnpm run build` and resolves with its exit code. Build
5
5
  * output goes to stderr, so a command's own stdout stays parseable. */
6
6
  function runThemeBuild(themeDir) {
@@ -22,5 +22,4 @@ function runThemeBuild(themeDir) {
22
22
  });
23
23
  });
24
24
  }
25
- //#endregion
26
25
  export { runThemeBuild };
@@ -1,26 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
  import { processIo } from "../audit/command.mjs";
3
+ import { MerchantCallError, merchant } from "../auth/api.mjs";
3
4
  import { defaultConfigDir } from "../auth/credentials.mjs";
4
5
  import { apiFlag, ensureLoggedIn, resolveApiUrl } from "../auth/oauth.mjs";
5
6
  import { openUrl } from "../open-url.mjs";
6
- import { graphql } from "../auth/api.mjs";
7
7
  import { parseArgs } from "node:util";
8
- //#region src/theme/credentials.ts
9
- const CREDENTIALS_USAGE = `usage: shop-on theme credentials revoke <client-id> [--api <url>]
8
+ // src/theme/credentials.ts
9
+ const CREDENTIALS_USAGE = `usage: shop-on theme credentials revoke <credential-id> [--api <url>]
10
10
 
11
- Revokes one of your store's dev storefront credentials, and every token minted
12
- with it. A theme whose .env holds it stops reaching the store.`;
13
- const LIST = `query ShopOnDevCredentials {
14
- storefrontDevCredentials { name clientId createdAt }
15
- }`;
16
- const REVOKE = `mutation ShopOnDevCredentialRevoke($input: StorefrontDevCredentialRevokeInput!) {
17
- storefrontDevCredentialRevoke(input: $input) { revokedClientId userErrors { code field message } }
18
- }`;
19
- const revokeCommand = (apiUrl, clientId) => `shop-on theme credentials revoke ${clientId}${apiFlag(apiUrl)}`;
11
+ Revokes one of your store's dev storefront credentials (its id, sfc_…, as
12
+ \`theme init\` lists them). A theme whose .env holds its key stops reaching
13
+ the store.`;
14
+ const revokeCommand = (apiUrl, id) => `shop-on theme credentials revoke ${id}${apiFlag(apiUrl)}`;
20
15
  /** The store's dev credentials, each with the command that revokes it. */
21
16
  async function formatCredentialList(ctx) {
22
- const { storefrontDevCredentials: list } = await graphql(ctx, LIST);
23
- return list.map((c) => ` ${c.name} (created ${c.createdAt.slice(0, 10)})\n ${revokeCommand(ctx.apiUrl, c.clientId)}`).join("\n");
17
+ const { items } = await merchant(ctx, (api) => api.storefrontCredentials.list());
18
+ return items.map((c) => ` ${c.name} (created ${c.createdAt.slice(0, 10)})\n ${revokeCommand(ctx.apiUrl, c.id)}`).join("\n");
24
19
  }
25
20
  async function runCredentialsRevoke({ argv, io = processIo, configDir = defaultConfigDir(), processEnv = process.env, deps: { openUrl: openUrl$1 = openUrl } = {} }) {
26
21
  let parsed;
@@ -45,8 +40,8 @@ async function runCredentialsRevoke({ argv, io = processIo, configDir = defaultC
45
40
  io.out(CREDENTIALS_USAGE);
46
41
  return 0;
47
42
  }
48
- const [clientId, ...extra] = parsed.positionals;
49
- if (!clientId || extra.length) {
43
+ const [id, ...extra] = parsed.positionals;
44
+ if (!id || extra.length) {
50
45
  io.err(CREDENTIALS_USAGE);
51
46
  return 2;
52
47
  }
@@ -58,20 +53,17 @@ async function runCredentialsRevoke({ argv, io = processIo, configDir = defaultC
58
53
  io,
59
54
  openUrl: openUrl$1
60
55
  });
61
- const { storefrontDevCredentialRevoke: result } = await graphql({
56
+ const credential = id;
57
+ await merchant({
62
58
  apiUrl,
63
59
  configDir
64
- }, REVOKE, { input: { clientId } });
65
- if (result.userErrors.length) {
66
- for (const e of result.userErrors) io.err(e.message);
67
- return 1;
68
- }
69
- io.out(`Revoked ${result.revokedClientId}.`);
60
+ }, (api) => api.storefrontCredentials.revoke({ id: credential }));
61
+ io.out(`Revoked ${id}.`);
70
62
  return 0;
71
63
  } catch (err) {
72
- io.err(err.message);
64
+ const unknown = err instanceof MerchantCallError && ["NOT_FOUND", "VALIDATION_FAILED"].includes(err.code);
65
+ io.err(unknown ? `${id} is not one of your store's dev storefront credentials.` : err.message);
73
66
  return 1;
74
67
  }
75
68
  }
76
- //#endregion
77
69
  export { CREDENTIALS_USAGE, formatCredentialList, revokeCommand, runCredentialsRevoke };
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import { MissingEnvError, loadThemeEnv } from "../audit/env.mjs";
3
2
  import { processIo } from "../audit/command.mjs";
3
+ import { MissingEnvError, loadThemeEnv } from "../audit/env.mjs";
4
+ import { MerchantCallError, merchant } from "../auth/api.mjs";
4
5
  import { defaultConfigDir } from "../auth/credentials.mjs";
5
- import { adminOrigin, discover, ensureLoggedIn, resolveApiUrl } from "../auth/oauth.mjs";
6
+ import { ensureLoggedIn, resolveApiUrl } from "../auth/oauth.mjs";
6
7
  import { openUrl } from "../open-url.mjs";
7
- import { graphql } from "../auth/api.mjs";
8
8
  import { createRequire } from "node:module";
9
9
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
10
  import path from "node:path";
11
11
  import { parseArgs } from "node:util";
12
12
  import { spawn } from "node:child_process";
13
- //#region src/theme/dev.ts
13
+ // src/theme/dev.ts
14
14
  const DEV_USAGE = `usage: shop-on theme dev [--api <url>] [--env dev|staging|prod] [--public-url <url>]
15
15
 
16
16
  Runs the theme in the current directory behind a public tunnel and opens the
@@ -21,33 +21,10 @@ const DEV_USAGE = `usage: shop-on theme dev [--api <url>] [--env dev|staging|pro
21
21
  for an api on this machine, else prod)
22
22
  --public-url <url> your own tunnel's https URL, already forwarding to the
23
23
  dev host, instead of a cloudflared quick tunnel`;
24
- const INSTALLS = `query ShopOnThemeInstalls($after: String) {
25
- themeInstalls(first: 40, after: $after) {
26
- nodes { installId dev }
27
- pageInfo { hasNextPage endCursor }
28
- }
29
- }`;
30
- const CREATE = `mutation ShopOnDevInstallCreate($input: ShopThemeDevInstallCreateInput!) {
31
- shopThemeDevInstallCreate(input: $input) {
32
- shopThemeInstall { installId }
33
- userErrors { code field message }
34
- }
35
- }`;
36
- const DEV_HOST_SET = `mutation ShopOnDevHostSet($input: ShopThemeDevHostSetInput!) {
37
- shopThemeDevHostSet(input: $input) {
38
- shopThemeInstall { installId }
39
- userErrors { code field message }
40
- }
41
- }`;
42
- const DEV_HOST_CLEAR = `mutation ShopOnDevHostClear($input: ShopThemeDevHostClearInput!) {
43
- shopThemeDevHostClear(input: $input) {
44
- userErrors { code field message }
45
- }
46
- }`;
47
- /** How long exit waits on `shopThemeDevHostClear`; a stale URL just fails to load. */
24
+ /** How long exit waits on `clearDevHost`; a stale URL just fails to load. */
48
25
  const CLEAR_TIMEOUT_MS = 2e3;
49
- /** The install's editor; it reads the dev host off the install. */
50
- const editorLink = (admin, installId) => `${admin}/themes/${encodeURIComponent(installId)}/editor`;
26
+ /** The install's editor on the admin `setDevHost` names; it reads the dev host off the install. */
27
+ const editorLink = (adminUrl, handle) => `${adminUrl}/themes/${encodeURIComponent(handle)}/editor`;
51
28
  const LOOPBACK = /* @__PURE__ */ new Set([
52
29
  "localhost",
53
30
  "127.0.0.1",
@@ -118,13 +95,20 @@ function rememberedInstall(themeDir) {
118
95
  return;
119
96
  }
120
97
  }
121
- async function devInstallListed(ctx, installId) {
122
- let after = null;
123
- for (;;) {
124
- const { themeInstalls } = await graphql(ctx, INSTALLS, { after });
125
- if (themeInstalls.nodes.some((n) => n.installId === installId && n.dev)) return true;
126
- if (!themeInstalls.pageInfo.hasNextPage) return false;
127
- after = themeInstalls.pageInfo.endCursor;
98
+ /** Whether `handle` is still one of the store's dev installs. */
99
+ async function devInstallListed(ctx, handle) {
100
+ const { items } = await merchant(ctx, (api) => api.themes.installs.list({}));
101
+ return items.some((install) => install.handle === handle && install.kind === "dev");
102
+ }
103
+ /** A new dev install for the theme; null once the store holds the most it can, said to `io`. */
104
+ async function createDevInstall(ctx, name, io) {
105
+ try {
106
+ return (await merchant(ctx, (api) => api.themes.installs.createDev({ name }))).handle;
107
+ } catch (err) {
108
+ if (!(err instanceof MerchantCallError && err.code === "LIMIT_EXCEEDED")) throw err;
109
+ const { limit } = err.data;
110
+ io.err(`Your store already holds ${limit} dev installs, the most it can. Remove one in admin (Online store → Themes), then run \`shop-on theme dev\` again.`);
111
+ return null;
128
112
  }
129
113
  }
130
114
  function themeName(themeDir) {
@@ -178,10 +162,8 @@ async function runDev({ argv, cwd = process.cwd(), io = processIo, configDir = d
178
162
  apiUrl,
179
163
  configDir
180
164
  };
181
- let admin;
182
165
  let installId = rememberedInstall(themeDir);
183
166
  try {
184
- admin = adminOrigin(await discover(apiUrl));
185
167
  await ensureLoggedIn({
186
168
  apiUrl,
187
169
  configDir,
@@ -189,12 +171,9 @@ async function runDev({ argv, cwd = process.cwd(), io = processIo, configDir = d
189
171
  openUrl: deps.openUrl
190
172
  });
191
173
  if (!installId || !await devInstallListed(ctx, installId)) {
192
- const { shopThemeDevInstallCreate: created } = await graphql(ctx, CREATE, { input: { name: themeName(themeDir) } });
193
- if (!created.shopThemeInstall) {
194
- for (const e of created.userErrors) io.err(e.message);
195
- return 1;
196
- }
197
- installId = created.shopThemeInstall.installId;
174
+ const created = await createDevInstall(ctx, themeName(themeDir), io);
175
+ if (!created) return 1;
176
+ installId = created;
198
177
  mkdirSync(path.dirname(projectFile(themeDir)), { recursive: true });
199
178
  writeFileSync(projectFile(themeDir), `${JSON.stringify({ installId }, null, 2)}\n`);
200
179
  io.err(`Created the dev install ${installId}`);
@@ -228,15 +207,15 @@ async function runDev({ argv, cwd = process.cwd(), io = processIo, configDir = d
228
207
  ],
229
208
  cwd: themeDir,
230
209
  onPublicUrl: (url, stop) => {
231
- registration = registerDevHost(ctx, devInstall, url).then((error) => {
232
- if (error) {
210
+ registration = registerDevHost(ctx, devInstall, url).then((answer) => {
211
+ if ("error" in answer) {
233
212
  failed = true;
234
- io.err(`Could not connect the editor to ${url}: ${error}`);
213
+ io.err(`Could not connect the editor to ${url}: ${answer.error}`);
235
214
  stop();
236
215
  return;
237
216
  }
238
217
  registered = true;
239
- const link = editorLink(admin, devInstall);
218
+ const link = editorLink(answer.adminUrl, devInstall);
240
219
  io.out(`\nTheme editor: ${link}\n Store: ${slug}. Admin edits the store it has selected; switch to ${slug} there if the editor says not found.\n`);
241
220
  deps.openUrl(link);
242
221
  });
@@ -246,27 +225,28 @@ async function runDev({ argv, cwd = process.cwd(), io = processIo, configDir = d
246
225
  if (registered) await clearDevHost(ctx, devInstall);
247
226
  return failed ? 1 : code;
248
227
  }
249
- /** Registers `url` on the dev install; the failure to print, else null. */
250
- async function registerDevHost(ctx, installId, url) {
228
+ /** Registers `url` on the dev install: the admin its editor is on, or the failure to print. */
229
+ async function registerDevHost(ctx, handle, url) {
251
230
  try {
252
- const { shopThemeDevHostSet: result } = await graphql(ctx, DEV_HOST_SET, { input: {
253
- installId,
231
+ const { adminUrl } = await merchant(ctx, (api) => api.themes.installs.setDevHost({
232
+ handle,
254
233
  url
255
- } });
256
- return result.userErrors.length ? result.userErrors.map((e) => e.message).join("; ") : null;
234
+ }));
235
+ return { adminUrl };
257
236
  } catch (err) {
258
- return err.message;
237
+ if (err instanceof MerchantCallError && err.code === "VALIDATION_FAILED") return { error: "the api takes https on a public name, or http on localhost against a development api" };
238
+ if (err instanceof MerchantCallError && err.code === "NOT_FOUND") return { error: `${handle} is no longer one of the store's dev installs; delete .shop-on/project.json and run \`shop-on theme dev\` again` };
239
+ return { error: err.message };
259
240
  }
260
241
  }
261
242
  /** Best effort, and never longer than `CLEAR_TIMEOUT_MS`. */
262
- async function clearDevHost(ctx, installId) {
243
+ async function clearDevHost(ctx, handle) {
263
244
  let timer;
264
245
  const timeout = new Promise((resolve) => {
265
246
  timer = setTimeout(resolve, CLEAR_TIMEOUT_MS);
266
247
  });
267
- const clear = graphql(ctx, DEV_HOST_CLEAR, { input: { installId } }).then(() => void 0, () => void 0);
248
+ const clear = merchant(ctx, (api) => api.themes.installs.clearDevHost({ handle })).then(() => void 0, () => void 0);
268
249
  await Promise.race([clear, timeout]);
269
250
  clearTimeout(timer);
270
251
  }
271
- //#endregion
272
252
  export { CLEAR_TIMEOUT_MS, DEV_USAGE, editorLink, rememberedInstall, runDev, spawnDevHost };