shopstack 0.2.6 → 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/src/config.d.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  export interface ShopstackProfile {
2
2
  accountId: string;
3
3
  apiKey: string;
4
+ baseUrl?: string;
4
5
  keyType: "developer" | "user";
5
6
  userId?: string;
6
7
  }
7
8
 
8
- export interface PendingLogin {
9
+ export interface PendingSignup {
9
10
  accountType: "developer" | "personal";
11
+ baseUrl?: string;
10
12
  attemptId?: string;
11
13
  email: string;
12
14
  expiresAt?: string;
@@ -15,7 +17,7 @@ export interface PendingLogin {
15
17
  pollToken?: string;
16
18
  profile: string;
17
19
  recoveryKey?: string;
18
- loginId?: string;
20
+ signupId?: string;
19
21
  }
20
22
 
21
23
  export class ConfigStore {
@@ -27,14 +29,14 @@ export class ConfigStore {
27
29
  options?: { activate?: boolean },
28
30
  ): Promise<ShopstackProfile>;
29
31
  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: {
32
+ savePendingSignup(signup: PendingSignup): Promise<PendingSignup>;
33
+ pendingSignup(signupId: string): Promise<PendingSignup | undefined>;
34
+ pendingSignups(): Promise<PendingSignup[]>;
35
+ findPendingSignup(input: {
34
36
  accountType: "developer" | "personal";
35
37
  email: string;
36
- }): Promise<PendingLogin | undefined>;
37
- completePendingLogin(
38
+ }): Promise<PendingSignup | undefined>;
39
+ completePendingSignup(
38
40
  attemptId: string,
39
41
  profileName: string,
40
42
  result: {
@@ -44,12 +46,17 @@ export class ConfigStore {
44
46
  user?: { id?: string };
45
47
  },
46
48
  ): Promise<ShopstackProfile>;
47
- deletePendingLogin(loginId: string): Promise<void>;
49
+ deletePendingSignup(signupId: string): Promise<void>;
48
50
  load(): Promise<{
49
51
  active: string | null;
50
- pendingLogins: Record<string, PendingLogin>;
52
+ pendingSignups: Record<string, PendingSignup>;
51
53
  profiles: Record<string, ShopstackProfile>;
52
54
  }>;
53
55
  }
54
56
 
55
57
  export function defaultConfigPath(): string;
58
+
59
+ export function resolveProfileBaseUrl(
60
+ profile?: { baseUrl?: string },
61
+ selectedBaseUrl?: string,
62
+ ): string | undefined;
package/src/config.js CHANGED
@@ -2,6 +2,17 @@ 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 function resolveProfileBaseUrl(profile, selectedBaseUrl) {
6
+ const saved = profile?.baseUrl?.replace(/\/+$/u, "");
7
+ const selected = selectedBaseUrl?.replace(/\/+$/u, "");
8
+ if (saved !== undefined && selected !== undefined && saved !== selected) {
9
+ throw new Error(
10
+ "This profile belongs to a different Shopstack API. Select its endpoint or use a separate profile store.",
11
+ );
12
+ }
13
+ return saved ?? selected;
14
+ }
15
+
5
16
  export function defaultConfigPath() {
6
17
  return (
7
18
  process.env.SHOPSTACK_CONFIG_FILE ??
@@ -26,21 +37,18 @@ export class ConfigStore {
26
37
  throw new Error("Shopstack configuration is invalid.");
27
38
  }
28
39
  if (
29
- parsed.pendingLogins !== undefined &&
30
- (typeof parsed.pendingLogins !== "object" ||
31
- parsed.pendingLogins === null ||
32
- Array.isArray(parsed.pendingLogins))
40
+ parsed.pendingSignups !== undefined &&
41
+ (typeof parsed.pendingSignups !== "object" ||
42
+ parsed.pendingSignups === null ||
43
+ Array.isArray(parsed.pendingSignups))
33
44
  ) {
34
45
  throw new Error("Shopstack configuration is invalid.");
35
46
  }
36
- return {
37
- active: parsed.active ?? null,
38
- pendingLogins: parsed.pendingLogins ?? {},
39
- profiles: parsed.profiles,
40
- };
47
+ parsed.pendingSignups ??= {};
48
+ return parsed;
41
49
  } catch (error) {
42
50
  if (error?.code === "ENOENT") {
43
- return { active: null, pendingLogins: {}, profiles: {} };
51
+ return { active: null, pendingSignups: {}, profiles: {} };
44
52
  }
45
53
  throw error;
46
54
  }
@@ -85,72 +93,73 @@ export class ConfigStore {
85
93
  return typeof name === "string" ? config.profiles[name] : undefined;
86
94
  }
87
95
 
88
- async savePendingLogin(login) {
96
+ async savePendingSignup(signup) {
89
97
  const config = await this.load();
90
- const key = login.attemptId ?? login.id;
98
+ const key = signup.attemptId ?? signup.id;
91
99
  if (typeof key !== "string" || key.length === 0) {
92
- throw new Error("Pending login identity is invalid.");
100
+ throw new Error("Pending signup identity is invalid.");
93
101
  }
94
- config.pendingLogins[key] = { ...login };
102
+ config.pendingSignups[key] = { ...signup };
95
103
  await this.write(config);
96
- return config.pendingLogins[key];
104
+ return config.pendingSignups[key];
97
105
  }
98
106
 
99
- async pendingLogin(loginId) {
107
+ async pendingSignup(signupId) {
100
108
  const config = await this.load();
101
109
  return (
102
- config.pendingLogins[loginId] ??
103
- Object.values(config.pendingLogins).find(
104
- (pending) => pending.id === loginId || pending.loginId === loginId,
110
+ config.pendingSignups[signupId] ??
111
+ Object.values(config.pendingSignups).find(
112
+ (pending) => pending.id === signupId || pending.signupId === signupId,
105
113
  )
106
114
  );
107
115
  }
108
116
 
109
- async pendingLogins() {
110
- return Object.values((await this.load()).pendingLogins);
117
+ async pendingSignups() {
118
+ return Object.values((await this.load()).pendingSignups);
111
119
  }
112
120
 
113
- async findPendingLogin({ accountType, email }) {
121
+ async findPendingSignup({ accountType, email }) {
114
122
  const normalizedEmail = email.trim().toLowerCase();
115
- return Object.values((await this.load()).pendingLogins).find(
123
+ return Object.values((await this.load()).pendingSignups).find(
116
124
  (pending) =>
117
125
  pending.accountType === accountType &&
118
126
  pending.email.trim().toLowerCase() === normalizedEmail,
119
127
  );
120
128
  }
121
129
 
122
- async completePendingLogin(attemptId, profileName, result) {
130
+ async completePendingSignup(attemptId, profileName, result) {
123
131
  const config = await this.load();
124
- const entry = Object.entries(config.pendingLogins).find(
132
+ const entry = Object.entries(config.pendingSignups).find(
125
133
  ([key, pending]) =>
126
134
  key === attemptId ||
127
135
  pending.id === attemptId ||
128
- pending.loginId === attemptId,
136
+ pending.signupId === attemptId,
129
137
  );
130
138
  if (entry === undefined) {
131
- throw new Error("Pending login is unavailable.");
139
+ throw new Error("Pending signup is unavailable.");
132
140
  }
133
141
  config.profiles[profileName] = {
134
142
  accountId: result.account.id,
135
143
  apiKey: result.api_key,
136
144
  keyType: result.key_type,
145
+ ...(entry[1].baseUrl === undefined ? {} : { baseUrl: entry[1].baseUrl }),
137
146
  ...(result.user?.id === undefined ? {} : { userId: result.user.id }),
138
147
  };
139
148
  config.active = profileName;
140
- delete config.pendingLogins[entry[0]];
149
+ delete config.pendingSignups[entry[0]];
141
150
  await this.write(config);
142
151
  return config.profiles[profileName];
143
152
  }
144
153
 
145
- async deletePendingLogin(loginId) {
154
+ async deletePendingSignup(signupId) {
146
155
  const config = await this.load();
147
- const entry = Object.entries(config.pendingLogins).find(
156
+ const entry = Object.entries(config.pendingSignups).find(
148
157
  ([key, pending]) =>
149
- key === loginId ||
150
- pending.id === loginId ||
151
- pending.loginId === loginId,
158
+ key === signupId ||
159
+ pending.id === signupId ||
160
+ pending.signupId === signupId,
152
161
  );
153
- if (entry !== undefined) delete config.pendingLogins[entry[0]];
162
+ if (entry !== undefined) delete config.pendingSignups[entry[0]];
154
163
  await this.write(config);
155
164
  }
156
165
  }
@@ -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.