shopstack 0.2.6 → 0.3.1

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/src/config.d.ts CHANGED
@@ -1,12 +1,16 @@
1
+ export const DEFAULT_API_URL: string;
2
+
1
3
  export interface ShopstackProfile {
2
4
  accountId: string;
3
5
  apiKey: string;
6
+ baseUrl?: string;
4
7
  keyType: "developer" | "user";
5
8
  userId?: string;
6
9
  }
7
10
 
8
- export interface PendingLogin {
11
+ export interface PendingSignup {
9
12
  accountType: "developer" | "personal";
13
+ baseUrl?: string;
10
14
  attemptId?: string;
11
15
  email: string;
12
16
  expiresAt?: string;
@@ -15,7 +19,7 @@ export interface PendingLogin {
15
19
  pollToken?: string;
16
20
  profile: string;
17
21
  recoveryKey?: string;
18
- loginId?: string;
22
+ signupId?: string;
19
23
  }
20
24
 
21
25
  export class ConfigStore {
@@ -27,14 +31,14 @@ export class ConfigStore {
27
31
  options?: { activate?: boolean },
28
32
  ): Promise<ShopstackProfile>;
29
33
  useProfile(name: string): Promise<ShopstackProfile>;
30
- savePendingLogin(login: PendingLogin): Promise<PendingLogin>;
31
- pendingLogin(loginId: string): Promise<PendingLogin | undefined>;
32
- pendingLogins(): Promise<PendingLogin[]>;
33
- findPendingLogin(input: {
34
+ savePendingSignup(signup: PendingSignup): Promise<PendingSignup>;
35
+ pendingSignup(signupId: string): Promise<PendingSignup | undefined>;
36
+ pendingSignups(): Promise<PendingSignup[]>;
37
+ findPendingSignup(input: {
34
38
  accountType: "developer" | "personal";
35
39
  email: string;
36
- }): Promise<PendingLogin | undefined>;
37
- completePendingLogin(
40
+ }): Promise<PendingSignup | undefined>;
41
+ completePendingSignup(
38
42
  attemptId: string,
39
43
  profileName: string,
40
44
  result: {
@@ -44,12 +48,17 @@ export class ConfigStore {
44
48
  user?: { id?: string };
45
49
  },
46
50
  ): Promise<ShopstackProfile>;
47
- deletePendingLogin(loginId: string): Promise<void>;
51
+ deletePendingSignup(signupId: string): Promise<void>;
48
52
  load(): Promise<{
49
53
  active: string | null;
50
- pendingLogins: Record<string, PendingLogin>;
54
+ pendingSignups: Record<string, PendingSignup>;
51
55
  profiles: Record<string, ShopstackProfile>;
52
56
  }>;
53
57
  }
54
58
 
55
59
  export function defaultConfigPath(): string;
60
+
61
+ export function resolveProfileBaseUrl(
62
+ profile?: { baseUrl?: string },
63
+ selectedBaseUrl?: string,
64
+ ): string | undefined;
package/src/config.js CHANGED
@@ -2,6 +2,20 @@ import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
3
  import { dirname, join } from "node:path";
4
4
 
5
+ export const DEFAULT_API_URL =
6
+ "https://shopstack-release-preview.shopstack.workers.dev/v1";
7
+
8
+ export function resolveProfileBaseUrl(profile, selectedBaseUrl) {
9
+ const saved = profile?.baseUrl?.replace(/\/+$/u, "");
10
+ const selected = selectedBaseUrl?.replace(/\/+$/u, "");
11
+ if (saved !== undefined && selected !== undefined && saved !== selected) {
12
+ throw new Error(
13
+ "This profile belongs to a different Shopstack API. Select its endpoint or use a separate profile store.",
14
+ );
15
+ }
16
+ return saved ?? selected ?? DEFAULT_API_URL;
17
+ }
18
+
5
19
  export function defaultConfigPath() {
6
20
  return (
7
21
  process.env.SHOPSTACK_CONFIG_FILE ??
@@ -26,21 +40,18 @@ export class ConfigStore {
26
40
  throw new Error("Shopstack configuration is invalid.");
27
41
  }
28
42
  if (
29
- parsed.pendingLogins !== undefined &&
30
- (typeof parsed.pendingLogins !== "object" ||
31
- parsed.pendingLogins === null ||
32
- Array.isArray(parsed.pendingLogins))
43
+ parsed.pendingSignups !== undefined &&
44
+ (typeof parsed.pendingSignups !== "object" ||
45
+ parsed.pendingSignups === null ||
46
+ Array.isArray(parsed.pendingSignups))
33
47
  ) {
34
48
  throw new Error("Shopstack configuration is invalid.");
35
49
  }
36
- return {
37
- active: parsed.active ?? null,
38
- pendingLogins: parsed.pendingLogins ?? {},
39
- profiles: parsed.profiles,
40
- };
50
+ parsed.pendingSignups ??= {};
51
+ return parsed;
41
52
  } catch (error) {
42
53
  if (error?.code === "ENOENT") {
43
- return { active: null, pendingLogins: {}, profiles: {} };
54
+ return { active: null, pendingSignups: {}, profiles: {} };
44
55
  }
45
56
  throw error;
46
57
  }
@@ -85,72 +96,73 @@ export class ConfigStore {
85
96
  return typeof name === "string" ? config.profiles[name] : undefined;
86
97
  }
87
98
 
88
- async savePendingLogin(login) {
99
+ async savePendingSignup(signup) {
89
100
  const config = await this.load();
90
- const key = login.attemptId ?? login.id;
101
+ const key = signup.attemptId ?? signup.id;
91
102
  if (typeof key !== "string" || key.length === 0) {
92
- throw new Error("Pending login identity is invalid.");
103
+ throw new Error("Pending signup identity is invalid.");
93
104
  }
94
- config.pendingLogins[key] = { ...login };
105
+ config.pendingSignups[key] = { ...signup };
95
106
  await this.write(config);
96
- return config.pendingLogins[key];
107
+ return config.pendingSignups[key];
97
108
  }
98
109
 
99
- async pendingLogin(loginId) {
110
+ async pendingSignup(signupId) {
100
111
  const config = await this.load();
101
112
  return (
102
- config.pendingLogins[loginId] ??
103
- Object.values(config.pendingLogins).find(
104
- (pending) => pending.id === loginId || pending.loginId === loginId,
113
+ config.pendingSignups[signupId] ??
114
+ Object.values(config.pendingSignups).find(
115
+ (pending) => pending.id === signupId || pending.signupId === signupId,
105
116
  )
106
117
  );
107
118
  }
108
119
 
109
- async pendingLogins() {
110
- return Object.values((await this.load()).pendingLogins);
120
+ async pendingSignups() {
121
+ return Object.values((await this.load()).pendingSignups);
111
122
  }
112
123
 
113
- async findPendingLogin({ accountType, email }) {
124
+ async findPendingSignup({ accountType, email }) {
114
125
  const normalizedEmail = email.trim().toLowerCase();
115
- return Object.values((await this.load()).pendingLogins).find(
126
+ return Object.values((await this.load()).pendingSignups).find(
116
127
  (pending) =>
117
128
  pending.accountType === accountType &&
118
129
  pending.email.trim().toLowerCase() === normalizedEmail,
119
130
  );
120
131
  }
121
132
 
122
- async completePendingLogin(attemptId, profileName, result) {
133
+ async completePendingSignup(attemptId, profileName, result) {
123
134
  const config = await this.load();
124
- const entry = Object.entries(config.pendingLogins).find(
135
+ const entry = Object.entries(config.pendingSignups).find(
125
136
  ([key, pending]) =>
126
137
  key === attemptId ||
127
138
  pending.id === attemptId ||
128
- pending.loginId === attemptId,
139
+ pending.signupId === attemptId,
129
140
  );
130
141
  if (entry === undefined) {
131
- throw new Error("Pending login is unavailable.");
142
+ throw new Error("Pending signup is unavailable.");
132
143
  }
133
144
  config.profiles[profileName] = {
134
145
  accountId: result.account.id,
135
146
  apiKey: result.api_key,
136
147
  keyType: result.key_type,
148
+ ...(entry[1].baseUrl === undefined ? {} : { baseUrl: entry[1].baseUrl }),
137
149
  ...(result.user?.id === undefined ? {} : { userId: result.user.id }),
138
150
  };
139
151
  config.active = profileName;
140
- delete config.pendingLogins[entry[0]];
152
+ delete config.pendingSignups[entry[0]];
141
153
  await this.write(config);
142
154
  return config.profiles[profileName];
143
155
  }
144
156
 
145
- async deletePendingLogin(loginId) {
157
+ async deletePendingSignup(signupId) {
146
158
  const config = await this.load();
147
- const entry = Object.entries(config.pendingLogins).find(
159
+ const entry = Object.entries(config.pendingSignups).find(
148
160
  ([key, pending]) =>
149
- key === loginId ||
150
- pending.id === loginId ||
151
- pending.loginId === loginId,
161
+ key === signupId ||
162
+ pending.id === signupId ||
163
+ pending.signupId === signupId,
152
164
  );
153
- if (entry !== undefined) delete config.pendingLogins[entry[0]];
165
+ if (entry !== undefined) delete config.pendingSignups[entry[0]];
154
166
  await this.write(config);
155
167
  }
156
168
  }
@@ -0,0 +1,132 @@
1
+ const operations = new Set([
2
+ "resolve_location",
3
+ "get_search_filters",
4
+ "search_restaurants",
5
+ "prepare_booking",
6
+ "confirm_booking",
7
+ "decline_booking",
8
+ "ask_user",
9
+ "reply",
10
+ "request",
11
+ "model_decision",
12
+ "model_request",
13
+ "model_retry_wait",
14
+ "restaurant_request",
15
+ "provider_session",
16
+ "location_lookup",
17
+ "availability_recheck",
18
+ "slot_lock",
19
+ "slot_unlock",
20
+ "guest_profile",
21
+ "booking_submit",
22
+ "booking_status",
23
+ "booking_cancel",
24
+ "guest_inbox",
25
+ ]);
26
+ const phases = new Set(["started", "completed", "failed", "selected"]);
27
+ const failures = new Set([
28
+ "ETIMEDOUT",
29
+ "ECONNRESET",
30
+ "ECONNREFUSED",
31
+ "ENOTFOUND",
32
+ "EAI_AGAIN",
33
+ "UND_ERR_CONNECT_TIMEOUT",
34
+ "UND_ERR_HEADERS_TIMEOUT",
35
+ "UND_ERR_BODY_TIMEOUT",
36
+ "UND_ERR_SOCKET",
37
+ "TimeoutError",
38
+ "AbortError",
39
+ "model_invalid_response",
40
+ "operation_failed",
41
+ ]);
42
+ const nonnegative = (value) => Number.isSafeInteger(value) && value >= 0;
43
+
44
+ // Reconstruct the closed display shape. Provider bodies and arbitrary fields never pass through.
45
+ function publicProgress(frame, previous, requestId) {
46
+ if (
47
+ frame.request_id !== requestId ||
48
+ !nonnegative(frame.sequence) ||
49
+ frame.sequence <= previous ||
50
+ frame.sequence > 512 ||
51
+ !nonnegative(frame.call_id) ||
52
+ !nonnegative(frame.elapsed_ms) ||
53
+ !operations.has(frame.operation) ||
54
+ !phases.has(frame.phase)
55
+ )
56
+ throw new Error("Invalid progress frame.");
57
+ const event = Object.fromEntries(
58
+ [
59
+ "type",
60
+ "request_id",
61
+ "sequence",
62
+ "call_id",
63
+ "operation",
64
+ "phase",
65
+ "elapsed_ms",
66
+ ].map((key) => [key, frame[key]]),
67
+ );
68
+ if (nonnegative(frame.duration_ms)) event.duration_ms = frame.duration_ms;
69
+ if (
70
+ Number.isInteger(frame.http_status) &&
71
+ frame.http_status >= 100 &&
72
+ frame.http_status <= 599
73
+ )
74
+ event.http_status = frame.http_status;
75
+ if (failures.has(frame.failure)) event.failure = frame.failure;
76
+ return event;
77
+ }
78
+
79
+ export async function readReservationProgress(response, onProgress) {
80
+ const requestId = response.headers.get("x-request-id");
81
+ if (!/^req_[a-f0-9]{32}$/u.test(requestId ?? "") || !response.body)
82
+ throw new Error("Invalid progress stream.");
83
+ const reader = response.body.getReader();
84
+ const decoder = new TextDecoder("utf-8", { fatal: true });
85
+ let text = "";
86
+ let bytes = 0;
87
+ let sequence = 0;
88
+ let result;
89
+ try {
90
+ for (;;) {
91
+ const chunk = await reader.read();
92
+ if (chunk.done) break;
93
+ bytes += chunk.value.byteLength;
94
+ if (bytes > 17 * 1024 * 1024)
95
+ throw new Error("Progress stream limit exceeded.");
96
+ text += decoder.decode(chunk.value, { stream: true });
97
+ for (;;) {
98
+ const end = text.indexOf("\n");
99
+ if (end < 0) break;
100
+ const frame = JSON.parse(text.slice(0, end));
101
+ text = text.slice(end + 1);
102
+ if (result || !frame || typeof frame !== "object")
103
+ throw new Error("Invalid stream order.");
104
+ if (frame.type === "progress") {
105
+ const event = publicProgress(frame, sequence, requestId);
106
+ sequence = event.sequence;
107
+ try {
108
+ Promise.resolve(onProgress?.(event)).catch(() => {});
109
+ } catch {
110
+ /* Display failure cannot retry a mutation. */
111
+ }
112
+ } else if (
113
+ frame.type === "result" &&
114
+ frame.request_id === requestId &&
115
+ Number.isInteger(frame.status) &&
116
+ frame.status >= 200 &&
117
+ frame.status <= 599 &&
118
+ Object.hasOwn(frame, "body")
119
+ ) {
120
+ result = { status: frame.status, payload: frame.body };
121
+ } else throw new Error("Invalid result frame.");
122
+ }
123
+ }
124
+ text += decoder.decode();
125
+ if (!result || text.length) throw new Error("Incomplete progress stream.");
126
+ return result;
127
+ } finally {
128
+ // Also release failed/truncated streams. No automatic request retry.
129
+ await reader.cancel().catch(() => {});
130
+ reader.releaseLock();
131
+ }
132
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Shopstack
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.