@small-web/kitten-types 1.0.0 → 1.0.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.
package/index.d.ts CHANGED
@@ -1,14 +1,11 @@
1
- // @small-web/kitten-types
2
- //
3
- // Types-only package for Kitten (https://kitten.small-web.org).
4
- //
5
- // This entry point re-exports the reusable Kitten types (for explicit
6
- // annotations) and pulls in the ambient `declare global` declaration of the
7
- // `kitten` namespace (so that the global `kitten` object is typed wherever
8
- // this package is on the type-checker’s include path).
1
+ /**
2
+ Kitten Types (@small-web/kitten-types)
3
+
4
+ This entry point re-exports Kitten types for use in explicit annotations.
5
+
6
+ Side-effect: Brings `declare global { var kitten }` into scope for any project that depends on this package.
7
+ */
9
8
 
10
- // Side-effect import: brings the ambient `declare global { var kitten }` into
11
- // scope for any project that depends on this package.
12
9
  import './global.d.ts'
13
10
 
14
11
  // Reusable types, re-exported for explicit annotations
@@ -38,6 +35,5 @@ export type {
38
35
 
39
36
  export { yaml } from './types.d.ts'
40
37
 
41
- // Also export the hand-written global namespace shape, in case a consumer
42
- // wants to reference it explicitly (e.g. `typeof kitten`).
43
- export type { KittenGlobal } from './global.d.ts'
38
+ // Also export hand-written global namespace shape, in case an author wants to reference it explicitly (e.g. `typeof kitten`).
39
+ export type { kitten } from './global.d.ts'
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@small-web/kitten-types",
3
- "version": "1.0.0",
4
- "description": "Types-only package for Kitten: declares the global `kitten` namespace and exports Kitten types.",
3
+ "version": "1.0.2",
4
+ "description": "Types-only package for Kitten: declares global `kitten` namespace and exports Kitten types.",
5
5
  "types": "index.d.ts",
6
6
  "exports": {
7
7
  ".": {
package/types.d.ts CHANGED
@@ -1,5 +1,34 @@
1
1
  import EventEmitter from 'node:events'
2
+ import type polka from 'polka'
2
3
 
4
+ /**
5
+ Represents a browser session.
6
+
7
+ Sessions are automatically persisted (and expired) in Kitten’s internal database.
8
+
9
+ Used by Kitten to provide automatic authentication for Small Web places.
10
+
11
+ You can also add/update arbitrary session data by adding/updating properties on this object in your routes (this object maps a session object in the `kitten._db.sessions` table in the internal database).
12
+
13
+ You can emit events on a session in order to communicate with other browser tabs and windows that share the same session.
14
+
15
+ @example
16
+ export default function ({ request }) {
17
+ request.session.kittens ??= { count: 1 }
18
+
19
+ return kitten.html`
20
+ <h1>Kitten count</h1>
21
+ <p>${'🐱️'.repeat(request.session.kittens.count++)}</p>
22
+ `
23
+ }
24
+
25
+ @see https://kitten.small-web.org/tutorials/sessions/
26
+
27
+ @remarks
28
+ Do not save custom classes on request.session or JSDB will throw an error when it tries to open the internal `_db` database and cannot find your custom class to instantiate.
29
+
30
+ If you want persisted session-level custom objects, store them in your own database table in `kitten.db` keyed by `session.id`.
31
+ */
3
32
  export class Session extends EventEmitter {
4
33
  id: string
5
34
  authenticated: boolean
@@ -11,7 +40,7 @@ export class Session extends EventEmitter {
11
40
 
12
41
  export type { default as WebSocket, BufferLike } from './ws/index.d.ts'
13
42
  export type { default as slugify } from './slugify/index.d.ts'
14
- export type { default as Polka } from './polka/index.d.ts'
43
+ export type Polka = ReturnType<typeof polka>
15
44
  export { default as MarkdownIt } from 'markdown-it'
16
45
 
17
46
  export namespace yaml {
@@ -34,10 +63,31 @@ interface UploadConstructorParameters {
34
63
  done: boolean
35
64
  }
36
65
 
66
+ /**
67
+ Represents an uploaded file.
68
+
69
+ @see https://kitten.small-web.org/tutorials/multipart-forms-and-file-uploads/
70
+ */
37
71
  export class Upload {
72
+ /**
73
+ @private
74
+ @remarks For internal use by Kitten’s automatic POST route handler
75
+ */
38
76
  constructor(parameters:UploadConstructorParameters)
77
+
78
+ /**
79
+ The absolute resource path for accessing this upload via a GET request (content-disposition: inline).
80
+ */
39
81
  resourcePath: string
82
+
83
+ /**
84
+ Returns the absolute download path (content-disposition: attachment).
85
+ */
40
86
  downloadPath: string
87
+
88
+ /**
89
+ Deletes this uploaded file from the file system and also from the internal database.
90
+ */
41
91
  delete(): Promise<void>
42
92
  }
43
93
 
@@ -104,12 +154,21 @@ export class MessageSender {
104
154
  */
105
155
  type JavaScriptFunction = (...args: any[]) => any
106
156
 
157
+ /**
158
+ A class constructor.
159
+ */
107
160
  type Constructor<T> = new (...args: any[]) => T
108
161
 
162
+ /**
163
+ Represents the render function of a component that is bound to component (as its `this`).
164
+ */
109
165
  type BoundComponentRenderFunction<T extends KittenComponent> =
110
166
  ((...args: Parameters<T['html']>) => Promise<Awaited<ReturnType<T['html']>>>)
111
167
  & { boundObject: T }
112
168
 
169
+ /**
170
+ An EventEmitter listener with a `remove()` method for cleanup.
171
+ */
113
172
  export class Listener {
114
173
  /**
115
174
  Create EventEmitter listener.
@@ -122,6 +181,60 @@ export class Listener {
122
181
  remove ():void
123
182
  }
124
183
 
184
+ /**
185
+ Kitten Component.
186
+
187
+ A class that makes it easier to author hierarchies of connected components.
188
+
189
+ Handles wiring up and disposal of event listeners for you and gives you an ergonomic, class-based way of writing maintainable applications that take advantage of Kitten’s Streaming HTML workflow while working with well-encapsulated, self-contained components in a clear hierarchy.
190
+
191
+ Extend and instantiate this class to create your own components (components, fragments, layout components, and pages) and provide at least an override for the `html()` method, which is just a function that returns `kitten.html`.
192
+
193
+ The example, below, updates a persisted counter via the + and - buttons (index.page.ts).
194
+
195
+ @example
196
+ // Initialise the database with a persisted counter object.
197
+ kitten.db.counter ??= { count: 0 }
198
+
199
+ export default class CounterPage extends kitten.Page {
200
+ counter
201
+
202
+ constructor () {
203
+ super()
204
+ this.counter = this.addChild(new Counter())
205
+ }
206
+
207
+ override html () {
208
+ return kitten.html`
209
+ <page css>
210
+ <h1>Counter</h1>
211
+ <${this.counter} />
212
+ `
213
+ }
214
+ }
215
+
216
+ class Counter extends kitten.Component {
217
+ override html () {
218
+ return kitten.html`
219
+ <div>
220
+ <div
221
+ id='count'
222
+ aria-live='assertive'
223
+ >
224
+ ${kitten.db.counter.count}
225
+ </div>
226
+ <button name='update' connect data='{value: -1}' aria-label='decrement'>-</button>
227
+ <button name='update' connect data='{value: 1}' aria-label='increment'>+</button>
228
+ </div>
229
+ `
230
+ }
231
+
232
+ onUpdate (data: { value: number } ) {
233
+ kitten.db.counter.count += data.value
234
+ this.update()
235
+ }
236
+ }
237
+ */
125
238
  export class KittenComponent {
126
239
  /**
127
240
  Unique ID (crypto.uuid) of this component. You can overwrite it with your own if you like.
@@ -195,16 +308,11 @@ export class KittenComponent {
195
308
  onAddToParent() :void
196
309
 
197
310
  /**
198
- Optional hook: override this method to provide custom logic for your app
199
- to be run when the page this component is on connects to the client via its WebSocket.
311
+ Optional hook: override this method to provide custom logic for your app to be run when the page this component is on connects to the client via its WebSocket.
200
312
 
201
- This hook will get called not just for initially-rendered components when the page
202
- first connects but also for any components dynamically added to an already-connected
203
- page/component hierarchy after the fact.
313
+ This hook will get called not just for initially-rendered components when the page first connects but also for any components dynamically added to an already-connected page/component hierarchy after the fact.
204
314
 
205
- (So you can be sure that this handler will be called once when a component is fully
206
- initialised on a connected page. This is a good place to add event handlers or to
207
- start streaming updates to the client.)
315
+ (So you can be sure that this handler will be called once when a component is fully initialised on a connected page. This is a good place to add event handlers or to start streaming updates to the client.)
208
316
  */
209
317
  onConnect(parameterObject: {
210
318
  page?: KittenComponent,
@@ -213,10 +321,7 @@ export class KittenComponent {
213
321
  }):void
214
322
 
215
323
  /**
216
- Optional hook: override this method to run custom logic when the page
217
- this component is on disconnects from the client via its WebSocket.
218
- (This usually means the page the about to be unloaded, either because the
219
- person is nagivating away from it or reloading it.)
324
+ Optional hook: override this method to run custom logic when the page this component is on disconnects from the client via its WebSocket. (This usually means the page the about to be unloaded, either because the person is nagivating away from it or reloading it.)
220
325
  */
221
326
  onDisconnect(parameterObject: {
222
327
  page?: KittenComponent,
@@ -227,8 +332,7 @@ export class KittenComponent {
227
332
  /**
228
333
  Adds child component to this one.
229
334
 
230
- Child components are entered into the event bubbling hierarchy and
231
- contain a reference to the page that they’re on.
335
+ Child components are entered into the event bubbling hierarchy and contain a reference to the page that they’re on.
232
336
  */
233
337
  addChild<T extends KittenComponent> (component: T): T
234
338
 
@@ -256,9 +360,7 @@ export class KittenComponent {
256
360
  /**
257
361
  Add event handler for an EventEmitter.
258
362
 
259
- Event listening and listener clean-up are automatically handled so the
260
- author doesn’t have to worry about implementing this finickety
261
- aspect manually.
363
+ Event listening and listener clean-up are automatically handled so the author doesn’t have to worry about implementing this finickety aspect manually.
262
364
  */
263
365
  addEventHandler (target: object, eventName: string, eventHandler: JavaScriptFunction):void
264
366
 
@@ -270,8 +372,7 @@ export class KittenComponent {
270
372
  /**
271
373
  Helper for removing this component from the live component hierachy.
272
374
 
273
- Also handles removal of event listeners for itself and all its
274
- children so we don’t have any leaks.
375
+ Also handles removal of event listeners for itself and all its children so we don’t have any leaks.
275
376
  */
276
377
  remove ():void
277
378
 
@@ -291,16 +392,14 @@ export class KittenComponent {
291
392
  emit (eventName:string, data?:any, event?:any, target?:string, self?:any):void
292
393
 
293
394
  /**
294
- Helper for adding an event handler for a page event and streaming an
295
- updated version of the component to the client (a common pattern).
395
+ Helper for adding an event handler for a page event and streaming an updated version of the component to the client (a common pattern).
296
396
 
297
397
  @param {string} eventName
298
398
  */
299
399
  updateOnEvent (eventName:string):void
300
400
 
301
401
  /**
302
- Helper (handler) for sending an updated version of this
303
- component to the page.
402
+ Helper (handler) for sending an updated version of this component to the page.
304
403
  */
305
404
  sendUpdatedComponentToPage ():void
306
405
  }
@@ -308,13 +407,13 @@ export class KittenComponent {
308
407
  /**
309
408
  KittenPage class.
310
409
 
311
- A KittenPage is a specialised KittenComponent that represents a live
312
- page in memory (a live page is one that has an automatic WebSocket connection
313
- to the page rendered by the PageRoute). It constitutes the root of the
314
- server-side component hierarchy. Its `html()` method is dynamically bound
315
- by the PageRoute to the authored page route function in function-based authoring
316
- and it is used directly via its global `kitten.Page` reference when authoring
317
- class-based page routes.
410
+ A KittenPage is a specialised KittenComponent that represents a live page in memory (a live page is one that has an automatic WebSocket connection to the page rendered by the PageRoute).
411
+
412
+ A KittenPage constitutes the root of the server-side component hierarchy.
413
+
414
+ Instance data in a `KittenPage` instance sticks around for the lifetime of the page (e.g., until a reload or a navigation event away from it in the browser).
415
+
416
+ If you need greater persistence, use session storage (`request.session`) or the built-in JSDB database (`kitten.db`).
318
417
  */
319
418
  export class KittenPage extends KittenComponent {
320
419
  request: KittenRequest
@@ -327,35 +426,20 @@ export class KittenPage extends KittenComponent {
327
426
  everyoneElse: MessageSender
328
427
 
329
428
  /**
330
- Construct new KittenPage instance with a reference to the
331
- request and response objects for the page.
429
+ Construct new KittenPage instance.
430
+
431
+ Note that the `request` and `response` properties are set after construction by Kitten to keep the constructor easy to override in your own subclasses. (The constructor is a good place to initialise known child components, etc.)
332
432
 
333
- Every page has a unique ID (inherited from KittenComponent) and can hold
334
- ephemeral page-level data. e.g., the states of components when
335
- using the Streaming HTML workfow. (Page storage is ephemeral is that
336
- it only lasts for the lifetime of a page in the browser and is destroyed
337
- when the page is closed or reloaded.)
433
+ Every page has a unique ID (inherited from KittenComponent) and can hold ephemeral page-level instance data. e.g., child components. (Page storage is ephemeral is that it only lasts for the lifetime of a page in the browser and is destroyed when the page is closed or reloaded.)
338
434
 
339
- If you need greater persistence, use session storage (request.session) or
340
- the built-in JSDB database (kitten.db).
435
+ If you need greater persistence, please use session storage (request.session) or the built-in JavaScript Database (JSDB) that you can reference at `kitten.db`.
341
436
 
342
- A page is an authored page if the author of the Kitten app/site wrote
343
- and exported a KittenPage subclass in the route (as opposed to exporting a
344
- simple function and function-based event handlers that then resulted
345
- in a generic page being created by Kitten’s PageRoute class). Keeping
346
- track of this is an optimisation that enabled the PageSocketRoute to
347
- not have to import the source file again if the page was authored
348
- as a page instance and thus already contains its event handlers (as
349
- opposed to the event handlers being exported as separate functions that
350
- have be read in and mixed into the generic KittenPage instance by the PageSocketRoute).
437
+ A page is known as an authored page if the author of the Kitten app/site wrote and exported a KittenPage subclass in the route (as opposed to exporting a simple function and function-based event handlers that then resulted in a generic page being created by Kitten’s `PageRoute` class). Keeping track of this is an optimisation that enables the `PageSocketRoute` to not have to import the source file again if the page was authored as a page instance and thus already contains its event handlers (as opposed to the event handlers being exported as separate functions that have be read in and mixed into the generic `KittenPage` instance by the `PageSocketRoute`).
351
438
  */
352
439
  constructor()
353
440
 
354
441
  /**
355
- The page has connected to its WebSocket. The list of sockets and the
356
- specific socket for this page are passed for storage on the page and the
357
- list of event handlers imported from the page (when using function-based
358
- page routes), if any, to be mixed into this instance as methods.
442
+ The page has connected to its WebSocket. The list of sockets and the specific socket for this page are passed for storage on the page and the list of event handlers imported from the page (when using function-based page routes), if any, to be mixed into this instance as methods.
359
443
  */
360
444
  connect (socket: WebSocketWithIsAlive, sockets: [WebSocketWithIsAlive], eventHandlers: Record<string, JavaScriptFunction>):void
361
445
 
@@ -369,11 +453,7 @@ export class KittenPage extends KittenComponent {
369
453
  /**
370
454
  Send specified message to just this page’s socket.
371
455
 
372
- You can specify an optional swap target that intelligently
373
- wraps what you’re sending with the necessary envelope tag.
374
- This is normally rather confusing with htmx’s oob swaps,
375
- especially when inserting table rows. See:
376
- https://htmx.org/attributes/hx-swap-oob/#using-alternate-swap-strategies
456
+ You can specify an optional swap target that intelligently wraps what you’re sending with the necessary envelope tag. This is normally rather confusing with htmx’s oob swaps, especially when inserting table rows. See: https://htmx.org/attributes/hx-swap-oob/#using-alternate-swap-strategies
377
457
  */
378
458
  send (message: BufferLike|Promise<BufferLike>, swapTarget?: {
379
459
  before?: string,
@@ -386,10 +466,7 @@ export class KittenPage extends KittenComponent {
386
466
  /**
387
467
  Request and response types.
388
468
 
389
- These vary per route type but are all built on the base of
390
- Polka’s request and response objects which are, themselves,
391
- based on the incoming message and server response types of
392
- Node’s own http module.
469
+ These vary per route type but are all built on the base of Polka’s request and response objects which are, themselves, based on the incoming message and server response types of Node’s own http module.
393
470
  */
394
471
 
395
472
  import type { IncomingMessage, ServerResponse } from 'http'
@@ -416,6 +493,11 @@ export interface PolkaRequest extends IncomingMessage {
416
493
  _parsedUrl: ParsedURL
417
494
  }
418
495
 
496
+ /**
497
+ The request objects received by Kitten routes.
498
+
499
+ Based on Polka’s request object with extra Kitten-specific properties and methods.
500
+ */
419
501
  export interface KittenRequest extends PolkaRequest {
420
502
  /**
421
503
  The raw body of non-multipart requests. Used, for example, for validation webhook signatures.
@@ -423,8 +505,7 @@ export interface KittenRequest extends PolkaRequest {
423
505
  rawBody: Buffer
424
506
 
425
507
  /**
426
- Check if the incoming request contains the "Content-Type"
427
- header field, and it contains the given mime `type`.
508
+ Check if the incoming request contains the `"Content-Type"` header field, and, if so, if it contains the specified mime `type`.
428
509
 
429
510
  Examples:
430
511
 
@@ -446,43 +527,71 @@ export interface KittenRequest extends PolkaRequest {
446
527
  */
447
528
  is (types:Array<string>|string):string|false|null
448
529
 
449
- session: Session
530
+ /**
531
+ Represents a browser session.
532
+
533
+ Sessions are automatically persisted (and expired) in Kitten’s internal database.
534
+
535
+ Used by Kitten to provide automatic authentication for Small Web places.
536
+
537
+ You can also add/update arbitrary session data by adding/updating properties on this object in your routes (this object maps a session object in the `kitten._db.sessions` table in the internal database).
538
+
539
+ You can emit events on a session in order to communicate with other browser tabs and windows that share the same session.
540
+
541
+ @example
542
+ export default function ({ request }) {
543
+ request.session.kittens ??= { count: 1 }
544
+
545
+ return kitten.html`
546
+ <h1>Kitten count</h1>
547
+ <p>${'🐱️'.repeat(request.session.kittens.count++)}</p>
548
+ `
549
+ }
550
+
551
+ @see https://kitten.small-web.org/tutorials/sessions/
552
+
553
+ @remarks
554
+ Do not save custom classes on request.session or JSDB will throw an error when it tries to open the internal `_db` database and cannot find your custom class to instantiate.
555
+
556
+ If you want persisted session-level custom objects, store them in your own database table in `kitten.db` keyed by `session.id`.
557
+ */
558
+ session: Session & {
559
+ [key: string]: any
560
+ }
450
561
  }
451
562
 
452
563
  type TypedArray = Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|BigInt64Array|BigUint64Array
453
564
 
565
+ /**
566
+ The response objects received by Kitten routes.
567
+
568
+ Based on Polka’s response object with extra Kitten-specific properties and methods.
569
+ */
454
570
  export interface KittenResponse extends PolkaResponse {
455
571
  /**
456
- JSON.stringifies passed data and ends response with
457
- inline JSON using proper headers.
572
+ JSON.stringifies passed data and ends response with inline JSON using proper headers.
458
573
  */
459
574
  json (data:any):void
460
575
 
461
576
  /**
462
- JSON.stringifies passed data and ends response with JSON attachment
463
- using proper headers and requested file name (or data.json as fallback
464
- if no file name is provided).
577
+ JSON.stringifies passed data and ends response with JSON attachment using proper headers and requested file name (or data.json as fallback if no file name is provided).
465
578
  */
466
579
  jsonFile (data:any, fileName?:string):void
467
580
 
468
581
  /**
469
- Ends response with a file. Optionally, uses passed file name
470
- (or 'dowload' as fallback) and passed mime type (or
471
- 'application/octet-stream' as fallback).
582
+ Ends response with a file. Optionally, uses passed file name (or `'download'` as fallback) and passed mime type (or `'application/octet-stream'` as fallback).
472
583
  */
473
584
  file (data:string|Buffer|TypedArray|DataView, fileName?:string, mimeType?:string):void
474
585
 
475
586
  /**
476
- Ends response with 200 OK response code, and the response body,
477
- if any (and '' if not).
587
+ Ends response with 200 OK response code, and the response body, if any (and `''` if not).
478
588
 
479
589
  @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200
480
590
  */
481
591
  ok (body?:string):void
482
592
 
483
593
  /**
484
- Ends response with 201 Created response code, and the response body,
485
- if any (and '' if not).
594
+ Ends response with 201 Created response code, and the response body, if any (and `''` if not).
486
595
 
487
596
  @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201
488
597
  */
@@ -508,9 +617,7 @@ export interface KittenResponse extends PolkaResponse {
508
617
  /**
509
618
  400 Bad Request
510
619
 
511
- Indicates that the server cannot or will not process the request due to something
512
- that is perceived to be a client error (e.g., malformed request syntax, invalid request
513
- message framing, or deceptive request routing).
620
+ Indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
514
621
 
515
622
  @link https://httpwg.org/specs/rfc9110.html#rfc.section.15.5.1
516
623
  */
@@ -524,13 +631,9 @@ export interface KittenResponse extends PolkaResponse {
524
631
  unauthenticated (body?:string):void
525
632
 
526
633
  /**
527
- 403 Forbidden response. This should be returned
528
- if the request is authenticated but lacks the authorisation
529
- (i.e., sufficient rights) to access the resource.
634
+ 403 Forbidden response. This should be returned if the request is authenticated but lacks the authorisation (i.e., sufficient rights) to access the resource.
530
635
 
531
- If the request requires authentication but has not been
532
- authenticated, you should return a “401 Unauthorized”
533
- (actually: unauthenticated) response.
636
+ If the request requires authentication but has not been authenticated, you should return a “401 Unauthorized” (actually: unauthenticated) response.
534
637
 
535
638
  @see unauthenticated
536
639
  */
@@ -549,12 +652,18 @@ export interface KittenResponse extends PolkaResponse {
549
652
  error (body?:string):void
550
653
 
551
654
  /**
552
- General shorthand helper for setting the status code and
553
- ending the response with an optional body.
655
+ General shorthand helper for setting the status code and ending the response with an optional body.
554
656
  */
555
657
  withCode (statusCode:number, body?:string):void
556
658
  }
557
659
 
660
+ /**
661
+ Kitten’s POST request object.
662
+
663
+ If the POST route had a multi-part form with file uploads, they will be handled automatically by Kitten and you can find them in the `uploads` property.
664
+
665
+ @see https://kitten.small-web.org/tutorials/multipart-forms-and-file-uploads/
666
+ */
558
667
  export interface KittenPostRequest extends KittenRequest {
559
668
  uploads: Upload[]
560
669
  }