@ampt/cli 1.2.0 → 1.3.2

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.
@@ -0,0 +1,541 @@
1
+ # Ampt SDK Reference
2
+
3
+ Detailed API reference for all Ampt SDK modules and interfaces.
4
+
5
+ ## @ampt/data
6
+
7
+ ```javascript
8
+ import { data } from '@ampt/data'
9
+ ```
10
+
11
+ ### Set Operations
12
+
13
+ ```javascript
14
+ // Simple value
15
+ await data.set('key', 'value')
16
+
17
+ // Object with options
18
+ await data.set(
19
+ 'user:jane',
20
+ { name: 'Jane', email: 'jane@example.com' },
21
+ {
22
+ meta: true, // return metadata
23
+ overwrite: true, // overwrite existing (default: true)
24
+ ttl: 3600, // time-to-live in seconds
25
+ label1: 'role:admin', // secondary index (up to label5)
26
+ label2: 'status:active',
27
+ exists: false, // fail if key already exists
28
+ removeNulls: true // remove null-valued properties
29
+ }
30
+ )
31
+
32
+ // Batch set (up to 25 items)
33
+ await data.set(
34
+ [
35
+ { key: 'user:1', value: { name: 'Alice' }, label1: 'role:user' },
36
+ { key: 'user:2', value: { name: 'Bob' }, ttl: 7200 }
37
+ ],
38
+ { overwrite: true }
39
+ )
40
+ ```
41
+
42
+ ### Get Operations
43
+
44
+ ```javascript
45
+ // Single item
46
+ const item = await data.get('key')
47
+
48
+ // With metadata
49
+ const item = await data.get('key', true)
50
+ // Returns: { key, value, modified, created, ttl, label1..5, expiry }
51
+
52
+ // Wildcard query (collection)
53
+ const result = await data.get('user:*')
54
+ // Returns: { items: [...], lastKey: "...", next: Function }
55
+
56
+ // Query with options
57
+ const result = await data.get('user:*', {
58
+ limit: 10,
59
+ reverse: true,
60
+ start: 'user:jane', // pagination cursor
61
+ meta: true
62
+ })
63
+
64
+ // Batch get (up to 25 keys)
65
+ const result = await data.get(['key1', 'key2', 'key3'])
66
+
67
+ // Range queries
68
+ await data.get('orders:>2024-01-01') // greater than
69
+ await data.get('orders:>=2024-01-01') // greater than or equal
70
+ await data.get('orders:<2024-12-31') // less than
71
+ await data.get('orders:<=2024-12-31') // less than or equal
72
+ await data.get('orders:2024-01-01|2024-12-31') // between (inclusive)
73
+ ```
74
+
75
+ ### Labels (Secondary Indexes)
76
+
77
+ ```javascript
78
+ // Set with labels
79
+ await data.set('order:123', orderData, {
80
+ label1: 'customer:cust_456',
81
+ label2: 'status:pending',
82
+ label3: 'date:2024-03-15'
83
+ })
84
+
85
+ // Query by label
86
+ const result = await data.getByLabel('label1', 'customer:cust_456')
87
+ const result = await data.getByLabel('label2', 'status:*')
88
+
89
+ // Query within a collection using a label
90
+ await data.get('ORDER_*', { label: 'label3', limit: 50 })
91
+ ```
92
+
93
+ ### Pagination
94
+
95
+ ```javascript
96
+ const page1 = await data.get('user:*', { limit: 10 })
97
+ // page1.items = [...], page1.lastKey = "user:mike"
98
+
99
+ // Using .next()
100
+ const page2 = await page1.next()
101
+
102
+ // Manual pagination
103
+ const page2 = await data.get('user:*', { limit: 10, start: page1.lastKey })
104
+ ```
105
+
106
+ ### Atomic Counters
107
+
108
+ ```javascript
109
+ await data.add('stats', 'pageViews', 1) // increment nested field
110
+ await data.add('counter', 1) // increment simple value
111
+ await data.add('counter', -1) // decrement
112
+
113
+ // Inline in set
114
+ await data.set('stats', { views: { $add: 1 }, name: 'page' })
115
+ ```
116
+
117
+ ### Remove
118
+
119
+ ```javascript
120
+ await data.remove('key') // single
121
+ await data.remove(['key1', 'key2']) // batch (up to 25)
122
+ // Note: wildcards NOT supported for remove
123
+ ```
124
+
125
+ ### Event Handlers
126
+
127
+ ```javascript
128
+ data.on('created', async (event) => {
129
+ console.log(event.item) // the created item
130
+ console.log(event.name) // "created"
131
+ })
132
+
133
+ data.on('updated', async (event) => {
134
+ console.log(event.item) // updated item
135
+ console.log(event.previous) // previous value
136
+ })
137
+
138
+ data.on('deleted', async (event) => {
139
+ console.log(event.item) // deleted item
140
+ })
141
+
142
+ // Multiple events
143
+ data.on(['created', 'updated'], handler)
144
+
145
+ // Wildcard (all events)
146
+ data.on('*', handler)
147
+
148
+ // Key pattern filtering
149
+ data.on('created:order_*', handler)
150
+ data.on('updated:user:*', handler)
151
+ ```
152
+
153
+ ## @ampt/sdk - Storage
154
+
155
+ ```javascript
156
+ import { storage } from '@ampt/sdk'
157
+ const bucket = storage('my-bucket')
158
+ ```
159
+
160
+ ### Write
161
+
162
+ ```javascript
163
+ await bucket.write('/path/file.txt', 'text content')
164
+ await bucket.write('/path/file.bin', buffer)
165
+ await bucket.write('/path/file.json', jsonBuffer, {
166
+ type: 'application/json',
167
+ metadata: { uploadedBy: 'user123' },
168
+ exists: false // fail if exists
169
+ })
170
+ ```
171
+
172
+ ### Read
173
+
174
+ ```javascript
175
+ const stream = await bucket.read('/path/file.txt') // ReadableStream
176
+ const buffer = await bucket.readBuffer('/path/file.txt') // Buffer
177
+ const buffer = await bucket.read('/path/file.txt', { buffer: true }) // Buffer
178
+ ```
179
+
180
+ ### File Management
181
+
182
+ ```javascript
183
+ await bucket.copy('/source/file.txt', '/dest')
184
+ await bucket.move('/source/file.txt', '/dest')
185
+ await bucket.remove('/path/file.txt')
186
+ const exists = await bucket.exists('/path/file.txt')
187
+ const stat = await bucket.stat('/path/file.txt')
188
+ // stat: { lastModified, size, metadata, type }
189
+ ```
190
+
191
+ ### List Files
192
+
193
+ ```javascript
194
+ const pages = await bucket.list('/', { recursive: true, pageSize: 100 })
195
+ const allFiles = []
196
+ for await (const page of pages) {
197
+ allFiles.push(...page)
198
+ }
199
+ ```
200
+
201
+ ### URLs (Pre-signed)
202
+
203
+ ```javascript
204
+ const downloadUrl = await bucket.getDownloadUrl('/path/file.txt') // 1hr default
205
+ const downloadUrl = await bucket.getDownloadUrl('/path/file.txt', 7200) // 2hrs
206
+ const uploadUrl = await bucket.getUploadUrl('/path/file.txt')
207
+ ```
208
+
209
+ ### Public Bucket
210
+
211
+ ```javascript
212
+ const pub = storage('public')
213
+ await pub.write('/logo.svg', svgBuffer, { maxAge: 3600 })
214
+ // Served at: https://[url].ampt.app/public/logo.svg
215
+ // CDN-cached in production stages
216
+ ```
217
+
218
+ ### Event Listeners
219
+
220
+ ```javascript
221
+ storage().on('write:uploads/*', async (event, context) => {
222
+ console.log(event.name) // file path
223
+ console.log(event.bucket) // bucket name
224
+ })
225
+
226
+ storage('images').on('write', { timeout: 10000 }, async (event, context) => {
227
+ // Process uploaded images
228
+ })
229
+
230
+ storage().on('remove:temp/*', async (event) => {
231
+ // Handle file deletion
232
+ })
233
+ ```
234
+
235
+ ## @ampt/sdk - Events
236
+
237
+ ```javascript
238
+ import { events } from '@ampt/sdk'
239
+ ```
240
+
241
+ ### Publish
242
+
243
+ ```javascript
244
+ events.publish('order.created', { orderId: '123', total: 99.99 })
245
+
246
+ // Delayed publishing
247
+ await events.publish('reminder.send', { after: '1 day' }, { userId: '456' })
248
+ await events.publish('cleanup', { after: '1 hour' }, {})
249
+ await events.publish('meeting', { after: new Date('2024-12-01') }, {})
250
+ ```
251
+
252
+ `after` accepts: milliseconds (number), Date object, UTC string, unix epoch, or duration string ("1 hour", "1 day", "1 week", "1 month", "1 year").
253
+
254
+ ### Handle
255
+
256
+ ```javascript
257
+ events.on('order.created', async (event, context) => {
258
+ // event.id -- unique event ID
259
+ // event.name -- "order.created"
260
+ // event.body -- { orderId, total }
261
+ // event.time -- ISO timestamp
262
+ // event.delay -- delay in ms (if delayed)
263
+ // event.attempt -- retry attempt number
264
+ })
265
+
266
+ // With timeout
267
+ events.on('heavy.process', { timeout: 30000 }, async (event, context) => {
268
+ context.setTimeout(45000) // extend dynamically
269
+ })
270
+ ```
271
+
272
+ ### Constraints
273
+
274
+ - Default handler timeout: 5 seconds, max 60 seconds
275
+ - Event body max size: 256KB
276
+ - Max delay: 1 year
277
+ - Failed events retry every 6 minutes for up to 14 days
278
+ - At-least-once delivery (design handlers to be idempotent)
279
+ - No guaranteed ordering
280
+
281
+ ## @ampt/sdk - Tasks
282
+
283
+ ```javascript
284
+ import { task } from '@ampt/sdk'
285
+ ```
286
+
287
+ ### Define
288
+
289
+ ```javascript
290
+ const myTask = task('my-task', async (event, context) => {
291
+ console.log(event.body) // task payload
292
+ context.progress('Processing...', 0.5)
293
+ return { result: 'done' } // max 64KB JSON
294
+ })
295
+ ```
296
+
297
+ ### Schedule
298
+
299
+ ```javascript
300
+ // Periodic (minimum interval: 1 minute)
301
+ myTask.every('1 hour', { optionalPayload: true })
302
+ myTask.every('5 minutes')
303
+
304
+ // Cron (6 fields: min hour day-of-month month day-of-week year)
305
+ myTask.cron('0 0 ? * MON *') // every Monday midnight
306
+ myTask.cron('*/15 * ? * * *') // every 15 minutes
307
+ myTask.cron('0 9 1 * ? *') // 1st of every month at 9am
308
+
309
+ // One-off execution
310
+ await myTask.run({ data: 'payload' }) // immediately
311
+ await myTask.run('1 hour', { data: 'payload' }) // delayed
312
+ ```
313
+
314
+ ### Status
315
+
316
+ ```javascript
317
+ const execution = await myTask.run({ data: 'test' })
318
+ const status = await task.status(execution.id)
319
+ // status.state: "created" | "scheduled" | "submitted" | "completed" | "failed"
320
+ // status.result: return value from handler
321
+ ```
322
+
323
+ ### Constraints
324
+
325
+ - Task names: max 64 characters, must be unique across your app
326
+ - Body max: 256KB, result max: 64KB
327
+ - Default timeout: 30 seconds
328
+ - Max timeout by plan: Preview=30s, Developer/Team=1hr, Enterprise=4hr
329
+ - Failed tasks are NOT automatically retried
330
+ - Status retained for 14 days
331
+
332
+ ## @ampt/sdk - HTTP
333
+
334
+ ```javascript
335
+ import { http } from '@ampt/sdk'
336
+ ```
337
+
338
+ ### Mount Framework
339
+
340
+ ```javascript
341
+ import express from 'express'
342
+ const app = express()
343
+
344
+ app.get('/api/health', (req, res) => res.json({ status: 'ok' }))
345
+ app.post('/api/data', (req, res) => {
346
+ /* ... */
347
+ })
348
+
349
+ // Mount at root
350
+ http.node.use(app)
351
+
352
+ // Mount at prefix
353
+ http.node.use('/api', expressApp)
354
+ ```
355
+
356
+ ### Configuration
357
+
358
+ ```javascript
359
+ http.setTimeout(10000) // 10 second timeout (default: 29s)
360
+ http.on(404, '404.html') // custom 404 page
361
+ http.on('4xx', 'error.html') // custom 4xx page
362
+ http.on('5xx', 'server-error.html') // custom 5xx page
363
+ ```
364
+
365
+ ### Static Files
366
+
367
+ ```javascript
368
+ // Read static files (works in both sandbox and deployed stages)
369
+ const stream = await http.readStaticFile('index.html') // ReadableStream
370
+ const nodeStream = await http.node.readStaticFile('index.html') // Node Readable
371
+
372
+ // SPA fallback pattern
373
+ app.use(async (req, res) => {
374
+ res.status(200).set('Content-Type', 'text/html')
375
+ const stream = await http.node.readStaticFile('index.html')
376
+ return stream.pipe(res)
377
+ })
378
+ ```
379
+
380
+ ## @ampt/sdk - WebSockets
381
+
382
+ ```javascript
383
+ import { ws } from '@ampt/sdk'
384
+ ```
385
+
386
+ ### Events
387
+
388
+ ```javascript
389
+ ws.on('connected', async (connection) => {
390
+ console.log(connection.connectionId)
391
+ console.log(connection.meta) // { connectedAt, queryStringParameters }
392
+ await connection.send('Welcome!')
393
+ })
394
+
395
+ ws.on('disconnected', async (connection, reason) => {
396
+ console.log(`${connection.connectionId} left: ${reason}`)
397
+ })
398
+
399
+ ws.on('message', async (connection, data) => {
400
+ // data is auto-parsed from JSON if possible
401
+ await connection.send({ echo: data })
402
+ })
403
+ ```
404
+
405
+ ### Send and Manage
406
+
407
+ ```javascript
408
+ await ws.send(connectionId, 'Hello')
409
+ await ws.send(connectionId, { type: 'update', data: {} })
410
+ await ws.close(connectionId)
411
+ await ws.close([id1, id2, id3]) // close multiple
412
+ const connected = await ws.isConnected(connectionId)
413
+ ```
414
+
415
+ ### Rate Limits
416
+
417
+ | Environment | Concurrent | Messages/sec |
418
+ | ----------- | ---------- | ------------ |
419
+ | Sandbox | 10 | 10 |
420
+ | Preview | 50 | 100 |
421
+ | Stage | 5,000 | 10,000 |
422
+
423
+ ## @ampt/api
424
+
425
+ ```javascript
426
+ import { api, v } from '@ampt/api'
427
+ ```
428
+
429
+ ### Router Setup
430
+
431
+ ```javascript
432
+ const publicApi = api('public').router('/api')
433
+ const adminApi = api('admin').router('/admin', undefined, authMiddleware)
434
+ ```
435
+
436
+ ### Routes
437
+
438
+ ```javascript
439
+ publicApi.get('/users', async (event) => {
440
+ return event.status(200).body({ users: [] })
441
+ })
442
+
443
+ publicApi.post('/users', async (event) => {
444
+ const body = await event.request.body()
445
+ return event.status(201).body(body)
446
+ })
447
+
448
+ publicApi.patch('/users/:id', async (event) => {
449
+ const { id } = event.params
450
+ return event.body({ updated: id })
451
+ })
452
+
453
+ publicApi.delete('/users/:id', async (event) => {
454
+ return event.status(204)
455
+ })
456
+ ```
457
+
458
+ ### Middleware
459
+
460
+ ```javascript
461
+ async function authMiddleware(event) {
462
+ const auth = event.request.headers.get('Authorization')
463
+ if (!auth) return event.status(401).body({ error: 'Unauthorized' })
464
+ event.context.userId = decodeToken(auth)
465
+ }
466
+
467
+ async function corsMiddleware(event) {
468
+ event.response.headers.append('Access-Control-Allow-Origin', '*')
469
+ event.response.headers.append('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS')
470
+ }
471
+ ```
472
+
473
+ ### HttpEvent Properties
474
+
475
+ - `event.request` -- Request object (headers, body(), query, method, url)
476
+ - `event.response` -- Response object (headers)
477
+ - `event.params` -- URL path parameters
478
+ - `event.context` -- Shared context across middleware chain
479
+ - `event.status(code)` -- Set response status
480
+ - `event.body(data)` -- Set response body (auto-serializes objects to JSON)
481
+ - `event.redirect(url, code?)` -- Redirect response
482
+
483
+ ## @ampt/ai
484
+
485
+ ```javascript
486
+ import { chat, render, summarize, translate, embed, invoke, models } from '@ampt/ai'
487
+ ```
488
+
489
+ Requires AI quota. Uses Amazon Bedrock under the hood.
490
+
491
+ ### Chat
492
+
493
+ ```javascript
494
+ const response = await chat([{ role: 'human', content: 'Explain cloud computing in one sentence.' }], {
495
+ modelId: 'anthropic.claude-v2'
496
+ })
497
+ const text = await response.text()
498
+ ```
499
+
500
+ ### Image Generation
501
+
502
+ ```javascript
503
+ const response = await render('A sunset over mountains', {
504
+ width: 512,
505
+ height: 512,
506
+ steps: 50
507
+ })
508
+ const buffer = await response.arrayBuffer()
509
+ ```
510
+
511
+ ### Summarize
512
+
513
+ ```javascript
514
+ const response = await summarize(longText, { modelId: 'anthropic.claude-v2' })
515
+ const summary = await response.text()
516
+ ```
517
+
518
+ ### Translate
519
+
520
+ ```javascript
521
+ const response = await translate('Hello, world!', {
522
+ sourceLanguage: 'auto',
523
+ targetLanguage: 'es'
524
+ })
525
+ const translated = await response.text()
526
+ ```
527
+
528
+ ### Embeddings
529
+
530
+ ```javascript
531
+ const { embedding } = await embed('search query', {
532
+ modelId: 'amazon.titan-embed-text-v1'
533
+ })
534
+ // embedding: number[]
535
+ ```
536
+
537
+ ### List Available Models
538
+
539
+ ```javascript
540
+ const available = await models()
541
+ ```