storenet 0.1.0__py3-none-any.whl
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.
- storenet/__init__.py +16 -0
- storenet/_signing.py +57 -0
- storenet/_version.py +8 -0
- storenet/cli.py +236 -0
- storenet/client.py +470 -0
- storenet/errors.py +37 -0
- storenet/py.typed +0 -0
- storenet-0.1.0.dist-info/METADATA +191 -0
- storenet-0.1.0.dist-info/RECORD +12 -0
- storenet-0.1.0.dist-info/WHEEL +4 -0
- storenet-0.1.0.dist-info/entry_points.txt +2 -0
- storenet-0.1.0.dist-info/licenses/LICENSE +21 -0
storenet/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""StoreNet Partner API: create, AI-edit and list shop designs from Python or the shell."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from storenet._version import __version__
|
|
6
|
+
from storenet.client import Edit, Site, StorenetClient
|
|
7
|
+
from storenet.errors import StorenetConfigError, StorenetError
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"Edit",
|
|
11
|
+
"Site",
|
|
12
|
+
"StorenetClient",
|
|
13
|
+
"StorenetConfigError",
|
|
14
|
+
"StorenetError",
|
|
15
|
+
"__version__",
|
|
16
|
+
]
|
storenet/_signing.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""HMAC-SHA256 request signing for the StoreNet Partner API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import uuid
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from urllib.parse import unquote
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _signed_path(path: str) -> str:
|
|
13
|
+
# The server signs the decoded path without the query string.
|
|
14
|
+
return unquote(path.split("?", 1)[0])
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def format_timestamp(moment: datetime) -> str:
|
|
18
|
+
"""ISO-8601 UTC with a trailing Z, the form the documented vector uses."""
|
|
19
|
+
return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def sign(
|
|
23
|
+
*, secret: str, method: str, path: str, raw_body: bytes, timestamp: str, nonce: str
|
|
24
|
+
) -> str:
|
|
25
|
+
"""Return `sha256=<hex>` over METHOD, path, body sha256, timestamp and nonce."""
|
|
26
|
+
body_hash = hashlib.sha256(raw_body).hexdigest()
|
|
27
|
+
canonical = "\n".join([method.upper(), _signed_path(path), body_hash, timestamp, nonce])
|
|
28
|
+
digest = hmac.new(secret.encode("utf-8"), canonical.encode("utf-8"), hashlib.sha256)
|
|
29
|
+
return f"sha256={digest.hexdigest()}"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def auth_headers(
|
|
33
|
+
*,
|
|
34
|
+
key_id: str,
|
|
35
|
+
secret: str,
|
|
36
|
+
method: str,
|
|
37
|
+
path: str,
|
|
38
|
+
raw_body: bytes,
|
|
39
|
+
timestamp: str | None = None,
|
|
40
|
+
nonce: str | None = None,
|
|
41
|
+
) -> dict[str, str]:
|
|
42
|
+
"""Authorization, timestamp, nonce and signature headers for one request."""
|
|
43
|
+
timestamp = timestamp or format_timestamp(datetime.now(timezone.utc))
|
|
44
|
+
nonce = nonce or str(uuid.uuid4())
|
|
45
|
+
return {
|
|
46
|
+
"Authorization": f"ApiKey {key_id}",
|
|
47
|
+
"X-Api-Timestamp": timestamp,
|
|
48
|
+
"X-Api-Nonce": nonce,
|
|
49
|
+
"X-Api-Signature": sign(
|
|
50
|
+
secret=secret,
|
|
51
|
+
method=method,
|
|
52
|
+
path=path,
|
|
53
|
+
raw_body=raw_body,
|
|
54
|
+
timestamp=timestamp,
|
|
55
|
+
nonce=nonce,
|
|
56
|
+
),
|
|
57
|
+
}
|
storenet/_version.py
ADDED
storenet/cli.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""The `storenet` command: create, AI-edit and list shop designs from the shell."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import contextlib
|
|
7
|
+
import json
|
|
8
|
+
import sys
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from storenet._version import __version__
|
|
13
|
+
from storenet.client import Edit, Site, StorenetClient, _is_uuid
|
|
14
|
+
from storenet.errors import StorenetConfigError, StorenetError
|
|
15
|
+
|
|
16
|
+
EXIT_OK = 0
|
|
17
|
+
EXIT_FAILED = 1
|
|
18
|
+
EXIT_USAGE = 2
|
|
19
|
+
SHORT_ID = 8
|
|
20
|
+
# The call may have finished on the server after the client stopped waiting or retrying.
|
|
21
|
+
MAYBE_DONE = frozenset({"timeout", "network_error", "409171", "503190", "503310"})
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _Exit(Exception):
|
|
25
|
+
def __init__(self, code: int, message: str) -> None:
|
|
26
|
+
super().__init__(message)
|
|
27
|
+
self.code = code
|
|
28
|
+
self.message = message
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
32
|
+
parser = argparse.ArgumentParser(
|
|
33
|
+
prog="storenet",
|
|
34
|
+
description="Create, edit with AI and list shop designs via the StoreNet Partner API.",
|
|
35
|
+
epilog="Environment: STORENET_BASE_URL, STORENET_KEY_ID, STORENET_SECRET.",
|
|
36
|
+
)
|
|
37
|
+
parser.add_argument("--version", action="version", version=f"storenet {__version__}")
|
|
38
|
+
groups = parser.add_subparsers(dest="group", metavar="GROUP")
|
|
39
|
+
groups.required = True
|
|
40
|
+
site = groups.add_parser("site", help="web designs")
|
|
41
|
+
actions = site.add_subparsers(dest="action", metavar="COMMAND")
|
|
42
|
+
actions.required = True
|
|
43
|
+
|
|
44
|
+
create = actions.add_parser("create", help="create a design from a shop description")
|
|
45
|
+
create.add_argument("prompt", nargs="?", metavar="DESCRIPTION", help="shop description")
|
|
46
|
+
create.add_argument(
|
|
47
|
+
"--file", "-f", metavar="FILE", help="read the description from a file ('-' for stdin)"
|
|
48
|
+
)
|
|
49
|
+
_common_flags(create)
|
|
50
|
+
|
|
51
|
+
update = actions.add_parser("update", help="edit a design with AI")
|
|
52
|
+
update.add_argument("site_id", metavar="ID", help="full ID or its first 8 characters")
|
|
53
|
+
update.add_argument(
|
|
54
|
+
"prompt", metavar="REQUEST", help="edit request, e.g. 'switch to a red colour scheme'"
|
|
55
|
+
)
|
|
56
|
+
_common_flags(update)
|
|
57
|
+
|
|
58
|
+
listing = actions.add_parser("list", help="list designs created through the API")
|
|
59
|
+
listing.add_argument("--json", action="store_true", help="print the raw JSON payload")
|
|
60
|
+
return parser
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _common_flags(parser: argparse.ArgumentParser) -> None:
|
|
64
|
+
parser.add_argument(
|
|
65
|
+
"--idempotency-key",
|
|
66
|
+
metavar="KEY",
|
|
67
|
+
help="deduplication key; retrying with the same key is safe",
|
|
68
|
+
)
|
|
69
|
+
parser.add_argument("--json", action="store_true", help="print the raw JSON payload")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _amount(value: float) -> str:
|
|
73
|
+
return f"{value:.4f}".rstrip("0").rstrip(".") or "0"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _when(moment: datetime | None) -> str:
|
|
77
|
+
return moment.astimezone().strftime("%Y-%m-%d %H:%M") if moment else "-"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _print_json(payload: Any) -> None:
|
|
81
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _bullets(title: str, lines: list[str]) -> None:
|
|
85
|
+
if lines:
|
|
86
|
+
print(title)
|
|
87
|
+
for line in lines:
|
|
88
|
+
print(f" - {line}")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _read_prompt(args: argparse.Namespace) -> str:
|
|
92
|
+
if args.prompt is not None and args.file is not None:
|
|
93
|
+
raise _Exit(EXIT_USAGE, "pass DESCRIPTION or --file, not both.")
|
|
94
|
+
if args.file is not None:
|
|
95
|
+
try:
|
|
96
|
+
if args.file == "-":
|
|
97
|
+
return str(sys.stdin.read())
|
|
98
|
+
with open(args.file, encoding="utf-8") as handle:
|
|
99
|
+
return handle.read()
|
|
100
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
101
|
+
raise _Exit(EXIT_USAGE, f"cannot read file {args.file}: {exc}") from None
|
|
102
|
+
if args.prompt is None:
|
|
103
|
+
raise _Exit(EXIT_USAGE, "missing description: pass DESCRIPTION or --file FILE.")
|
|
104
|
+
return str(args.prompt)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _non_empty(prompt: str) -> str:
|
|
108
|
+
prompt = prompt.strip()
|
|
109
|
+
if not prompt:
|
|
110
|
+
raise _Exit(EXIT_USAGE, "the text is empty.")
|
|
111
|
+
return prompt
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _resolve_id(client: StorenetClient, ref: str) -> str:
|
|
115
|
+
ref = ref.strip()
|
|
116
|
+
if _is_uuid(ref):
|
|
117
|
+
return ref
|
|
118
|
+
if not ref:
|
|
119
|
+
raise _Exit(EXIT_USAGE, "the ID is empty.")
|
|
120
|
+
matches = [site for site in client.sites.list() if site.id.lower().startswith(ref.lower())]
|
|
121
|
+
if not matches:
|
|
122
|
+
raise _Exit(EXIT_FAILED, f"no design has an ID starting with '{ref}'.")
|
|
123
|
+
if len(matches) > 1:
|
|
124
|
+
ids = "\n".join(f" {site.id} {site.name}" for site in matches)
|
|
125
|
+
raise _Exit(
|
|
126
|
+
EXIT_USAGE, f"'{ref}' matches {len(matches)} designs, type more characters:\n{ids}"
|
|
127
|
+
)
|
|
128
|
+
return matches[0].id
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _print_site(site: Site) -> None:
|
|
132
|
+
print(f"Created: {site.name} ({site.industry})")
|
|
133
|
+
print(f"ID: {site.id}")
|
|
134
|
+
print(f"Preview: {site.url}")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _print_edit(edit: Edit) -> None:
|
|
138
|
+
if edit.applied:
|
|
139
|
+
_bullets("Changed:", edit.changed)
|
|
140
|
+
else:
|
|
141
|
+
print(f"The AI changed nothing ({edit.outcome}).")
|
|
142
|
+
_bullets("Not done:", edit.refused + edit.unsupported)
|
|
143
|
+
if edit.applied:
|
|
144
|
+
credit = f"Credits: -{_amount(edit.credits_used)}"
|
|
145
|
+
if edit.credits_available is not None:
|
|
146
|
+
credit += f" ({_amount(edit.credits_available)} left)"
|
|
147
|
+
print(credit)
|
|
148
|
+
print(f"Preview: {edit.url}")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _print_table(sites: list[Site]) -> None:
|
|
152
|
+
header = ("ID", "NAME", "INDUSTRY", "UPDATED", "LINK")
|
|
153
|
+
rows = [
|
|
154
|
+
(site.id[:SHORT_ID], site.name, site.industry, _when(site.updated_at), site.url)
|
|
155
|
+
for site in sites
|
|
156
|
+
]
|
|
157
|
+
widths = [max(len(row[col]) for row in [header, *rows]) for col in range(len(header) - 1)]
|
|
158
|
+
for row in [header, *rows]:
|
|
159
|
+
cells = [cell.ljust(width) for cell, width in zip(row[:-1], widths, strict=True)]
|
|
160
|
+
print(" ".join([*cells, row[-1]]))
|
|
161
|
+
print(f"Total: {len(sites)} designs")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _run(args: argparse.Namespace) -> int:
|
|
165
|
+
if args.action == "create":
|
|
166
|
+
prompt = _non_empty(_read_prompt(args))
|
|
167
|
+
client = StorenetClient.from_env()
|
|
168
|
+
data = client.sites._create_data(prompt, args.idempotency_key)
|
|
169
|
+
if args.json:
|
|
170
|
+
_print_json(data)
|
|
171
|
+
else:
|
|
172
|
+
_print_site(client._site(data))
|
|
173
|
+
return EXIT_OK
|
|
174
|
+
if args.action == "update":
|
|
175
|
+
prompt = _non_empty(args.prompt)
|
|
176
|
+
client = StorenetClient.from_env()
|
|
177
|
+
site_id = _resolve_id(client, args.site_id)
|
|
178
|
+
data = client.sites._update_data(site_id, prompt, args.idempotency_key)
|
|
179
|
+
edit = client._edit(data)
|
|
180
|
+
if args.json:
|
|
181
|
+
_print_json(data)
|
|
182
|
+
else:
|
|
183
|
+
_print_edit(edit)
|
|
184
|
+
return EXIT_OK if edit.applied else EXIT_FAILED
|
|
185
|
+
client = StorenetClient.from_env()
|
|
186
|
+
items = client.sites._list_data()
|
|
187
|
+
if args.json:
|
|
188
|
+
_print_json(items)
|
|
189
|
+
return EXIT_OK
|
|
190
|
+
if not items:
|
|
191
|
+
print('No designs yet. Create the first one: storenet site create "<description>"')
|
|
192
|
+
return EXIT_OK
|
|
193
|
+
_print_table([client._site(item) for item in items])
|
|
194
|
+
return EXIT_OK
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _tolerate_unencodable_output() -> None:
|
|
198
|
+
# Shop names and server messages may be non-ASCII; a non-UTF-8 console must not crash.
|
|
199
|
+
for stream in (sys.stdout, sys.stderr):
|
|
200
|
+
reconfigure = getattr(stream, "reconfigure", None)
|
|
201
|
+
if reconfigure is not None:
|
|
202
|
+
with contextlib.suppress(ValueError, OSError):
|
|
203
|
+
reconfigure(errors="replace")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def main(argv: list[str] | None = None) -> int:
|
|
207
|
+
"""Run the CLI and return its exit code."""
|
|
208
|
+
_tolerate_unencodable_output()
|
|
209
|
+
try:
|
|
210
|
+
args = _build_parser().parse_args(argv)
|
|
211
|
+
except SystemExit as exc:
|
|
212
|
+
return exc.code if isinstance(exc.code, int) else (EXIT_OK if exc.code is None else 1)
|
|
213
|
+
try:
|
|
214
|
+
return _run(args)
|
|
215
|
+
except _Exit as exc:
|
|
216
|
+
print(f"Error: {exc.message}", file=sys.stderr)
|
|
217
|
+
return exc.code
|
|
218
|
+
except StorenetConfigError as exc:
|
|
219
|
+
print(f"Error: {exc.message}", file=sys.stderr)
|
|
220
|
+
return EXIT_USAGE
|
|
221
|
+
except StorenetError as exc:
|
|
222
|
+
print(f"Error {exc.code}: {exc.message}", file=sys.stderr)
|
|
223
|
+
key = exc.details.get("idempotency_key")
|
|
224
|
+
if exc.code in MAYBE_DONE and isinstance(key, str):
|
|
225
|
+
print(
|
|
226
|
+
"This request may have completed on the server. Run again with "
|
|
227
|
+
f"--idempotency-key {key} to get the result without being charged again.",
|
|
228
|
+
file=sys.stderr,
|
|
229
|
+
)
|
|
230
|
+
return EXIT_FAILED
|
|
231
|
+
except KeyboardInterrupt:
|
|
232
|
+
return 130
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
if __name__ == "__main__":
|
|
236
|
+
sys.exit(main())
|
storenet/client.py
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
"""Synchronous StoreNet Partner API client for shop designs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import builtins
|
|
6
|
+
import http.client
|
|
7
|
+
import ipaddress
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import time
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.request
|
|
13
|
+
import uuid
|
|
14
|
+
from collections.abc import Callable, Mapping
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from datetime import datetime, timezone
|
|
17
|
+
from typing import Any
|
|
18
|
+
from urllib.parse import urlencode, urlsplit
|
|
19
|
+
|
|
20
|
+
from storenet._signing import auth_headers, format_timestamp
|
|
21
|
+
from storenet._version import __version__
|
|
22
|
+
from storenet.errors import StorenetConfigError, StorenetError
|
|
23
|
+
|
|
24
|
+
API_PREFIX = "/api/public/v1"
|
|
25
|
+
ENV_BASE_URL = "STORENET_BASE_URL"
|
|
26
|
+
ENV_KEY_ID = "STORENET_KEY_ID"
|
|
27
|
+
ENV_SECRET = "STORENET_SECRET"
|
|
28
|
+
DEFAULT_TIMEOUT = 130.0
|
|
29
|
+
DEFAULT_MAX_RETRIES = 2
|
|
30
|
+
MAX_RETRY_AFTER = 60.0
|
|
31
|
+
BACKOFF_BASE = 2.0
|
|
32
|
+
PAGE_SIZE = 100
|
|
33
|
+
RETRYABLE_CODES = frozenset({"503310", "503190", "409171", "timeout", "network_error"})
|
|
34
|
+
EDIT_CONFLICT = "409310"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _RefuseRedirect(urllib.request.HTTPRedirectHandler):
|
|
38
|
+
# Following a redirect would resend the signed headers to a host the user never configured.
|
|
39
|
+
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _is_uuid(value: str) -> bool:
|
|
44
|
+
if len(value) not in (32, 36):
|
|
45
|
+
return False
|
|
46
|
+
try:
|
|
47
|
+
uuid.UUID(value)
|
|
48
|
+
except ValueError:
|
|
49
|
+
return False
|
|
50
|
+
return True
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _is_loopback(host: str | None) -> bool:
|
|
54
|
+
try:
|
|
55
|
+
return host is not None and ipaddress.ip_address(host).is_loopback
|
|
56
|
+
except ValueError:
|
|
57
|
+
return False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _base_url_problem(name: str, code: str) -> str:
|
|
61
|
+
if code == "insecure_base_url":
|
|
62
|
+
return f"{name} must use https; plain http is allowed only for a loopback IP address."
|
|
63
|
+
return f"{name} must be a full URL, for example https://shop.example.com"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class Site:
|
|
68
|
+
"""A shop design created through the Partner API."""
|
|
69
|
+
|
|
70
|
+
id: str
|
|
71
|
+
name: str
|
|
72
|
+
industry: str
|
|
73
|
+
url: str
|
|
74
|
+
updated_at: datetime | None = None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class Edit:
|
|
79
|
+
"""The result of one AI edit; `outcome` is "applied", "refused" or "empty"."""
|
|
80
|
+
|
|
81
|
+
id: str
|
|
82
|
+
outcome: str
|
|
83
|
+
changed: list[str]
|
|
84
|
+
refused: list[str]
|
|
85
|
+
unsupported: list[str]
|
|
86
|
+
credits_used: float
|
|
87
|
+
credits_available: float | None
|
|
88
|
+
url: str
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def applied(self) -> bool:
|
|
92
|
+
return self.outcome == "applied"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _invalid(message: str, status: int = 200) -> StorenetError:
|
|
96
|
+
return StorenetError("invalid_response", status, message)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _text(payload: Mapping[str, Any], key: str) -> str:
|
|
100
|
+
value = payload.get(key)
|
|
101
|
+
if not isinstance(value, str):
|
|
102
|
+
raise _invalid(f"Response is missing the field '{key}'.")
|
|
103
|
+
return value
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _number(payload: Mapping[str, Any], key: str) -> float | None:
|
|
107
|
+
value = payload.get(key)
|
|
108
|
+
if value is None:
|
|
109
|
+
return None
|
|
110
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
111
|
+
raise _invalid(f"Field '{key}' is not a number.")
|
|
112
|
+
return float(value)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _texts(payload: Mapping[str, Any], key: str) -> list[str]:
|
|
116
|
+
value = payload.get(key, [])
|
|
117
|
+
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
|
118
|
+
raise _invalid(f"Field '{key}' is not a list of strings.")
|
|
119
|
+
return list(value)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _parse_datetime(value: object) -> datetime | None:
|
|
123
|
+
if not isinstance(value, str) or not value:
|
|
124
|
+
return None
|
|
125
|
+
# Python 3.10 fromisoformat does not accept a trailing "Z".
|
|
126
|
+
text = value[:-1] + "+00:00" if value.endswith(("Z", "z")) else value
|
|
127
|
+
try:
|
|
128
|
+
moment = datetime.fromisoformat(text)
|
|
129
|
+
except ValueError:
|
|
130
|
+
return None
|
|
131
|
+
return moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _snippet(raw: bytes) -> str:
|
|
135
|
+
return raw[:200].decode("utf-8", "replace")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _retry_after(headers: Any) -> float | None:
|
|
139
|
+
value = headers.get("Retry-After") if headers is not None else None
|
|
140
|
+
if value is None:
|
|
141
|
+
return None
|
|
142
|
+
try:
|
|
143
|
+
seconds = float(value)
|
|
144
|
+
except (TypeError, ValueError):
|
|
145
|
+
return None
|
|
146
|
+
return seconds if seconds >= 0 else None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def error_from_response(status: int, raw: bytes, headers: Any = None) -> StorenetError:
|
|
150
|
+
"""Map a non-2xx response to a StorenetError."""
|
|
151
|
+
if 300 <= status < 400:
|
|
152
|
+
location = headers.get("Location") if headers is not None else None
|
|
153
|
+
return StorenetError(
|
|
154
|
+
"redirected",
|
|
155
|
+
status,
|
|
156
|
+
f"The server redirected (HTTP {status}) to {location or 'another address'}. "
|
|
157
|
+
f"Set {ENV_BASE_URL} to the shop's final https address and try again.",
|
|
158
|
+
{"location": location},
|
|
159
|
+
)
|
|
160
|
+
retry_after = _retry_after(headers)
|
|
161
|
+
try:
|
|
162
|
+
body = json.loads(raw.decode("utf-8"))
|
|
163
|
+
except (UnicodeDecodeError, ValueError):
|
|
164
|
+
return StorenetError(
|
|
165
|
+
"invalid_response",
|
|
166
|
+
status,
|
|
167
|
+
f"The server returned HTTP {status} with a body that is not JSON.",
|
|
168
|
+
{"body": _snippet(raw)},
|
|
169
|
+
retry_after=retry_after,
|
|
170
|
+
)
|
|
171
|
+
if isinstance(body, dict):
|
|
172
|
+
error = body.get("error")
|
|
173
|
+
if isinstance(error, dict) and error.get("code") is not None:
|
|
174
|
+
details = error.get("details")
|
|
175
|
+
return StorenetError(
|
|
176
|
+
str(error["code"]),
|
|
177
|
+
status,
|
|
178
|
+
str(error.get("message") or f"HTTP {status}"),
|
|
179
|
+
details if isinstance(details, dict) else {},
|
|
180
|
+
retry_after=retry_after,
|
|
181
|
+
)
|
|
182
|
+
detail = body.get("detail")
|
|
183
|
+
if status in (404, 405) and detail is not None:
|
|
184
|
+
return StorenetError(
|
|
185
|
+
"not_deployed",
|
|
186
|
+
status,
|
|
187
|
+
"The shop's server does not support this operation yet. "
|
|
188
|
+
"Ask the shop administrator to update it.",
|
|
189
|
+
{"detail": detail},
|
|
190
|
+
)
|
|
191
|
+
if status == 422 and isinstance(detail, list):
|
|
192
|
+
return StorenetError(
|
|
193
|
+
"validation_error",
|
|
194
|
+
status,
|
|
195
|
+
"The server rejected the request data.",
|
|
196
|
+
{"errors": detail},
|
|
197
|
+
)
|
|
198
|
+
return StorenetError(
|
|
199
|
+
"invalid_response",
|
|
200
|
+
status,
|
|
201
|
+
f"The server returned HTTP {status} with an unrecognised body.",
|
|
202
|
+
{"body": _snippet(raw)},
|
|
203
|
+
retry_after=retry_after,
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _error_body(exc: urllib.error.HTTPError) -> bytes:
|
|
208
|
+
try:
|
|
209
|
+
return exc.read() or b""
|
|
210
|
+
except (AttributeError, OSError, http.client.HTTPException):
|
|
211
|
+
return b""
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _retryable(error: StorenetError) -> bool:
|
|
215
|
+
return error.status == 429 or error.code in RETRYABLE_CODES
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class Sites:
|
|
219
|
+
"""Shop design operations, reached as `client.sites`."""
|
|
220
|
+
|
|
221
|
+
def __init__(self, client: StorenetClient) -> None:
|
|
222
|
+
self._client = client
|
|
223
|
+
|
|
224
|
+
def create(self, prompt: str, idempotency_key: str | None = None) -> Site:
|
|
225
|
+
"""Generate a new design from a description (about 15 s)."""
|
|
226
|
+
return self._client._site(self._create_data(prompt, idempotency_key))
|
|
227
|
+
|
|
228
|
+
def update(self, site_id: str, prompt: str, idempotency_key: str | None = None) -> Edit:
|
|
229
|
+
"""Ask the AI to change a design; a refused edit is returned, not raised."""
|
|
230
|
+
return self._client._edit(self._update_data(site_id, prompt, idempotency_key))
|
|
231
|
+
|
|
232
|
+
def list(self) -> builtins.list[Site]:
|
|
233
|
+
"""Every design of the key's owner, newest first, across all pages."""
|
|
234
|
+
return [self._client._site(item) for item in self._list_data()]
|
|
235
|
+
|
|
236
|
+
def _create_data(self, prompt: str, idempotency_key: str | None = None) -> dict[str, Any]:
|
|
237
|
+
envelope = self._client._call(
|
|
238
|
+
"POST", "/shop-designs", body={"prompt": prompt}, idempotency_key=idempotency_key
|
|
239
|
+
)
|
|
240
|
+
return _data_object(envelope)
|
|
241
|
+
|
|
242
|
+
def _update_data(
|
|
243
|
+
self, site_id: str, prompt: str, idempotency_key: str | None = None
|
|
244
|
+
) -> dict[str, Any]:
|
|
245
|
+
site_id = site_id.strip()
|
|
246
|
+
if not _is_uuid(site_id):
|
|
247
|
+
raise ValueError("site_id must be a full UUID")
|
|
248
|
+
envelope = self._client._call(
|
|
249
|
+
"POST",
|
|
250
|
+
f"/shop-designs/{site_id}/edits",
|
|
251
|
+
body={"prompt": prompt},
|
|
252
|
+
idempotency_key=idempotency_key,
|
|
253
|
+
retry_once=frozenset({EDIT_CONFLICT}),
|
|
254
|
+
)
|
|
255
|
+
return _data_object(envelope)
|
|
256
|
+
|
|
257
|
+
def _list_data(self) -> builtins.list[dict[str, Any]]:
|
|
258
|
+
items: builtins.list[dict[str, Any]] = []
|
|
259
|
+
page = 1
|
|
260
|
+
while True:
|
|
261
|
+
envelope = self._client._call(
|
|
262
|
+
"GET", "/shop-designs", query={"page": page, "per_page": PAGE_SIZE}
|
|
263
|
+
)
|
|
264
|
+
data = envelope.get("data")
|
|
265
|
+
meta = envelope.get("meta")
|
|
266
|
+
if not isinstance(data, list) or not isinstance(meta, dict):
|
|
267
|
+
raise _invalid("List response is missing 'data' or 'meta'.")
|
|
268
|
+
if not all(isinstance(item, dict) for item in data):
|
|
269
|
+
raise _invalid("List item is not an object.")
|
|
270
|
+
items.extend(data)
|
|
271
|
+
total_pages = meta.get("total_pages")
|
|
272
|
+
if not data or not isinstance(total_pages, int) or page >= total_pages:
|
|
273
|
+
return items
|
|
274
|
+
page += 1
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _data_object(envelope: Mapping[str, Any]) -> dict[str, Any]:
|
|
278
|
+
data = envelope.get("data")
|
|
279
|
+
if not isinstance(data, dict):
|
|
280
|
+
raise _invalid("Response is missing 'data'.")
|
|
281
|
+
return data
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
class StorenetClient:
|
|
285
|
+
"""Signs and sends Partner API calls; retries transient failures with the same key."""
|
|
286
|
+
|
|
287
|
+
def __init__(
|
|
288
|
+
self,
|
|
289
|
+
base_url: str,
|
|
290
|
+
key_id: str,
|
|
291
|
+
secret: str,
|
|
292
|
+
*,
|
|
293
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
294
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
295
|
+
) -> None:
|
|
296
|
+
given = {"base_url": base_url, "key_id": key_id, "secret": secret}
|
|
297
|
+
missing = [name for name, value in given.items() if not (value or "").strip()]
|
|
298
|
+
if missing:
|
|
299
|
+
raise StorenetConfigError("Missing configuration: " + ", ".join(missing), missing)
|
|
300
|
+
parts = urlsplit(base_url.strip())
|
|
301
|
+
if parts.scheme not in ("http", "https") or not parts.netloc:
|
|
302
|
+
code = "missing_config"
|
|
303
|
+
raise StorenetConfigError(_base_url_problem("base_url", code), ["base_url"], code)
|
|
304
|
+
if parts.scheme == "http" and not _is_loopback(parts.hostname):
|
|
305
|
+
code = "insecure_base_url"
|
|
306
|
+
raise StorenetConfigError(_base_url_problem("base_url", code), ["base_url"], code)
|
|
307
|
+
if max_retries < 0:
|
|
308
|
+
raise ValueError("max_retries must be >= 0")
|
|
309
|
+
root = parts.path.rstrip("/")
|
|
310
|
+
if root.endswith(API_PREFIX):
|
|
311
|
+
root = root[: -len(API_PREFIX)]
|
|
312
|
+
self._origin = f"{parts.scheme}://{parts.netloc}"
|
|
313
|
+
self._root = root
|
|
314
|
+
self.base_url = self._origin + root
|
|
315
|
+
self.key_id = key_id.strip()
|
|
316
|
+
self._secret = secret.strip()
|
|
317
|
+
self.timeout = float(timeout)
|
|
318
|
+
self.max_retries = max_retries
|
|
319
|
+
self.sites = Sites(self)
|
|
320
|
+
self._urlopen: Callable[..., Any] = urllib.request.build_opener(_RefuseRedirect()).open
|
|
321
|
+
self._sleep: Callable[[float], None] = time.sleep
|
|
322
|
+
self._now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)
|
|
323
|
+
self._nonce: Callable[[], str] = lambda: str(uuid.uuid4())
|
|
324
|
+
|
|
325
|
+
@classmethod
|
|
326
|
+
def from_env(
|
|
327
|
+
cls, *, timeout: float = DEFAULT_TIMEOUT, max_retries: int = DEFAULT_MAX_RETRIES
|
|
328
|
+
) -> StorenetClient:
|
|
329
|
+
"""Build a client from STORENET_BASE_URL, STORENET_KEY_ID and STORENET_SECRET."""
|
|
330
|
+
names = (ENV_BASE_URL, ENV_KEY_ID, ENV_SECRET)
|
|
331
|
+
values = {name: os.environ.get(name, "").strip() for name in names}
|
|
332
|
+
missing = [name for name in names if not values[name]]
|
|
333
|
+
if missing:
|
|
334
|
+
raise StorenetConfigError(
|
|
335
|
+
"Missing environment variables: " + ", ".join(missing), missing
|
|
336
|
+
)
|
|
337
|
+
try:
|
|
338
|
+
return cls(
|
|
339
|
+
values[ENV_BASE_URL],
|
|
340
|
+
values[ENV_KEY_ID],
|
|
341
|
+
values[ENV_SECRET],
|
|
342
|
+
timeout=timeout,
|
|
343
|
+
max_retries=max_retries,
|
|
344
|
+
)
|
|
345
|
+
except StorenetConfigError as exc:
|
|
346
|
+
message = _base_url_problem(ENV_BASE_URL, exc.code)
|
|
347
|
+
raise StorenetConfigError(message, [ENV_BASE_URL], exc.code) from exc
|
|
348
|
+
|
|
349
|
+
def __repr__(self) -> str:
|
|
350
|
+
return f"StorenetClient(base_url={self.base_url!r}, key_id={self.key_id!r})"
|
|
351
|
+
|
|
352
|
+
def _absolute(self, url: str) -> str:
|
|
353
|
+
return self._origin + url if url.startswith("/") else url
|
|
354
|
+
|
|
355
|
+
def _site(self, payload: Mapping[str, Any]) -> Site:
|
|
356
|
+
return Site(
|
|
357
|
+
id=_text(payload, "id"),
|
|
358
|
+
name=_text(payload, "name"),
|
|
359
|
+
industry=_text(payload, "industry"),
|
|
360
|
+
url=self._absolute(_text(payload, "url")),
|
|
361
|
+
updated_at=_parse_datetime(payload.get("updated_at")),
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
def _edit(self, payload: Mapping[str, Any]) -> Edit:
|
|
365
|
+
return Edit(
|
|
366
|
+
id=_text(payload, "id"),
|
|
367
|
+
outcome=_text(payload, "outcome"),
|
|
368
|
+
changed=_texts(payload, "changed"),
|
|
369
|
+
refused=_texts(payload, "refused"),
|
|
370
|
+
unsupported=_texts(payload, "unsupported"),
|
|
371
|
+
credits_used=_number(payload, "credits_used") or 0.0,
|
|
372
|
+
credits_available=_number(payload, "credits_available"),
|
|
373
|
+
url=self._absolute(_text(payload, "url")),
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
def _call(
|
|
377
|
+
self,
|
|
378
|
+
method: str,
|
|
379
|
+
path: str,
|
|
380
|
+
*,
|
|
381
|
+
body: object | None = None,
|
|
382
|
+
query: Mapping[str, object] | None = None,
|
|
383
|
+
idempotency_key: str | None = None,
|
|
384
|
+
retry_once: frozenset[str] = frozenset(),
|
|
385
|
+
) -> dict[str, Any]:
|
|
386
|
+
raw_body = b""
|
|
387
|
+
if body is not None:
|
|
388
|
+
raw_body = json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
389
|
+
key = None if method == "GET" else (idempotency_key or uuid.uuid4().hex)
|
|
390
|
+
full_path = self._root + API_PREFIX + path
|
|
391
|
+
url = self._origin + full_path + (f"?{urlencode(query)}" if query else "")
|
|
392
|
+
retries_left = self.max_retries
|
|
393
|
+
once = set(retry_once)
|
|
394
|
+
step = 0
|
|
395
|
+
while True:
|
|
396
|
+
try:
|
|
397
|
+
return self._send(method, full_path, url, raw_body, key)
|
|
398
|
+
except StorenetError as exc:
|
|
399
|
+
if exc.code in once:
|
|
400
|
+
once.discard(exc.code)
|
|
401
|
+
continue
|
|
402
|
+
if retries_left <= 0 or not _retryable(exc):
|
|
403
|
+
if key is not None:
|
|
404
|
+
exc.details["idempotency_key"] = key
|
|
405
|
+
raise
|
|
406
|
+
retries_left -= 1
|
|
407
|
+
if exc.retry_after is not None:
|
|
408
|
+
delay = min(exc.retry_after, MAX_RETRY_AFTER)
|
|
409
|
+
else:
|
|
410
|
+
delay = BACKOFF_BASE * (2**step)
|
|
411
|
+
step += 1
|
|
412
|
+
self._sleep(delay)
|
|
413
|
+
|
|
414
|
+
def _send(
|
|
415
|
+
self, method: str, path: str, url: str, raw_body: bytes, key: str | None
|
|
416
|
+
) -> dict[str, Any]:
|
|
417
|
+
headers = auth_headers(
|
|
418
|
+
key_id=self.key_id,
|
|
419
|
+
secret=self._secret,
|
|
420
|
+
method=method,
|
|
421
|
+
path=path,
|
|
422
|
+
raw_body=raw_body,
|
|
423
|
+
timestamp=format_timestamp(self._now()),
|
|
424
|
+
nonce=self._nonce(),
|
|
425
|
+
)
|
|
426
|
+
headers["Accept"] = "application/json"
|
|
427
|
+
headers["User-Agent"] = f"storenet-python/{__version__}"
|
|
428
|
+
if raw_body:
|
|
429
|
+
headers["Content-Type"] = "application/json"
|
|
430
|
+
if key is not None:
|
|
431
|
+
headers["Idempotency-Key"] = key
|
|
432
|
+
request = urllib.request.Request(url, data=raw_body or None, headers=headers, method=method)
|
|
433
|
+
try:
|
|
434
|
+
with self._urlopen(request, timeout=self.timeout) as response:
|
|
435
|
+
status = int(response.status)
|
|
436
|
+
raw = response.read()
|
|
437
|
+
response_headers = getattr(response, "headers", None)
|
|
438
|
+
except urllib.error.HTTPError as exc:
|
|
439
|
+
raise error_from_response(exc.code, _error_body(exc), exc.headers) from None
|
|
440
|
+
except TimeoutError:
|
|
441
|
+
raise self._timeout() from None
|
|
442
|
+
except urllib.error.URLError as exc:
|
|
443
|
+
if isinstance(exc.reason, TimeoutError):
|
|
444
|
+
raise self._timeout() from None
|
|
445
|
+
raise StorenetError(
|
|
446
|
+
"network_error", 0, f"Could not connect to {self._origin}: {exc.reason}"
|
|
447
|
+
) from None
|
|
448
|
+
except (http.client.HTTPException, OSError) as exc:
|
|
449
|
+
raise StorenetError(
|
|
450
|
+
"network_error", 0, f"Connection to {self._origin} dropped: {exc!r}"
|
|
451
|
+
) from None
|
|
452
|
+
if not 200 <= status < 300:
|
|
453
|
+
raise error_from_response(status, raw, response_headers)
|
|
454
|
+
try:
|
|
455
|
+
envelope = json.loads(raw.decode("utf-8"))
|
|
456
|
+
except (UnicodeDecodeError, ValueError):
|
|
457
|
+
raise StorenetError(
|
|
458
|
+
"invalid_response",
|
|
459
|
+
status,
|
|
460
|
+
"The server returned a body that is not JSON.",
|
|
461
|
+
{"body": _snippet(raw)},
|
|
462
|
+
) from None
|
|
463
|
+
if not isinstance(envelope, dict) or "data" not in envelope:
|
|
464
|
+
raise _invalid("Response has no 'data'.", status)
|
|
465
|
+
return envelope
|
|
466
|
+
|
|
467
|
+
def _timeout(self) -> StorenetError:
|
|
468
|
+
return StorenetError(
|
|
469
|
+
"timeout", 0, f"No response from {self._origin} within {self.timeout:g} seconds."
|
|
470
|
+
)
|
storenet/errors.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Errors raised by the StoreNet client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class StorenetError(Exception):
|
|
7
|
+
"""A failed call: `code` is the server code as sent (e.g. "409310") or a client-side word."""
|
|
8
|
+
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
code: str,
|
|
12
|
+
status: int,
|
|
13
|
+
message: str,
|
|
14
|
+
details: dict[str, object] | None = None,
|
|
15
|
+
*,
|
|
16
|
+
retry_after: float | None = None,
|
|
17
|
+
) -> None:
|
|
18
|
+
super().__init__(message)
|
|
19
|
+
self.code = code
|
|
20
|
+
self.status = status
|
|
21
|
+
self.message = message
|
|
22
|
+
self.details: dict[str, object] = dict(details or {})
|
|
23
|
+
self.retry_after = retry_after
|
|
24
|
+
|
|
25
|
+
def __str__(self) -> str:
|
|
26
|
+
return f"[{self.code}] {self.message}"
|
|
27
|
+
|
|
28
|
+
def __repr__(self) -> str:
|
|
29
|
+
name = type(self).__name__
|
|
30
|
+
return f"{name}(code={self.code!r}, status={self.status}, message={self.message!r})"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class StorenetConfigError(StorenetError):
|
|
34
|
+
"""Missing or unusable connection settings; `details["missing"]` names them."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, message: str, missing: list[str], code: str = "missing_config") -> None:
|
|
37
|
+
super().__init__(code, 0, message, {"missing": list(missing)})
|
storenet/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: storenet
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Command-line tool and Python library for the StoreNet Partner API: create, edit with AI and list shop web designs.
|
|
5
|
+
Project-URL: Homepage, https://storenet.ai
|
|
6
|
+
Project-URL: Source, https://github.com/storenet-ai/storenet-python
|
|
7
|
+
Author-email: StoreNet <support@storenet.ai>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: cli,partner-api,shop-design,storenet
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# storenet
|
|
26
|
+
|
|
27
|
+
Python library and `storenet` command-line tool for the StoreNet Partner API: create, edit with
|
|
28
|
+
AI, and list the web designs of a StoreNet shop without signing HMAC requests yourself.
|
|
29
|
+
|
|
30
|
+
- Python 3.10 or later, standard library only (no dependencies).
|
|
31
|
+
- Version 0.1 covers three operations on shop designs: `create`, `update`, `list`.
|
|
32
|
+
|
|
33
|
+
## Requirements
|
|
34
|
+
|
|
35
|
+
- The StoreNet shop is on the **Pro plan or higher** and has the quick shop designer turned on.
|
|
36
|
+
A lower plan returns `403290`; a disabled designer returns `404310`.
|
|
37
|
+
- A Partner API key with the `shop_designs:write` scope, created by a shop administrator.
|
|
38
|
+
Designs belong to the administrator who created the key, and AI credits are charged to that
|
|
39
|
+
administrator's wallet.
|
|
40
|
+
|
|
41
|
+
## Installation
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install storenet
|
|
45
|
+
storenet --version
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Configuration
|
|
49
|
+
|
|
50
|
+
The package reads three environment variables. If any is missing, the command exits with code 2
|
|
51
|
+
and names the missing variable. There is no default URL.
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
export STORENET_BASE_URL="https://shop.example.com" # your shop's address
|
|
55
|
+
export STORENET_KEY_ID="<key id>"
|
|
56
|
+
export STORENET_SECRET="<secret>"
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`STORENET_BASE_URL` must use https; plain http is accepted only for a loopback IP address on
|
|
60
|
+
your own machine. The package does not follow redirects (3xx): set the shop's final https
|
|
61
|
+
address.
|
|
62
|
+
|
|
63
|
+
Treat `STORENET_SECRET` like a password: never commit it or paste it into an issue. The package
|
|
64
|
+
never prints the secret or includes it in error messages.
|
|
65
|
+
|
|
66
|
+
## Command-line usage
|
|
67
|
+
|
|
68
|
+
### Create a design
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
storenet site create "A small bakery in the old quarter, warm cream colours"
|
|
72
|
+
storenet site create --file description.txt
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Prints the design name, its industry, its ID and a public preview link. A create takes about
|
|
76
|
+
15 seconds. The description must be 1 to 600 characters long.
|
|
77
|
+
|
|
78
|
+
### Edit a design with AI
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
storenet site update 1b2c3d4e "Switch to a red colour scheme and make the title larger"
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Prints what the AI changed, what it could not do (with reasons), the credits charged and the
|
|
85
|
+
remaining balance, and the preview link.
|
|
86
|
+
|
|
87
|
+
- `ID` is the full ID or its first few characters (usually the 8 shown by `site list`). A prefix
|
|
88
|
+
that matches several designs lists the matching IDs and exits with code 2; a prefix that
|
|
89
|
+
matches none exits with code 1.
|
|
90
|
+
- The request must be 1 to 400 characters long. An edit can take up to about 110 seconds.
|
|
91
|
+
- When the AI applies no change, the command prints the reasons, charges no credit and exits
|
|
92
|
+
with code 1.
|
|
93
|
+
- The preview link stays the same after an edit.
|
|
94
|
+
|
|
95
|
+
### List designs
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
storenet site list
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Prints a table with the columns ID (first 8 characters), name, industry, last update and link,
|
|
102
|
+
followed by the total. The list contains only the designs created through the Partner API by
|
|
103
|
+
the key's owner, most recently updated first; the command fetches every page.
|
|
104
|
+
|
|
105
|
+
### Common options
|
|
106
|
+
|
|
107
|
+
- `--json`: print the server's raw JSON payload (for scripts).
|
|
108
|
+
- `--idempotency-key KEY` (`create`, `update`): set your own deduplication key. Sending the same
|
|
109
|
+
key with the same body again returns the original result, without creating anything new or
|
|
110
|
+
charging credits a second time.
|
|
111
|
+
|
|
112
|
+
### Exit codes
|
|
113
|
+
|
|
114
|
+
| Code | Meaning |
|
|
115
|
+
|---|---|
|
|
116
|
+
| 0 | Success |
|
|
117
|
+
| 1 | The server returned an error, the AI changed nothing, or the ID prefix matched no design |
|
|
118
|
+
| 2 | Invalid usage, a missing or invalid environment variable, or an ID prefix that matched several designs |
|
|
119
|
+
|
|
120
|
+
## Library usage
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
from storenet import StorenetClient, StorenetError
|
|
124
|
+
|
|
125
|
+
client = StorenetClient.from_env() # or StorenetClient(base_url, key_id, secret)
|
|
126
|
+
|
|
127
|
+
site = client.sites.create("A pet shop with a green colour scheme")
|
|
128
|
+
print(site.id, site.name, site.industry, site.url)
|
|
129
|
+
|
|
130
|
+
edit = client.sites.update(site.id, "Switch to an orange colour scheme")
|
|
131
|
+
if edit.applied:
|
|
132
|
+
print(edit.changed, edit.credits_used, edit.credits_available)
|
|
133
|
+
else:
|
|
134
|
+
print(edit.outcome, edit.refused, edit.unsupported)
|
|
135
|
+
|
|
136
|
+
for item in client.sites.list():
|
|
137
|
+
print(item.id[:8], item.name, item.updated_at)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
- `sites.update` returns an `Edit` even when the AI changes nothing (`outcome` is `refused` or
|
|
141
|
+
`empty`); only real errors raise `StorenetError`.
|
|
142
|
+
- `sites.update` needs the full ID (a UUID) as in `Site.id`; any other value raises `ValueError`
|
|
143
|
+
before anything is sent. Only the `storenet` command resolves an ID from its first characters.
|
|
144
|
+
- `StorenetClient(..., timeout=130, max_retries=2)`: the timeout applies to each request.
|
|
145
|
+
|
|
146
|
+
## Automatic retries
|
|
147
|
+
|
|
148
|
+
Every `create` / `update` sends an `Idempotency-Key` (generated if you do not pass one). On a
|
|
149
|
+
temporary error the package retries up to `max_retries` times (default 2) with the **same** key
|
|
150
|
+
and a fresh signature:
|
|
151
|
+
|
|
152
|
+
- `429`: waits for the `Retry-After` header (at most 60 seconds); without the header it waits
|
|
153
|
+
2, then 4 seconds.
|
|
154
|
+
- `503310`, `503190`, `409171`, a timeout or a dropped connection: waits 2, then 4 seconds.
|
|
155
|
+
- `409310` (the design was just saved elsewhere) on `update`: retries exactly once against the
|
|
156
|
+
latest version.
|
|
157
|
+
|
|
158
|
+
Other 4xx errors (for example `403080`, out of credits) are not retried.
|
|
159
|
+
|
|
160
|
+
When `create` / `update` still fails after every retry, `StorenetError.details["idempotency_key"]`
|
|
161
|
+
holds the key that was sent. The request may have completed on the server: call again with that
|
|
162
|
+
same key to get the result without being charged again. The `storenet` command prints an
|
|
163
|
+
`--idempotency-key <key>` hint for you.
|
|
164
|
+
|
|
165
|
+
## Errors
|
|
166
|
+
|
|
167
|
+
Errors returned by the server carry the server's code in `StorenetError.code` (for example
|
|
168
|
+
`"409310"`), together with `status`, `message` and `details`. Client-side errors use text codes:
|
|
169
|
+
|
|
170
|
+
| Code | When |
|
|
171
|
+
|---|---|
|
|
172
|
+
| `missing_config` | A missing environment variable, or a `base_url` that is not a full URL (`StorenetConfigError`) |
|
|
173
|
+
| `insecure_base_url` | `base_url` uses http to a host other than a loopback IP address (`StorenetConfigError`) |
|
|
174
|
+
| `redirected` | The server answered with a 3xx redirect; `details["location"]` is the target. Set `STORENET_BASE_URL` to the final https address |
|
|
175
|
+
| `not_deployed` | The shop's server does not support this operation yet (usually `list` / `update`); ask the shop administrator to update |
|
|
176
|
+
| `validation_error` | The server rejected the request data (422) |
|
|
177
|
+
| `timeout` | No response within the timeout |
|
|
178
|
+
| `network_error` | Could not connect, or the connection dropped |
|
|
179
|
+
| `invalid_response` | The server returned something that is not JSON or not in the expected format |
|
|
180
|
+
|
|
181
|
+
Error messages that come from the server may be in Vietnamese.
|
|
182
|
+
|
|
183
|
+
## Security
|
|
184
|
+
|
|
185
|
+
Report vulnerabilities as described in
|
|
186
|
+
[SECURITY.md](https://github.com/storenet-ai/storenet-python/blob/main/SECURITY.md), not in a
|
|
187
|
+
public issue.
|
|
188
|
+
|
|
189
|
+
## License
|
|
190
|
+
|
|
191
|
+
MIT.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
storenet/__init__.py,sha256=ekll3OLZaJfeoEebx-4akZlea3ikVTvyNZljfEPTU6w,417
|
|
2
|
+
storenet/_signing.py,sha256=MKrKyzSqhmu3DQFiLy9LuL_6KI_l6qUssuhyM75DS08,1768
|
|
3
|
+
storenet/_version.py,sha256=uKe7bKslQ-UAQtyRPafzsfjB5eFr1tJ9EW-pM2aYDvg,196
|
|
4
|
+
storenet/cli.py,sha256=yrF7r08IuWDPkamnAWqyf3Vw1LPR4OhOZ4GoxrrPI2g,8409
|
|
5
|
+
storenet/client.py,sha256=bIk4SZRe2ke8ZtDvCdLDXsZ7XSiAkD0nHVFzsmfKGxQ,17274
|
|
6
|
+
storenet/errors.py,sha256=-326kcuDyfJeWjyrUiimeLttcF5KK1x6q474hqu0Opc,1179
|
|
7
|
+
storenet/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
storenet-0.1.0.dist-info/METADATA,sha256=2rylc05C81lYuS0LoZtqIBkdoxu1HTKYEgc-zP-jM08,7700
|
|
9
|
+
storenet-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
storenet-0.1.0.dist-info/entry_points.txt,sha256=iZ91MxmaSFLFFqML1Ol6YaZuq6mLihrkc6hKCaOTrAI,47
|
|
11
|
+
storenet-0.1.0.dist-info/licenses/LICENSE,sha256=a925Lc_o3H9v2RIB6u_9vvj2--Y-7xXKr2CoXPw8AiY,1065
|
|
12
|
+
storenet-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 StoreNet
|
|
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.
|