Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Simplify CLI: precompute completion paths, dedupe --format option

Damian Legawiec161cdd125d94
diff --git a/packages/cli/scripts/bundle-spec.mjs b/packages/cli/scripts/bundle-spec.mjs
index 1e86725cc8..418fea69ea 100644
--- a/packages/cli/scripts/bundle-spec.mjs
+++ b/packages/cli/scripts/bundle-spec.mjs
@@ -20,6 +20,10 @@ import { parse } from 'yaml'
const here = path.dirname(fileURLToPath(import.meta.url))
const SPEC_PATH = path.resolve(here, '../../../docs/api-reference/admin.yaml')
const OUT_PATH = path.resolve(here, '../src/generated/admin-spec.json')
+// A tiny sibling of just the top-level resource paths, so shell completion
+// (which fires on every Tab) imports ~40 strings instead of materializing the
+// full ~250KB operation graph.
+const PATHS_OUT = path.resolve(here, '../src/generated/resource-paths.json')
function stripExamples(node) {
if (Array.isArray(node)) {
@@ -46,6 +50,18 @@ const slim = {
fs.mkdirSync(path.dirname(OUT_PATH), { recursive: true })
fs.writeFileSync(OUT_PATH, JSON.stringify(slim))
+// Distinct top-level resource path segments (e.g. "/products", "/orders"),
+// excluding `{...}` placeholders — the only data shell completion needs.
+const resourcePaths = [
+ ...new Set(
+ Object.keys(slim.paths ?? {})
+ .map((p) => p.replace('/api/v3/admin', '').split('/')[1])
+ .filter((seg) => seg && !seg.startsWith('{'))
+ .map((seg) => `/${seg}`),
+ ),
+].sort()
+fs.writeFileSync(PATHS_OUT, JSON.stringify(resourcePaths))
+
const HTTP_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete'])
const size = (fs.statSync(OUT_PATH).size / 1024).toFixed(0)
const operations = Object.values(slim.paths ?? {}).reduce(
diff --git a/packages/cli/src/api/spec.ts b/packages/cli/src/api/spec.ts
index 69d4af3744..eaa6f29cd1 100644
--- a/packages/cli/src/api/spec.ts
+++ b/packages/cli/src/api/spec.ts
@@ -39,22 +39,6 @@ export function loadBundledSpec(): AdminSpec {
return adminSpecJson as unknown as AdminSpec
}
-/**
- * Top-level resource paths (`/products`, `/orders`, …) from the bundled spec —
- * the completion candidates for `spree api <verb> <TAB>`. Deduped, sorted, and
- * limited to first-segment paths (nested paths carry `{id}` placeholders a
- * shell can't usefully complete).
- */
-export function resourcePaths(spec: AdminSpec): string[] {
- const segments = new Set<string>()
- for (const specPath of Object.keys(spec.paths)) {
- const shortPath = specPath.replace('/api/v3/admin', '') || '/'
- const segment = shortPath.split('/')[1]
- if (segment && !segment.startsWith('{')) segments.add(`/${segment}`)
- }
- return [...segments].sort()
-}
-
/**
* Extracts the `**Required scope:** ...` line rswag writes into operation
* descriptions. Free-form notes (e.g. exports — gated by the exported
diff --git a/packages/cli/src/commands/api.ts b/packages/cli/src/commands/api.ts
index 1ba88cc6a7..996e5ca094 100644
--- a/packages/cli/src/commands/api.ts
+++ b/packages/cli/src/commands/api.ts
@@ -43,11 +43,14 @@ function withCredentialFlags(command: Command): Command {
.option('--store-id <id>', 'X-Spree-Store-Id for hosts serving multiple stores')
}
+/** The `--format json|table` option, shared by the verbs and `endpoints`. */
+function formatOption(): Option {
+ return new Option('--format <format>', 'output format').choices(['json', 'table']).default('json')
+}
+
/** Credential flags plus `--format` for verbs that render a response. */
function withSharedFlags(command: Command): Command {
- return withCredentialFlags(command).addOption(
- new Option('--format <format>', 'output format').choices(['json', 'table']).default('json'),
- )
+ return withCredentialFlags(command).addOption(formatOption())
}
async function clientFor(
@@ -149,9 +152,7 @@ export function registerApiCommand(program: Command): void {
.description('List Admin API endpoints with their required scopes')
.option('--resource <name>', 'filter by first path segment, e.g. orders')
.option('--search <term>', 'filter by method, path, or summary')
- .addOption(
- new Option('--format <format>', 'output format').choices(['json', 'table']).default('json'),
- )
+ .addOption(formatOption())
.action((flags: { resource?: string; search?: string; format: OutputFormat }) => {
const rows = listEndpoints(loadBundledSpec(), {
resource: flags.resource,
diff --git a/packages/cli/src/commands/completion.ts b/packages/cli/src/commands/completion.ts
index e38c44567f..5caf007c0a 100644
--- a/packages/cli/src/commands/completion.ts
+++ b/packages/cli/src/commands/completion.ts
@@ -1,5 +1,7 @@
import type { Command } from 'commander'
-import { loadBundledSpec, resourcePaths } from '../api/spec.js'
+// Import the tiny precomputed path list, NOT the full spec — completion fires
+// on every Tab keypress and only needs the ~40 resource path segments.
+import RESOURCE_PATHS from '../generated/resource-paths.json' with { type: 'json' }
/**
* Shell completion, following the `gh`/`kubectl` architecture: `spree
@@ -35,6 +37,11 @@ const RANSACK_PREDICATES = [
]
const API_VERBS = ['get', 'post', 'patch', 'delete', 'endpoints', 'schema', 'status']
+
+// Keep in sync with `Spree::ApiKey::SCOPES` (spree/core/app/models/spree/api_key.rb).
+// Not derived from the bundled spec: the spec only annotates per-endpoint
+// scopes, so the aggregate scopes (read_all/write_all/read_dashboard) wouldn't
+// appear. Hand-maintained, hence this pointer.
const SCOPES = [
'read_all',
'write_all',
@@ -88,7 +95,7 @@ export function completionCandidates(words: string[]): string[] {
// `spree api get /pro<TAB>` — resource paths (only for path-taking verbs).
if (['get', 'post', 'patch', 'delete', 'schema'].includes(sub) && rest.length <= 1) {
- return filterByPrefix(resourcePaths(loadBundledSpec()), current)
+ return filterByPrefix(RESOURCE_PATHS, current)
}
// `spree api get /products -q <attr>_<TAB>` — append Ransack predicates to
diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts
index 45022900f4..c1e9178da1 100644
--- a/packages/cli/src/config.ts
+++ b/packages/cli/src/config.ts
@@ -315,7 +315,7 @@ export async function resolveCredentials(
// defaults to the local dev server, so `SPREE_API_KEY=sk_… spree api get …`
// just works. Profile/project sources always carry their own host, so this
// never silently re-points a saved remote key.
- if (apiKey && !baseUrl && (resolved?.source === 'flags' || resolved?.source === 'env')) {
+ if (!baseUrl && (resolved?.source === 'flags' || resolved?.source === 'env')) {
baseUrl = LOCAL_DEV_URL
}
diff --git a/packages/cli/src/generated/resource-paths.json b/packages/cli/src/generated/resource-paths.json
new file mode 100644
index 0000000000..f59ec27cd6
--- /dev/null
+++ b/packages/cli/src/generated/resource-paths.json
@@ -0,0 +1 @@
+["/admin_users","/allowed_origins","/api_keys","/auth","/channels","/custom_field_definitions","/customer_groups","/customers","/exports","/gift_card_batches","/gift_cards","/invitations","/markets","/me","/option_types","/orders","/payment_methods","/price_lists","/prices","/products","/promotion_actions","/promotion_rules","/promotions","/roles","/stock_locations","/store","/store_credit_categories","/tags","/webhook_endpoints"]
\ No newline at end of file