calmlens 0.5.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +51 -518
  3. package/bin/calmlens.js +15991 -1298
  4. package/bin/package.json +1 -0
  5. package/cjs/BrowserUpload-BT091eOB.d.ts +11 -0
  6. package/cjs/BrowserUpload-DRdjobfF.js +10 -0
  7. package/cjs/CalmLensAppClient-CV_K26Ce.d.ts +40 -0
  8. package/cjs/CalmLensAppClient-CkyH_fXH.js +89 -0
  9. package/cjs/CalmLensConnection-CX1A0Q4N.js +659 -0
  10. package/cjs/CalmLensServerClient-C1djppvN.js +645 -0
  11. package/cjs/CalmLensServerClient-JtP687a3.d.ts +235 -0
  12. package/cjs/CalmLensTypes-9Vt16pc7.d.ts +40400 -0
  13. package/cjs/Classification-94kSYWZw-CMnQKW13.d.ts +5873 -0
  14. package/cjs/CryptoUtils-B_x8lMIx-YBW1-bvL.js +42 -0
  15. package/cjs/FileIcons-Ob003MdS.js +175 -0
  16. package/cjs/Jurisdiction-FusEXb4U-zVs21tDv.js +91 -0
  17. package/cjs/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +67 -0
  18. package/cjs/ModerationContextLimits-nJtd4Tag.js +1311 -0
  19. package/cjs/ReactUpload-CAyCsyG6.d.ts +17 -0
  20. package/cjs/ReactUpload-DmBmtsbJ.js +54 -0
  21. package/cjs/TestTriggers-By07LR31-CmK0yTyR.d.ts +271 -0
  22. package/cjs/TestTriggers-DTc_iMJF-BjMPq4_3.js +1327 -0
  23. package/cjs/UploadController-0YTjjzXh.js +618 -0
  24. package/cjs/WebhookPayload-2aL31v0J.d.ts +352 -0
  25. package/cjs/app.d.ts +7 -0
  26. package/cjs/app.js +13 -0
  27. package/cjs/elements.d.ts +88 -0
  28. package/cjs/elements.js +555 -0
  29. package/cjs/file-icons.d.ts +67 -0
  30. package/cjs/file-icons.js +10 -0
  31. package/cjs/index-CI4BzN4W.d.ts +252 -0
  32. package/cjs/index.d.ts +6 -2741
  33. package/cjs/index.js +9 -1205
  34. package/cjs/react-native.d.ts +56 -0
  35. package/cjs/react-native.js +495 -0
  36. package/cjs/react.d.ts +30 -0
  37. package/cjs/react.js +370 -0
  38. package/cjs/server.d.ts +33 -0
  39. package/cjs/server.js +20 -0
  40. package/cjs/test-inputs.d.ts +2 -0
  41. package/cjs/test-inputs.js +10 -0
  42. package/cjs/testing.d.ts +309 -80
  43. package/cjs/testing.js +10443 -658
  44. package/cjs/ui-BG2kKWUq.js +583 -0
  45. package/cjs/ui-wIiMfqMB.d.ts +526 -0
  46. package/cjs/ui.d.ts +2 -0
  47. package/cjs/ui.js +27 -0
  48. package/cjs/vue.d.ts +490 -0
  49. package/cjs/vue.js +419 -0
  50. package/esm/BrowserUpload-BT091eOB.d.ts +11 -0
  51. package/esm/BrowserUpload-DRHcNM9a.js +5 -0
  52. package/esm/CalmLensAppClient-COK1Cxfp.js +84 -0
  53. package/esm/CalmLensAppClient-CV_K26Ce.d.ts +40 -0
  54. package/esm/CalmLensConnection-BLw8vC-6.js +582 -0
  55. package/esm/CalmLensServerClient-BwRJKhn7.js +586 -0
  56. package/esm/CalmLensServerClient-JtP687a3.d.ts +235 -0
  57. package/esm/CalmLensTypes-9Vt16pc7.d.ts +40400 -0
  58. package/esm/Classification-94kSYWZw-CMnQKW13.d.ts +5873 -0
  59. package/esm/CryptoUtils-B_x8lMIx-DhuWGzqn.js +25 -0
  60. package/esm/FileIcons-M6dzjFxd.js +128 -0
  61. package/esm/Jurisdiction-FusEXb4U-1ov6m5yE.js +46 -0
  62. package/esm/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +67 -0
  63. package/esm/ModerationContextLimits-Cv1qXWB9.js +1114 -0
  64. package/esm/ReactUpload-CAyCsyG6.d.ts +17 -0
  65. package/esm/ReactUpload-DooBhDOR.js +37 -0
  66. package/esm/TestTriggers-By07LR31-CmK0yTyR.d.ts +271 -0
  67. package/esm/TestTriggers-DTc_iMJF-HfB533Gx.js +1267 -0
  68. package/esm/UploadController-BDIL9GKO.js +589 -0
  69. package/esm/WebhookPayload-2aL31v0J.d.ts +352 -0
  70. package/esm/app.d.ts +7 -0
  71. package/esm/app.js +4 -0
  72. package/esm/elements.d.ts +88 -0
  73. package/esm/elements.js +528 -0
  74. package/esm/file-icons.d.ts +67 -0
  75. package/esm/file-icons.js +1 -0
  76. package/esm/index-CI4BzN4W.d.ts +252 -0
  77. package/esm/index.d.ts +6 -2741
  78. package/esm/index.js +1 -1196
  79. package/esm/react-native.d.ts +56 -0
  80. package/esm/react-native.js +467 -0
  81. package/esm/react.d.ts +30 -0
  82. package/esm/react.js +343 -0
  83. package/esm/server.d.ts +33 -0
  84. package/esm/server.js +4 -0
  85. package/esm/styles.css +147 -0
  86. package/esm/svelte/CalmLensMedia.svelte +134 -0
  87. package/esm/svelte/CalmLensUploader.svelte +175 -0
  88. package/esm/svelte/Icon.svelte +7 -0
  89. package/esm/svelte/index.d.ts +37 -0
  90. package/esm/svelte/index.js +6 -0
  91. package/esm/test-inputs.d.ts +2 -0
  92. package/esm/test-inputs.js +1 -0
  93. package/esm/testing.d.ts +309 -80
  94. package/esm/testing.js +10432 -657
  95. package/esm/ui-DdoweZQx.js +458 -0
  96. package/esm/ui-wIiMfqMB.d.ts +526 -0
  97. package/esm/ui.d.ts +2 -0
  98. package/esm/ui.js +3 -0
  99. package/esm/vue.d.ts +490 -0
  100. package/esm/vue.js +392 -0
  101. package/package.json +173 -34
  102. package/cjs/CalmLensTypes-DG_kHVqY.d.ts +0 -3521
  103. package/cjs/CalmLensUtils-0QaxbI3A.js +0 -551
  104. package/esm/CalmLensTypes-DG_kHVqY.d.ts +0 -3521
  105. package/esm/CalmLensUtils-BQEgxGWk.js +0 -410
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CalmLens
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.
package/README.md CHANGED
@@ -1,38 +1,44 @@
1
- > This package is the same as [`@calmlens/sdk`](https://www.npmjs.com/package/@calmlens/sdk), published as `calmlens` so `npx calmlens` runs the CLI without installing anything. In code, depend on `@calmlens/sdk`.
1
+ # CalmLens JavaScript SDK
2
2
 
3
- # @calmlens/sdk
4
-
5
- Official JavaScript/TypeScript SDK for CalmLens API
6
-
7
- CalmLens provides content moderation and classification for text, images, documents and websites, plus optional storage and CDN delivery. This SDK makes it easy to integrate CalmLens into your JavaScript/TypeScript applications.
3
+ The official JavaScript and TypeScript SDK for [CalmLens](https://calmlens.com): content moderation and classification for text, images, documents and websites, plus optional storage and CDN delivery.
8
4
 
9
5
  ## Installation
10
6
 
11
7
  ```bash
12
- npm install @calmlens/sdk
8
+ npm install calmlens
13
9
  ```
14
10
 
15
- Every public SDK operation accepts one options object. This keeps call sites stable as optional fields are added.
11
+ The same package is also published as `@calmlens/sdk`, at the same version. Import from the name you installed: `calmlens/server` with `calmlens`, or `@calmlens/sdk/server` with `@calmlens/sdk`.
12
+
13
+ The package has two clients, each with its own import:
14
+
15
+ | Import | Client | Runs | Authenticates with |
16
+ | ----------------- | ---------------------- | ------------------------------------------------------------------ | ---------------------------------------------------------------- |
17
+ | `calmlens/server` | `CalmLensServerClient` | On your server: Node.js 22 or later, Bun, Deno, Cloudflare Workers | A project API key |
18
+ | `calmlens/app` | `CalmLensAppClient` | In browsers and React Native apps | An upload preset, with an optional upload token from your server |
16
19
 
17
- ## Quick Start
20
+ API keys are secret, so `CalmLensServerClient` refuses to start in a web page or app. Upload from browsers and apps with `CalmLensAppClient`, and serve private content to them with signed URLs. The package ships ES modules and CommonJS with type declarations and loads no other packages at runtime.
21
+
22
+ ## Quick start
18
23
 
19
24
  Create an API key under **Developer → API Keys** in the CalmLens portal. The same page shows your **Project ID**. Keep both on your server.
20
25
 
21
26
  ```typescript
22
- import { CalmLensClient } from "@calmlens/sdk";
27
+ import { CalmLensServerClient } from "calmlens/server";
23
28
 
24
- const client = new CalmLensClient({
29
+ const client = new CalmLensServerClient({
25
30
  apiKey: process.env.CALMLENS_API_KEY!,
26
31
  projectId: process.env.CALMLENS_PROJECT_ID!,
27
32
  });
28
33
 
29
34
  // Text (comments, captions, bios): waits for the decision
30
- const comment = await client.text.moderate({ text: "Great photo!", externalId: "comment-42" });
35
+ const comment = await client.text.classify({ text: "Great photo!", externalId: "comment-42" });
31
36
 
32
- if (comment.status === "approved") {
33
- // publish it; if comment.report?.flagged is true, also queue it for review
37
+ const { status } = comment.classification.moderation;
38
+ if (status === "allowed" || status === "limited") {
39
+ // publish it; keep "limited" out of recommendations, trending and notifications
34
40
  } else {
35
- // "rejected": don't publish it
41
+ // "age-restricted": show it only behind your own age check; "blocked" or "purged": don't publish it
36
42
  }
37
43
 
38
44
  // Images and documents: queued, resolved by webhook or assets.retrieve()
@@ -41,517 +47,44 @@ const image = await client.assets.create({
41
47
  content: { data: file, type: "image/jpeg" },
42
48
  externalId: "post-7",
43
49
  });
44
- console.log(image.status); // "pending"
50
+ console.log(image.classification.status, image.classification.moderation.status); // "processing" "pending"
45
51
  ```
46
52
 
47
- | `status` | `report.flagged` | Meaning |
48
- | --- | --- | --- |
49
- | `approved` | `false` | Safe to show. |
50
- | `approved` | `true` | Show it, but your policy asked to be alerted. |
51
- | `rejected` | `true` | Your policy hid or purged it. Don't show it. |
52
- | `pending` | — | Still being classified. |
53
- | `error` | — | Processing failed. |
54
-
55
- See [How CalmLens works](https://calmlens.com/docs/how-it-works) and [Testing your integration](https://calmlens.com/docs/guides/testing) for test inputs that trigger rejections safely.
56
-
57
- ## API Reference
53
+ | `classification.status` | `classification.moderation.status` | Meaning |
54
+ | ------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------ |
55
+ | `completed` | `allowed` | Safe to show. |
56
+ | `completed` | `limited` | Delivered like `allowed`; reduce its reach, such as keeping it out of recommendations. |
57
+ | `completed` | `age-restricted` | Delivered only with `viewerClaims.ageConfirmed=true`. Show it only to age-checked viewers. |
58
+ | `completed` | `blocked` | Your policy blocked it; the CDN doesn't deliver it. Don't show it. |
59
+ | `completed` | `purged` | Your policy blocked it and deleted its content. Don't show it. |
60
+ | `pending` or `processing` | `pending` | Still being received or classified. |
61
+ | `failed` | `pending` | Processing failed; see `assets.retry`. |
58
62
 
59
- ### CalmLensClient
63
+ The latest applied review in `classification.moderation.manualReviews` takes precedence over the automated decision. Treat a status you don't recognise as not allowed. See [How CalmLens works](https://calmlens.com/docs/how-it-works).
60
64
 
61
- The main client class for interacting with the CalmLens API.
65
+ ## What you can do
62
66
 
63
- #### Constructor
67
+ - [Moderate text](https://calmlens.com/docs/sdk/javascript#text-moderation), including [replies in a conversation](https://calmlens.com/docs/guides/threaded-moderation), and [classify images, documents, audio, video and websites](https://calmlens.com/docs/guides/classifying-assets).
68
+ - [Read classification results](https://calmlens.com/docs/guides/classification-results) by category and qualifier, and [ask for the complete policy evidence](https://calmlens.com/docs/guides/classification-results#complete-policy-evidence) behind a decision.
69
+ - Send [multipart uploads](https://calmlens.com/docs/sdk/javascript/reference#multipart-uploads) for large files, from any [content payload](https://calmlens.com/docs/sdk/javascript/reference#content-payloads), with [safe retries and idempotency keys](https://calmlens.com/docs/sdk/javascript/reference#retries-and-idempotency).
70
+ - [Upload from browsers and apps](https://calmlens.com/docs/sdk/javascript/reference#app-client) through [upload presets](https://calmlens.com/docs/guides/upload-presets) and locally signed [upload tokens](https://calmlens.com/docs/sdk/javascript/reference#upload-tokens).
71
+ - Drop in the [upload widget and media component](https://calmlens.com/docs/widgets) for React, React Native, Vue, Svelte or custom elements.
72
+ - [Deliver assets from the CDN](https://calmlens.com/docs/guides/delivering-assets) with [lenses and transforms](https://calmlens.com/docs/guides/lenses), [signed URLs](https://calmlens.com/docs/guides/delivering-assets#signed-urls) and [viewer claims](https://calmlens.com/docs/api/cdn#viewer-claims).
73
+ - Record [reviewer decisions](https://calmlens.com/docs/guides/human-review), [retry failed processing](https://calmlens.com/docs/guides/asset-lifecycle#recover-from-processing-failure), and [organise assets in folders](https://calmlens.com/docs/sdk/javascript/reference#folders).
74
+ - [Verify and parse webhooks](https://calmlens.com/docs/sdk/javascript#webhooks), or poll the [events feed](https://calmlens.com/docs/sdk/javascript/reference#events-feed).
75
+ - [Handle errors](https://calmlens.com/docs/sdk/javascript/reference#errors) by stable code, and set [timeouts and request budgets](https://calmlens.com/docs/sdk/javascript/reference#request-budgets).
76
+ - Forward events to a local handler with the bundled [`calmlens` CLI](https://calmlens.com/docs/guides/local-development): `npx calmlens listen --forward-to http://localhost:3000/api/webhooks/calmlens`.
64
77
 
65
- ```typescript
66
- new CalmLensClient(options: CalmLensClientOptions)
67
- ```
68
-
69
- **Options:**
70
- - `apiKey` (string, required): Your CalmLens API key
71
- - `projectId` (string, required): Your CalmLens project ID
72
- - `baseUrl` (string, optional): API base URL (defaults to `https://api.calmlens.com/v1`)
73
- - `cdnBaseUrl` (string, optional): CDN base URL (defaults to `https://cdn.calmlens.com/v1`)
74
-
75
- #### Methods
76
-
77
- ##### assets.create(options)
78
-
79
- Queue an asset for processing and return the created asset immediately.
80
-
81
- ```typescript
82
- async assets.create(options: SubmitAssetOptions): Promise<Asset>
83
- ```
84
-
85
- **Options:**
86
- - `name` (string, required): Name of the asset
87
- - `content` (optional): Binary or plain-text content and its concrete MIME type, e.g. `{ plainText: "hello", type: "text/plain" }` or `{ data: file, type: file.type }`
88
- - `url` (string, optional): External URL to fetch instead of sending content
89
- - `part` (optional): First part of a sequential multipart upload
90
- - `description` (string, optional): Description of the asset
91
- - `processingOptions.keepContentAfterProcessing` (boolean, optional): Retain content after processing
92
- - `visibility` (string, optional): "public" or "private"
93
-
94
- **Example:**
95
- ```typescript
96
- // Submit from file content
97
- const asset = await client.assets.create({
98
- name: "document.pdf",
99
- content: {
100
- base64: "JVBERi0xLjQKJcfs...",
101
- type: "application/pdf",
102
- },
103
- description: "Important document",
104
- visibility: "private"
105
- });
106
-
107
- // Submit from URL
108
- const asset = await client.assets.create({
109
- name: "website-content",
110
- url: "https://example.com/page",
111
- description: "Web page to moderate"
112
- });
113
- ```
114
-
115
- ##### assets.moderate(options)
116
-
117
- Submit an asset and wait for classification to finish. Accepts the same options as `assets.create()` for text, images, documents, and URLs.
118
-
119
- ```typescript
120
- async assets.moderate(options: SubmitAssetOptions): Promise<Asset>
121
- ```
122
-
123
- ##### assets.retrieve(options)
124
-
125
- Retrieve details of a specific asset.
126
-
127
- ```typescript
128
- async assets.retrieve(options: { assetId: string }): Promise<Asset>
129
- ```
130
-
131
- **Example:**
132
- ```typescript
133
- const asset = await client.assets.retrieve({ assetId: "asset-uuid-here" });
134
- console.log(asset.status);
135
- console.log(asset.report); // Classification results
136
- ```
137
-
138
- ##### ensureLens(options)
139
-
140
- Create a project-scoped named lens, or update it safely. A lens can start at any positive version. Repeating the exact same version and definition is idempotent; any other update must use a version greater than the current one. A stale or conflicting version throws `lens/version-conflict`.
141
-
142
- ```typescript
143
- const lens = await client.ensureLens({
144
- identifier: "picmagic-normal",
145
- name: "PicMagic normal",
146
- type: "image",
147
- active: true,
148
- version: 1,
149
- transforms: [
150
- {
151
- type: "imageTransform",
152
- options: { fit: "scale-down", width: 1024, format: "png" },
153
- },
154
- ],
155
- });
156
-
157
- const image = await client.cdn.serve({
158
- assetIdentifier: assetId,
159
- lens: lens.identifier,
160
- });
161
- ```
162
-
163
- For several lenses, use `ensureLenses()` to perform all ensures in one request. Each lens keeps the same independent versioning rules.
164
-
165
- ```typescript
166
- const [normal, uhd] = await client.ensureLenses({ lenses: [normalLens, uhdLens] });
167
- ```
168
-
169
- The CDN uses named lenses with an `@` prefix in URLs, such as `/content/@picmagic-normal`. The SDK adds it automatically when you supply `lens`. Use `transform` for one-off direct transforms, for example `client.cdn.serve({ assetIdentifier: assetId, transform: "imageTransform[format=png,width=1024]" })`. Supply either `lens` or `transform`, not both. The resolved lens version is part of CalmLens's CDN cache and ETag identity, so changing a lens with the next version invalidates prior derived output.
170
-
171
- ##### assets.list(options)
172
-
173
- List assets in your project with pagination.
174
-
175
- ```typescript
176
- async assets.list(options: {
177
- pageIndex?: number;
178
- pageSize?: number;
179
- ordering?: Array<{ field: string; direction: "ASC" | "DESC" }>;
180
- filter?: string | null;
181
- }): Promise<{
182
- items: Asset[];
183
- total: number;
184
- hasMore: boolean;
185
- pageIndex: number;
186
- pageSize: number;
187
- }>
188
- ```
189
-
190
- **Example:**
191
- ```typescript
192
- const result = await client.assets.list({
193
- pageIndex: 0,
194
- pageSize: 20
195
- });
196
-
197
- console.log(`Found ${result.total} assets`);
198
- result.items.forEach(asset => {
199
- console.log(`${asset.name}: ${asset.status}`);
200
- });
201
- ```
202
-
203
- ##### assets.listChildren(options)
204
-
205
- List assets extracted from a website or multimedia document.
206
-
207
- ```typescript
208
- const children = await client.assets.listChildren({
209
- assetId: parentAssetId,
210
- pageIndex: 0,
211
- pageSize: 20,
212
- });
213
- ```
214
-
215
- ##### assets.createSignedUrl(options)
216
-
217
- Create a short-lived URL for private CDN content or previews.
218
-
219
- ```typescript
220
- const signed = await client.assets.createSignedUrl({
221
- assetId,
222
- resource: "preview",
223
- lens: "thumbnail",
224
- expiresInSeconds: 900,
225
- });
226
- ```
227
-
228
- ##### assets.move(options)
229
-
230
- Move an asset into a folder, or to the project root by passing `null`.
231
-
232
- ```typescript
233
- // Move asset to a folder
234
- await client.assets.move({
235
- assetId: "asset-uuid",
236
- folderId: "folder-uuid",
237
- });
238
-
239
- // Move asset to project root
240
- await client.assets.move({
241
- assetId: "asset-uuid",
242
- folderId: null,
243
- });
244
- ```
245
-
246
- ##### assets.retry(options)
247
-
248
- Process an asset that failed (status `error`) again. It returns to `pending` and is moderated like a
249
- new upload, so handle the result the same way (webhook or polling). Its content must still be stored:
250
- otherwise this throws `asset/content-unavailable`, and you need to upload it again.
251
-
252
- ```typescript
253
- const asset = await client.assets.retry({ assetId: "asset-uuid" });
254
- // asset.status === "pending"
255
- ```
256
-
257
- ##### folders.list()
258
-
259
- List all folders in the current project.
260
-
261
- ```typescript
262
- const folders = await client.folders.list();
263
- ```
264
-
265
- ##### folders.retrieve(options)
266
-
267
- Retrieve details of a specific folder by ID.
268
-
269
- ```typescript
270
- const folder = await client.folders.retrieve({ folderId: "folder-uuid" });
271
- ```
272
-
273
- ##### folders.create(options)
274
-
275
- Create a folder at the project root or nested under another folder.
276
-
277
- ```typescript
278
- // Create root folder
279
- const marketing = await client.folders.create({ name: "Marketing" });
280
-
281
- // Create nested subfolder
282
- const launch = await client.folders.create({
283
- name: "Launch 2026",
284
- parentId: marketing.id,
285
- });
286
- ```
287
-
288
- ##### folders.update(options)
289
-
290
- Rename an existing folder.
291
-
292
- ```typescript
293
- const updated = await client.folders.update({
294
- folderId: "folder-uuid",
295
- name: "New Name",
296
- });
297
- ```
298
-
299
- ##### folders.move(options)
300
-
301
- Move a folder under another folder, or to the project root by passing `parentId: null`. Moving a folder into itself or a descendant throws `folder/parent-cycle`.
302
-
303
- ```typescript
304
- // Move folder to another parent
305
- await client.folders.move({
306
- folderId: child.id,
307
- parentId: anotherParent.id,
308
- });
309
-
310
- // Move folder to project root
311
- await client.folders.move({
312
- folderId: child.id,
313
- parentId: null,
314
- });
315
- ```
316
-
317
- ##### folders.delete(options)
318
-
319
- Delete an empty folder. If the folder still contains assets or child folders, this throws `folder/not-empty`.
320
-
321
- ```typescript
322
- await client.folders.delete({ folderId: "folder-uuid" });
323
- ```
324
-
325
- ##### cdn.getAssetUrl(options) and cdn.serve(options)
326
-
327
- `getAssetUrl` constructs a CDN URL without fetching it. `serve` fetches the resource and sends the client's API key.
328
-
329
- ```typescript
330
- const url = client.cdn.getAssetUrl({
331
- assetIdentifier: assetId,
332
- resource: "content",
333
- lens: "thumbnail",
334
- });
335
-
336
- const response = await client.cdn.serve({
337
- assetIdentifier: assetId,
338
- resource: "content",
339
- });
340
- ```
341
-
342
- Private CDN content cannot be read directly with API keys. Use a short-lived signed URL for application clients.
343
-
344
- ##### Multipart upload flow
345
-
346
- Use `create` with `part` to start multipart uploads, and `uploadPart` for subsequent chunks. `partNumber` defaults to `1` and `isFinal` defaults to `false` when starting an upload.
347
-
348
- Image upload sizes use distinct direct and multipart paths:
349
-
350
- - Direct image uploads must be smaller than `10MB`.
351
- - Multipart image uploads must total between `10MB` and `20MB`, inclusive. CalmLens accumulates the uploaded parts and rejects a final image outside that range; callers do not need to provide a total-size field.
352
- - Retained multipart image originals remain in private backing storage. Public or authorized delivery and transformations use CalmLens CDN URLs.
353
-
354
- Each non-final multipart part must be at least `5MiB`; only the final part may be smaller. If you send base64, split the original bytes first, then base64-encode each part. Do not split one full base64 string into substrings.
355
-
356
- Payloads can be sent as `{ plainText: string }` (text content only), `{ base64: string }`, `{ uint8Array: number[] | Uint8Array }`, `{ buffer: Buffer | ArrayBuffer }`, `{ data: Blob | Response | ReadableStream }`. Use `{ data: file }` for `File` objects. Upload metadata is URL query data and the SDK sends the binary payload as the raw request body without constructing multipart form data. Multipart `ReadableStream` uploads must include the exact `sizeInBytes` so CalmLens can stream each part without buffering it.
357
-
358
- Use a concrete asset MIME type such as `image/png`, `application/pdf`, or `text/plain`. The SDK rejects ambiguous/container request MIME types such as `application/octet-stream` and `multipart/*`.
359
-
360
- **Example (queued finalization):**
361
- ```typescript
362
- const uploading = await client.assets.create({
363
- name: "large-image.png",
364
- part: {
365
- uint8Array: firstPartBytes,
366
- type: "image/png"
367
- }
368
- });
369
-
370
- await client.assets.uploadPart({
371
- assetId: uploading.id,
372
- part: {
373
- base64: secondPartBase64,
374
- partNumber: 2,
375
- },
376
- });
377
-
378
- const completed = await client.assets.uploadPart({
379
- assetId: uploading.id,
380
- part: {
381
- base64: finalPartBase64,
382
- partNumber: 3,
383
- isFinal: true,
384
- },
385
- });
386
- ```
387
-
388
- **Example (single-call synchronous analysis):**
389
- ```typescript
390
- const analyzed = await client.assets.moderate({
391
- name: "large-image.png",
392
- part: {
393
- base64: finalPartBase64,
394
- type: "image/png",
395
- isFinal: true
396
- }
397
- });
398
- console.log(analyzed.status);
399
- ```
400
-
401
- #### Static Methods
402
-
403
- ##### verifyWebhookSignature(options)
404
-
405
- Verify that a webhook delivery came from CalmLens and is fresh. Also exported as a standalone `verifyWebhookSignature` function.
406
-
407
- ```typescript
408
- static async verifyWebhookSignature(options: {
409
- payload: string | object; // raw request body (pass the string, not parsed JSON)
410
- signature: string | null | undefined; // x-calmlens-signature header
411
- timestamp: string | number | null | undefined; // x-calmlens-timestamp header
412
- secret: string;
413
- toleranceSeconds?: number; // default 300
414
- now?: Date | number; // default Date.now(), for tests
415
- }): Promise<boolean>
416
- ```
417
-
418
- It returns `true` only when the `x-calmlens-signature` header contains a `v1=` HMAC-SHA256 of `"<timestamp>.<raw body>"` (one match in a comma-separated list is enough) and the timestamp is within `toleranceSeconds` of now.
419
-
420
- **Example:**
421
- ```typescript
422
- // In your webhook handler (Fetch API Request)
423
- const payload = await request.text();
424
- const isValid = await CalmLensClient.verifyWebhookSignature({
425
- payload,
426
- signature: request.headers.get('x-calmlens-signature'),
427
- timestamp: request.headers.get('x-calmlens-timestamp'),
428
- secret: WEBHOOK_SECRET,
429
- });
430
-
431
- if (!isValid) {
432
- return new Response('Unauthorized', { status: 401 });
433
- }
434
- const event: WebhookEventPayload = JSON.parse(payload);
435
- ```
436
-
437
- ## Asset Types
438
-
439
- Assets can be of the following types:
440
- - `image` - Images (JPEG, PNG, GIF, WebP, etc.)
441
- - `video` - Video files (MP4, WebM, etc.)
442
- - `audio` - Audio files (MP3, WAV, etc.)
443
- - `plaintext-document` - Plain-text formats such as TXT, JSON, CSV, and YAML
444
- - `multimedia-document` - Documents such as PDF, DOCX, DOC, RTF, and ODT
445
- - `website` - Web pages and URLs
446
- - `file` - Other supported binary files
447
-
448
- ## Asset Status
449
-
450
- Assets progress through these statuses:
451
- - `uploading` - Multipart upload is accepting more parts
452
- - `pending` - Asset is being processed
453
- - `approved` - Processing completed and delivery is allowed; an `alert` action can still leave `report.flagged` set to `true`
454
- - `rejected` - A hide, purge, child-asset, or manual rejection decision was applied
455
- - `error` - Processing failed
456
-
457
- ## Moderation Reports
458
-
459
- Completed reports always contain the six parent categories: `sexual`, `violence`, `self-harm`, `harassment`, `hate`, and `criminal-activity`. Category-specific detail is nested under `qualifiers`, for example `violence.qualifiers.graphic`. Reports have no `subcategories` field or dedicated minor-safety placeholder. Retired generic qualifier IDs are rejected.
460
-
461
- Always narrow on a category's `status` before reading `score`. An `evaluated` or `partial` result includes `score` and `likelihood`; a `not-evaluated` result includes a reason and represents unknown coverage, not a safe zero score.
462
-
463
- ```typescript
464
- const violence = asset.report?.categories.violence;
465
- if (violence?.status === 'evaluated' || violence?.status === 'partial') {
466
- console.log(violence.score);
467
- }
468
- ```
469
-
470
- See the [moderation report guide](https://calmlens.com/docs/guides/moderation-reports) for aggregation, provider coverage, OCR merging, and policy actions. General Sexual Content moderation does not estimate age or provide dedicated CSAM detection.
471
-
472
- ## Asset Visibility
473
-
474
- - `public` - Retained content can be requested directly from the CDN
475
- - `private` - Retained content requires a signed URL or an authenticated owner session
476
-
477
- ## Error Handling
478
-
479
- The SDK throws errors for common issues:
480
-
481
- ```typescript
482
- try {
483
- const asset = await client.assets.create({
484
- name: "test.jpg",
485
- // Missing required content, URL, or multipart part
486
- });
487
- } catch (error) {
488
- console.error(error.message); // "Either file content, URL, or multipart part is required"
489
- }
490
- ```
491
-
492
- Public API failures are normalized to `CalmLensError`. Use its stable `code` property for control flow and `details` for diagnostics.
78
+ Every public SDK operation accepts one options object, so call sites stay stable as optional fields are added. The [SDK reference](https://calmlens.com/docs/sdk/javascript/reference) lists every option and method.
493
79
 
494
80
  ## Testing
495
81
 
496
- `@calmlens/sdk/testing` exports a matching object-parameter `MockCalmLensClient`, in-memory storage implementations, and mock API key helpers for local unit testing without network requests.
497
-
498
- The main `@calmlens/sdk` entry point does not load or export testing helpers to keep production bundles minimal. Keep `/testing` imports in test files.
499
-
500
- ```typescript
501
- import { MockCalmLensClient, createMockApiKey } from "@calmlens/sdk/testing";
502
-
503
- const client = new MockCalmLensClient({
504
- apiKey: createMockApiKey(),
505
- projectId: crypto.randomUUID(),
506
- });
507
- ```
508
-
509
- For configuration options (`mockOptions`), deterministic timestamps and IDs, storage inspection, and testing recipes, see the [JavaScript SDK Testing Guide](https://calmlens.com/docs/sdk/javascript#testing).
510
-
511
- ## Webhooks
512
-
513
- A `webhook` connector POSTs each event to your URL as JSON:
514
-
515
- ```json
516
- {
517
- "id": "…",
518
- "type": "asset.flagged",
519
- "createdAt": 1760000000000,
520
- "projectId": "…",
521
- "data": { "severity": "high", "title": "…", "description": null, "assetId": "…", "asset": null, "metadata": null }
522
- }
523
- ```
524
-
525
- Each delivery has these headers:
526
-
527
- | Header | Value |
528
- |---|---|
529
- | `x-calmlens-delivery` | Delivery ID (the same across retries) |
530
- | `x-calmlens-timestamp` | Unix time in seconds when the delivery was signed |
531
- | `x-calmlens-signature` | `v1=<lowercase hex HMAC-SHA256(secret, "<timestamp>.<raw body>")>` |
532
-
533
- Verify the exact raw request body with `verifyWebhookSignature` before parsing it; re-serializing parsed JSON can change the signed bytes. Deliveries more than 5 minutes old (or ahead of your clock) are rejected to prevent replays. The body type is exported as `WebhookEventPayload`; narrow it on `type` to get that event type's typed `data.facts` (`EventType` and `EventFacts<Type>` are exported too, and [the webhooks guide](https://calmlens.com/docs/guides/webhooks#event-types) lists every type). The header names are exported as `WEBHOOK_SIGNATURE_HEADER`, `WEBHOOK_TIMESTAMP_HEADER` and `WEBHOOK_DELIVERY_HEADER`.
534
-
535
- ## Command-line tool
536
-
537
- The SDK installs a `calmlens` command. Webhook connectors must use public HTTPS URLs, so during development use it to forward events to a local handler instead. Each event is sent with the same body, headers and signature as a real delivery:
538
-
539
- ```bash
540
- npx calmlens listen --forward-to http://localhost:3000/api/webhooks/calmlens --env-file .env.local
541
- ```
542
-
543
- The CLI reads `CALMLENS_API_KEY`, `CALMLENS_PROJECT_ID` and `CALMLENS_WEBHOOK_SECRET` from the environment or `--env-file`; without a secret it prints a generated one for your app. `npx calmlens trigger [harassment|hate|criminal-activity|clean]` moderates a harmless test input so events appear (one upload each). Run `npx calmlens --help` for all options. To install the command globally, use `npm install -g calmlens`: the same package, published under a shorter name.
544
-
545
- The same feed is available in code: `client.events.list({ after, limit })` returns events oldest first with a `cursor` to pass back.
546
-
547
- ## Releasing
548
-
549
- Stable releases are published automatically from `main` when packed SDK contents differ from npm `latest` and an SDK Changeset is present. Contributors must run `bun run changeset` to choose the release type and write release notes. CI updates and commits this package's `CHANGELOG.md` automatically. See the repository's [.changeset release guide](../../.changeset/README.md).
550
-
551
- ### Request budgets and errors
552
-
553
- Set `timeoutMs` (default 120000) or `signal` on the client. Use `client.withRequestOptions({ signal, timeoutMs: 30000 })` to scope them to an operation without changing the original client. Multipart state is shared between scoped clients. Deadlines include response-body reads; authenticated default REST, upload and CDN requests reject redirects. Custom non-Fetch backends own their redirect/cancellation policies.
82
+ `calmlens/testing` runs the real clients against an in-memory CalmLens API and CDN, with moderation outcomes, recorded requests, injected failures and signed webhook deliveries. See [JavaScript testing](https://calmlens.com/docs/sdk/javascript/testing).
554
83
 
555
- `CalmLensError` exposes `code`, optional HTTP `status`, `details` and native `cause`. Transport failures use `sdk/transport-error`, deadlines `sdk/timeout`, cancellation `sdk/cancelled`, malformed successful uploads `sdk/invalid-response`, and unstructured HTTP failures `sdk/http-error`. API error codes/messages are preserved. Core model types (`Asset`, `Folder`, `Lens`, `AssetPage`, `EventsPage`, `ClassificationReport`) and request types are exported from the package root.
84
+ ## Links
556
85
 
557
- `text.moderate` is a convenience wrapper around asset moderation: it supplies `text/plain` content and defaults the asset name to `text`. `assets.create` queues processing; `assets.moderate` waits for classification. The old asset analyze method is removed.
86
+ - [Documentation](https://calmlens.com/docs/sdk/javascript)
87
+ - [SDK reference](https://calmlens.com/docs/sdk/javascript/reference)
88
+ - [HTTP API reference](https://calmlens.com/docs/api)
89
+ - [Changelog](https://github.com/CalmLens/sdks/blob/main/javascript/CHANGELOG.md)
90
+ - [License](https://github.com/CalmLens/sdks/blob/main/javascript/LICENSE)