@superjackfruitlabs/treaty-cloudevents 0.0.2 → 0.0.3

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,14 @@
1
+ export interface CloudEvent {
2
+ /** Context attributes, including extensions, by name. Values are canonical strings. */
3
+ attributes: Record<string, string>;
4
+ data?: Uint8Array;
5
+ }
6
+ export type Binding = "http" | "nats";
7
+ export interface BinaryMessage {
8
+ headers: Record<string, string>;
9
+ body: Uint8Array;
10
+ }
11
+ /** Throws unless the attributes are a valid CloudEvents 1.0 context. */
12
+ export declare function validate(attributes: Record<string, string>): void;
13
+ export declare function toBinary(event: CloudEvent, binding: Binding): BinaryMessage;
14
+ export declare function fromBinary(message: BinaryMessage, binding: Binding): CloudEvent;
package/dist/codec.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * CloudEvents 1.0 in binary content mode, over HTTP headers and NATS headers.
3
+ *
4
+ * An event is its context attributes as canonical strings plus the data as bytes, so the same
5
+ * shape crosses every binding and every language. Typed values (a time, an integer) are the
6
+ * producer's business: it writes their canonical string form.
7
+ */
8
+ import { REQUIRED_ATTRIBUTES, SPEC_VERSION } from "./constants.js";
9
+ import { CloudEventError, percentDecode, percentEncode, unquote, } from "./encoding.js";
10
+ const PREFIX = "ce-";
11
+ const NAME = /^[a-z0-9]{1,20}$/;
12
+ /** Throws unless the attributes are a valid CloudEvents 1.0 context. */
13
+ export function validate(attributes) {
14
+ for (const name of REQUIRED_ATTRIBUTES) {
15
+ if (!attributes[name]) {
16
+ throw new CloudEventError(`missing required attribute ${name}`);
17
+ }
18
+ }
19
+ if (attributes["specversion"] !== SPEC_VERSION) {
20
+ throw new CloudEventError(`unsupported specversion ${attributes["specversion"]}`);
21
+ }
22
+ for (const name of Object.keys(attributes)) {
23
+ if (!NAME.test(name)) {
24
+ throw new CloudEventError(`attribute name ${JSON.stringify(name)} is not 1-20 of a-z0-9`);
25
+ }
26
+ }
27
+ }
28
+ export function toBinary(event, binding) {
29
+ validate(event.attributes);
30
+ const headers = {};
31
+ for (const [name, value] of Object.entries(event.attributes)) {
32
+ if (binding === "http" && name === "datacontenttype") {
33
+ headers["content-type"] = value;
34
+ }
35
+ else {
36
+ headers[PREFIX + name] = percentEncode(value);
37
+ }
38
+ }
39
+ return { headers, body: event.data ?? new Uint8Array() };
40
+ }
41
+ export function fromBinary(message, binding) {
42
+ const attributes = {};
43
+ for (const [rawName, rawValue] of Object.entries(message.headers)) {
44
+ const name = rawName.toLowerCase();
45
+ if (name === "content-type") {
46
+ if (/^application\/cloudevents/i.test(rawValue)) {
47
+ throw new CloudEventError("structured and batched content modes are not supported");
48
+ }
49
+ if (binding === "http")
50
+ attributes["datacontenttype"] = rawValue;
51
+ continue;
52
+ }
53
+ if (!name.startsWith(PREFIX))
54
+ continue;
55
+ const attribute = name.slice(PREFIX.length);
56
+ if (binding === "http" && attribute === "datacontenttype") {
57
+ throw new CloudEventError("HTTP carries datacontenttype as Content-Type, never ce-datacontenttype");
58
+ }
59
+ if (attribute in attributes) {
60
+ throw new CloudEventError(`attribute ${attribute} appears twice`);
61
+ }
62
+ attributes[attribute] = percentDecode(binding === "http" ? unquote(rawValue) : rawValue);
63
+ }
64
+ validate(attributes);
65
+ return message.body.length > 0
66
+ ? { attributes, data: message.body }
67
+ : { attributes };
68
+ }
@@ -0,0 +1,5 @@
1
+ /** The CloudEvents `specversion` every suite event carries. */
2
+ export declare const SPEC_VERSION: "1.0";
3
+ /** The four attributes CloudEvents 1.0 requires on every event. */
4
+ export declare const REQUIRED_ATTRIBUTES: readonly ["id", "source", "specversion", "type"];
5
+ export type RequiredAttribute = (typeof REQUIRED_ATTRIBUTES)[number];
@@ -0,0 +1,9 @@
1
+ /** The CloudEvents `specversion` every suite event carries. */
2
+ export const SPEC_VERSION = "1.0";
3
+ /** The four attributes CloudEvents 1.0 requires on every event. */
4
+ export const REQUIRED_ATTRIBUTES = [
5
+ "id",
6
+ "source",
7
+ "specversion",
8
+ "type",
9
+ ];
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Header-value encoding for binary content mode, shared by the HTTP and NATS bindings.
3
+ *
4
+ * Senders percent-encode space, double quote, percent and every character outside U+0021-U+007E,
5
+ * one `%XY` per UTF-8 byte, upper-case hex. Receivers run one round of percent-decoding, accept
6
+ * unnecessary or lower-case encoding, and reject a sequence that is not valid UTF-8.
7
+ */
8
+ export declare function percentEncode(value: string): string;
9
+ export declare function percentDecode(value: string): string;
10
+ /** HTTP only: a header value sent as a quoted-string is unquoted before it is percent-decoded. */
11
+ export declare function unquote(value: string): string;
12
+ export declare class CloudEventError extends Error {
13
+ name: string;
14
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Header-value encoding for binary content mode, shared by the HTTP and NATS bindings.
3
+ *
4
+ * Senders percent-encode space, double quote, percent and every character outside U+0021-U+007E,
5
+ * one `%XY` per UTF-8 byte, upper-case hex. Receivers run one round of percent-decoding, accept
6
+ * unnecessary or lower-case encoding, and reject a sequence that is not valid UTF-8.
7
+ */
8
+ const UTF8 = new TextEncoder();
9
+ const SAFE = /^[!#$&-~]$/; // printable ASCII less `"` and `%`
10
+ export function percentEncode(value) {
11
+ let out = "";
12
+ for (const char of value) {
13
+ if (SAFE.test(char)) {
14
+ out += char;
15
+ continue;
16
+ }
17
+ for (const byte of UTF8.encode(char)) {
18
+ out += `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
19
+ }
20
+ }
21
+ return out;
22
+ }
23
+ const STRICT_UTF8 = new TextDecoder("utf-8", { fatal: true });
24
+ export function percentDecode(value) {
25
+ const bytes = [];
26
+ let i = 0;
27
+ while (i < value.length) {
28
+ if (value[i] === "%") {
29
+ const hex = value.slice(i + 1, i + 3);
30
+ if (!/^[0-9A-Fa-f]{2}$/.test(hex)) {
31
+ throw new CloudEventError(`malformed percent-encoding in ${JSON.stringify(value)}`);
32
+ }
33
+ bytes.push(parseInt(hex, 16));
34
+ i += 3;
35
+ continue;
36
+ }
37
+ const char = String.fromCodePoint(value.codePointAt(i));
38
+ bytes.push(...UTF8.encode(char));
39
+ i += char.length;
40
+ }
41
+ try {
42
+ return STRICT_UTF8.decode(new Uint8Array(bytes));
43
+ }
44
+ catch {
45
+ throw new CloudEventError(`not valid UTF-8 once decoded: ${JSON.stringify(value)}`);
46
+ }
47
+ }
48
+ /** HTTP only: a header value sent as a quoted-string is unquoted before it is percent-decoded. */
49
+ export function unquote(value) {
50
+ if (value.length < 2 || !value.startsWith('"') || !value.endsWith('"')) {
51
+ return value;
52
+ }
53
+ return value.slice(1, -1).replace(/\\(.)/g, "$1");
54
+ }
55
+ export class CloudEventError extends Error {
56
+ name = "CloudEventError";
57
+ }
package/dist/index.d.ts CHANGED
@@ -1,10 +1,8 @@
1
1
  /**
2
- * The suite's event envelope: CloudEvents 1.0 in binary mode.
3
- *
4
- * Step 1 of the treaty plan only scaffolds this package. The codec lands in step 3.
2
+ * The suite's event envelope: CloudEvents 1.0 in binary content mode, over HTTP and NATS
3
+ * headers, and the suite's names for event subjects and types.
5
4
  */
6
- /** The CloudEvents `specversion` every suite event carries. */
7
- export declare const SPEC_VERSION: "1.0";
8
- /** The four attributes CloudEvents 1.0 requires on every event. */
9
- export declare const REQUIRED_ATTRIBUTES: readonly ["id", "source", "specversion", "type"];
10
- export type RequiredAttribute = (typeof REQUIRED_ATTRIBUTES)[number];
5
+ export { REQUIRED_ATTRIBUTES, SPEC_VERSION, type RequiredAttribute, } from "./constants.ts";
6
+ export { CloudEventError, percentDecode, percentEncode } from "./encoding.ts";
7
+ export { fromBinary, toBinary, validate, type BinaryMessage, type Binding, type CloudEvent, } from "./codec.ts";
8
+ export { eventSubject, eventType, parseSubject, parseType, type EventName, } from "./naming.ts";
package/dist/index.js CHANGED
@@ -1,14 +1,8 @@
1
1
  /**
2
- * The suite's event envelope: CloudEvents 1.0 in binary mode.
3
- *
4
- * Step 1 of the treaty plan only scaffolds this package. The codec lands in step 3.
2
+ * The suite's event envelope: CloudEvents 1.0 in binary content mode, over HTTP and NATS
3
+ * headers, and the suite's names for event subjects and types.
5
4
  */
6
- /** The CloudEvents `specversion` every suite event carries. */
7
- export const SPEC_VERSION = "1.0";
8
- /** The four attributes CloudEvents 1.0 requires on every event. */
9
- export const REQUIRED_ATTRIBUTES = [
10
- "id",
11
- "source",
12
- "specversion",
13
- "type",
14
- ];
5
+ export { REQUIRED_ATTRIBUTES, SPEC_VERSION, } from "./constants.js";
6
+ export { CloudEventError, percentDecode, percentEncode } from "./encoding.js";
7
+ export { fromBinary, toBinary, validate, } from "./codec.js";
8
+ export { eventSubject, eventType, parseSubject, parseType, } from "./naming.js";
@@ -0,0 +1,13 @@
1
+ export interface EventName {
2
+ product: string;
3
+ entity: string;
4
+ verb: string;
5
+ }
6
+ export declare function eventSubject(workspace: string, name: EventName): string;
7
+ export declare function eventType(name: EventName, version: number): string;
8
+ export declare function parseSubject(subject: string): {
9
+ workspace: string;
10
+ } & EventName;
11
+ export declare function parseType(type: string): EventName & {
12
+ version: number;
13
+ };
package/dist/naming.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The suite's names for events (treaty plan, Naming).
3
+ *
4
+ * Subjects: `evt.<workspace>.<product>.<entity>.<verb>`. Tenancy and filtering work on prefixes.
5
+ * Types: `com.superjackfruit.<product>.<entity>.<verb>.v<N>`. A version lives in the type, never
6
+ * in the subject, so a consumer can filter across versions.
7
+ */
8
+ import { CloudEventError } from "./encoding.js";
9
+ const WORD = /^[a-z][a-z0-9_]*$/;
10
+ const WORKSPACE = /^[A-Za-z0-9_-]+$/;
11
+ function check(name) {
12
+ for (const [part, value] of Object.entries(name)) {
13
+ if (!WORD.test(value)) {
14
+ throw new CloudEventError(`${part} ${JSON.stringify(value)} must match ${WORD}`);
15
+ }
16
+ }
17
+ }
18
+ export function eventSubject(workspace, name) {
19
+ if (!WORKSPACE.test(workspace)) {
20
+ throw new CloudEventError(`workspace ${JSON.stringify(workspace)} must match ${WORKSPACE}`);
21
+ }
22
+ check(name);
23
+ return `evt.${workspace}.${name.product}.${name.entity}.${name.verb}`;
24
+ }
25
+ export function eventType(name, version) {
26
+ check(name);
27
+ if (!Number.isInteger(version) || version < 1) {
28
+ throw new CloudEventError(`version ${version} must be a positive integer`);
29
+ }
30
+ return `com.superjackfruit.${name.product}.${name.entity}.${name.verb}.v${version}`;
31
+ }
32
+ export function parseSubject(subject) {
33
+ const [evt, workspace, product, entity, verb, ...rest] = subject.split(".");
34
+ if (evt !== "evt" ||
35
+ !workspace ||
36
+ !product ||
37
+ !entity ||
38
+ !verb ||
39
+ rest.length) {
40
+ throw new CloudEventError(`not an event subject: ${JSON.stringify(subject)}`);
41
+ }
42
+ const name = { product, entity, verb };
43
+ eventSubject(workspace, name);
44
+ return { workspace, ...name };
45
+ }
46
+ export function parseType(type) {
47
+ const match = /^com\.superjackfruit\.([^.]+)\.([^.]+)\.([^.]+)\.v([1-9][0-9]*)$/.exec(type);
48
+ if (!match) {
49
+ throw new CloudEventError(`not a suite event type: ${JSON.stringify(type)}`);
50
+ }
51
+ const name = { product: match[1], entity: match[2], verb: match[3] };
52
+ check(name);
53
+ return { ...name, version: Number(match[4]) };
54
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@superjackfruitlabs/treaty-cloudevents",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "The CloudEvents 1.0 envelope shared by Super Jackfruit Labs products.",
5
5
  "license": "MIT",
6
6
  "type": "module",