calmlens 0.0.0-stage → 0.2.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.
package/README.md CHANGED
@@ -1,3 +1,524 @@
1
- # Temporary Holding Version
1
+ > This package is the same as [`@calmlens/js-sdk`](https://www.npmjs.com/package/@calmlens/js-sdk), published as `calmlens` so `npx calmlens` runs the CLI without installing anything. In code, depend on `@calmlens/js-sdk`.
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @calmlens/js-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.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @calmlens/js-sdk
13
+ ```
14
+
15
+ Every public SDK operation accepts one options object. This keeps call sites stable as optional fields are added.
16
+
17
+ ## Quick Start
18
+
19
+ 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
+
21
+ ```typescript
22
+ import { CalmLensClient } from "@calmlens/js-sdk";
23
+
24
+ const client = new CalmLensClient({
25
+ apiKey: process.env.CALMLENS_API_KEY!,
26
+ projectId: process.env.CALMLENS_PROJECT_ID!,
27
+ });
28
+
29
+ // Text (comments, captions, bios): waits for the decision
30
+ const comment = await client.text.moderate({
31
+ text: "Great photo!",
32
+ externalId: "comment-42", // your own ID
33
+ });
34
+
35
+ if (comment.status === "approved") {
36
+ // publish it; if comment.report?.flagged is true, also queue it for review
37
+ } else {
38
+ // "rejected": don't publish it
39
+ }
40
+
41
+ // Images and documents: queued, resolved by webhook or assets.retrieve()
42
+ const image = await client.assets.create({
43
+ name: "photo.jpg",
44
+ content: { data: file, type: "image/jpeg" },
45
+ externalId: "post-7",
46
+ });
47
+ console.log(image.status); // "pending"
48
+ ```
49
+
50
+ | `status` | `report.flagged` | Meaning |
51
+ | --- | --- | --- |
52
+ | `approved` | `false` | Safe to show. |
53
+ | `approved` | `true` | Show it, but your policy asked to be alerted. |
54
+ | `rejected` | `true` | Your policy hid or purged it. Don't show it. |
55
+ | `pending` | — | Still being classified. |
56
+ | `error` | — | Processing failed. |
57
+
58
+ 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.
59
+
60
+ ## API Reference
61
+
62
+ ### CalmLensClient
63
+
64
+ The main client class for interacting with the CalmLens API.
65
+
66
+ #### Constructor
67
+
68
+ ```typescript
69
+ new CalmLensClient(options: CalmLensClientOptions)
70
+ ```
71
+
72
+ **Options:**
73
+ - `apiKey` (string, required): Your CalmLens API key
74
+ - `projectId` (string, required): Your CalmLens project ID
75
+ - `baseUrl` (string, optional): API base URL (defaults to `https://api.calmlens.com/v1`)
76
+ - `cdnBaseUrl` (string, optional): CDN base URL (defaults to `https://cdn.calmlens.com/v1`)
77
+
78
+ #### Methods
79
+
80
+ ##### text.moderate(options)
81
+
82
+ Moderate a comment, caption, bio or message and wait for the decision.
83
+
84
+ ```typescript
85
+ async text.moderate(options: ModerateTextOptions): Promise<Asset>
86
+ ```
87
+
88
+ **Options:**
89
+ - `text` (string, required): The text to moderate
90
+ - `name` (string, optional): Asset name shown in the portal. Defaults to `"text"`
91
+ - `externalId`, `metadata`, `folderId`, `processingOptions` (optional): As for `assets.create`
92
+
93
+ This is shorthand for `assets.analyze` with `content: { plainText: text, type: "text/plain" }`.
94
+
95
+ ##### assets.create(options)
96
+
97
+ Queue an asset for processing and return the created asset immediately.
98
+
99
+ ```typescript
100
+ async assets.create(options: SubmitAssetOptions): Promise<Asset>
101
+ ```
102
+
103
+ **Options:**
104
+ - `name` (string, required): Name of the asset
105
+ - `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 }`
106
+ - `url` (string, optional): External URL to fetch instead of sending content
107
+ - `part` (optional): First part of a sequential multipart upload
108
+ - `description` (string, optional): Description of the asset
109
+ - `processingOptions.keepContentAfterProcessing` (boolean, optional): Retain content after processing
110
+ - `visibility` (string, optional): "public" or "private"
111
+
112
+ **Example:**
113
+ ```typescript
114
+ // Submit from file content
115
+ const asset = await client.assets.create({
116
+ name: "document.pdf",
117
+ content: {
118
+ base64: "JVBERi0xLjQKJcfs...",
119
+ type: "application/pdf",
120
+ },
121
+ description: "Important document",
122
+ visibility: "private"
123
+ });
124
+
125
+ // Submit from URL
126
+ const asset = await client.assets.create({
127
+ name: "website-content",
128
+ url: "https://example.com/page",
129
+ description: "Web page to analyze"
130
+ });
131
+ ```
132
+
133
+ Use `client.assets.analyze(options)` with the same options when the request should wait for classification to finish instead of queueing it.
134
+
135
+ ##### assets.retrieve(options)
136
+
137
+ Retrieve details of a specific asset.
138
+
139
+ ```typescript
140
+ async assets.retrieve(options: { assetId: string }): Promise<Asset>
141
+ ```
142
+
143
+ **Example:**
144
+ ```typescript
145
+ const asset = await client.assets.retrieve({ assetId: "asset-uuid-here" });
146
+ console.log(asset.status);
147
+ console.log(asset.report); // Classification results
148
+ ```
149
+
150
+ ##### ensureLens(options)
151
+
152
+ 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`.
153
+
154
+ ```typescript
155
+ const lens = await client.ensureLens({
156
+ identifier: "picmagic-normal",
157
+ name: "PicMagic normal",
158
+ type: "image",
159
+ active: true,
160
+ version: 1,
161
+ transforms: [
162
+ {
163
+ type: "imageTransform",
164
+ options: { fit: "scale-down", width: 1024, format: "png" },
165
+ },
166
+ ],
167
+ });
168
+
169
+ const image = await client.cdn.serve({
170
+ assetIdentifier: assetId,
171
+ lens: lens.identifier,
172
+ });
173
+ ```
174
+
175
+ For several lenses, use `ensureLenses()` to perform all ensures in one request. Each lens keeps the same independent versioning rules.
176
+
177
+ ```typescript
178
+ const [normal, uhd] = await client.ensureLenses({ lenses: [normalLens, uhdLens] });
179
+ ```
180
+
181
+ 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.
182
+
183
+ ##### assets.list(options)
184
+
185
+ List assets in your project with pagination.
186
+
187
+ ```typescript
188
+ async assets.list(options: {
189
+ pageIndex?: number;
190
+ pageSize?: number;
191
+ ordering?: Array<{ field: string; direction: "ASC" | "DESC" }>;
192
+ filter?: string | null;
193
+ }): Promise<{
194
+ items: Asset[];
195
+ total: number;
196
+ hasMore: boolean;
197
+ pageIndex: number;
198
+ pageSize: number;
199
+ }>
200
+ ```
201
+
202
+ **Example:**
203
+ ```typescript
204
+ const result = await client.assets.list({
205
+ pageIndex: 0,
206
+ pageSize: 20
207
+ });
208
+
209
+ console.log(`Found ${result.total} assets`);
210
+ result.items.forEach(asset => {
211
+ console.log(`${asset.name}: ${asset.status}`);
212
+ });
213
+ ```
214
+
215
+ ##### assets.listChildren(options)
216
+
217
+ List assets extracted from a website or multimedia document.
218
+
219
+ ```typescript
220
+ const children = await client.assets.listChildren({
221
+ assetId: parentAssetId,
222
+ pageIndex: 0,
223
+ pageSize: 20,
224
+ });
225
+ ```
226
+
227
+ ##### assets.createSignedUrl(options)
228
+
229
+ Create a short-lived URL for private CDN content or previews.
230
+
231
+ ```typescript
232
+ const signed = await client.assets.createSignedUrl({
233
+ assetId,
234
+ resource: "preview",
235
+ lens: "thumbnail",
236
+ expiresInSeconds: 900,
237
+ });
238
+ ```
239
+
240
+ ##### assets.move(options)
241
+
242
+ Move an asset into a folder, or to the project root by passing `null`.
243
+
244
+ ```typescript
245
+ // Move asset to a folder
246
+ await client.assets.move({
247
+ assetId: "asset-uuid",
248
+ folderId: "folder-uuid",
249
+ });
250
+
251
+ // Move asset to project root
252
+ await client.assets.move({
253
+ assetId: "asset-uuid",
254
+ folderId: null,
255
+ });
256
+ ```
257
+
258
+ ##### folders.list()
259
+
260
+ List all folders in the current project.
261
+
262
+ ```typescript
263
+ const folders = await client.folders.list();
264
+ ```
265
+
266
+ ##### folders.retrieve(options)
267
+
268
+ Retrieve details of a specific folder by ID.
269
+
270
+ ```typescript
271
+ const folder = await client.folders.retrieve({ folderId: "folder-uuid" });
272
+ ```
273
+
274
+ ##### folders.create(options)
275
+
276
+ Create a folder at the project root or nested under another folder.
277
+
278
+ ```typescript
279
+ // Create root folder
280
+ const marketing = await client.folders.create({ name: "Marketing" });
281
+
282
+ // Create nested subfolder
283
+ const launch = await client.folders.create({
284
+ name: "Launch 2026",
285
+ parentId: marketing.id,
286
+ });
287
+ ```
288
+
289
+ ##### folders.update(options)
290
+
291
+ Rename an existing folder.
292
+
293
+ ```typescript
294
+ const updated = await client.folders.update({
295
+ folderId: "folder-uuid",
296
+ name: "New Name",
297
+ });
298
+ ```
299
+
300
+ ##### folders.move(options)
301
+
302
+ 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`.
303
+
304
+ ```typescript
305
+ // Move folder to another parent
306
+ await client.folders.move({
307
+ folderId: child.id,
308
+ parentId: anotherParent.id,
309
+ });
310
+
311
+ // Move folder to project root
312
+ await client.folders.move({
313
+ folderId: child.id,
314
+ parentId: null,
315
+ });
316
+ ```
317
+
318
+ ##### folders.delete(options)
319
+
320
+ Delete an empty folder. If the folder still contains assets or child folders, this throws `folder/not-empty`.
321
+
322
+ ```typescript
323
+ await client.folders.delete({ folderId: "folder-uuid" });
324
+ ```
325
+
326
+ ##### cdn.getAssetUrl(options) and cdn.serve(options)
327
+
328
+ `getAssetUrl` constructs a CDN URL without fetching it. `serve` fetches the resource and sends the client's API key.
329
+
330
+ ```typescript
331
+ const url = client.cdn.getAssetUrl({
332
+ assetIdentifier: assetId,
333
+ resource: "content",
334
+ lens: "thumbnail",
335
+ });
336
+
337
+ const response = await client.cdn.serve({
338
+ assetIdentifier: assetId,
339
+ resource: "content",
340
+ });
341
+ ```
342
+
343
+ Private CDN content cannot be read directly with API keys. Use a short-lived signed URL for application clients.
344
+
345
+ ##### Multipart upload flow
346
+
347
+ 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.
348
+
349
+ Image upload sizes use distinct direct and multipart paths:
350
+
351
+ - Direct image uploads must be smaller than `10MB`.
352
+ - 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.
353
+ - Retained multipart image originals remain in private backing storage. Public or authorized delivery and transformations use CalmLens CDN URLs.
354
+
355
+ 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.
356
+
357
+ 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.
358
+
359
+ 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/*`.
360
+
361
+ **Example (queued finalization):**
362
+ ```typescript
363
+ const uploading = await client.assets.create({
364
+ name: "large-image.png",
365
+ part: {
366
+ uint8Array: firstPartBytes,
367
+ type: "image/png"
368
+ }
369
+ });
370
+
371
+ await client.assets.uploadPart({
372
+ assetId: uploading.id,
373
+ part: {
374
+ base64: secondPartBase64,
375
+ partNumber: 2,
376
+ },
377
+ });
378
+
379
+ const completed = await client.assets.uploadPart({
380
+ assetId: uploading.id,
381
+ part: {
382
+ base64: finalPartBase64,
383
+ partNumber: 3,
384
+ isFinal: true,
385
+ },
386
+ });
387
+ ```
388
+
389
+ **Example (single-call synchronous analysis):**
390
+ ```typescript
391
+ const analyzed = await client.assets.analyze({
392
+ name: "large-image.png",
393
+ part: {
394
+ base64: finalPartBase64,
395
+ type: "image/png",
396
+ isFinal: true
397
+ }
398
+ });
399
+ console.log(analyzed.status);
400
+ ```
401
+
402
+ #### Static Methods
403
+
404
+ ##### verifyWebhookSignature(options)
405
+
406
+ Verify webhook signatures to ensure authenticity.
407
+
408
+ ```typescript
409
+ static async verifyWebhookSignature(options: {
410
+ payload: string | object;
411
+ signatureHex: string;
412
+ secret: string;
413
+ }): Promise<boolean>
414
+ ```
415
+
416
+ **Example:**
417
+ ```typescript
418
+ // In your webhook handler
419
+ const signature = req.headers['x-calmlens-signature'];
420
+ const payload = req.body;
421
+ const isValid = await CalmLensClient.verifyWebhookSignature({
422
+ payload,
423
+ signatureHex: signature,
424
+ secret: WEBHOOK_SECRET,
425
+ });
426
+
427
+ if (!isValid) {
428
+ return res.status(401).send('Unauthorized');
429
+ }
430
+ ```
431
+
432
+ ## Asset Types
433
+
434
+ Assets can be of the following types:
435
+ - `image` - Images (JPEG, PNG, GIF, WebP, etc.)
436
+ - `video` - Video files (MP4, WebM, etc.)
437
+ - `audio` - Audio files (MP3, WAV, etc.)
438
+ - `plaintext-document` - Plain-text formats such as TXT, JSON, CSV, and YAML
439
+ - `multimedia-document` - Documents such as PDF, DOCX, DOC, RTF, and ODT
440
+ - `website` - Web pages and URLs
441
+ - `file` - Other supported binary files
442
+
443
+ ## Asset Status
444
+
445
+ Assets progress through these statuses:
446
+ - `uploading` - Multipart upload is accepting more parts
447
+ - `pending` - Asset is being processed
448
+ - `approved` - Processing completed and delivery is allowed; an `alert` action can still leave `report.flagged` set to `true`
449
+ - `rejected` - A hide, purge, child-asset, or manual rejection decision was applied
450
+ - `error` - Processing failed
451
+
452
+ ## Moderation Reports
453
+
454
+ 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.
455
+
456
+ 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.
457
+
458
+ ```typescript
459
+ const violence = asset.report?.categories.violence;
460
+ if (violence?.status === 'evaluated' || violence?.status === 'partial') {
461
+ console.log(violence.score);
462
+ }
463
+ ```
464
+
465
+ 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.
466
+
467
+ ## Asset Visibility
468
+
469
+ - `public` - Retained content can be requested directly from the CDN
470
+ - `private` - Retained content requires a signed URL or an authenticated owner session
471
+
472
+ ## Error Handling
473
+
474
+ The SDK throws errors for common issues:
475
+
476
+ ```typescript
477
+ try {
478
+ const asset = await client.assets.create({
479
+ name: "test.jpg",
480
+ // Missing required content, URL, or multipart part
481
+ });
482
+ } catch (error) {
483
+ console.error(error.message); // "Either file content, URL, or multipart part is required"
484
+ }
485
+ ```
486
+
487
+ Public API failures are normalized to `CalmLensError`. Use its stable `code` property for control flow and `details` for diagnostics.
488
+
489
+ ## Testing
490
+
491
+ `@calmlens/js-sdk/testing` exports a matching object-parameter `MockCalmLensClient`, in-memory storage implementations, and mock API key helpers for local unit testing without network requests.
492
+
493
+ The main `@calmlens/js-sdk` entry point does not load or export testing helpers to keep production bundles minimal. Keep `/testing` imports in test files.
494
+
495
+ ```typescript
496
+ import { MockCalmLensClient, createMockApiKey } from "@calmlens/js-sdk/testing";
497
+
498
+ const client = new MockCalmLensClient({
499
+ apiKey: createMockApiKey(),
500
+ projectId: crypto.randomUUID(),
501
+ });
502
+ ```
503
+
504
+ 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).
505
+
506
+ ## Webhooks
507
+
508
+ CalmLens can send webhooks when asset processing is complete. Verify the exact raw request body before parsing it; re-serializing parsed JSON can change the signed bytes.
509
+
510
+ ## Command-line tool
511
+
512
+ The SDK installs a `calmlens` command. Webhook destinations must be 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:
513
+
514
+ ```bash
515
+ npx calmlens listen --forward-to http://localhost:3000/api/webhooks/calmlens --env-file .env.local
516
+ ```
517
+
518
+ 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.
519
+
520
+ The same feed is available in code: `client.events.list({ after, limit })` returns events oldest first with a `cursor` to pass back.
521
+
522
+ ## Releasing
523
+
524
+ 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).