@ziffr/sdk 0.0.0-stage → 0.14.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/LICENSE +21 -0
- package/README.md +65 -2
- package/dist/index.d.ts +1130 -0
- package/dist/index.js +364 -0
- package/package.json +42 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
// @ziffr/sdk (spec 0002, ticket #51; GLOSSARY: Access Key, Metric, Observation): typed calls to the Ziffr API. It
|
|
2
|
+
// knows only HTTP and the API's published shapes, nothing of the server. Safe by default: it waits out a 429 as the
|
|
3
|
+
// server's Retry-After says, and every submission carries an idempotency key, so a retry never records a value twice.
|
|
4
|
+
/** Most periods one call sets or removes in a Target Series or Projections. */
|
|
5
|
+
export const SERIES_ITEMS_MAX = 500;
|
|
6
|
+
/** At most this many items in one batch. */
|
|
7
|
+
export const FEED_BATCH_MAX = 500;
|
|
8
|
+
/** An error answer of the API, or a failure to reach it (status 0). `code` is stable; handle errors by it. */
|
|
9
|
+
export class ZiffrError extends Error {
|
|
10
|
+
/** The HTTP status; 0 when Ziffr could not be reached. */
|
|
11
|
+
status;
|
|
12
|
+
/** The API's stable error code. */
|
|
13
|
+
code;
|
|
14
|
+
/** Seconds the server asked to wait, for `rate_limited`. */
|
|
15
|
+
retryAfter;
|
|
16
|
+
// Plain fields, not parameter properties, so Node can run this file with its built-in type stripping.
|
|
17
|
+
constructor(status, code, message, retryAfter = null) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = "ZiffrError";
|
|
20
|
+
this.status = status;
|
|
21
|
+
this.code = code;
|
|
22
|
+
this.retryAfter = retryAfter;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
26
|
+
const newIdempotencyKey = () => globalThis.crypto.randomUUID();
|
|
27
|
+
/** A client for one Ziffr and one Access Key. */
|
|
28
|
+
export class Ziffr {
|
|
29
|
+
base;
|
|
30
|
+
key;
|
|
31
|
+
maxRetries;
|
|
32
|
+
maxRetryWait;
|
|
33
|
+
fetcher;
|
|
34
|
+
constructor(options) {
|
|
35
|
+
if (!options?.url)
|
|
36
|
+
throw new Error("Ziffr needs the url where it runs.");
|
|
37
|
+
if (!options.accessKey)
|
|
38
|
+
throw new Error("Ziffr needs an Access Key.");
|
|
39
|
+
this.base = `${options.url.replace(/\/+$/, "")}/api/v1`;
|
|
40
|
+
this.key = options.accessKey;
|
|
41
|
+
this.maxRetries = options.maxRetries ?? 3;
|
|
42
|
+
this.maxRetryWait = options.maxRetryWait ?? 60;
|
|
43
|
+
this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
44
|
+
}
|
|
45
|
+
/** The Metrics the key's creator sees. */
|
|
46
|
+
metrics = {
|
|
47
|
+
/** One page of Metrics: those in use, or with `archived` only the Archived Metrics. */
|
|
48
|
+
list: ({ archived, ...options } = {}) => this.get("/metrics", { ...options, archived: archived ? "true" : undefined }),
|
|
49
|
+
/** Every Metric in use, or with `archived` every Archived Metric, page by page. */
|
|
50
|
+
all: (options = {}) => this.every((cursor) => this.metrics.list({ cursor, limit: 100, archived: options.archived })),
|
|
51
|
+
/** One Metric's description. */
|
|
52
|
+
get: (slug) => this.get(`/metrics/${encodeURIComponent(slug)}`),
|
|
53
|
+
/** Creates a Metric owned by the key's creator (scope metrics:write). A fresh idempotency key is sent unless one is
|
|
54
|
+
* given; pass your own to make retries across runs of your program safe too. */
|
|
55
|
+
create: async (metric, options = {}) => {
|
|
56
|
+
const { body, headers } = await this.request("POST", "/metrics", undefined, metric, options.idempotencyKey ?? newIdempotencyKey());
|
|
57
|
+
return { ...body, replayed: headers.get("idempotent-replayed") === "true" };
|
|
58
|
+
},
|
|
59
|
+
/** Deletes a Metric the key's creator owns (scope metrics:write), repeating its exact name to confirm. Refused
|
|
60
|
+
* (ZiffrError 422) while another Metric's formula, a widget, a deck or a working View Link uses it. */
|
|
61
|
+
delete: async (slug, confirmName) => (await this.request("DELETE", `/metrics/${encodeURIComponent(slug)}`, { confirm: confirmName })).body,
|
|
62
|
+
/** Archives a Metric (scope metrics:write), when the key's creator is an Owner or Admin or owns it: its values and
|
|
63
|
+
* history stay, it is asked for nothing and takes no values. Answers the Metric as it is now. */
|
|
64
|
+
archive: async (slug) => (await this.request("POST", `/metrics/${encodeURIComponent(slug)}/archive`)).body,
|
|
65
|
+
/** Brings an Archived Metric back (scope metrics:write), under the same rule. Answers the Metric as it is now. */
|
|
66
|
+
restore: async (slug) => (await this.request("POST", `/metrics/${encodeURIComponent(slug)}/restore`)).body,
|
|
67
|
+
/** Changes a Metric's Polarity, Target Range or Attainment method (scope metrics:edit), when
|
|
68
|
+
* the key's creator owns it or is its Editor. Answers the Metric as it is now. */
|
|
69
|
+
update: async (slug, patch) => (await this.request("PATCH", `/metrics/${encodeURIComponent(slug)}`, undefined, patch)).body,
|
|
70
|
+
/** Who submits to a Metric (scope metrics:read). */
|
|
71
|
+
submitters: async (slug) => (await this.get(`/metrics/${encodeURIComponent(slug)}/submitters`)).items,
|
|
72
|
+
/** Adds and removes up to 20 Submitters each (scope metrics:edit), when the key's creator owns the Metric or is its
|
|
73
|
+
* Editor. Each person added gets a first Prompt. Answers who submits now. */
|
|
74
|
+
setSubmitters: async (slug, change) => (await this.request("POST", `/metrics/${encodeURIComponent(slug)}/submitters`, undefined, change)).body,
|
|
75
|
+
/** What makes a value unusual in the Metric's Workflow (scope metrics:read). */
|
|
76
|
+
unusualValueCheck: (slug) => this.get(`/metrics/${encodeURIComponent(slug)}/unusual-value-check`),
|
|
77
|
+
/** Changes the check step of the Metric's Workflow, and so of every Metric sharing it (scope metrics:edit); only
|
|
78
|
+
* when the key's creator owns the Workflow. */
|
|
79
|
+
setUnusualValueCheck: async (slug, change) => (await this.request("PATCH", `/metrics/${encodeURIComponent(slug)}/unusual-value-check`, undefined, change)).body,
|
|
80
|
+
};
|
|
81
|
+
/** A Metric's Target Series: target values for single periods, such as a monthly budget. Where a period has none,
|
|
82
|
+
* the Metric's Target Range applies. */
|
|
83
|
+
targetSeries = this.series("target-series");
|
|
84
|
+
/** A Metric's Projections: values for the current period or later ones, from an outside forecast, always shown as
|
|
85
|
+
* projections. */
|
|
86
|
+
projections = this.series("projections");
|
|
87
|
+
/** A Metric's values. */
|
|
88
|
+
observations = {
|
|
89
|
+
/** One page of a Metric's values, oldest first. */
|
|
90
|
+
list: (slug, options = {}) => this.get(`/metrics/${encodeURIComponent(slug)}/observations`, options),
|
|
91
|
+
/** All of a Metric's values in a range, page by page. */
|
|
92
|
+
all: (slug, options = {}) => this.every((cursor) => this.observations.list(slug, { ...options, cursor, limit: 100 })),
|
|
93
|
+
/** Submits a value. A fresh idempotency key is sent unless one is given; pass your own to make retries across
|
|
94
|
+
* runs of your program safe too. A locked period, or one a rule refuses, throws a ZiffrError (422). */
|
|
95
|
+
submit: async (slug, value, options = {}) => {
|
|
96
|
+
const { body, headers } = await this.request("POST", `/metrics/${encodeURIComponent(slug)}/observations`, undefined, value, options.idempotencyKey ?? newIdempotencyKey());
|
|
97
|
+
return { ...body, replayed: headers.get("idempotent-replayed") === "true" };
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
/** The Threads on one period of a Metric that the key's creator may read, with authors, times and words (scope
|
|
101
|
+
* metrics:read). `period` is the period's first day, YYYY-MM-DD. A period with none, and one whose Threads the creator
|
|
102
|
+
* may not read, answer the same: an empty list. */
|
|
103
|
+
thread = (slug, period) => this.get(`/metrics/${encodeURIComponent(slug)}/thread`, { period });
|
|
104
|
+
/** The month the workspace's fiscal year starts in (1 is January): where quarterly and yearly Metrics' periods start. */
|
|
105
|
+
workspace = () => this.get("/workspace");
|
|
106
|
+
/** What the key's creator has to do, by day (scope metrics:read). `from` and `to` are days, YYYY-MM-DD, at most 90
|
|
107
|
+
* days apart; this week when left out. An Owner or Admin may name a teammate with `person_id` (from `people`). */
|
|
108
|
+
schedule = (span = {}) => this.get("/schedule", span);
|
|
109
|
+
/** Finds Metrics by name, and "Metric + period" for words such as "churn march 2026" (scope metrics:read). Period
|
|
110
|
+
* results come first; `slug` and `period` are what `metrics.get` and `observations` take. */
|
|
111
|
+
find = async (words) => (await this.get("/find", { q: words })).items;
|
|
112
|
+
/** The workspace's Workflows, to find the one to ask about (scope metrics:read). */
|
|
113
|
+
workflows = {
|
|
114
|
+
/** One page of Workflows. */
|
|
115
|
+
list: (options = {}) => this.get("/workflows", options),
|
|
116
|
+
/** Every Workflow, page by page. */
|
|
117
|
+
all: () => this.every((cursor) => this.workflows.list({ cursor, limit: 100 })),
|
|
118
|
+
/** A Workflow the key's creator owns, with its steps (scope metrics:read). */
|
|
119
|
+
get: (id) => this.get(`/workflows/${id}`),
|
|
120
|
+
/** Makes a Workflow (scope workflows:write). An Approve or Tell step also needs workflows:people, which only a program's key can hold. */
|
|
121
|
+
create: async (input) => (await this.request("POST", "/workflows", undefined, input)).body,
|
|
122
|
+
/** Changes a Workflow the key's creator owns (scope workflows:write). Without workflows:people, send Approve and Tell steps back as read. */
|
|
123
|
+
update: async (id, patch) => (await this.request("PATCH", `/workflows/${id}`, undefined, patch)).body,
|
|
124
|
+
/** Deletes a Workflow the key's creator owns (scope workflows:write). */
|
|
125
|
+
remove: async (id) => (await this.request("DELETE", `/workflows/${id}`)).body,
|
|
126
|
+
/** How a Workflow's period is going, as the key's creator may see it (scope metrics:read): `period` is a period's
|
|
127
|
+
* first day, the newest one that has anything when left out. */
|
|
128
|
+
periodStatus: (id, period) => this.get(`/workflows/${id}/period-status`, period ? { period } : {}),
|
|
129
|
+
};
|
|
130
|
+
/** The workspace's people and Contacts. */
|
|
131
|
+
people = {
|
|
132
|
+
/** One page of people. */
|
|
133
|
+
list: (options = {}) => this.get("/people", options),
|
|
134
|
+
/** Everyone, page by page. */
|
|
135
|
+
all: () => this.every((cursor) => this.people.list({ cursor, limit: 100 })),
|
|
136
|
+
/** Adds a Contact: a person without a sign-in who only submits values (scope people:write; Owners and Admins).
|
|
137
|
+
* Answers with their id and name, never the details. */
|
|
138
|
+
addContact: async (input) => (await this.request("POST", "/people", undefined, input)).body,
|
|
139
|
+
/** Changes a member's Workspace Role (scope people:write); only Owners make or change Owners. */
|
|
140
|
+
setRole: async (id, role) => (await this.request("PATCH", `/people/${encodeURIComponent(id)}`, undefined, { role })).body,
|
|
141
|
+
/** Removes a Contact, or a member whose things go to `successor` (another member, not a Guest). Scope people:write. */
|
|
142
|
+
remove: async (id, options = {}) => (await this.request("DELETE", `/people/${encodeURIComponent(id)}`, options.successor ? { successor: options.successor } : undefined)).body,
|
|
143
|
+
};
|
|
144
|
+
/** Inviting people (scope people:write, Owners and Admins; only a program's own key, never an assistant's). */
|
|
145
|
+
invitations = {
|
|
146
|
+
/** The open invitations, never with their secret links. */
|
|
147
|
+
list: async () => (await this.get("/invitations")).items,
|
|
148
|
+
/** Invites an address with a role and emails it the link. */
|
|
149
|
+
invite: async (input) => (await this.request("POST", "/invitations", undefined, input)).body,
|
|
150
|
+
/** Makes a link anyone can join by, as Member or Guest, for 7 days. Keep it as you would a password. */
|
|
151
|
+
link: async (role) => (await this.request("POST", "/invitations/links", undefined, { role })).body,
|
|
152
|
+
/** Revokes an invitation or invite link. */
|
|
153
|
+
revoke: async (id) => (await this.request("DELETE", `/invitations/${id}`)).body,
|
|
154
|
+
/** Emails an open invitation again. */
|
|
155
|
+
resend: async (id) => (await this.request("POST", `/invitations/${id}/resend`)).body,
|
|
156
|
+
};
|
|
157
|
+
/** Requests to join the workspace by its domain (scope people:write, Owners and Admins). */
|
|
158
|
+
joinRequests = {
|
|
159
|
+
/** The open requests. */
|
|
160
|
+
list: async () => (await this.get("/join-requests")).items,
|
|
161
|
+
/** Lets the person in as a Member (true) or declines (false). */
|
|
162
|
+
decide: async (id, approve) => (await this.request("POST", `/join-requests/${id}`, undefined, { approve })).body,
|
|
163
|
+
};
|
|
164
|
+
/** Shares (scope shares:write; only a program's own key, never an assistant's). Only the owner shares. */
|
|
165
|
+
shares = {
|
|
166
|
+
/** Who can see a Metric, dashboard or deck the key's creator sees, and why. */
|
|
167
|
+
who: (target) => this.get("/shares", { type: target.type, id: String(target.id) }),
|
|
168
|
+
/** Shares it with a member or a Group as viewer or editor; a null role takes the Share away. */
|
|
169
|
+
set: async (target, to, role) => (await this.request("POST", "/shares", undefined, { ...target, ...to, role })).body,
|
|
170
|
+
/** The owner grants Viewer access to a request listed by `who` (true) or declines it (false). */
|
|
171
|
+
decide: async (requestId, grant) => (await this.request("POST", `/shares/requests/${requestId}`, undefined, { grant })).body,
|
|
172
|
+
};
|
|
173
|
+
/** The workspace's live Feeds by id and name, to name one as a Submitter (scope metrics:edit). */
|
|
174
|
+
feeds = async () => (await this.get("/feeds")).items;
|
|
175
|
+
/** The workspace's Groups. */
|
|
176
|
+
groups = {
|
|
177
|
+
/** One page of Groups. */
|
|
178
|
+
list: (options = {}) => this.get("/groups", options),
|
|
179
|
+
/** Every Group, page by page. */
|
|
180
|
+
all: () => this.every((cursor) => this.groups.list({ cursor, limit: 100 })),
|
|
181
|
+
/** Makes a Group (scope groups:write; Owners and Admins; only a program's own key, never an assistant's). */
|
|
182
|
+
create: async (name) => (await this.request("POST", "/groups", undefined, { name })).body,
|
|
183
|
+
/** Renames a Group; never Everyone. */
|
|
184
|
+
rename: async (id, name) => (await this.request("PATCH", `/groups/${id}`, undefined, { name })).body,
|
|
185
|
+
/** Deletes a Group; what was shared with it stops being shared. */
|
|
186
|
+
remove: async (id) => (await this.request("DELETE", `/groups/${id}`)).body,
|
|
187
|
+
/** Puts a member of the workspace into a Group. */
|
|
188
|
+
addMember: async (id, person) => (await this.request("POST", `/groups/${id}/members`, undefined, { person })).body,
|
|
189
|
+
/** Takes a member out of a Group. */
|
|
190
|
+
removeMember: async (id, person) => (await this.request("DELETE", `/groups/${id}/members/${encodeURIComponent(person)}`)).body,
|
|
191
|
+
};
|
|
192
|
+
/** For a Feed Key (spec 0012): the Feed's Metrics, and recording values for them in batches. */
|
|
193
|
+
feed = {
|
|
194
|
+
/** The Feed's name and one page of its Metrics. */
|
|
195
|
+
get: (options = {}) => this.get("/feed", options),
|
|
196
|
+
/** Every Metric of the Feed, page by page. */
|
|
197
|
+
metrics: () => this.every(async (cursor) => (await this.feed.get({ cursor, limit: 100 })).metrics),
|
|
198
|
+
/** Records up to FEED_BATCH_MAX values, with one result per item in order. A fresh idempotency key is sent unless
|
|
199
|
+
* one is given; pass your own (made from the values) to make a repeated run record nothing twice. */
|
|
200
|
+
submit: async (items, options = {}) => {
|
|
201
|
+
if (!items.length || items.length > FEED_BATCH_MAX)
|
|
202
|
+
throw new Error(`A batch holds 1 to ${FEED_BATCH_MAX} items.`);
|
|
203
|
+
const { body, headers } = await this.request("POST", "/feed/observations", undefined, { items }, options.idempotencyKey ?? newIdempotencyKey());
|
|
204
|
+
return { results: body.results, replayed: headers.get("idempotent-replayed") === "true" };
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
/** The Questions and Tasks of the key's creator (GLOSSARY: Action): listing needs actions:read, replying, closing,
|
|
208
|
+
* reopening and marking done actions:write, confirming or correcting in a Self-check values:submit and approving
|
|
209
|
+
* values:approve, which only a program's key holds. Each acts as the key's creator, on the Actions they may read. */
|
|
210
|
+
actions = {
|
|
211
|
+
/** One page of the Actions waiting for the creator and those they asked. */
|
|
212
|
+
list: (options = {}) => this.get("/actions", options),
|
|
213
|
+
/** Every one of them, page by page. */
|
|
214
|
+
all: (options = {}) => this.every((cursor) => this.actions.list({ ...options, cursor, limit: 100 })),
|
|
215
|
+
/** Replies in an Action's Thread, with a Correction (a value) when given. Only words: never decides a Self-check or an Approval. */
|
|
216
|
+
reply: async (id, body, correction) => (await this.request("POST", `/actions/${id}/replies`, undefined, correction === undefined ? { body } : { body, correction })).body,
|
|
217
|
+
/** Closes an Action the creator asked. */
|
|
218
|
+
close: async (id) => (await this.request("PATCH", `/actions/${id}`, undefined, { status: "closed" })).body,
|
|
219
|
+
/** Reopens one the creator asked. */
|
|
220
|
+
reopen: async (id) => (await this.request("PATCH", `/actions/${id}`, undefined, { status: "open" })).body,
|
|
221
|
+
/** Marks the creator's own open Task done. */
|
|
222
|
+
done: async (id) => (await this.request("POST", `/actions/${id}/done`)).body,
|
|
223
|
+
/** Confirms the creator's own value in a Self-check. */
|
|
224
|
+
confirm: async (id) => (await this.request("POST", `/actions/${id}/self-check`, undefined, { decision: "confirm" })).body,
|
|
225
|
+
/** Corrects the creator's own value in a Self-check. */
|
|
226
|
+
correct: async (id, value) => (await this.request("POST", `/actions/${id}/self-check`, undefined, { decision: "correct", value })).body,
|
|
227
|
+
/** Approves a value waiting for the creator (scope values:approve, a program's key only). Refused for their own value. */
|
|
228
|
+
approve: async (id) => (await this.request("POST", `/actions/${id}/approval`, undefined, { decision: "approve" })).body,
|
|
229
|
+
/** Sends a value back with what to check (scope values:approve, a program's key only). */
|
|
230
|
+
sendBack: async (id, comment) => (await this.request("POST", `/actions/${id}/approval`, undefined, { decision: "send_back", comment })).body,
|
|
231
|
+
};
|
|
232
|
+
/** The key's creator's own Alerts (GLOSSARY: Alert): never anyone else's. Reading needs metrics:read, the rest the
|
|
233
|
+
* scope alerts:write. */
|
|
234
|
+
alerts = {
|
|
235
|
+
/** Their Alerts on Metrics they still see, newest first; of one Metric when its slug is given. At most 20. */
|
|
236
|
+
list: async (options = {}) => (await this.get("/alerts", options)).items,
|
|
237
|
+
/** Makes one for the key's creator. Refused (ZiffrError 422) at a limit or for a condition the Metric cannot give. */
|
|
238
|
+
create: async (input) => (await this.request("POST", "/alerts", undefined, input)).body,
|
|
239
|
+
/** Changes one of theirs: condition, way of delivery, option or pause. */
|
|
240
|
+
update: async (id, patch) => (await this.request("PATCH", `/alerts/${id}`, undefined, patch)).body,
|
|
241
|
+
/** Removes one of theirs. */
|
|
242
|
+
remove: async (id) => (await this.request("DELETE", `/alerts/${id}`)).body,
|
|
243
|
+
};
|
|
244
|
+
/** Share Proposals (GLOSSARY: Share Proposal): prepares a share for the key's creator to confirm in Ziffr. It shares and sends
|
|
245
|
+
* nothing; there is no call to confirm it, because only the person can, with their own sign-in. Needs shares:propose and dashboards:read. */
|
|
246
|
+
shareProposals = {
|
|
247
|
+
/** Proposes a View Link (an address, an end date, a message) or a Share (a person or a Group) of a dashboard the creator owns. */
|
|
248
|
+
create: async (input) => (await this.request("POST", "/share-proposals", undefined, input)).body,
|
|
249
|
+
};
|
|
250
|
+
/** The dashboards the key's creator sees (scope dashboards:read), and building them as the creator (scope
|
|
251
|
+
* dashboards:write). A key changes only what its creator may change, and never shares or deletes. */
|
|
252
|
+
dashboards = {
|
|
253
|
+
/** One page of dashboards. */
|
|
254
|
+
list: (options = {}) => this.get("/dashboards", options),
|
|
255
|
+
/** Every dashboard, page by page. */
|
|
256
|
+
all: () => this.every((cursor) => this.dashboards.list({ cursor, limit: 100 })),
|
|
257
|
+
/** One dashboard with its introduction and widgets. */
|
|
258
|
+
get: (id) => this.get(`/dashboards/${id}`),
|
|
259
|
+
/** Creates an empty dashboard, with an introduction if given. A fresh idempotency key is sent unless one is given. */
|
|
260
|
+
create: async (input, options = {}) => {
|
|
261
|
+
const { body, headers } = await this.request("POST", "/dashboards", undefined, input, options.idempotencyKey ?? newIdempotencyKey());
|
|
262
|
+
return { ...body, replayed: headers.get("idempotent-replayed") === "true" };
|
|
263
|
+
},
|
|
264
|
+
/** Makes a dashboard from a Dashboard Template, with Metric slugs for each Slot in order. */
|
|
265
|
+
fromTemplate: async (input, options = {}) => {
|
|
266
|
+
const { body, headers } = await this.request("POST", "/dashboards/from-template", undefined, input, options.idempotencyKey ?? newIdempotencyKey());
|
|
267
|
+
return { ...body, replayed: headers.get("idempotent-replayed") === "true" };
|
|
268
|
+
},
|
|
269
|
+
/** Adds a widget in the first free place. */
|
|
270
|
+
addWidget: async (dashboardId, widget) => (await this.request("POST", `/dashboards/${dashboardId}/widgets`, undefined, widget)).body,
|
|
271
|
+
/** Changes a widget's view, Metrics, title or settings. */
|
|
272
|
+
updateWidget: async (dashboardId, widgetId, patch) => (await this.request("PATCH", `/dashboards/${dashboardId}/widgets/${widgetId}`, undefined, patch)).body,
|
|
273
|
+
/** Removes a widget or a Finding. */
|
|
274
|
+
removeWidget: async (dashboardId, widgetId) => (await this.request("DELETE", `/dashboards/${dashboardId}/widgets/${widgetId}`)).body,
|
|
275
|
+
/** Changes a dashboard's name or introduction. */
|
|
276
|
+
update: async (dashboardId, patch) => (await this.request("PATCH", `/dashboards/${dashboardId}`, undefined, patch)).body,
|
|
277
|
+
/** Adds a Finding about one Metric below everything on the dashboard, full width. */
|
|
278
|
+
addFinding: async (dashboardId, finding) => (await this.request("POST", `/dashboards/${dashboardId}/findings`, undefined, finding)).body,
|
|
279
|
+
/** Changes a Finding's words. */
|
|
280
|
+
updateFinding: async (dashboardId, findingId, words) => (await this.request("PATCH", `/dashboards/${dashboardId}/findings/${findingId}`, undefined, words)).body,
|
|
281
|
+
};
|
|
282
|
+
/** Snapshots (ticket #435): reading needs dashboards:read, taking one dashboards:write. A key reads only what its
|
|
283
|
+
* creator may open, and never shows, deletes or rewrites a Snapshot. */
|
|
284
|
+
snapshots = {
|
|
285
|
+
/** A dashboard's Snapshots, newest period first (at most 200). */
|
|
286
|
+
list: async (dashboardId) => (await this.get(`/dashboards/${dashboardId}/snapshots`)).items,
|
|
287
|
+
/** One Snapshot with the values it kept. */
|
|
288
|
+
get: (id) => this.get(`/snapshots/${id}`),
|
|
289
|
+
/** Takes a Snapshot of a period that is over (`start` is its first day, yyyy-mm-dd). A draft until a person shows it;
|
|
290
|
+
* ZiffrError 422 when the period is not over or one exists already. */
|
|
291
|
+
take: async (dashboardId, period) => (await this.request("POST", `/dashboards/${dashboardId}/snapshots`, undefined, period)).body,
|
|
292
|
+
};
|
|
293
|
+
/** View Links to dashboards (ticket #435), all behind the scope view-links:write, which a key is given on purpose and
|
|
294
|
+
* an assistant never is: a View Link publishes data to people outside the workspace. */
|
|
295
|
+
viewLinks = {
|
|
296
|
+
/** A dashboard's View Links without their tokens. */
|
|
297
|
+
list: async (dashboardId) => (await this.get(`/dashboards/${dashboardId}/view-links`)).items,
|
|
298
|
+
/** Makes one, ending on `expires` (yyyy-mm-dd, within 90 days). Its `token` and `url` are in this answer only. Not
|
|
299
|
+
* idempotent: a repeated call makes another link. */
|
|
300
|
+
create: async (dashboardId, input) => (await this.request("POST", `/dashboards/${dashboardId}/view-links`, undefined, input)).body,
|
|
301
|
+
/** Revokes one at once and for good. */
|
|
302
|
+
revoke: async (id) => (await this.request("DELETE", `/view-links/${id}`)).body,
|
|
303
|
+
};
|
|
304
|
+
/** What a key can build with (scope dashboards:read). */
|
|
305
|
+
templates = {
|
|
306
|
+
/** The built-in views, the team's Widget Templates and the Dashboard Templates, or one kind of them. */
|
|
307
|
+
all: async (options = {}) => (await this.get("/templates", options)).items,
|
|
308
|
+
};
|
|
309
|
+
/** Reading (scope metrics:read) and setting (scope metrics:edit) one kind of series, the same for both. */
|
|
310
|
+
series(path) {
|
|
311
|
+
return {
|
|
312
|
+
/** Every period that has a value, oldest first. */
|
|
313
|
+
list: async (slug) => (await this.get(`/metrics/${encodeURIComponent(slug)}/${path}`)).items,
|
|
314
|
+
/** Sets or removes 1 to SERIES_ITEMS_MAX periods (their first days): a number sets one, null removes it. All
|
|
315
|
+
* or nothing: a refused item (ZiffrError 422) writes none. Safe to repeat. */
|
|
316
|
+
set: async (slug, items) => {
|
|
317
|
+
if (!items.length || items.length > SERIES_ITEMS_MAX)
|
|
318
|
+
throw new Error(`Send 1 to ${SERIES_ITEMS_MAX} items.`);
|
|
319
|
+
return (await this.request("POST", `/metrics/${encodeURIComponent(slug)}/${path}`, undefined, { items })).body;
|
|
320
|
+
},
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
async get(path, query = {}) {
|
|
324
|
+
return (await this.request("GET", path, query)).body;
|
|
325
|
+
}
|
|
326
|
+
async *every(page) {
|
|
327
|
+
let cursor;
|
|
328
|
+
do {
|
|
329
|
+
const p = await page(cursor);
|
|
330
|
+
yield* p.items;
|
|
331
|
+
cursor = p.next ?? undefined;
|
|
332
|
+
} while (cursor);
|
|
333
|
+
}
|
|
334
|
+
async request(method, path, query, body, idempotencyKey) {
|
|
335
|
+
const url = new URL(this.base + path);
|
|
336
|
+
for (const [k, v] of Object.entries(query ?? {}))
|
|
337
|
+
if (v !== undefined)
|
|
338
|
+
url.searchParams.set(k, String(v));
|
|
339
|
+
const headers = { authorization: `Bearer ${this.key}`, accept: "application/json" };
|
|
340
|
+
if (body !== undefined)
|
|
341
|
+
headers["content-type"] = "application/json";
|
|
342
|
+
if (idempotencyKey)
|
|
343
|
+
headers["idempotency-key"] = idempotencyKey;
|
|
344
|
+
for (let attempt = 0;; attempt++) {
|
|
345
|
+
let res;
|
|
346
|
+
try {
|
|
347
|
+
res = await this.fetcher(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
348
|
+
}
|
|
349
|
+
catch (e) {
|
|
350
|
+
throw new ZiffrError(0, "network", `Could not reach Ziffr: ${e.message}`);
|
|
351
|
+
}
|
|
352
|
+
if (res.ok)
|
|
353
|
+
return { body: (await res.json()), headers: res.headers };
|
|
354
|
+
const err = await res.json().catch(() => null);
|
|
355
|
+
const retryAfter = res.headers.has("retry-after") ? Number(res.headers.get("retry-after")) : null;
|
|
356
|
+
const error = new ZiffrError(res.status, err?.error?.code ?? "unknown", err?.error?.message ?? `Ziffr answered ${res.status}.`, retryAfter);
|
|
357
|
+
// Only a 429 is retried, and only GETs or submissions with an idempotency key: both are safe to repeat.
|
|
358
|
+
const wait = retryAfter ?? 1;
|
|
359
|
+
if (res.status !== 429 || attempt >= this.maxRetries || wait > this.maxRetryWait || (method !== "GET" && !idempotencyKey))
|
|
360
|
+
throw error;
|
|
361
|
+
await sleep(wait * 1000);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ziffr/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.14.0",
|
|
4
|
+
"description": "Call the Ziffr API from TypeScript: read Metrics and their values, submit values.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/ziffr/ziffr.git",
|
|
9
|
+
"directory": "packages/sdk"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"default": "./dist/index.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"README.md",
|
|
24
|
+
"LICENSE"
|
|
25
|
+
],
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=20"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@types/node": "^20",
|
|
31
|
+
"eslint": "^9.39.5",
|
|
32
|
+
"eslint-plugin-jsdoc": "^65.4.5",
|
|
33
|
+
"typescript": "^5",
|
|
34
|
+
"typescript-eslint": "^8.72.2",
|
|
35
|
+
"vitest": "^4.1.12",
|
|
36
|
+
"@ziffr/core": "0.11.0"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsc -p tsconfig.build.json",
|
|
40
|
+
"typecheck": "tsc --noEmit",
|
|
41
|
+
"lint": "eslint",
|
|
42
|
+
"test": "vitest run",
|
|
43
|
+
"test:app": "vitest run --config vitest.app.config.ts"
|
|
44
|
+
}
|
|
6
45
|
}
|