@templr/sdk 0.2.0 → 0.4.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/CHANGELOG.md CHANGED
@@ -7,6 +7,39 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.4.0] - 2026-12-05
11
+
12
+ ### Added
13
+
14
+ - `templates.create` and `templates.update` to create templates as drafts and change their name, document
15
+ or brand kit, with the `CreateTemplateOptions`, `UpdateTemplateOptions` and `SavedTemplate` types. They
16
+ return `editorUrl`, the link that opens the template in the editor, and require a `write` key.
17
+ - `UnprocessableEntityError` for 422 responses: a template document that does not match the document
18
+ model (`invalid_document`), with every problem in `issues`.
19
+ - `brandKitId` field in `Template` (`null` for the workspace default brand kit, or when the instance does
20
+ not return it).
21
+ - `assetFolders.list` to list the image folders of the workspace, with the `AssetFolder` type.
22
+ - `folder` and `search` options in `assets.list`: the images of one folder (`root` for those outside every
23
+ folder) and those whose file name or description contains a text (`ListAssetsOptions`).
24
+ - `assets.importFromUrl` to upload an image from a public URL (`ImportAssetOptions`), and `assets.update`
25
+ to change its description and folder (`UpdateAssetOptions`). Both require a `write` key.
26
+ - `description`, `folderId`, `width`, `height` and `previewUrl` fields in `Asset`. Sizes in pixels are read
27
+ by the server from the image; `previewUrl` is the image `url` with instances that do not return previews.
28
+
29
+ ## [0.3.0] - 2026-12-04
30
+
31
+ ### Added
32
+
33
+ - `name` option in `assets.upload` and `assets.createUpload`: the file name shown in the workspace audit log.
34
+ `upload` sends the name of a `File` by default.
35
+ - `name` field in `Asset` (`null` when the image was uploaded without one, or by an instance that does not
36
+ return it).
37
+ - `auditEvents.list` and `auditEvents.listAll` to read the workspace audit log, newest first, with the
38
+ `AuditEvent` type. They require a key with the `audit` grant.
39
+ - `payments.list` and `payments.listAll` to read the payments of the workspace owner's subscription, newest
40
+ first, with the `Payment` type and the `receiptUrl` of each receipt. They require a key with the `billing`
41
+ grant, which only the workspace owner can give.
42
+
10
43
  ## [0.2.0] - 2026-12-03
11
44
 
12
45
  ### Added
package/README.md CHANGED
@@ -49,6 +49,9 @@ Templr under the workspace settings.
49
49
 
50
50
  - A `read` key can list, get and render templates, and list images.
51
51
  - A `write` key can also upload and delete images.
52
+ - A key with the `audit` grant (given by an owner or admin when creating it) can also list the audit log.
53
+ - A key with the `billing` grant (given only by the workspace owner when creating it) can also list the payments
54
+ of the owner's subscription.
52
55
 
53
56
  Keys have a fixed expiration and are never renewed automatically. Keep them secret: use the SDK only on
54
57
  your server, never in a browser or mobile app, and read the key from the environment instead of
@@ -86,6 +89,24 @@ const email = await templr.templates.render(templateId, { values: { name: 'Ada',
86
89
  const preview = await templr.templates.render(templateId, { draft: true, values: { name: 'Ada' } });
87
90
  ```
88
91
 
92
+ ### Creating and updating templates
93
+
94
+ With a `write` key you can create templates and change their drafts. The document is TipTap JSON that
95
+ must match the `TemplateDocumentModel` schema of the OpenAPI document; otherwise the API answers with an
96
+ `UnprocessableEntityError` whose `issues` list every problem. Nothing is published: templates are
97
+ published from the editor, at the returned `editorUrl`.
98
+
99
+ ```ts
100
+ const created = await templr.templates.create({
101
+ document: { content: [{ content: [{ text: 'Hello', type: 'text' }], type: 'paragraph' }], type: 'doc' },
102
+ name: 'Welcome',
103
+ }); // brandKitId: '...' for a brand kit other than the workspace default
104
+ console.log(created.editorUrl);
105
+
106
+ // Change the name, the document, the brand kit (null for the workspace default) or several of them
107
+ await templr.templates.update(created.id, { name: 'Welcome email' });
108
+ ```
109
+
89
110
  ### Variables
90
111
 
91
112
  The variables of a template are the values `render` takes. Each key appears once, in document order.
@@ -122,12 +143,13 @@ do {
122
143
 
123
144
  `upload` starts the upload, sends the file straight to the storage bucket and confirms it. It requires a
124
145
  `write` key; accepted types are gif, jpeg, png and webp, up to 5 MiB. The file can be a `Uint8Array`
125
- (such as a Node.js `Buffer`) or a `Blob`.
146
+ (such as a Node.js `Buffer`) or a `Blob`. The optional `name` is the file name shown in the workspace audit
147
+ log; a `File` sends its own name.
126
148
 
127
149
  ```ts
128
150
  import { readFile } from 'node:fs/promises';
129
151
 
130
- const asset = await templr.assets.upload(await readFile('logo.png'), { contentType: 'image/png' });
152
+ const asset = await templr.assets.upload(await readFile('logo.png'), { contentType: 'image/png', name: 'logo.png' });
131
153
  console.log(asset.url);
132
154
  ```
133
155
 
@@ -150,11 +172,52 @@ if (!response.ok) throw new Error(`Upload failed with ${response.status}`);
150
172
  const confirmed = await templr.assets.confirm(upload.assetId);
151
173
  ```
152
174
 
175
+ The server reads the `width` and `height` of every confirmed image from the image itself, and stores a
176
+ small WebP preview (`previewUrl`, at most 256 pixels on its longest side).
177
+
178
+ An image can also be uploaded from a public URL: the server downloads it (PNG, JPEG, GIF or WebP, up to
179
+ 5 MiB) and stores it. URLs that point to private addresses are refused with a `BadRequestError`.
180
+
181
+ ```ts
182
+ const hero = await templr.assets.importFromUrl('https://images.example.com/hero.png', { description: 'Summer hero', name: 'hero.png' });
183
+ ```
184
+
185
+ Images can be grouped in folders, searched by file name or description, described and moved:
186
+
153
187
  ```ts
154
- const images = await templr.assets.list();
188
+ const folders = await templr.assetFolders.list(); // [{ id, name, assetCount, ... }]
189
+ const inFolder = await templr.assets.list({ folder: folders[0].id, search: 'logo' });
190
+ const atRoot = await templr.assets.list({ folder: 'root' });
191
+
192
+ await templr.assets.update(asset.id, { description: 'Company logo', folderId: null }); // null moves it to the root
155
193
  await templr.assets.delete(asset.id); // Templates that use it will show a broken image
156
194
  ```
157
195
 
196
+ ### Audit log
197
+
198
+ With a key that has the `audit` grant, `auditEvents.list` returns one page of the workspace audit log,
199
+ newest first, and `auditEvents.listAll` iterates over every event, page by page. In the cloud only the
200
+ events within the audit history of the workspace owner's plan are listed.
201
+
202
+ ```ts
203
+ for await (const event of templr.auditEvents.listAll({ limit: 100 })) {
204
+ console.log(event.createdAt, event.actor.type, event.action, event.resourceType, event.metadata);
205
+ }
206
+ ```
207
+
208
+ ### Payments
209
+
210
+ With a key that has the `billing` grant, `payments.list` returns one page of the payments of the workspace
211
+ owner's subscription, newest first, and `payments.listAll` iterates over every payment, page by page. Each
212
+ payment has a `receiptUrl` that opens its receipt in the app, where the owner can print it as PDF (`null` when
213
+ the payment has no receipt: only approved payments get one).
214
+
215
+ ```ts
216
+ for await (const payment of templr.payments.listAll({ limit: 100 })) {
217
+ console.log(payment.paidAt ?? payment.createdAt, payment.status, payment.amount, payment.currency, payment.receiptUrl);
218
+ }
219
+ ```
220
+
158
221
  ## Error handling
159
222
 
160
223
  Every error thrown by the SDK extends `TemplrError` and has a machine-readable `code`. Errors returned by
@@ -181,20 +244,21 @@ try {
181
244
  }
182
245
  ```
183
246
 
184
- | Error | Status | API codes |
185
- | ------------------------- | ------ | ---------------------------------------------------------------------------------------------- |
186
- | `BadRequestError` | 400 | `invalid_input`, `validation_error` |
187
- | `AuthenticationError` | 401 | `unauthorized` |
188
- | `PermissionDeniedError` | 403 | `forbidden` |
189
- | `NotFoundError` | 404 | `not_found` |
190
- | `ConflictError` | 409 | `upload_missing`, `conflict` |
191
- | `PayloadTooLargeError` | 413 | `payload_too_large` |
192
- | `RateLimitError` | 429 | `rate_limited` |
193
- | `InternalServerError` | 5xx | `internal_error`, `database_error`, `render_failed`, `storage_error`, `storage_not_configured` |
194
- | `UploadError` | bucket | `upload_failed`: the storage bucket rejected the file sent by `assets.upload` |
195
- | `APIConnectionError` | none | `connection_error` |
196
- | `APITimeoutError` | none | `timeout` |
197
- | `UnexpectedResponseError` | 2xx | `unexpected_response`: the server answered with a body this SDK does not understand |
247
+ | Error | Status | API codes |
248
+ | -------------------------- | ------ | ---------------------------------------------------------------------------------------------- |
249
+ | `BadRequestError` | 400 | `invalid_input`, `validation_error` |
250
+ | `AuthenticationError` | 401 | `unauthorized` |
251
+ | `PermissionDeniedError` | 403 | `forbidden` |
252
+ | `NotFoundError` | 404 | `not_found` |
253
+ | `ConflictError` | 409 | `upload_missing`, `conflict` |
254
+ | `PayloadTooLargeError` | 413 | `payload_too_large` |
255
+ | `UnprocessableEntityError` | 422 | `invalid_document` |
256
+ | `RateLimitError` | 429 | `rate_limited` |
257
+ | `InternalServerError` | 5xx | `internal_error`, `database_error`, `render_failed`, `storage_error`, `storage_not_configured` |
258
+ | `UploadError` | bucket | `upload_failed`: the storage bucket rejected the file sent by `assets.upload` |
259
+ | `APIConnectionError` | none | `connection_error` |
260
+ | `APITimeoutError` | none | `timeout` |
261
+ | `UnexpectedResponseError` | 2xx | `unexpected_response`: the server answered with a body this SDK does not understand |
198
262
 
199
263
  An error response without a Templr error body (for example, an HTML page from a proxy) throws the class
200
264
  of its status with the code `unknown_error`. Invalid options (an empty `apiKey`, or a `baseUrl` that is
package/dist/client.d.ts CHANGED
@@ -3,7 +3,10 @@
3
3
  *
4
4
  * @module
5
5
  */
6
+ import { AssetFolders } from './resources/asset-folders.js';
6
7
  import { Assets } from './resources/assets.js';
8
+ import { AuditEvents } from './resources/audit-events.js';
9
+ import { Payments } from './resources/payments.js';
7
10
  import { Templates } from './resources/templates.js';
8
11
  import { type OpenApiDocument } from './schemas.js';
9
12
  import { type Fetch } from './transport.js';
@@ -34,8 +37,14 @@ export declare class Templr {
34
37
  #private;
35
38
  /** List, get and render templates. */
36
39
  readonly templates: Templates;
37
- /** Upload, list and delete images. */
40
+ /** Upload, list, search, organize and delete images. */
38
41
  readonly assets: Assets;
42
+ /** Folders of images. */
43
+ readonly assetFolders: AssetFolders;
44
+ /** Read the audit log; requires a key with the `audit` grant. */
45
+ readonly auditEvents: AuditEvents;
46
+ /** Read the payments of the workspace owner's subscription; requires a key with the `billing` grant. */
47
+ readonly payments: Payments;
39
48
  /**
40
49
  * Creates a client.
41
50
  *
package/dist/client.js CHANGED
@@ -3,7 +3,10 @@
3
3
  *
4
4
  * @module
5
5
  */
6
+ import { AssetFolders } from './resources/asset-folders.js';
6
7
  import { Assets } from './resources/assets.js';
8
+ import { AuditEvents } from './resources/audit-events.js';
9
+ import { Payments } from './resources/payments.js';
7
10
  import { Templates } from './resources/templates.js';
8
11
  import { openApiDocumentSchema } from './schemas.js';
9
12
  import { DEFAULT_TIMEOUT_MS, Transport } from './transport.js';
@@ -22,8 +25,14 @@ import { DEFAULT_TIMEOUT_MS, Transport } from './transport.js';
22
25
  export class Templr {
23
26
  /** List, get and render templates. */
24
27
  templates;
25
- /** Upload, list and delete images. */
28
+ /** Upload, list, search, organize and delete images. */
26
29
  assets;
30
+ /** Folders of images. */
31
+ assetFolders;
32
+ /** Read the audit log; requires a key with the `audit` grant. */
33
+ auditEvents;
34
+ /** Read the payments of the workspace owner's subscription; requires a key with the `billing` grant. */
35
+ payments;
27
36
  #transport;
28
37
  /**
29
38
  * Creates a client.
@@ -39,6 +48,9 @@ export class Templr {
39
48
  });
40
49
  this.templates = new Templates(this.#transport);
41
50
  this.assets = new Assets(this.#transport);
51
+ this.assetFolders = new AssetFolders(this.#transport);
52
+ this.auditEvents = new AuditEvents(this.#transport);
53
+ this.payments = new Payments(this.#transport);
42
54
  }
43
55
  /** Gets the OpenAPI 3.1 document of the API served by this instance. */
44
56
  getOpenApiDocument() {
package/dist/errors.d.ts CHANGED
@@ -80,6 +80,12 @@ export declare class NotFoundError extends APIError {
80
80
  */
81
81
  export declare class ConflictError extends APIError {
82
82
  }
83
+ /**
84
+ * 422: the template document does not match the document model
85
+ * (`invalid_document`); `issues` lists every problem, each naming the block it is in.
86
+ */
87
+ export declare class UnprocessableEntityError extends APIError {
88
+ }
83
89
  /** 413: the request body is too large (`payload_too_large`). */
84
90
  export declare class PayloadTooLargeError extends APIError {
85
91
  }
package/dist/errors.js CHANGED
@@ -90,6 +90,12 @@ export class NotFoundError extends APIError {
90
90
  */
91
91
  export class ConflictError extends APIError {
92
92
  }
93
+ /**
94
+ * 422: the template document does not match the document model
95
+ * (`invalid_document`); `issues` lists every problem, each naming the block it is in.
96
+ */
97
+ export class UnprocessableEntityError extends APIError {
98
+ }
93
99
  /** 413: the request body is too large (`payload_too_large`). */
94
100
  export class PayloadTooLargeError extends APIError {
95
101
  }
package/dist/index.d.ts CHANGED
@@ -13,9 +13,12 @@
13
13
  * @module
14
14
  */
15
15
  export { Templr, type TemplrOptions } from './client.js';
16
- export { APIConnectionError, APIError, type APIErrorDetails, APITimeoutError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PayloadTooLargeError, PermissionDeniedError, RateLimitError, TemplrError, UnexpectedResponseError, UploadError, } from './errors.js';
17
- export type { Assets, CreateUploadOptions, UploadOptions } from './resources/assets.js';
18
- export type { ListOptions, ListTemplatesOptions, ListVariablesOptions, RenderOptions, SortOrder, Templates, UpdateVariableOptions } from './resources/templates.js';
19
- export type { Asset, AssetUpload, Deleted, ImageContentType, JsonValue, OpenApiDocument, Page, PresignedUpload, RenderedTemplate, Template, TemplateDocument, TemplateMark, TemplateNode, TemplateSummary, TemplateVariable, TemplateVersion, TemplateVersionSummary, } from './schemas.js';
16
+ export { APIConnectionError, APIError, type APIErrorDetails, APITimeoutError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PayloadTooLargeError, PermissionDeniedError, RateLimitError, TemplrError, UnexpectedResponseError, UnprocessableEntityError, UploadError, } from './errors.js';
17
+ export type { AssetFolders } from './resources/asset-folders.js';
18
+ export type { Assets, CreateUploadOptions, ImportAssetOptions, ListAssetsOptions, UpdateAssetOptions, UploadOptions } from './resources/assets.js';
19
+ export type { AuditEvents } from './resources/audit-events.js';
20
+ export type { Payments } from './resources/payments.js';
21
+ export type { CreateTemplateOptions, ListOptions, ListTemplatesOptions, ListVariablesOptions, RenderOptions, SortOrder, Templates, UpdateTemplateOptions, UpdateVariableOptions, } from './resources/templates.js';
22
+ export type { Asset, AssetFolder, AssetUpload, AuditEvent, Deleted, ImageContentType, JsonValue, OpenApiDocument, Page, Payment, PresignedUpload, RenderedTemplate, SavedTemplate, Template, TemplateDocument, TemplateMark, TemplateNode, TemplateSummary, TemplateVariable, TemplateVersion, TemplateVersionSummary, } from './schemas.js';
20
23
  export type { Fetch } from './transport.js';
21
24
  export { VERSION } from './version.js';
package/dist/index.js CHANGED
@@ -13,5 +13,5 @@
13
13
  * @module
14
14
  */
15
15
  export { Templr } from './client.js';
16
- export { APIConnectionError, APIError, APITimeoutError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PayloadTooLargeError, PermissionDeniedError, RateLimitError, TemplrError, UnexpectedResponseError, UploadError, } from './errors.js';
16
+ export { APIConnectionError, APIError, APITimeoutError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PayloadTooLargeError, PermissionDeniedError, RateLimitError, TemplrError, UnexpectedResponseError, UnprocessableEntityError, UploadError, } from './errors.js';
17
17
  export { VERSION } from './version.js';
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The `assetFolders` resource: the folders that group the images of the workspace.
3
+ *
4
+ * @module
5
+ */
6
+ import { type AssetFolder } from '../schemas.js';
7
+ import type { Transport } from '../transport.js';
8
+ /** Folders of images of the workspace. */
9
+ export declare class AssetFolders {
10
+ #private;
11
+ /** @internal */
12
+ constructor(transport: Transport);
13
+ /** Lists every folder by name, with how many images each holds. Requires a `read` or `write` API key. */
14
+ list(): Promise<readonly AssetFolder[]>;
15
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The `assetFolders` resource: the folders that group the images of the workspace.
3
+ *
4
+ * @module
5
+ */
6
+ import { assetFolderListSchema } from '../schemas.js';
7
+ /** Folders of images of the workspace. */
8
+ export class AssetFolders {
9
+ #transport;
10
+ /** @internal */
11
+ constructor(transport) {
12
+ this.#transport = transport;
13
+ }
14
+ /** Lists every folder by name, with how many images each holds. Requires a `read` or `write` API key. */
15
+ async list() {
16
+ const list = await this.#transport.send({ method: 'GET', path: '/api/v1/asset-folders' }, assetFolderListSchema);
17
+ return list.items;
18
+ }
19
+ }
@@ -1,5 +1,6 @@
1
1
  /**
2
- * The `assets` resource: upload, list and delete the images used by templates.
2
+ * The `assets` resource: upload, list, search, describe, move and delete the
3
+ * images used by templates.
3
4
  *
4
5
  * @module
5
6
  */
@@ -10,14 +11,41 @@ import type { ListOptions } from './templates.js';
10
11
  export interface UploadOptions {
11
12
  /** The image type. */
12
13
  readonly contentType: ImageContentType;
14
+ /** The file name shown in the audit log, e.g. `logo.png`. Defaults to the name of a `File`. */
15
+ readonly name?: string;
13
16
  }
14
17
  /** Options of {@link Assets.createUpload}. */
15
18
  export interface CreateUploadOptions {
16
19
  /** The image type. */
17
20
  readonly contentType: ImageContentType;
21
+ /** The file name shown in the audit log, e.g. `logo.png` (at most 255 characters). */
22
+ readonly name?: string;
18
23
  /** The exact size of the file, in bytes (at most 5 MiB). */
19
24
  readonly sizeBytes: number;
20
25
  }
26
+ /** Options of {@link Assets.list}. */
27
+ export interface ListAssetsOptions extends ListOptions {
28
+ /** Only the images of this folder: its id, or `root` for the images outside every folder. Every image when omitted. */
29
+ readonly folder?: string;
30
+ /** Only the images whose file name or description contains this text, whatever its case (at most 100 characters). */
31
+ readonly search?: string;
32
+ }
33
+ /** Options of {@link Assets.importFromUrl}. */
34
+ export interface ImportAssetOptions {
35
+ /** What the image shows, used as its alt text (at most 500 characters). */
36
+ readonly description?: string;
37
+ /** The folder to store it in; the root when omitted. */
38
+ readonly folderId?: string;
39
+ /** The file name (at most 255 characters). Defaults to the last segment of the URL's path. */
40
+ readonly name?: string;
41
+ }
42
+ /** The changes of {@link Assets.update}; give `description`, `folderId` or both. */
43
+ export interface UpdateAssetOptions {
44
+ /** What the image shows, used as its alt text; `null` or an empty text clears it. */
45
+ readonly description?: string | null;
46
+ /** The folder to move it to; `null` moves it to the root. */
47
+ readonly folderId?: string | null;
48
+ }
21
49
  /**
22
50
  * Images of the workspace.
23
51
  *
@@ -29,8 +57,29 @@ export declare class Assets {
29
57
  #private;
30
58
  /** @internal */
31
59
  constructor(transport: Transport);
32
- /** Lists the confirmed images, newest first. Requires a `read` or `write` API key. */
33
- list(options?: ListOptions): Promise<Page<Asset>>;
60
+ /**
61
+ * Lists the confirmed images, newest first: every image, those of one
62
+ * `folder`, and only those matching `search`. Requires a `read` or `write` API key.
63
+ *
64
+ * @throws NotFoundError when the folder does not exist.
65
+ */
66
+ list(options?: ListAssetsOptions): Promise<Page<Asset>>;
67
+ /**
68
+ * Uploads an image from a public URL: the server downloads it (PNG, JPEG,
69
+ * GIF or WebP, at most 5 MiB) and stores it with its size in pixels and a
70
+ * preview. Requires a `write` API key.
71
+ *
72
+ * @param url - The public `http` or `https` URL of the image.
73
+ * @throws BadRequestError when the URL is refused (e.g. a private address) or is not such an image.
74
+ * @throws NotFoundError when the folder does not exist.
75
+ */
76
+ importFromUrl(url: string, options?: ImportAssetOptions): Promise<Asset>;
77
+ /**
78
+ * Changes the description of an image, moves it to another folder, or both. Requires a `write` API key.
79
+ *
80
+ * @throws NotFoundError when the image or the folder does not exist.
81
+ */
82
+ update(assetId: string, changes: UpdateAssetOptions): Promise<Asset>;
34
83
  /**
35
84
  * Uploads an image: starts the upload, sends the file to the storage bucket
36
85
  * and confirms it. Requires a `write` API key.
@@ -1,5 +1,6 @@
1
1
  /**
2
- * The `assets` resource: upload, list and delete the images used by templates.
2
+ * The `assets` resource: upload, list, search, describe, move and delete the
3
+ * images used by templates.
3
4
  *
4
5
  * @module
5
6
  */
@@ -19,9 +20,44 @@ export class Assets {
19
20
  constructor(transport) {
20
21
  this.#transport = transport;
21
22
  }
22
- /** Lists the confirmed images, newest first. Requires a `read` or `write` API key. */
23
+ /**
24
+ * Lists the confirmed images, newest first: every image, those of one
25
+ * `folder`, and only those matching `search`. Requires a `read` or `write` API key.
26
+ *
27
+ * @throws NotFoundError when the folder does not exist.
28
+ */
23
29
  list(options = {}) {
24
- return this.#transport.send({ method: 'GET', path: '/api/v1/assets', query: { cursor: options.cursor, limit: options.limit } }, assetPage);
30
+ return this.#transport.send({ method: 'GET', path: '/api/v1/assets', query: { cursor: options.cursor, folder: options.folder, limit: options.limit, search: options.search } }, assetPage);
31
+ }
32
+ /**
33
+ * Uploads an image from a public URL: the server downloads it (PNG, JPEG,
34
+ * GIF or WebP, at most 5 MiB) and stores it with its size in pixels and a
35
+ * preview. Requires a `write` API key.
36
+ *
37
+ * @param url - The public `http` or `https` URL of the image.
38
+ * @throws BadRequestError when the URL is refused (e.g. a private address) or is not such an image.
39
+ * @throws NotFoundError when the folder does not exist.
40
+ */
41
+ importFromUrl(url, options = {}) {
42
+ const { description, folderId, name } = options;
43
+ return this.#transport.send({
44
+ body: { url, ...(description === undefined ? {} : { description }), ...(folderId === undefined ? {} : { folderId }), ...(name === undefined ? {} : { name }) },
45
+ method: 'POST',
46
+ path: '/api/v1/assets/import',
47
+ }, assetSchema);
48
+ }
49
+ /**
50
+ * Changes the description of an image, moves it to another folder, or both. Requires a `write` API key.
51
+ *
52
+ * @throws NotFoundError when the image or the folder does not exist.
53
+ */
54
+ update(assetId, changes) {
55
+ const { description, folderId } = changes;
56
+ return this.#transport.send({
57
+ body: { ...(description === undefined ? {} : { description }), ...(folderId === undefined ? {} : { folderId }) },
58
+ method: 'PATCH',
59
+ path: `/api/v1/assets/${pathId(assetId)}`,
60
+ }, assetSchema);
25
61
  }
26
62
  /**
27
63
  * Uploads an image: starts the upload, sends the file to the storage bucket
@@ -34,7 +70,8 @@ export class Assets {
34
70
  */
35
71
  async upload(file, options) {
36
72
  const sizeBytes = file instanceof Blob ? file.size : file.byteLength;
37
- const upload = await this.createUpload({ contentType: options.contentType, sizeBytes });
73
+ const name = options.name ?? (file instanceof File ? file.name : undefined);
74
+ const upload = await this.createUpload({ contentType: options.contentType, sizeBytes, ...(name === undefined ? {} : { name }) });
38
75
  await this.#transport.upload({ contentType: options.contentType, fields: upload.upload.fields, file, url: upload.upload.url });
39
76
  return this.confirm(upload.assetId);
40
77
  }
@@ -46,7 +83,7 @@ export class Assets {
46
83
  * {@link Assets.confirm}.
47
84
  */
48
85
  createUpload(options) {
49
- return this.#transport.send({ body: { contentType: options.contentType, sizeBytes: options.sizeBytes }, method: 'POST', path: '/api/v1/assets' }, assetUploadSchema);
86
+ return this.#transport.send({ body: { contentType: options.contentType, sizeBytes: options.sizeBytes, ...(options.name === undefined ? {} : { name: options.name }) }, method: 'POST', path: '/api/v1/assets' }, assetUploadSchema);
50
87
  }
51
88
  /**
52
89
  * Confirms an upload once the file is uploaded. Confirming twice is harmless. Requires a `write` API key.
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The `auditEvents` resource: read the workspace audit log.
3
+ *
4
+ * @module
5
+ */
6
+ import { type AuditEvent, type Page } from '../schemas.js';
7
+ import type { Transport } from '../transport.js';
8
+ import type { ListOptions } from './templates.js';
9
+ /**
10
+ * The audit log of the workspace: who did what, newest first. Requires an
11
+ * API key with the `audit` grant. In the cloud only the events within the
12
+ * audit history of the workspace owner's plan are listed.
13
+ */
14
+ export declare class AuditEvents {
15
+ #private;
16
+ /** @internal */
17
+ constructor(transport: Transport);
18
+ /** Lists one page of events, newest first. */
19
+ list(options?: ListOptions): Promise<Page<AuditEvent>>;
20
+ /**
21
+ * Iterates over every event, newest first, requesting the next page when
22
+ * the previous one is used up.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * for await (const event of templr.auditEvents.listAll({ limit: 100 })) console.log(event.action);
27
+ * ```
28
+ */
29
+ listAll(options?: Omit<ListOptions, 'cursor'>): AsyncGenerator<AuditEvent, void, undefined>;
30
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The `auditEvents` resource: read the workspace audit log.
3
+ *
4
+ * @module
5
+ */
6
+ import { auditEventSchema, pageSchema } from '../schemas.js';
7
+ const auditEventPage = pageSchema(auditEventSchema);
8
+ /**
9
+ * The audit log of the workspace: who did what, newest first. Requires an
10
+ * API key with the `audit` grant. In the cloud only the events within the
11
+ * audit history of the workspace owner's plan are listed.
12
+ */
13
+ export class AuditEvents {
14
+ #transport;
15
+ /** @internal */
16
+ constructor(transport) {
17
+ this.#transport = transport;
18
+ }
19
+ /** Lists one page of events, newest first. */
20
+ list(options = {}) {
21
+ return this.#transport.send({ method: 'GET', path: '/api/v1/audit-events', query: { cursor: options.cursor, limit: options.limit } }, auditEventPage);
22
+ }
23
+ /**
24
+ * Iterates over every event, newest first, requesting the next page when
25
+ * the previous one is used up.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * for await (const event of templr.auditEvents.listAll({ limit: 100 })) console.log(event.action);
30
+ * ```
31
+ */
32
+ async *listAll(options = {}) {
33
+ let cursor;
34
+ do {
35
+ const page = await this.list(cursor === undefined ? options : { ...options, cursor });
36
+ yield* page.items;
37
+ cursor = page.nextCursor ?? undefined;
38
+ } while (cursor !== undefined);
39
+ }
40
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The `payments` resource: read the payments of the subscription of the
3
+ * workspace owner.
4
+ *
5
+ * @module
6
+ */
7
+ import { type Page, type Payment } from '../schemas.js';
8
+ import type { Transport } from '../transport.js';
9
+ import type { ListOptions } from './templates.js';
10
+ /**
11
+ * The payments of the workspace owner's subscription, newest first, each
12
+ * with the link to its receipt in the app. Requires an API key with the
13
+ * `billing` grant, which only the workspace owner can give.
14
+ */
15
+ export declare class Payments {
16
+ #private;
17
+ /** @internal */
18
+ constructor(transport: Transport);
19
+ /** Lists one page of payments, newest first. */
20
+ list(options?: ListOptions): Promise<Page<Payment>>;
21
+ /**
22
+ * Iterates over every payment, newest first, requesting the next page when
23
+ * the previous one is used up.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * for await (const payment of templr.payments.listAll({ limit: 100 })) console.log(payment.status, payment.receiptUrl);
28
+ * ```
29
+ */
30
+ listAll(options?: Omit<ListOptions, 'cursor'>): AsyncGenerator<Payment, void, undefined>;
31
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The `payments` resource: read the payments of the subscription of the
3
+ * workspace owner.
4
+ *
5
+ * @module
6
+ */
7
+ import { pageSchema, paymentSchema } from '../schemas.js';
8
+ const paymentPage = pageSchema(paymentSchema);
9
+ /**
10
+ * The payments of the workspace owner's subscription, newest first, each
11
+ * with the link to its receipt in the app. Requires an API key with the
12
+ * `billing` grant, which only the workspace owner can give.
13
+ */
14
+ export class Payments {
15
+ #transport;
16
+ /** @internal */
17
+ constructor(transport) {
18
+ this.#transport = transport;
19
+ }
20
+ /** Lists one page of payments, newest first. */
21
+ list(options = {}) {
22
+ return this.#transport.send({ method: 'GET', path: '/api/v1/payments', query: { cursor: options.cursor, limit: options.limit } }, paymentPage);
23
+ }
24
+ /**
25
+ * Iterates over every payment, newest first, requesting the next page when
26
+ * the previous one is used up.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * for await (const payment of templr.payments.listAll({ limit: 100 })) console.log(payment.status, payment.receiptUrl);
31
+ * ```
32
+ */
33
+ async *listAll(options = {}) {
34
+ let cursor;
35
+ do {
36
+ const page = await this.list(cursor === undefined ? options : { ...options, cursor });
37
+ yield* page.items;
38
+ cursor = page.nextCursor ?? undefined;
39
+ } while (cursor !== undefined);
40
+ }
41
+ }
@@ -1,9 +1,9 @@
1
1
  /**
2
- * The `templates` resource: list, get and render templates, and manage their variables.
2
+ * The `templates` resource: create, update, list, get and render templates, and manage their variables.
3
3
  *
4
4
  * @module
5
5
  */
6
- import { type Page, type RenderedTemplate, type Template, type TemplateSummary, type TemplateVariable, type TemplateVersion, type TemplateVersionSummary } from '../schemas.js';
6
+ import { type JsonValue, type Page, type RenderedTemplate, type SavedTemplate, type Template, type TemplateSummary, type TemplateVariable, type TemplateVersion, type TemplateVersionSummary } from '../schemas.js';
7
7
  import { type Transport } from '../transport.js';
8
8
  /** Options of the list methods. */
9
9
  export interface ListOptions {
@@ -38,8 +38,32 @@ export interface UpdateVariableOptions {
38
38
  /** The new key: letters, digits and `_`, starting with a letter or `_`. */
39
39
  readonly key?: string;
40
40
  }
41
+ /** A new template. */
42
+ export interface CreateTemplateOptions {
43
+ /** The brand kit the template renders with, from the same workspace; omit it or pass `null` for the workspace default. */
44
+ readonly brandKitId?: string | null;
45
+ /**
46
+ * The document: TipTap JSON with a `doc` root that matches the
47
+ * `TemplateDocumentModel` schema of the OpenAPI document. The API checks it
48
+ * and answers 422 with every problem when it does not.
49
+ */
50
+ readonly document: JsonValue;
51
+ /** The name, from 1 to 200 characters. */
52
+ readonly name: string;
53
+ }
54
+ /** A change to the draft of a template; give at least one field. */
55
+ export interface UpdateTemplateOptions {
56
+ /** The brand kit the template renders with, from the same workspace; `null` for the workspace default. Omit it to keep the current one. */
57
+ readonly brandKitId?: string | null;
58
+ /** The new document, like {@link CreateTemplateOptions.document}. Omit it to keep the current one. */
59
+ readonly document?: JsonValue;
60
+ /** The new name. Omit it to keep the current one. */
61
+ readonly name?: string;
62
+ }
41
63
  /**
42
- * Templates of the workspace. Requires a `read` or `write` API key.
64
+ * Templates of the workspace. Reads require a `read` or `write` API key;
65
+ * {@link Templates.create}, {@link Templates.update} and
66
+ * {@link Templates.updateVariable} require a `write` key.
43
67
  *
44
68
  * By default the API serves the latest **published** version of each template;
45
69
  * the `*Draft*` methods and `draft: true` serve the draft editors work on.
@@ -48,6 +72,26 @@ export declare class Templates {
48
72
  #private;
49
73
  /** @internal */
50
74
  constructor(transport: Transport);
75
+ /**
76
+ * Creates a template as a draft: nothing is published until someone
77
+ * publishes it in the editor. Returns it with `editorUrl`, the link that
78
+ * opens it in the editor. Requires a `write` API key.
79
+ *
80
+ * @throws BadRequestError when the name is invalid or the brand kit is not in the workspace.
81
+ * @throws UnprocessableEntityError when the document does not match the document model; `issues` lists every problem.
82
+ * @throws APIError with status 402 (`quota_exceeded`) on Templr Cloud when the plan allows no more templates.
83
+ */
84
+ create(template: CreateTemplateOptions): Promise<SavedTemplate>;
85
+ /**
86
+ * Changes the name, the document, the brand kit or several of them in the
87
+ * draft of a template, like an autosave of the editor: published versions
88
+ * are not changed. Returns it with `editorUrl`. Requires a `write` API key.
89
+ *
90
+ * @throws BadRequestError when no field is given, the name is invalid or the brand kit is not in the workspace.
91
+ * @throws NotFoundError when the template does not exist.
92
+ * @throws UnprocessableEntityError when the document does not match the document model; `issues` lists every problem.
93
+ */
94
+ update(templateId: string, change: UpdateTemplateOptions): Promise<SavedTemplate>;
51
95
  /** Lists the published templates, each with its latest version, most recently published first (oldest first with `order: 'asc'`). */
52
96
  list(options?: ListTemplatesOptions): Promise<Page<TemplateVersionSummary>>;
53
97
  /** Lists every template with its draft, most recently updated first (oldest first with `order: 'asc'`). */
@@ -1,14 +1,16 @@
1
1
  /**
2
- * The `templates` resource: list, get and render templates, and manage their variables.
2
+ * The `templates` resource: create, update, list, get and render templates, and manage their variables.
3
3
  *
4
4
  * @module
5
5
  */
6
- import { pageSchema, renderedTemplateSchema, templateSchema, templateSummarySchema, templateVariableListSchema, templateVariableSchema, templateVersionSchema, templateVersionSummarySchema, } from '../schemas.js';
6
+ import { pageSchema, renderedTemplateSchema, savedTemplateSchema, templateSchema, templateSummarySchema, templateVariableListSchema, templateVariableSchema, templateVersionSchema, templateVersionSummarySchema, } from '../schemas.js';
7
7
  import { pathId } from '../transport.js';
8
8
  const versionPage = pageSchema(templateVersionSummarySchema);
9
9
  const draftPage = pageSchema(templateSummarySchema);
10
10
  /**
11
- * Templates of the workspace. Requires a `read` or `write` API key.
11
+ * Templates of the workspace. Reads require a `read` or `write` API key;
12
+ * {@link Templates.create}, {@link Templates.update} and
13
+ * {@link Templates.updateVariable} require a `write` key.
12
14
  *
13
15
  * By default the API serves the latest **published** version of each template;
14
16
  * the `*Draft*` methods and `draft: true` serve the draft editors work on.
@@ -19,6 +21,42 @@ export class Templates {
19
21
  constructor(transport) {
20
22
  this.#transport = transport;
21
23
  }
24
+ /**
25
+ * Creates a template as a draft: nothing is published until someone
26
+ * publishes it in the editor. Returns it with `editorUrl`, the link that
27
+ * opens it in the editor. Requires a `write` API key.
28
+ *
29
+ * @throws BadRequestError when the name is invalid or the brand kit is not in the workspace.
30
+ * @throws UnprocessableEntityError when the document does not match the document model; `issues` lists every problem.
31
+ * @throws APIError with status 402 (`quota_exceeded`) on Templr Cloud when the plan allows no more templates.
32
+ */
33
+ create(template) {
34
+ return this.#transport.send({
35
+ body: { ...(template.brandKitId === undefined ? {} : { brandKitId: template.brandKitId }), document: template.document, name: template.name },
36
+ method: 'POST',
37
+ path: '/api/v1/templates',
38
+ }, savedTemplateSchema);
39
+ }
40
+ /**
41
+ * Changes the name, the document, the brand kit or several of them in the
42
+ * draft of a template, like an autosave of the editor: published versions
43
+ * are not changed. Returns it with `editorUrl`. Requires a `write` API key.
44
+ *
45
+ * @throws BadRequestError when no field is given, the name is invalid or the brand kit is not in the workspace.
46
+ * @throws NotFoundError when the template does not exist.
47
+ * @throws UnprocessableEntityError when the document does not match the document model; `issues` lists every problem.
48
+ */
49
+ update(templateId, change) {
50
+ return this.#transport.send({
51
+ body: {
52
+ ...(change.brandKitId === undefined ? {} : { brandKitId: change.brandKitId }),
53
+ ...(change.document === undefined ? {} : { document: change.document }),
54
+ ...(change.name === undefined ? {} : { name: change.name }),
55
+ },
56
+ method: 'PATCH',
57
+ path: `/api/v1/templates/${pathId(templateId)}`,
58
+ }, savedTemplateSchema);
59
+ }
22
60
  /** Lists the published templates, each with its latest version, most recently published first (oldest first with `order: 'asc'`). */
23
61
  list(options = {}) {
24
62
  return this.#transport.send({ method: 'GET', path: '/api/v1/templates', query: { cursor: options.cursor, limit: options.limit, order: options.order } }, versionPage);
package/dist/schemas.d.ts CHANGED
@@ -46,8 +46,20 @@ export declare const templateSchema: z.ZodReadonly<z.ZodObject<{
46
46
  name: z.ZodString;
47
47
  updatedAt: z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>;
48
48
  workspaceId: z.ZodString;
49
+ brandKitId: z.ZodDefault<z.ZodNullable<z.ZodString>>;
49
50
  document: z.ZodType<TemplateDocument, unknown, z.core.$ZodTypeInternals<TemplateDocument, unknown>>;
50
51
  }, z.core.$strip>>;
52
+ /** A template created or updated through the API, with the link that opens it in the editor. */
53
+ export declare const savedTemplateSchema: z.ZodReadonly<z.ZodObject<{
54
+ createdAt: z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>;
55
+ id: z.ZodString;
56
+ name: z.ZodString;
57
+ updatedAt: z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>;
58
+ workspaceId: z.ZodString;
59
+ brandKitId: z.ZodDefault<z.ZodNullable<z.ZodString>>;
60
+ document: z.ZodType<TemplateDocument, unknown, z.core.$ZodTypeInternals<TemplateDocument, unknown>>;
61
+ editorUrl: z.ZodString;
62
+ }, z.core.$strip>>;
51
63
  /** A published version of a template, without its document. */
52
64
  export declare const templateVersionSummarySchema: z.ZodReadonly<z.ZodObject<{
53
65
  id: z.ZodString;
@@ -85,14 +97,66 @@ export declare const templateVariableListSchema: z.ZodReadonly<z.ZodObject<{
85
97
  }, z.core.$strip>>>>;
86
98
  }, z.core.$strip>>;
87
99
  /** An uploaded image with its public URL. */
88
- export declare const assetSchema: z.ZodReadonly<z.ZodObject<{
100
+ export declare const assetSchema: z.ZodReadonly<z.ZodPipe<z.ZodObject<{
89
101
  contentType: z.ZodString;
90
102
  createdAt: z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>;
103
+ description: z.ZodDefault<z.ZodNullable<z.ZodString>>;
104
+ folderId: z.ZodDefault<z.ZodNullable<z.ZodString>>;
105
+ height: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
91
106
  id: z.ZodString;
107
+ name: z.ZodDefault<z.ZodNullable<z.ZodString>>;
108
+ previewUrl: z.ZodOptional<z.ZodString>;
92
109
  sizeBytes: z.ZodNumber;
93
110
  url: z.ZodString;
111
+ width: z.ZodDefault<z.ZodNullable<z.ZodNumber>>;
112
+ workspaceId: z.ZodString;
113
+ }, z.core.$strip>, z.ZodTransform<{
114
+ contentType: string;
115
+ createdAt: Date;
116
+ description: string | null;
117
+ folderId: string | null;
118
+ height: number | null;
119
+ id: string;
120
+ name: string | null;
121
+ sizeBytes: number;
122
+ url: string;
123
+ width: number | null;
124
+ workspaceId: string;
125
+ previewUrl: string;
126
+ }, {
127
+ contentType: string;
128
+ createdAt: Date;
129
+ description: string | null;
130
+ folderId: string | null;
131
+ height: number | null;
132
+ id: string;
133
+ name: string | null;
134
+ previewUrl?: string | undefined;
135
+ sizeBytes: number;
136
+ url: string;
137
+ width: number | null;
138
+ workspaceId: string;
139
+ }>>>;
140
+ /** A folder of images. */
141
+ export declare const assetFolderSchema: z.ZodReadonly<z.ZodObject<{
142
+ assetCount: z.ZodNumber;
143
+ createdAt: z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>;
144
+ id: z.ZodString;
145
+ name: z.ZodString;
146
+ updatedAt: z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>;
94
147
  workspaceId: z.ZodString;
95
148
  }, z.core.$strip>>;
149
+ /** Every folder of the workspace. */
150
+ export declare const assetFolderListSchema: z.ZodReadonly<z.ZodObject<{
151
+ items: z.ZodReadonly<z.ZodArray<z.ZodReadonly<z.ZodObject<{
152
+ assetCount: z.ZodNumber;
153
+ createdAt: z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>;
154
+ id: z.ZodString;
155
+ name: z.ZodString;
156
+ updatedAt: z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>;
157
+ workspaceId: z.ZodString;
158
+ }, z.core.$strip>>>>;
159
+ }, z.core.$strip>>;
96
160
  /** Where and how to upload the file of a pending image upload. */
97
161
  export declare const presignedUploadSchema: z.ZodReadonly<z.ZodObject<{
98
162
  fields: z.ZodReadonly<z.ZodRecord<z.ZodString, z.ZodString>>;
@@ -124,6 +188,34 @@ export declare function pageSchema<Item extends z.ZodType>(item: Item): z.ZodRea
124
188
  nextCursor: z.ZodNullable<z.ZodString>;
125
189
  total: z.ZodNumber;
126
190
  }, z.core.$strip>>;
191
+ export declare const auditEventSchema: z.ZodReadonly<z.ZodObject<{
192
+ action: z.ZodString;
193
+ actor: z.ZodReadonly<z.ZodObject<{
194
+ id: z.ZodString;
195
+ type: z.ZodEnum<{
196
+ api_key: "api_key";
197
+ user: "user";
198
+ }>;
199
+ }, z.core.$strip>>;
200
+ createdAt: z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>;
201
+ id: z.ZodString;
202
+ metadata: z.ZodReadonly<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>>>;
203
+ resourceExists: z.ZodBoolean;
204
+ resourceId: z.ZodString;
205
+ resourceType: z.ZodString;
206
+ }, z.core.$strip>>;
207
+ export declare const paymentSchema: z.ZodReadonly<z.ZodObject<{
208
+ amount: z.ZodNumber;
209
+ amountRefunded: z.ZodNumber;
210
+ cardLastFourDigits: z.ZodNullable<z.ZodString>;
211
+ createdAt: z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>;
212
+ currency: z.ZodString;
213
+ id: z.ZodString;
214
+ paidAt: z.ZodNullable<z.ZodPipe<z.ZodISODateTime, z.ZodTransform<Date, string>>>;
215
+ paymentMethodId: z.ZodNullable<z.ZodString>;
216
+ receiptUrl: z.ZodNullable<z.ZodString>;
217
+ status: z.ZodString;
218
+ }, z.core.$strip>>;
127
219
  /** The body of every error response. */
128
220
  export declare const errorBodySchema: z.ZodObject<{
129
221
  error: z.ZodObject<{
@@ -145,6 +237,12 @@ export interface Page<Item> {
145
237
  export type TemplateSummary = z.output<typeof templateSummarySchema>;
146
238
  /** A template with its draft document. */
147
239
  export type Template = z.output<typeof templateSchema>;
240
+ /**
241
+ * A template created or updated through the API, with `editorUrl`: the page
242
+ * of the app that opens it in the editor (the editor shows the templates of
243
+ * the user's active workspace).
244
+ */
245
+ export type SavedTemplate = z.output<typeof savedTemplateSchema>;
148
246
  /** A published version of a template, without its document. */
149
247
  export type TemplateVersionSummary = z.output<typeof templateVersionSummarySchema>;
150
248
  /** A published version of a template, with its document. */
@@ -153,8 +251,36 @@ export type TemplateVersion = z.output<typeof templateVersionSchema>;
153
251
  export type TemplateVariable = z.output<typeof templateVariableSchema>;
154
252
  /** A rendered email: `html` and its plain `text` version. */
155
253
  export type RenderedTemplate = z.output<typeof renderedTemplateSchema>;
156
- /** An uploaded image with its public URL. */
254
+ /**
255
+ * An uploaded image: its public `url` and `previewUrl` (a WebP of at most 256
256
+ * pixels on its longest side; the image `url` for images uploaded before
257
+ * previews existed), its `folderId` (`null` at the root), its `description`
258
+ * (the alt text; `null` until someone writes one) and its `width` and
259
+ * `height` in pixels, read from the image by the server (`null` for images
260
+ * uploaded before they were read).
261
+ */
157
262
  export type Asset = z.output<typeof assetSchema>;
263
+ /** A folder of images, with how many images it holds (`assetCount`). */
264
+ export type AssetFolder = z.output<typeof assetFolderSchema>;
265
+ /**
266
+ * A recorded event of the workspace audit log: who did it (`actor`, a member
267
+ * by user id or an API key by key id), what happened (`action`, e.g.
268
+ * `template.published`), to which resource, and its non-secret details
269
+ * (`metadata`, which depend on the action). `resourceExists` tells whether a
270
+ * template or component still exists; it is always `false` for other resources.
271
+ */
272
+ export type AuditEvent = z.output<typeof auditEventSchema>;
273
+ /**
274
+ * A payment of the workspace owner's subscription: its `amount`, the
275
+ * `amountRefunded` (`0` when nothing was refunded) and the `currency` (an ISO
276
+ * 4217 code, e.g. `USD`); the card brand (`paymentMethodId`, e.g. `visa`) and
277
+ * its last four digits, when known; its `status` as Mercado Pago reports it
278
+ * (e.g. `approved`, `rejected`, `refunded`); when it was created and, once
279
+ * approved, paid (`paidAt`). `receiptUrl` opens the receipt in the app, where
280
+ * the workspace owner can print it as PDF; it is `null` when the payment has
281
+ * no receipt (only approved payments get one).
282
+ */
283
+ export type Payment = z.output<typeof paymentSchema>;
158
284
  /**
159
285
  * Where and how to upload the file of a pending image upload: send every
160
286
  * entry of `fields`, then the file as the last field, as `multipart/form-data`
package/dist/schemas.js CHANGED
@@ -34,8 +34,16 @@ const templateVersionSummaryShape = {
34
34
  };
35
35
  /** A template without its document (the draft editors work on). */
36
36
  export const templateSummarySchema = z.object(templateSummaryShape).readonly();
37
+ const templateShape = {
38
+ ...templateSummaryShape,
39
+ // Instances older than brand kits return no `brandKitId`.
40
+ brandKitId: z.string().nullable().default(null),
41
+ document: templateDocument,
42
+ };
37
43
  /** A template with its draft document. */
38
- export const templateSchema = z.object({ ...templateSummaryShape, document: templateDocument }).readonly();
44
+ export const templateSchema = z.object(templateShape).readonly();
45
+ /** A template created or updated through the API, with the link that opens it in the editor. */
46
+ export const savedTemplateSchema = z.object({ ...templateShape, editorUrl: z.string() }).readonly();
39
47
  /** A published version of a template, without its document. */
40
48
  export const templateVersionSummarySchema = z.object(templateVersionSummaryShape).readonly();
41
49
  /** A published version of a template, with its document. */
@@ -47,7 +55,29 @@ export const templateVariableSchema = z.object({ fallback: z.string().nullable()
47
55
  /** Every variable of a template, once per key, in document order. */
48
56
  export const templateVariableListSchema = z.object({ items: z.array(templateVariableSchema).readonly() }).readonly();
49
57
  /** An uploaded image with its public URL. */
50
- export const assetSchema = z.object({ contentType: z.string(), createdAt: timestamp, id: z.string(), sizeBytes: z.number().int(), url: z.string(), workspaceId: z.string() }).readonly();
58
+ export const assetSchema = z
59
+ .object({
60
+ contentType: z.string(),
61
+ createdAt: timestamp,
62
+ // Instances older than folders, descriptions, sizes in pixels or previews do not return them.
63
+ description: z.string().nullable().default(null),
64
+ folderId: z.string().nullable().default(null),
65
+ height: z.number().int().nullable().default(null),
66
+ id: z.string(),
67
+ // Instances older than the file name return no `name`.
68
+ name: z.string().nullable().default(null),
69
+ previewUrl: z.string().optional(),
70
+ sizeBytes: z.number().int(),
71
+ url: z.string(),
72
+ width: z.number().int().nullable().default(null),
73
+ workspaceId: z.string(),
74
+ })
75
+ .transform(asset => ({ ...asset, previewUrl: asset.previewUrl ?? asset.url }))
76
+ .readonly();
77
+ /** A folder of images. */
78
+ export const assetFolderSchema = z.object({ assetCount: z.number().int(), createdAt: timestamp, id: z.string(), name: z.string(), updatedAt: timestamp, workspaceId: z.string() }).readonly();
79
+ /** Every folder of the workspace. */
80
+ export const assetFolderListSchema = z.object({ items: z.array(assetFolderSchema).readonly() }).readonly();
51
81
  /** Where and how to upload the file of a pending image upload. */
52
82
  export const presignedUploadSchema = z.object({ fields: z.record(z.string(), z.string()).readonly(), url: z.string() }).readonly();
53
83
  /** A pending image upload. */
@@ -64,5 +94,31 @@ export const openApiDocumentSchema = z.record(z.string(), jsonValue).readonly();
64
94
  export function pageSchema(item) {
65
95
  return z.object({ items: z.array(item).readonly(), nextCursor: z.string().nullable(), total: z.number().int() }).readonly();
66
96
  }
97
+ export const auditEventSchema = z
98
+ .object({
99
+ action: z.string(),
100
+ actor: z.object({ id: z.string(), type: z.enum(['user', 'api_key']) }).readonly(),
101
+ createdAt: timestamp,
102
+ id: z.string(),
103
+ metadata: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()])).readonly(),
104
+ resourceExists: z.boolean(),
105
+ resourceId: z.string(),
106
+ resourceType: z.string(),
107
+ })
108
+ .readonly();
109
+ export const paymentSchema = z
110
+ .object({
111
+ amount: z.number(),
112
+ amountRefunded: z.number(),
113
+ cardLastFourDigits: z.string().nullable(),
114
+ createdAt: timestamp,
115
+ currency: z.string(),
116
+ id: z.string(),
117
+ paidAt: timestamp.nullable(),
118
+ paymentMethodId: z.string().nullable(),
119
+ receiptUrl: z.string().nullable(),
120
+ status: z.string(),
121
+ })
122
+ .readonly();
67
123
  /** The body of every error response. */
68
124
  export const errorBodySchema = z.object({ error: z.object({ code: z.string(), issues: z.array(z.string()), message: z.string() }) });
package/dist/transport.js CHANGED
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * @module
6
6
  */
7
- import { APIConnectionError, APIError, APITimeoutError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PayloadTooLargeError, PermissionDeniedError, RateLimitError, UnexpectedResponseError, UploadError, } from './errors.js';
7
+ import { APIConnectionError, APIError, APITimeoutError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PayloadTooLargeError, PermissionDeniedError, RateLimitError, UnexpectedResponseError, UnprocessableEntityError, UploadError, } from './errors.js';
8
8
  import { errorBodySchema } from './schemas.js';
9
9
  import { VERSION } from './version.js';
10
10
  /** The header that carries the workspace API key. */
@@ -68,6 +68,8 @@ export function errorFromResponse(response, text) {
68
68
  return new ConflictError(details);
69
69
  case 413:
70
70
  return new PayloadTooLargeError(details);
71
+ case 422:
72
+ return new UnprocessableEntityError(details);
71
73
  case 429:
72
74
  return new RateLimitError(details, retryAfter(response));
73
75
  default:
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The version of this SDK; kept equal to `package.json` by a test. */
2
- export declare const VERSION = "0.2.0";
2
+ export declare const VERSION = "0.4.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The version of this SDK; kept equal to `package.json` by a test. */
2
- export const VERSION = '0.2.0';
2
+ export const VERSION = '0.4.0';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@templr/sdk",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Official TypeScript SDK for the Templr REST API.",
5
5
  "keywords": ["templr", "email", "email-templates", "react-email", "sdk", "api-client"],
6
6
  "homepage": "https://github.com/SebastianUrdaneguiBisalaya/templr/tree/main/sdks/typescript#readme",