@velajs/cloudflare 1.32.0 → 1.34.0
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/CHANGELOG.md +46 -0
- package/README.md +198 -1
- package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +9 -0
- package/dist/bindings.js +25 -1
- package/dist/bindings.js.map +1 -1
- package/dist/{cloudflare-application-CXDy9C1R.d.ts → cloudflare-application-Dsscb3Mo.d.ts} +2 -2
- package/dist/{cloudflare-factory-CuFNUJJD.d.ts → cloudflare-factory-DM9CBvNH.d.ts} +5 -5
- package/dist/durable-objects.d.ts +1 -1
- package/dist/email.d.ts +1 -1
- package/dist/entrypoints.d.ts +1 -1
- package/dist/index.d.ts +27 -12
- package/dist/index.js +2 -2
- package/dist/pipelines.d.ts +20 -0
- package/dist/pipelines.js +87 -0
- package/dist/pipelines.js.map +1 -0
- package/dist/queue-events/consume.js +120 -0
- package/dist/queue-events/consume.js.map +1 -0
- package/dist/queue-events.d.ts +71 -0
- package/dist/queue-events.js +2 -0
- package/dist/services/flagship-flag.driver.js +64 -6
- package/dist/services/flagship-flag.driver.js.map +1 -1
- package/dist/services/kv-cache.store.js +4 -4
- package/dist/services/kv-cache.store.js.map +1 -1
- package/dist/tail.d.ts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/tracing.d.ts +15 -0
- package/dist/tracing.js +24 -0
- package/dist/tracing.js.map +1 -0
- package/dist/websocket/binding-gateways.js +1 -1
- package/dist/websocket/binding-gateways.js.map +1 -1
- package/dist/workflows.d.ts +1 -1
- package/package.json +21 -9
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { SchemaValidationError, isStandardSchema, parseSchemaAsync } from "@velajs/vela/validation";
|
|
2
|
+
//#region src/pipelines.ts
|
|
3
|
+
const MAX_BATCH_BYTES = 5e6;
|
|
4
|
+
const encoder = new TextEncoder();
|
|
5
|
+
/**
|
|
6
|
+
* Bind a Standard Schema producer to one trusted, configured stream. Schema
|
|
7
|
+
* outputs must fit the binding's record type; send() accepts schema inputs.
|
|
8
|
+
* Resolution means ingestion acceptance only, not downstream delivery or query
|
|
9
|
+
* visibility. There is no retry, splitting, buffering, or cross-writer state.
|
|
10
|
+
*/
|
|
11
|
+
function createPipelinesWriter(binding, { schema }) {
|
|
12
|
+
if (!binding || typeof binding.send !== "function") throw new TypeError("Pipelines requires a stream binding with send(records).");
|
|
13
|
+
if (!isStandardSchema(schema)) throw new TypeError("Pipelines requires a Standard Schema validator.");
|
|
14
|
+
return { async send(records) {
|
|
15
|
+
if (!Array.isArray(records) || records.length === 0) throw new TypeError("Pipelines requires a nonempty array of records.");
|
|
16
|
+
const inputs = [];
|
|
17
|
+
for (let index = 0; index < records.length; index++) {
|
|
18
|
+
const descriptor = Object.getOwnPropertyDescriptor(records, String(index));
|
|
19
|
+
if (!descriptor || !("value" in descriptor)) throw new TypeError(`Pipelines record ${index} must be an array element, not an accessor or hole.`);
|
|
20
|
+
inputs.push(descriptor.value);
|
|
21
|
+
}
|
|
22
|
+
const outputs = [];
|
|
23
|
+
let batchBytes = 2;
|
|
24
|
+
for (const [index, input] of inputs.entries()) {
|
|
25
|
+
let output;
|
|
26
|
+
try {
|
|
27
|
+
output = await parseSchemaAsync(schema, input);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (error instanceof SchemaValidationError) throw new SchemaValidationError(error.issues.map((issue) => ({
|
|
30
|
+
...issue,
|
|
31
|
+
path: [index, ...issue.path ?? []]
|
|
32
|
+
})));
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
if (output === null || typeof output !== "object" || Array.isArray(output)) throw new TypeError(`Pipelines record ${index} must validate to a JSON object.`);
|
|
36
|
+
const snapshot = snapshotJson(output, [index], /* @__PURE__ */ new Set());
|
|
37
|
+
const bytes = encoder.encode(JSON.stringify(snapshot)).byteLength;
|
|
38
|
+
if (bytes > 4999998) throw new RangeError(`Pipelines record ${index} exceeds 4999998 JSON bytes.`);
|
|
39
|
+
batchBytes += bytes + (index === 0 ? 0 : 1);
|
|
40
|
+
if (batchBytes > MAX_BATCH_BYTES) throw new RangeError(`Pipelines batch exceeds ${MAX_BATCH_BYTES} JSON bytes.`);
|
|
41
|
+
outputs.push(snapshot);
|
|
42
|
+
}
|
|
43
|
+
await binding.send(outputs);
|
|
44
|
+
} };
|
|
45
|
+
}
|
|
46
|
+
function snapshotJson(value, path, ancestors) {
|
|
47
|
+
const invalid = (reason) => {
|
|
48
|
+
throw new TypeError(`Pipelines JSON value at ${JSON.stringify(path)} ${reason}.`);
|
|
49
|
+
};
|
|
50
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
51
|
+
if (typeof value === "number") {
|
|
52
|
+
if (!Number.isFinite(value)) invalid("must be finite");
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
if (typeof value !== "object") return invalid("is not representable");
|
|
56
|
+
if (ancestors.has(value)) return invalid("is circular");
|
|
57
|
+
const array = Array.isArray(value);
|
|
58
|
+
const prototype = Object.getPrototypeOf(value);
|
|
59
|
+
if (prototype !== null && prototype !== (array ? Array.prototype : Object.prototype)) return invalid("must use a plain object or array");
|
|
60
|
+
ancestors.add(value);
|
|
61
|
+
try {
|
|
62
|
+
const copy = array ? [] : {};
|
|
63
|
+
const keys = Reflect.ownKeys(value);
|
|
64
|
+
if (array && keys.length !== value.length + 1) return invalid("must be a dense array");
|
|
65
|
+
for (const key of keys) {
|
|
66
|
+
if (array && key === "length") continue;
|
|
67
|
+
if (typeof key !== "string") return invalid("cannot have symbol keys");
|
|
68
|
+
if (array && (!/^(0|[1-9]\d*)$/.test(key) || Number(key) >= value.length)) return invalid("cannot have extra array properties");
|
|
69
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
70
|
+
if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) return invalid("must contain only enumerable data properties");
|
|
71
|
+
const child = snapshotJson(descriptor.value, [...path, array ? Number(key) : key], ancestors);
|
|
72
|
+
Object.defineProperty(copy, key, {
|
|
73
|
+
value: child,
|
|
74
|
+
enumerable: true,
|
|
75
|
+
writable: true,
|
|
76
|
+
configurable: true
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
return copy;
|
|
80
|
+
} finally {
|
|
81
|
+
ancestors.delete(value);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
//#endregion
|
|
85
|
+
export { createPipelinesWriter };
|
|
86
|
+
|
|
87
|
+
//# sourceMappingURL=pipelines.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pipelines.js","names":[],"sources":["../src/pipelines.ts"],"sourcesContent":["import {\n isStandardSchema,\n parseSchemaAsync,\n SchemaValidationError,\n type StandardSchemaV1,\n} from '@velajs/vela/validation';\n\n/** The native stream handle remains usable independently of the writer. */\nexport interface PipelinesBinding<Output = Record<string, unknown>> {\n readonly send: (records: Output[]) => Promise<void>;\n}\n\nexport interface PipelinesWriter<Input> {\n /** Validate the entire nonempty batch, then await one native ingestion request. */\n send(records: readonly Input[]): Promise<void>;\n}\n\n// Current streams document 5 MB per ingestion request, without a separate record\n// cap. Use decimal MB conservatively, including JSON array brackets and commas.\n// https://developers.cloudflare.com/pipelines/platform/limits/\nconst MAX_BATCH_BYTES = 5_000_000;\nconst encoder = new TextEncoder();\n\n/**\n * Bind a Standard Schema producer to one trusted, configured stream. Schema\n * outputs must fit the binding's record type; send() accepts schema inputs.\n * Resolution means ingestion acceptance only, not downstream delivery or query\n * visibility. There is no retry, splitting, buffering, or cross-writer state.\n */\nexport function createPipelinesWriter<S extends StandardSchemaV1<unknown, Record<string, unknown>>>(\n binding: PipelinesBinding<NoInfer<StandardSchemaV1.InferOutput<S>>>,\n { schema }: { readonly schema: S },\n): PipelinesWriter<StandardSchemaV1.InferInput<S>> {\n if (!binding || typeof binding.send !== 'function') {\n throw new TypeError('Pipelines requires a stream binding with send(records).');\n }\n if (!isStandardSchema(schema)) {\n throw new TypeError('Pipelines requires a Standard Schema validator.');\n }\n\n return {\n async send(records) {\n if (!Array.isArray(records) || records.length === 0) {\n throw new TypeError('Pipelines requires a nonempty array of records.');\n }\n // Capture batch membership before the first asynchronous validation.\n const inputs: unknown[] = [];\n for (let index = 0; index < records.length; index++) {\n const descriptor = Object.getOwnPropertyDescriptor(records, String(index));\n if (!descriptor || !('value' in descriptor)) {\n throw new TypeError(\n `Pipelines record ${index} must be an array element, not an accessor or hole.`,\n );\n }\n inputs.push(descriptor.value);\n }\n\n const outputs: StandardSchemaV1.InferOutput<S>[] = [];\n let batchBytes = 2;\n for (const [index, input] of inputs.entries()) {\n let output: unknown;\n try {\n output = await parseSchemaAsync(schema, input);\n } catch (error) {\n if (error instanceof SchemaValidationError) {\n throw new SchemaValidationError(\n error.issues.map((issue) => ({ ...issue, path: [index, ...(issue.path ?? [])] })),\n );\n }\n throw error;\n }\n if (output === null || typeof output !== 'object' || Array.isArray(output)) {\n throw new TypeError(`Pipelines record ${index} must validate to a JSON object.`);\n }\n // Snapshot now: later async validators or callers may mutate earlier\n // outputs. The native send must receive exactly the JSON we checked.\n const snapshot = snapshotJson(output, [index], new Set());\n const bytes = encoder.encode(JSON.stringify(snapshot)).byteLength;\n if (bytes > MAX_BATCH_BYTES - 2) {\n throw new RangeError(\n `Pipelines record ${index} exceeds ${MAX_BATCH_BYTES - 2} JSON bytes.`,\n );\n }\n batchBytes += bytes + (index === 0 ? 0 : 1);\n if (batchBytes > MAX_BATCH_BYTES) {\n throw new RangeError(`Pipelines batch exceeds ${MAX_BATCH_BYTES} JSON bytes.`);\n }\n // The schema checked the shape; snapshotJson only copies JSON data and\n // rejects values JSON would silently drop or coerce.\n outputs.push(snapshot as StandardSchemaV1.InferOutput<S>);\n }\n await binding.send(outputs);\n },\n };\n}\n\nfunction snapshotJson(value: unknown, path: (string | number)[], ancestors: Set<object>): unknown {\n const invalid = (reason: string): never => {\n throw new TypeError(`Pipelines JSON value at ${JSON.stringify(path)} ${reason}.`);\n };\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) invalid('must be finite');\n return value;\n }\n if (typeof value !== 'object') return invalid('is not representable');\n if (ancestors.has(value)) return invalid('is circular');\n const array = Array.isArray(value);\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== (array ? Array.prototype : Object.prototype)) {\n return invalid('must use a plain object or array');\n }\n ancestors.add(value);\n try {\n // Native RPC bindings require ordinary objects, including when the input\n // has a null prototype. Define own properties below to preserve __proto__.\n const copy: Record<string, unknown> | unknown[] = array ? [] : {};\n const keys = Reflect.ownKeys(value);\n if (array && keys.length !== value.length + 1) return invalid('must be a dense array');\n for (const key of keys) {\n if (array && key === 'length') continue;\n if (typeof key !== 'string') return invalid('cannot have symbol keys');\n if (array && (!/^(0|[1-9]\\d*)$/.test(key) || Number(key) >= value.length)) {\n return invalid('cannot have extra array properties');\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor || !('value' in descriptor) || !descriptor.enumerable) {\n return invalid('must contain only enumerable data properties');\n }\n const child = snapshotJson(descriptor.value, [...path, array ? Number(key) : key], ancestors);\n Object.defineProperty(copy, key, {\n value: child,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n return copy;\n } finally {\n ancestors.delete(value);\n }\n}\n"],"mappings":";;AAoBA,MAAM,kBAAkB;AACxB,MAAM,UAAU,IAAI,YAAY;;;;;;;AAQhC,SAAgB,sBACd,SACA,EAAE,UAC+C;CACjD,IAAI,CAAC,WAAW,OAAO,QAAQ,SAAS,YACtC,MAAM,IAAI,UAAU,yDAAyD;CAE/E,IAAI,CAAC,iBAAiB,MAAM,GAC1B,MAAM,IAAI,UAAU,iDAAiD;CAGvE,OAAO,EACL,MAAM,KAAK,SAAS;EAClB,IAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,GAChD,MAAM,IAAI,UAAU,iDAAiD;EAGvE,MAAM,SAAoB,CAAC;EAC3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 +1,120 @@
|
|
|
1
|
+
import { isStandardSchema, validateSchema } from "@velajs/vela/validation";
|
|
2
|
+
//#region src/queue-events/consume.ts
|
|
3
|
+
var QueueEventError = class extends Error {
|
|
4
|
+
code;
|
|
5
|
+
constructor(code, options) {
|
|
6
|
+
super(`Queue event ${code}`, options);
|
|
7
|
+
this.code = code;
|
|
8
|
+
this.name = "QueueEventError";
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
/** Successful siblings are already acknowledged; failures have requested native retries. */
|
|
12
|
+
var QueueEventsBatchError = class extends AggregateError {
|
|
13
|
+
failures;
|
|
14
|
+
constructor(failures) {
|
|
15
|
+
super(failures.map(({ error }) => error), `${failures.length} queue event(s) failed`);
|
|
16
|
+
this.failures = failures;
|
|
17
|
+
this.name = "QueueEventsBatchError";
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
const dispatch = Symbol("queue-event-dispatch");
|
|
21
|
+
function nonempty(value) {
|
|
22
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
23
|
+
}
|
|
24
|
+
/** No module registration or global state: define handlers alongside their consuming provider. */
|
|
25
|
+
function defineQueueEvent(options) {
|
|
26
|
+
if (!nonempty(options.type) || !nonempty(options.source.type) || !Object.values(options.source).every(nonempty)) throw new TypeError("Queue event type and source expectations must be nonempty strings");
|
|
27
|
+
if (!isStandardSchema(options.schema)) throw new TypeError("Expected a Standard Schema validator");
|
|
28
|
+
const { type, schema, handle } = options;
|
|
29
|
+
const source = Object.entries(options.source);
|
|
30
|
+
return Object.freeze({
|
|
31
|
+
type,
|
|
32
|
+
async [dispatch](event, context) {
|
|
33
|
+
if (!source.every(([key, value]) => event.source[key] === value)) throw new QueueEventError("unexpected-source");
|
|
34
|
+
let payload;
|
|
35
|
+
try {
|
|
36
|
+
payload = await validateSchema(schema, event.payload);
|
|
37
|
+
} catch (cause) {
|
|
38
|
+
throw new QueueEventError("invalid-payload", { cause });
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
await handle({
|
|
42
|
+
...event,
|
|
43
|
+
payload
|
|
44
|
+
}, context);
|
|
45
|
+
} catch (cause) {
|
|
46
|
+
throw new QueueEventError("handler-failed", { cause });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function record(value) {
|
|
52
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
53
|
+
}
|
|
54
|
+
function parseEvent(value) {
|
|
55
|
+
if (!record(value) || !nonempty(value.type) || !record(value.source) || !nonempty(value.source.type) || !Object.hasOwn(value, "payload") || !record(value.metadata)) throw new QueueEventError("invalid-envelope");
|
|
56
|
+
const { source, metadata } = value;
|
|
57
|
+
if (!nonempty(metadata.accountId) || !nonempty(metadata.eventSubscriptionId) || !Number.isInteger(metadata.eventSchemaVersion) || !nonempty(metadata.eventTimestamp) || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(metadata.eventTimestamp) || !Number.isFinite(Date.parse(metadata.eventTimestamp)) || new Date(metadata.eventTimestamp.slice(0, 10)).toISOString().slice(0, 10) !== metadata.eventTimestamp.slice(0, 10)) throw new QueueEventError("invalid-envelope");
|
|
58
|
+
if (metadata.eventSchemaVersion !== 1) throw new QueueEventError("unsupported-version");
|
|
59
|
+
return {
|
|
60
|
+
type: value.type,
|
|
61
|
+
source: {
|
|
62
|
+
...source,
|
|
63
|
+
type: value.source.type
|
|
64
|
+
},
|
|
65
|
+
payload: value.payload,
|
|
66
|
+
metadata: {
|
|
67
|
+
...metadata,
|
|
68
|
+
accountId: metadata.accountId,
|
|
69
|
+
eventSubscriptionId: metadata.eventSubscriptionId,
|
|
70
|
+
eventSchemaVersion: 1,
|
|
71
|
+
eventTimestamp: metadata.eventTimestamp
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Await each validated handler, then acknowledge that message. Every malformed,
|
|
77
|
+
* unmatched or failing message requests retry; all siblings are attempted before
|
|
78
|
+
* throwing QueueEventsBatchError. Cloudflare owns retry limits, delays and DLQ routing.
|
|
79
|
+
* Do not acknowledge the batch elsewhere or convert these bodies into Vela jobs.
|
|
80
|
+
*/
|
|
81
|
+
async function consumeQueueEvents(batch, options) {
|
|
82
|
+
if (!nonempty(options.queue) || !nonempty(options.accountId) || options.eventSubscriptionIds.length === 0 || !options.eventSubscriptionIds.every(nonempty)) throw new TypeError("Expected a physical queue, account and nonempty subscription allowlist");
|
|
83
|
+
if (batch.queue !== options.queue) throw new Error("Unexpected physical queue for platform events");
|
|
84
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
85
|
+
for (const handler of options.handlers) {
|
|
86
|
+
if (handlers.has(handler.type)) throw new TypeError(`Duplicate queue event handler: ${handler.type}`);
|
|
87
|
+
handlers.set(handler.type, handler);
|
|
88
|
+
}
|
|
89
|
+
const accountId = options.accountId;
|
|
90
|
+
const subscriptions = new Set(options.eventSubscriptionIds);
|
|
91
|
+
const failures = [];
|
|
92
|
+
for (const message of batch.messages) {
|
|
93
|
+
try {
|
|
94
|
+
const event = parseEvent(message.body);
|
|
95
|
+
if (event.metadata.accountId !== accountId) throw new QueueEventError("unexpected-account");
|
|
96
|
+
if (!subscriptions.has(event.metadata.eventSubscriptionId)) throw new QueueEventError("unexpected-subscription");
|
|
97
|
+
const handler = handlers.get(event.type);
|
|
98
|
+
if (!handler) throw new QueueEventError("unhandled-type");
|
|
99
|
+
await handler[dispatch](event, {
|
|
100
|
+
queue: batch.queue,
|
|
101
|
+
messageId: message.id,
|
|
102
|
+
timestamp: message.timestamp,
|
|
103
|
+
attempts: message.attempts
|
|
104
|
+
});
|
|
105
|
+
} catch (error) {
|
|
106
|
+
message.retry();
|
|
107
|
+
failures.push({
|
|
108
|
+
messageId: message.id,
|
|
109
|
+
error: error instanceof QueueEventError ? error : new QueueEventError("handler-failed", { cause: error })
|
|
110
|
+
});
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
message.ack();
|
|
114
|
+
}
|
|
115
|
+
if (failures.length > 0) throw new QueueEventsBatchError(failures);
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
export { QueueEventError, QueueEventsBatchError, consumeQueueEvents, defineQueueEvent };
|
|
119
|
+
|
|
120
|
+
//# sourceMappingURL=consume.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"consume.js","names":[],"sources":["../../src/queue-events/consume.ts"],"sourcesContent":["import { isStandardSchema, validateSchema, type StandardSchemaV1 } from '@velajs/vela/validation';\n\nexport interface QueueEvent<Payload = unknown> {\n readonly type: string;\n readonly source: Readonly<Record<string, unknown>> & { readonly type: string };\n readonly payload: Payload;\n readonly metadata: Readonly<Record<string, unknown>> & {\n readonly accountId: string;\n readonly eventSubscriptionId: string;\n readonly eventSchemaVersion: 1;\n readonly eventTimestamp: string;\n };\n}\n\n/** Native delivery identity, not a universal platform event ID or an idempotency guarantee. */\nexport interface QueueEventContext {\n readonly queue: string;\n readonly messageId: string;\n readonly timestamp: Date;\n readonly attempts: number;\n}\n\nexport type QueueEventErrorCode =\n | 'invalid-envelope'\n | 'unsupported-version'\n | 'unexpected-account'\n | 'unexpected-subscription'\n | 'unhandled-type'\n | 'unexpected-source'\n | 'invalid-payload'\n | 'handler-failed';\n\nexport class QueueEventError extends Error {\n constructor(\n readonly code: QueueEventErrorCode,\n options?: ErrorOptions,\n ) {\n super(`Queue event ${code}`, options);\n this.name = 'QueueEventError';\n }\n}\n\nexport interface QueueEventFailure {\n readonly messageId: string;\n readonly error: QueueEventError;\n}\n\n/** Successful siblings are already acknowledged; failures have requested native retries. */\nexport class QueueEventsBatchError extends AggregateError {\n constructor(readonly failures: readonly QueueEventFailure[]) {\n super(\n failures.map(({ error }) => error),\n `${failures.length} queue event(s) failed`,\n );\n this.name = 'QueueEventsBatchError';\n }\n}\n\nexport interface QueueEventOptions<Payload> {\n /** The full documented event type, for example cf.workersBuilds.worker.build.succeeded. */\n readonly type: string;\n /** Exact matches for source.type and any source selectors required by the application. */\n readonly source: Readonly<Record<string, string>> & { readonly type: string };\n readonly schema: StandardSchemaV1<unknown, Payload>;\n readonly handle: (event: QueueEvent<Payload>, context: QueueEventContext) => void | Promise<void>;\n}\n\nconst dispatch = Symbol('queue-event-dispatch');\n\n/** Created with defineQueueEvent so each heterogeneous payload retains its validated type. */\nexport interface QueueEventHandler {\n readonly type: string;\n readonly [dispatch]: (event: QueueEvent, context: QueueEventContext) => Promise<void>;\n}\n\nfunction nonempty(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\n/** No module registration or global state: define handlers alongside their consuming provider. */\nexport function defineQueueEvent<Payload>(options: QueueEventOptions<Payload>): QueueEventHandler {\n if (\n !nonempty(options.type) ||\n !nonempty(options.source.type) ||\n !Object.values(options.source).every(nonempty)\n ) {\n throw new TypeError('Queue event type and source expectations must be nonempty strings');\n }\n if (!isStandardSchema(options.schema))\n throw new TypeError('Expected a Standard Schema validator');\n const { type, schema, handle } = options;\n const source = Object.entries(options.source);\n return Object.freeze({\n type,\n async [dispatch](event: QueueEvent, context: QueueEventContext) {\n if (!source.every(([key, value]) => event.source[key] === value)) {\n throw new QueueEventError('unexpected-source');\n }\n let payload: Payload;\n try {\n payload = await validateSchema(schema, event.payload);\n } catch (cause) {\n throw new QueueEventError('invalid-payload', { cause });\n }\n try {\n await handle({ ...event, payload }, context);\n } catch (cause) {\n throw new QueueEventError('handler-failed', { cause });\n }\n },\n });\n}\n\nexport interface ConsumeQueueEventsOptions {\n /** Dedicated physical queue name, also claimed by @QueueConsumer. */\n readonly queue: string;\n readonly accountId: string;\n readonly eventSubscriptionIds: readonly string[];\n /** One handler per exact event type; each may require source selectors. */\n readonly handlers: readonly QueueEventHandler[];\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction parseEvent(value: unknown): QueueEvent {\n if (\n !record(value) ||\n !nonempty(value.type) ||\n !record(value.source) ||\n !nonempty(value.source.type) ||\n !Object.hasOwn(value, 'payload') ||\n !record(value.metadata)\n ) {\n throw new QueueEventError('invalid-envelope');\n }\n const { source, metadata } = value;\n if (\n !nonempty(metadata.accountId) ||\n !nonempty(metadata.eventSubscriptionId) ||\n !Number.isInteger(metadata.eventSchemaVersion) ||\n !nonempty(metadata.eventTimestamp) ||\n !/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(\n metadata.eventTimestamp,\n ) ||\n !Number.isFinite(Date.parse(metadata.eventTimestamp)) ||\n // Date.parse normalizes impossible dates such as February 30. Reject those too.\n new Date(metadata.eventTimestamp.slice(0, 10)).toISOString().slice(0, 10) !==\n metadata.eventTimestamp.slice(0, 10)\n ) {\n throw new QueueEventError('invalid-envelope');\n }\n if (metadata.eventSchemaVersion !== 1) throw new QueueEventError('unsupported-version');\n return {\n type: value.type,\n source: { ...source, type: value.source.type },\n payload: value.payload,\n metadata: {\n ...metadata,\n accountId: metadata.accountId,\n eventSubscriptionId: metadata.eventSubscriptionId,\n eventSchemaVersion: 1,\n eventTimestamp: metadata.eventTimestamp,\n },\n };\n}\n\n/**\n * Await each validated handler, then acknowledge that message. Every malformed,\n * unmatched or failing message requests retry; all siblings are attempted before\n * throwing QueueEventsBatchError. Cloudflare owns retry limits, delays and DLQ routing.\n * Do not acknowledge the batch elsewhere or convert these bodies into Vela jobs.\n */\nexport async function consumeQueueEvents(\n batch: MessageBatch<unknown>,\n options: ConsumeQueueEventsOptions,\n): Promise<void> {\n if (\n !nonempty(options.queue) ||\n !nonempty(options.accountId) ||\n options.eventSubscriptionIds.length === 0 ||\n !options.eventSubscriptionIds.every(nonempty)\n ) {\n throw new TypeError('Expected a physical queue, account and nonempty subscription allowlist');\n }\n if (batch.queue !== options.queue)\n throw new Error('Unexpected physical queue for platform events');\n const handlers = new Map<string, QueueEventHandler>();\n for (const handler of options.handlers) {\n if (handlers.has(handler.type))\n throw new TypeError(`Duplicate queue event handler: ${handler.type}`);\n handlers.set(handler.type, handler);\n }\n const accountId = options.accountId;\n const subscriptions = new Set(options.eventSubscriptionIds);\n const failures: QueueEventFailure[] = [];\n for (const message of batch.messages) {\n try {\n const event = parseEvent(message.body);\n if (event.metadata.accountId !== accountId) throw new QueueEventError('unexpected-account');\n if (!subscriptions.has(event.metadata.eventSubscriptionId))\n throw new QueueEventError('unexpected-subscription');\n const handler = handlers.get(event.type);\n if (!handler) throw new QueueEventError('unhandled-type');\n await handler[dispatch](event, {\n queue: batch.queue,\n messageId: message.id,\n timestamp: message.timestamp,\n attempts: message.attempts,\n });\n } catch (error) {\n message.retry();\n failures.push({\n messageId: message.id,\n error:\n error instanceof QueueEventError\n ? error\n : new QueueEventError('handler-failed', { cause: error }),\n });\n continue;\n }\n message.ack();\n }\n if (failures.length > 0) throw new QueueEventsBatchError(failures);\n}\n"],"mappings":";;AAgCA,IAAa,kBAAb,cAAqC,MAAM;CAE9B;CADX,YACE,MACA,SACA;EACA,MAAM,eAAe,QAAQ,OAAO;EAH3B,KAAA,OAAA;EAIT,KAAK,OAAO;CACd;AACF;;AAQA,IAAa,wBAAb,cAA2C,eAAe;CACnC;CAArB,YAAY,UAAiD;EAC3D,MACE,SAAS,KAAK,EAAE,YAAY,KAAK,GACjC,GAAG,SAAS,OAAO,uBACrB;EAJmB,KAAA,WAAA;EAKnB,KAAK,OAAO;CACd;AACF;AAWA,MAAM,WAAW,OAAO,sBAAsB;AAQ9C,SAAS,SAAS,OAAiC;CACjD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS;AAC5D;;AAGA,SAAgB,iBAA0B,SAAwD;CAChG,IACE,CAAC,SAAS,QAAQ,IAAI,KACtB,CAAC,SAAS,QAAQ,OAAO,IAAI,KAC7B,CAAC,OAAO,OAAO,QAAQ,MAAM,CAAC,CAAC,MAAM,QAAQ,GAE7C,M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I,CAAC,cAAc,IAAI,MAAM,SAAS,mBAAmB,GACvD,MAAM,IAAI,gBAAgB,yBAAyB;GACrD,MAAM,UAAU,SAAS,IAAI,MAAM,IAAI;GACvC,IAAI,CAAC,SAAS,MAAM,IAAI,gBAAgB,gBAAgB;GACxD,MAAM,QAAQ,SAAS,CAAC,OAAO;IAC7B,OAAO,MAAM;IACb,WAAW,QAAQ;IACnB,WAAW,QAAQ;IACnB,UAAU,QAAQ;GACpB,CAAC;EACH,SAAS,OAAO;GACd,QAAQ,MAAM;GACd,SAAS,KAAK;IACZ,WAAW,QAAQ;IACnB,OACE,iBAAiB,kBACb,QACA,IAAI,gBAAgB,kBAAkB,EAAE,OAAO,MAAM,CAAC;GAC9D,CAAC;GACD;EACF;EACA,QAAQ,IAAI;CACd;CACA,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,sBAAsB,QAAQ;AACnE"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { StandardSchemaV1 } from "@velajs/vela/validation";
|
|
2
|
+
//#region src/queue-events/consume.d.ts
|
|
3
|
+
interface QueueEvent<Payload = unknown> {
|
|
4
|
+
readonly type: string;
|
|
5
|
+
readonly source: Readonly<Record<string, unknown>> & {
|
|
6
|
+
readonly type: string;
|
|
7
|
+
};
|
|
8
|
+
readonly payload: Payload;
|
|
9
|
+
readonly metadata: Readonly<Record<string, unknown>> & {
|
|
10
|
+
readonly accountId: string;
|
|
11
|
+
readonly eventSubscriptionId: string;
|
|
12
|
+
readonly eventSchemaVersion: 1;
|
|
13
|
+
readonly eventTimestamp: string;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/** Native delivery identity, not a universal platform event ID or an idempotency guarantee. */
|
|
17
|
+
interface QueueEventContext {
|
|
18
|
+
readonly queue: string;
|
|
19
|
+
readonly messageId: string;
|
|
20
|
+
readonly timestamp: Date;
|
|
21
|
+
readonly attempts: number;
|
|
22
|
+
}
|
|
23
|
+
type QueueEventErrorCode = 'invalid-envelope' | 'unsupported-version' | 'unexpected-account' | 'unexpected-subscription' | 'unhandled-type' | 'unexpected-source' | 'invalid-payload' | 'handler-failed';
|
|
24
|
+
export declare class QueueEventError extends Error {
|
|
25
|
+
readonly code: QueueEventErrorCode;
|
|
26
|
+
constructor(code: QueueEventErrorCode, options?: ErrorOptions);
|
|
27
|
+
}
|
|
28
|
+
interface QueueEventFailure {
|
|
29
|
+
readonly messageId: string;
|
|
30
|
+
readonly error: QueueEventError;
|
|
31
|
+
}
|
|
32
|
+
/** Successful siblings are already acknowledged; failures have requested native retries. */
|
|
33
|
+
export declare class QueueEventsBatchError extends AggregateError {
|
|
34
|
+
readonly failures: readonly QueueEventFailure[];
|
|
35
|
+
constructor(failures: readonly QueueEventFailure[]);
|
|
36
|
+
}
|
|
37
|
+
interface QueueEventOptions<Payload> {
|
|
38
|
+
/** The full documented event type, for example cf.workersBuilds.worker.build.succeeded. */
|
|
39
|
+
readonly type: string;
|
|
40
|
+
/** Exact matches for source.type and any source selectors required by the application. */
|
|
41
|
+
readonly source: Readonly<Record<string, string>> & {
|
|
42
|
+
readonly type: string;
|
|
43
|
+
};
|
|
44
|
+
readonly schema: StandardSchemaV1<unknown, Payload>;
|
|
45
|
+
readonly handle: (event: QueueEvent<Payload>, context: QueueEventContext) => void | Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
declare const dispatch: unique symbol;
|
|
48
|
+
/** Created with defineQueueEvent so each heterogeneous payload retains its validated type. */
|
|
49
|
+
interface QueueEventHandler {
|
|
50
|
+
readonly type: string;
|
|
51
|
+
readonly [dispatch]: (event: QueueEvent, context: QueueEventContext) => Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
/** No module registration or global state: define handlers alongside their consuming provider. */
|
|
54
|
+
export declare function defineQueueEvent<Payload>(options: QueueEventOptions<Payload>): QueueEventHandler;
|
|
55
|
+
interface ConsumeQueueEventsOptions {
|
|
56
|
+
/** Dedicated physical queue name, also claimed by @QueueConsumer. */
|
|
57
|
+
readonly queue: string;
|
|
58
|
+
readonly accountId: string;
|
|
59
|
+
readonly eventSubscriptionIds: readonly string[];
|
|
60
|
+
/** One handler per exact event type; each may require source selectors. */
|
|
61
|
+
readonly handlers: readonly QueueEventHandler[];
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Await each validated handler, then acknowledge that message. Every malformed,
|
|
65
|
+
* unmatched or failing message requests retry; all siblings are attempted before
|
|
66
|
+
* throwing QueueEventsBatchError. Cloudflare owns retry limits, delays and DLQ routing.
|
|
67
|
+
* Do not acknowledge the batch elsewhere or convert these bodies into Vela jobs.
|
|
68
|
+
*/
|
|
69
|
+
export declare function consumeQueueEvents(batch: MessageBatch<unknown>, options: ConsumeQueueEventsOptions): Promise<void>;
|
|
70
|
+
//#endregion
|
|
71
|
+
export type { ConsumeQueueEventsOptions, QueueEvent, QueueEventContext, QueueEventErrorCode, QueueEventFailure, QueueEventHandler, QueueEventOptions };
|
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
* {@link FeatureFlagDriver} backed by a Cloudflare Flagship binding.
|
|
4
4
|
*
|
|
5
5
|
* A thin, honest wrapper: each contract method maps 1:1 onto the binding's
|
|
6
|
-
* corresponding
|
|
7
|
-
* `defaultValue`) and evaluation context.
|
|
6
|
+
* corresponding native method, forwarding the caller's `fallback` (the binding's
|
|
7
|
+
* `defaultValue`) and validated scalar evaluation context. Optional detail methods
|
|
8
|
+
* preserve native reasons, variants and error codes; value-only bindings report UNKNOWN. The binding resolves the fallback on
|
|
8
9
|
* evaluation errors; anything the binding *rejects* with (e.g. a `remote: true`
|
|
9
10
|
* dev-proxy tunnel dropping) propagates — `@velajs/feature-flags`'s service owns
|
|
10
11
|
* the never-throw guarantee.
|
|
@@ -30,22 +31,79 @@ var FlagshipFlagDriver = class {
|
|
|
30
31
|
this.name = options.name ?? "flagship";
|
|
31
32
|
}
|
|
32
33
|
getBoolean(key, fallback, ctx) {
|
|
33
|
-
return this.resolve().getBooleanValue(key, fallback, ctx);
|
|
34
|
+
return this.resolve().getBooleanValue(key, fallback, nativeContext(ctx));
|
|
34
35
|
}
|
|
35
36
|
getString(key, fallback, ctx) {
|
|
36
|
-
return this.resolve().getStringValue(key, fallback, ctx);
|
|
37
|
+
return this.resolve().getStringValue(key, fallback, nativeContext(ctx));
|
|
37
38
|
}
|
|
38
39
|
getNumber(key, fallback, ctx) {
|
|
39
|
-
return this.resolve().getNumberValue(key, fallback, ctx);
|
|
40
|
+
return this.resolve().getNumberValue(key, fallback, nativeContext(ctx));
|
|
40
41
|
}
|
|
41
42
|
getObject(key, fallback, ctx) {
|
|
42
|
-
return this.resolve().getObjectValue(key, fallback, ctx);
|
|
43
|
+
return this.resolve().getObjectValue(key, fallback, nativeContext(ctx));
|
|
44
|
+
}
|
|
45
|
+
getBooleanDetails(key, fallback, ctx) {
|
|
46
|
+
return this.details(key, fallback, ctx, (binding, context) => binding.getBooleanDetails ? binding.getBooleanDetails(key, fallback, context) : binding.getBooleanValue(key, fallback, context).then((value) => ({
|
|
47
|
+
flagKey: key,
|
|
48
|
+
value,
|
|
49
|
+
reason: "UNKNOWN"
|
|
50
|
+
})));
|
|
51
|
+
}
|
|
52
|
+
getStringDetails(key, fallback, ctx) {
|
|
53
|
+
return this.details(key, fallback, ctx, (binding, context) => binding.getStringDetails ? binding.getStringDetails(key, fallback, context) : binding.getStringValue(key, fallback, context).then((value) => ({
|
|
54
|
+
flagKey: key,
|
|
55
|
+
value,
|
|
56
|
+
reason: "UNKNOWN"
|
|
57
|
+
})));
|
|
58
|
+
}
|
|
59
|
+
getNumberDetails(key, fallback, ctx) {
|
|
60
|
+
return this.details(key, fallback, ctx, (binding, context) => binding.getNumberDetails ? binding.getNumberDetails(key, fallback, context) : binding.getNumberValue(key, fallback, context).then((value) => ({
|
|
61
|
+
flagKey: key,
|
|
62
|
+
value,
|
|
63
|
+
reason: "UNKNOWN"
|
|
64
|
+
})));
|
|
65
|
+
}
|
|
66
|
+
getObjectDetails(key, fallback, ctx) {
|
|
67
|
+
return this.details(key, fallback, ctx, (binding, context) => binding.getObjectDetails ? binding.getObjectDetails(key, fallback, context) : binding.getObjectValue(key, fallback, context).then((value) => ({
|
|
68
|
+
flagKey: key,
|
|
69
|
+
value,
|
|
70
|
+
reason: "UNKNOWN"
|
|
71
|
+
})));
|
|
72
|
+
}
|
|
73
|
+
async details(key, fallback, ctx, read) {
|
|
74
|
+
let context;
|
|
75
|
+
try {
|
|
76
|
+
context = nativeContext(ctx);
|
|
77
|
+
} catch {
|
|
78
|
+
return {
|
|
79
|
+
flagKey: key,
|
|
80
|
+
value: fallback,
|
|
81
|
+
reason: "ERROR",
|
|
82
|
+
errorCode: "INVALID_CONTEXT"
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
const details = await read(this.resolve(), context);
|
|
86
|
+
return {
|
|
87
|
+
...details,
|
|
88
|
+
reason: details.reason === void 0 ? "UNKNOWN" : details.reason
|
|
89
|
+
};
|
|
43
90
|
}
|
|
44
91
|
};
|
|
45
92
|
/** Convenience factory for {@link FlagshipFlagDriver}. */
|
|
46
93
|
function flagshipFlagDriver(binding, options) {
|
|
47
94
|
return new FlagshipFlagDriver(binding, options);
|
|
48
95
|
}
|
|
96
|
+
/** Copy only validated scalar attributes; never coerce nested or non-finite values. */
|
|
97
|
+
function nativeContext(ctx) {
|
|
98
|
+
if (ctx === void 0) return void 0;
|
|
99
|
+
if (ctx === null || typeof ctx !== "object" || Array.isArray(ctx) || Object.getPrototypeOf(ctx) !== Object.prototype && Object.getPrototypeOf(ctx) !== null) throw new TypeError("Invalid Flagship evaluation context");
|
|
100
|
+
const entries = [];
|
|
101
|
+
for (const [key, value] of Object.entries(ctx)) {
|
|
102
|
+
if (typeof value !== "string" && typeof value !== "boolean" && !(typeof value === "number" && Number.isFinite(value))) throw new TypeError("Invalid Flagship evaluation context");
|
|
103
|
+
entries.push([key, value]);
|
|
104
|
+
}
|
|
105
|
+
return Object.fromEntries(entries);
|
|
106
|
+
}
|
|
49
107
|
//#endregion
|
|
50
108
|
export { FlagshipFlagDriver, flagshipFlagDriver };
|
|
51
109
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flagship-flag.driver.js","names":[],"sources":["../../src/services/flagship-flag.driver.ts"],"sourcesContent":["import type { FeatureFlagDriver, FlagContext } from '@velajs/feature-flags';\n\n/**\n * The subset of a Cloudflare **Flagship** binding this driver evaluates against\n * — the four typed value methods. The binding itself returns the supplied\n * `defaultValue` on evaluation errors; transport-level failures reject and are\n * left to propagate (never-throw is the service layer's job, not the driver's).\n *\n * @see https://developers.cloudflare.com/flagship/binding/\n */\nexport interface FlagshipBinding {\n getBooleanValue(key: string, defaultValue: boolean, context?: FlagContext): Promise<boolean>;\n getStringValue(key: string, defaultValue: string, context?: FlagContext): Promise<string>;\n getNumberValue(key: string, defaultValue: number, context?: FlagContext): Promise<number>;\n getObjectValue(key: string, defaultValue: object, context?: FlagContext): Promise<unknown>;\n}\n\nexport interface FlagshipFlagDriverOptions {\n /** Driver name used for `use(name)` / default-driver selection. Default `\"flagship\"`. */\n name?: string;\n}\n\n/**\n * {@link FeatureFlagDriver} backed by a Cloudflare Flagship binding.\n *\n * A thin, honest wrapper: each contract method maps 1:1 onto the binding's\n * corresponding value method, forwarding the caller's `fallback` (the binding's\n * `defaultValue`) and evaluation context. The binding resolves the fallback on\n * evaluation errors; anything the binding *rejects* with (e.g. a `remote: true`\n * dev-proxy tunnel dropping) propagates — `@velajs/feature-flags`'s service owns\n * the never-throw guarantee.\n *\n * Build the driver inside a provider factory with the native environment:\n *\n * ```ts\n * FeatureFlagsModule.forRootAsync({\n * inject: [ENV],\n * useFactory: (env: WorkerEnv) => ({ drivers: [flagshipFlagDriver(env.FLAGS)] }),\n * });\n * ```\n *\n * Evaluation ergonomics (the 1:1 binding-method mapping) are ported from the\n * Stratal feature-flags service (MIT, © Temitayo Fadojutimi), reshaped as a\n * bare driver.\n */\nexport class FlagshipFlagDriver implements FeatureFlagDriver {\n readonly name: string;\n private readonly resolve: () => FlagshipBinding;\n\n constructor(\n binding: FlagshipBinding | (() => FlagshipBinding),\n options: FlagshipFlagDriverOptions = {},\n ) {\n this.resolve = typeof binding === 'function' ? binding : () => binding;\n this.name = options.name ?? 'flagship';\n }\n\n getBoolean(key: string, fallback: boolean, ctx?: FlagContext): Promise<boolean> {\n return this.resolve().getBooleanValue(key, fallback, ctx);\n }\n\n getString(key: string, fallback: string, ctx?: FlagContext): Promise<string> {\n return this.resolve().getStringValue(key, fallback, ctx);\n }\n\n getNumber(key: string, fallback: number, ctx?: FlagContext): Promise<number> {\n return this.resolve().getNumberValue(key, fallback, ctx);\n }\n\n getObject(key: string, fallback: object, ctx?: FlagContext): Promise<unknown> {\n return this.resolve().getObjectValue(key, fallback, ctx);\n }\n}\n\n/** Convenience factory for {@link FlagshipFlagDriver}. */\nexport function flagshipFlagDriver(\n binding: FlagshipBinding | (() => FlagshipBinding),\n options?: FlagshipFlagDriverOptions,\n): FlagshipFlagDriver {\n return new FlagshipFlagDriver(binding, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6CA,IAAa,qBAAb,MAA6D;CAC3D;CACA;CAEA,YACE,SACA,UAAqC,CAAC,GACtC;EACA,KAAK,UAAU,OAAO,YAAY,aAAa,gBAAgB;EAC/D,KAAK,OAAO,QAAQ,QAAQ;CAC9B;CAEA,WAAW,KAAa,UAAmB,KAAqC;EAC9E,OAAO,KAAK,QAAQ,CAAC,CAAC,gBAAgB,KAAK,UAAU,GAAG;CAC1D;CAEA,UAAU,KAAa,UAAkB,KAAoC;EAC3E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,GAAG;CACzD;CAEA,UAAU,KAAa,UAAkB,KAAoC;EAC3E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,GAAG;CACzD;CAEA,UAAU,KAAa,UAAkB,KAAqC;EAC5E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,GAAG;CACzD;AACF;;AAGA,SAAgB,mBACd,SACA,SACoB;CACpB,OAAO,IAAI,mBAAmB,SAAS,OAAO;AAChD"}
|
|
1
|
+
{"version":3,"file":"flagship-flag.driver.js","names":[],"sources":["../../src/services/flagship-flag.driver.ts"],"sourcesContent":["import type { FeatureFlagDriver, FlagContext, FlagEvaluationDetails } from '@velajs/feature-flags';\n\n/**\n * The subset of a Cloudflare **Flagship** binding this driver evaluates against\n * — typed value methods and optional evaluation details. The binding itself returns the supplied\n * `defaultValue` on evaluation errors; transport-level failures reject and are\n * left to propagate (never-throw is the service layer's job, not the driver's).\n *\n * @see https://developers.cloudflare.com/flagship/binding/\n */\ntype NativeFlagDetails<T> = Omit<FlagEvaluationDetails<T>, 'reason'> & { reason?: string };\n\nexport interface FlagshipBinding {\n getBooleanValue(\n key: string,\n defaultValue: boolean,\n context?: Record<string, string | number | boolean>,\n ): Promise<boolean>;\n getStringValue(\n key: string,\n defaultValue: string,\n context?: Record<string, string | number | boolean>,\n ): Promise<string>;\n getNumberValue(\n key: string,\n defaultValue: number,\n context?: Record<string, string | number | boolean>,\n ): Promise<number>;\n getObjectValue(\n key: string,\n defaultValue: object,\n context?: Record<string, string | number | boolean>,\n ): Promise<unknown>;\n getBooleanDetails?(\n key: string,\n defaultValue: boolean,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<boolean>>;\n getStringDetails?(\n key: string,\n defaultValue: string,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<string>>;\n getNumberDetails?(\n key: string,\n defaultValue: number,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<number>>;\n getObjectDetails?(\n key: string,\n defaultValue: object,\n context?: Record<string, string | number | boolean>,\n ): Promise<NativeFlagDetails<unknown>>;\n}\n\nexport interface FlagshipFlagDriverOptions {\n /** Driver name used for `use(name)` / default-driver selection. Default `\"flagship\"`. */\n name?: string;\n}\n\n/**\n * {@link FeatureFlagDriver} backed by a Cloudflare Flagship binding.\n *\n * A thin, honest wrapper: each contract method maps 1:1 onto the binding's\n * corresponding native method, forwarding the caller's `fallback` (the binding's\n * `defaultValue`) and validated scalar evaluation context. Optional detail methods\n * preserve native reasons, variants and error codes; value-only bindings report UNKNOWN. The binding resolves the fallback on\n * evaluation errors; anything the binding *rejects* with (e.g. a `remote: true`\n * dev-proxy tunnel dropping) propagates — `@velajs/feature-flags`'s service owns\n * the never-throw guarantee.\n *\n * Build the driver inside a provider factory with the native environment:\n *\n * ```ts\n * FeatureFlagsModule.forRootAsync({\n * inject: [ENV],\n * useFactory: (env: WorkerEnv) => ({ drivers: [flagshipFlagDriver(env.FLAGS)] }),\n * });\n * ```\n *\n * Evaluation ergonomics (the 1:1 binding-method mapping) are ported from the\n * Stratal feature-flags service (MIT, © Temitayo Fadojutimi), reshaped as a\n * bare driver.\n */\nexport class FlagshipFlagDriver implements FeatureFlagDriver {\n readonly name: string;\n private readonly resolve: () => FlagshipBinding;\n\n constructor(\n binding: FlagshipBinding | (() => FlagshipBinding),\n options: FlagshipFlagDriverOptions = {},\n ) {\n this.resolve = typeof binding === 'function' ? binding : () => binding;\n this.name = options.name ?? 'flagship';\n }\n\n getBoolean(key: string, fallback: boolean, ctx?: FlagContext): Promise<boolean> {\n return this.resolve().getBooleanValue(key, fallback, nativeContext(ctx));\n }\n\n getString(key: string, fallback: string, ctx?: FlagContext): Promise<string> {\n return this.resolve().getStringValue(key, fallback, nativeContext(ctx));\n }\n\n getNumber(key: string, fallback: number, ctx?: FlagContext): Promise<number> {\n return this.resolve().getNumberValue(key, fallback, nativeContext(ctx));\n }\n\n getObject(key: string, fallback: object, ctx?: FlagContext): Promise<unknown> {\n return this.resolve().getObjectValue(key, fallback, nativeContext(ctx));\n }\n getBooleanDetails(\n key: string,\n fallback: boolean,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<boolean>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getBooleanDetails\n ? binding.getBooleanDetails(key, fallback, context)\n : binding\n .getBooleanValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n getStringDetails(\n key: string,\n fallback: string,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<string>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getStringDetails\n ? binding.getStringDetails(key, fallback, context)\n : binding\n .getStringValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n getNumberDetails(\n key: string,\n fallback: number,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<number>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getNumberDetails\n ? binding.getNumberDetails(key, fallback, context)\n : binding\n .getNumberValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n getObjectDetails(\n key: string,\n fallback: object,\n ctx?: FlagContext,\n ): Promise<FlagEvaluationDetails<unknown>> {\n return this.details(key, fallback, ctx, (binding, context) =>\n binding.getObjectDetails\n ? binding.getObjectDetails(key, fallback, context)\n : binding\n .getObjectValue(key, fallback, context)\n .then((value) => ({ flagKey: key, value, reason: 'UNKNOWN' })),\n );\n }\n\n private async details<T>(\n key: string,\n fallback: T,\n ctx: FlagContext | undefined,\n read: (\n binding: FlagshipBinding,\n context: Record<string, string | number | boolean> | undefined,\n ) => Promise<NativeFlagDetails<T>>,\n ): Promise<FlagEvaluationDetails<T>> {\n let context: Record<string, string | number | boolean> | undefined;\n try {\n context = nativeContext(ctx);\n } catch {\n return { flagKey: key, value: fallback, reason: 'ERROR', errorCode: 'INVALID_CONTEXT' };\n }\n const details = await read(this.resolve(), context);\n return { ...details, reason: details.reason === undefined ? 'UNKNOWN' : details.reason };\n }\n}\n\n/** Convenience factory for {@link FlagshipFlagDriver}. */\nexport function flagshipFlagDriver(\n binding: FlagshipBinding | (() => FlagshipBinding),\n options?: FlagshipFlagDriverOptions,\n): FlagshipFlagDriver {\n return new FlagshipFlagDriver(binding, options);\n}\n\n/** Copy only validated scalar attributes; never coerce nested or non-finite values. */\nfunction nativeContext(\n ctx: FlagContext | undefined,\n): Record<string, string | number | boolean> | undefined {\n if (ctx === undefined) return undefined;\n if (\n ctx === null ||\n typeof ctx !== 'object' ||\n Array.isArray(ctx) ||\n (Object.getPrototypeOf(ctx) !== Object.prototype && Object.getPrototypeOf(ctx) !== null)\n )\n throw new TypeError('Invalid Flagship evaluation context');\n const entries: [string, string | number | boolean][] = [];\n for (const [key, value] of Object.entries(ctx)) {\n if (\n typeof value !== 'string' &&\n typeof value !== 'boolean' &&\n !(typeof value === 'number' && Number.isFinite(value))\n )\n throw new TypeError('Invalid Flagship evaluation context');\n entries.push([key, value]);\n }\n return Object.fromEntries(entries);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAoFA,IAAa,qBAAb,MAA6D;CAC3D;CACA;CAEA,YACE,SACA,UAAqC,CAAC,GACtC;EACA,KAAK,UAAU,OAAO,YAAY,aAAa,gBAAgB;EAC/D,KAAK,OAAO,QAAQ,QAAQ;CAC9B;CAEA,WAAW,KAAa,UAAmB,KAAqC;EAC9E,OAAO,KAAK,QAAQ,CAAC,CAAC,gBAAgB,KAAK,UAAU,cAAc,GAAG,CAAC;CACzE;CAEA,UAAU,KAAa,UAAkB,KAAoC;EAC3E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,cAAc,GAAG,CAAC;CACxE;CAEA,UAAU,KAAa,UAAkB,KAAoC;EAC3E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,cAAc,GAAG,CAAC;CACxE;CAEA,UAAU,KAAa,UAAkB,KAAqC;EAC5E,OAAO,KAAK,QAAQ,CAAC,CAAC,eAAe,KAAK,UAAU,cAAc,GAAG,CAAC;CACxE;CACA,kBACE,KACA,UACA,KACyC;EACzC,OAAO,KAAK,QAAQ,KAAK,UAAU,MAAM,SAAS,YAChD,QAAQ,oBACJ,QAAQ,kBAAkB,KAAK,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,mBAAmB,SAAS,OAAO;AAChD;;AAGA,SAAS,cACP,KACuD;CACvD,IAAI,QAAQ,KAAA,GAAW,OAAO,KAAA;CAC9B,IACE,QAAQ,QACR,OAAO,QAAQ,YACf,MAAM,QAAQ,GAAG,KAChB,OAAO,eAAe,GAAG,MAAM,OAAO,aAAa,OAAO,eAAe,GAAG,MAAM,MAEnF,MAAM,IAAI,UAAU,qCAAqC;CAC3D,MAAM,UAAiD,CAAC;CACxD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAAG;EAC9C,IACE,OAAO,UAAU,YACjB,OAAO,UAAU,aACjB,EAAE,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAEpD,MAAM,IAAI,UAAU,qCAAqC;EAC3D,QAAQ,KAAK,CAAC,KAAK,KAAK,CAAC;CAC3B;CACA,OAAO,OAAO,YAAY,OAAO;AACnC"}
|
|
@@ -3,8 +3,8 @@ import { kv } from "../bindings.js";
|
|
|
3
3
|
const namespaceOf = (source) => typeof source === "function" ? source : () => source;
|
|
4
4
|
/**
|
|
5
5
|
* Native KV JSON value store. Metadata retains logical expiry even when KV's
|
|
6
|
-
* physical retention rounds up to its 60-second minimum.
|
|
7
|
-
*
|
|
6
|
+
* physical retention rounds up to its 60-second minimum. Values without
|
|
7
|
+
* Vela expiry metadata are cache misses.
|
|
8
8
|
*/
|
|
9
9
|
var KVCacheStore = class {
|
|
10
10
|
#namespace;
|
|
@@ -22,13 +22,13 @@ var KVCacheStore = class {
|
|
|
22
22
|
if (value === null) return void 0;
|
|
23
23
|
if (typeof metadata === "object" && metadata !== null && "velaCacheExpiresAt" in metadata) {
|
|
24
24
|
const expiresAt = metadata.velaCacheExpiresAt;
|
|
25
|
+
if (expiresAt === null) return { value };
|
|
25
26
|
if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt) || expiresAt <= Date.now()) return void 0;
|
|
26
27
|
return {
|
|
27
28
|
value,
|
|
28
29
|
expiresAt
|
|
29
30
|
};
|
|
30
31
|
}
|
|
31
|
-
return { value };
|
|
32
32
|
}
|
|
33
33
|
async set(key, value, ttl) {
|
|
34
34
|
if (ttl !== void 0 && (!Number.isFinite(ttl) || ttl < 0)) throw new TypeError("Cache TTL must be finite and nonnegative.");
|
|
@@ -36,7 +36,7 @@ var KVCacheStore = class {
|
|
|
36
36
|
value,
|
|
37
37
|
expiresAt: Date.now() + ttl * 1e3
|
|
38
38
|
});
|
|
39
|
-
await this.ns.put(key, JSON.stringify(value));
|
|
39
|
+
await this.ns.put(key, JSON.stringify(value), { metadata: { velaCacheExpiresAt: null } });
|
|
40
40
|
}
|
|
41
41
|
async setEntry(key, entry) {
|
|
42
42
|
if (!Number.isFinite(entry.expiresAt)) throw new TypeError("Cache expiry must be finite.");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kv-cache.store.js","names":[],"sources":["../../src/services/kv-cache.store.ts"],"sourcesContent":["import type {\n CacheEntry,\n CacheEntryReader,\n CacheEntryWriter,\n CacheInvalidationStore,\n CacheStore,\n} from '@velajs/vela/cache';\nimport type { EnvFactory } from '@velajs/vela/module-kit';\nimport { kv } from '../bindings';\n\n/** A KV namespace, or a function that reads it when an operation needs it. */\nexport type KVNamespaceSource = KVNamespace | (() => KVNamespace);\n\nconst namespaceOf = (source: KVNamespaceSource): (() => KVNamespace) =>\n typeof source === 'function' ? source : () => source;\n\n/**\n * Native KV JSON value store. Metadata retains logical expiry even when KV's\n * physical retention rounds up to its 60-second minimum.
|
|
1
|
+
{"version":3,"file":"kv-cache.store.js","names":[],"sources":["../../src/services/kv-cache.store.ts"],"sourcesContent":["import type {\n CacheEntry,\n CacheEntryReader,\n CacheEntryWriter,\n CacheInvalidationStore,\n CacheStore,\n} from '@velajs/vela/cache';\nimport type { EnvFactory } from '@velajs/vela/module-kit';\nimport { kv } from '../bindings';\n\n/** A KV namespace, or a function that reads it when an operation needs it. */\nexport type KVNamespaceSource = KVNamespace | (() => KVNamespace);\n\nconst namespaceOf = (source: KVNamespaceSource): (() => KVNamespace) =>\n typeof source === 'function' ? source : () => source;\n\n/**\n * Native KV JSON value store. Metadata retains logical expiry even when KV's\n * physical retention rounds up to its 60-second minimum. Values without\n * Vela expiry metadata are cache misses.\n */\nexport class KVCacheStore implements CacheStore, CacheEntryReader, CacheEntryWriter {\n readonly #namespace: () => KVNamespace;\n constructor(namespace: KVNamespaceSource) {\n this.#namespace = namespaceOf(namespace);\n }\n\n private get ns(): KVNamespace {\n return this.#namespace();\n }\n\n async get(key: string): Promise<unknown> {\n return (await this.getEntry(key))?.value;\n }\n\n async getEntry(key: string): Promise<{ value: unknown; expiresAt?: number } | undefined> {\n const { value, metadata } = await this.ns.getWithMetadata<unknown, unknown>(key, 'json');\n if (value === null) return undefined;\n if (typeof metadata === 'object' && metadata !== null && 'velaCacheExpiresAt' in metadata) {\n const expiresAt = metadata.velaCacheExpiresAt;\n if (expiresAt === null) return { value };\n if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt) || expiresAt <= Date.now())\n return undefined;\n return { value, expiresAt };\n }\n return undefined;\n }\n\n async set(key: string, value: unknown, ttl?: number): Promise<void> {\n if (ttl !== undefined && (!Number.isFinite(ttl) || ttl < 0))\n throw new TypeError('Cache TTL must be finite and nonnegative.');\n if (ttl !== undefined) return this.setEntry(key, { value, expiresAt: Date.now() + ttl * 1000 });\n await this.ns.put(key, JSON.stringify(value), { metadata: { velaCacheExpiresAt: null } });\n }\n\n async setEntry(key: string, entry: CacheEntry): Promise<void> {\n if (!Number.isFinite(entry.expiresAt)) throw new TypeError('Cache expiry must be finite.');\n const remaining = (entry.expiresAt - Date.now()) / 1000;\n if (remaining <= 0) return this.del(key);\n await this.ns.put(key, JSON.stringify(entry.value), {\n expirationTtl: Math.max(60, Math.ceil(remaining)),\n metadata: { velaCacheExpiresAt: entry.expiresAt },\n });\n }\n\n async del(key: string): Promise<void> {\n await this.ns.delete(key);\n }\n\n /** Namespace-wide, best effort. Use a dedicated value namespace; never use for scoped invalidation. */\n async clear(): Promise<void> {\n let cursor: string | undefined;\n do {\n const list = await this.ns.list(cursor ? { cursor } : undefined);\n await Promise.all(list.keys.map((entry) => this.ns.delete(entry.name)));\n cursor = list.list_complete ? undefined : list.cursor;\n } while (cursor);\n }\n}\n\n/**\n * Optional, eventually consistent generation store. Use a dedicated KV namespace\n * without TTL/lifecycle cleanup. Never delete/reset generations while entries can\n * survive. Concurrent writes and cached/negative reads prevent strong invalidation;\n * this is unsuitable for strict read-after-write or authorization revocation.\n */\nexport class KVCacheInvalidationStore implements CacheInvalidationStore {\n readonly #namespace: () => KVNamespace;\n constructor(namespace: KVNamespaceSource) {\n this.#namespace = namespaceOf(namespace);\n }\n\n private get ns(): KVNamespace {\n return this.#namespace();\n }\n\n async getVersion(key: string): Promise<string> {\n const value: unknown = await this.ns.get(key, 'json');\n if (value === null) return 'initial';\n if (typeof value !== 'string' || value.length === 0 || value.length > 2048)\n throw new TypeError('Invalid cache generation.');\n return value;\n }\n async invalidate(key: string): Promise<void> {\n await this.ns.put(key, JSON.stringify(crypto.randomUUID()));\n }\n}\n\n/**\n * `CacheModule`'s value store over the KV namespace named `binding`, read from\n * each application's `ENV` when an operation needs it:\n * `CacheModule.forRoot({ namespace, scope, store: kvCache({ binding: 'CACHE' }) })`.\n */\nexport function kvCache(ref: { binding: string }): EnvFactory<CacheStore> {\n const namespace = kv(ref);\n return (env) => new KVCacheStore(() => namespace(env));\n}\n\n/**\n * `CacheModule`'s generation store over a dedicated KV namespace named\n * `binding`, without TTLs or lifecycle cleanup. Eventually consistent; see\n * {@link KVCacheInvalidationStore}.\n */\nexport function kvCacheInvalidation(ref: { binding: string }): EnvFactory<CacheInvalidationStore> {\n const namespace = kv(ref);\n return (env) => new KVCacheInvalidationStore(() => namespace(env));\n}\n"],"mappings":";;AAaA,MAAM,eAAe,WACnB,OAAO,WAAW,aAAa,eAAe;;;;;;AAOhD,IAAa,eAAb,MAAoF;CAClF;CACA,YAAY,WAA8B;EACxC,KAAK,aAAa,Y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are-application-
|
|
2
|
+
import "./cloudflare-application-Dsscb3Mo.js";
|
|
3
3
|
import { EntrypointExecutionContext } from "@velajs/vela/module-kit";
|
|
4
4
|
//#region src/tail/on-tail.d.ts
|
|
5
5
|
/** A method decorator whose method receives a batch of Tail Workers events. */
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./vela-env-DFvyoNT3.js";
|
|
2
|
-
import { d as CloudflareWorkerOptions, y as CloudflareRoot } from "./cloudflare-factory-
|
|
2
|
+
import { d as CloudflareWorkerOptions, y as CloudflareRoot } from "./cloudflare-factory-DM9CBvNH.js";
|
|
3
3
|
import { VelaEnv } from "@velajs/vela";
|
|
4
4
|
import { QueueJob, QueueJobDefinition, QueueJobInput } from "@velajs/vela/queue";
|
|
5
5
|
import { TestingModule, TestingModuleBuilder } from "@velajs/testing";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { CallHandler, ExecutionContext, NestInterceptor } from "@velajs/vela";
|
|
2
|
+
//#region src/tracing.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Native Workers spans around awaited HTTP/RPC handler work. Register through
|
|
5
|
+
* `@UseInterceptors(CloudflareTracingInterceptor)` on a controller or RPC host.
|
|
6
|
+
*
|
|
7
|
+
* The callback establishes the native async parent for inner interceptors,
|
|
8
|
+
* handler code and awaited platform calls. Guards/pipes run before it; response
|
|
9
|
+
* streams, deferred work and scope disposal can outlive it. Cloudflare owns
|
|
10
|
+
* sampling, ending and export. This is not a portable Telemetry recorder.
|
|
11
|
+
*/
|
|
12
|
+
export declare class CloudflareTracingInterceptor implements NestInterceptor {
|
|
13
|
+
intercept(context: ExecutionContext, next: CallHandler): Promise<unknown>;
|
|
14
|
+
}
|
|
15
|
+
//#endregion
|
package/dist/tracing.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import __decorate from "./_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js";
|
|
2
|
+
import { Injectable } from "@velajs/vela";
|
|
3
|
+
import { tracing } from "cloudflare:workers";
|
|
4
|
+
//#region src/tracing.ts
|
|
5
|
+
const MAX_LABEL_LENGTH = 128;
|
|
6
|
+
let CloudflareTracingInterceptor = class CloudflareTracingInterceptor {
|
|
7
|
+
intercept(context, next) {
|
|
8
|
+
const kind = context.getType();
|
|
9
|
+
if (kind !== "http" && kind !== "rpc") return next.handle();
|
|
10
|
+
return tracing.enterSpan(kind === "http" ? "vela.http.handler" : "vela.rpc.handler", (span) => {
|
|
11
|
+
if (span.isTraced) {
|
|
12
|
+
span.setAttribute("vela.handler.class", context.getClass().name.slice(0, MAX_LABEL_LENGTH));
|
|
13
|
+
const method = context.getHandlerName();
|
|
14
|
+
if (typeof method === "string") span.setAttribute("vela.handler.method", method.slice(0, MAX_LABEL_LENGTH));
|
|
15
|
+
}
|
|
16
|
+
return next.handle();
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
CloudflareTracingInterceptor = __decorate([Injectable()], CloudflareTracingInterceptor);
|
|
21
|
+
//#endregion
|
|
22
|
+
export { CloudflareTracingInterceptor };
|
|
23
|
+
|
|
24
|
+
//# sourceMappingURL=tracing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tracing.js","names":[],"sources":["../src/tracing.ts"],"sourcesContent":["import { tracing } from 'cloudflare:workers';\nimport {\n Injectable,\n type CallHandler,\n type ExecutionContext,\n type NestInterceptor,\n} from '@velajs/vela';\n\nconst MAX_LABEL_LENGTH = 128;\n\n/**\n * Native Workers spans around awaited HTTP/RPC handler work. Register through\n * `@UseInterceptors(CloudflareTracingInterceptor)` on a controller or RPC host.\n *\n * The callback establishes the native async parent for inner interceptors,\n * handler code and awaited platform calls. Guards/pipes run before it; response\n * streams, deferred work and scope disposal can outlive it. Cloudflare owns\n * sampling, ending and export. This is not a portable Telemetry recorder.\n */\n@Injectable()\nexport class CloudflareTracingInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Promise<unknown> {\n const kind = context.getType();\n if (kind !== 'http' && kind !== 'rpc') return next.handle();\n\n return tracing.enterSpan(kind === 'http' ? 'vela.http.handler' : 'vela.rpc.handler', (span) => {\n if (span.isTraced) {\n span.setAttribute('vela.handler.class', context.getClass().name.slice(0, MAX_LABEL_LENGTH));\n const method = context.getHandlerName();\n // Symbol descriptions may contain caller data; only declared string\n // method names belong in these fixed, bounded instrumentation labels.\n if (typeof method === 'string') {\n span.setAttribute('vela.handler.method', method.slice(0, MAX_LABEL_LENGTH));\n }\n }\n // Return the actual handler promise from INSIDE enterSpan. Starting a\n // span in an onStart observer would lose native parent-child nesting.\n return next.handle();\n });\n }\n}\n"],"mappings":";;;;AAQA,MAAM,mBAAmB;AAYlB,IAAM,+BAAN,MAAM,6BAAwD;CACnE,UAAU,SAA2B,MAAqC;EACxE,MAAM,OAAO,QAAQ,QAAQ;EAC7B,IAAI,SAAS,UAAU,SAAS,OAAO,OAAO,KAAK,OAAO;EAE1D,OAAO,QAAQ,UAAU,SAAS,SAAS,sBAAsB,qBAAqB,SAAS;GAC7F,IAAI,KAAK,UAAU;IACjB,KAAK,aAAa,sBAAsB,QAAQ,SAAS,CAAC,CAAC,KAAK,MAAM,GAAG,gBAAgB,CAAC;IAC1F,MAAM,SAAS,QAAQ,eAAe;IAGtC,IAAI,OAAO,WAAW,UACpB,KAAK,aAAa,uBAAuB,OAAO,MAAM,GAAG,gBAAgB,CAAC;GAE9E;GAGA,OAAO,KAAK,OAAO;EACrB,CAAC;CACH;AACF;AArBC,+BAAA,WAAA,CAAA,WAAW,CAAA,GAAA,4BAAA"}
|
|
@@ -7,7 +7,7 @@ import { WS_GATEWAY_METADATA, WS_SERVER } from "@velajs/vela/websocket";
|
|
|
7
7
|
*/
|
|
8
8
|
function bindingGateways(discovery) {
|
|
9
9
|
const gateways = /* @__PURE__ */ new Map();
|
|
10
|
-
for (const { metatype, meta } of discovery.
|
|
10
|
+
for (const { metatype, meta } of discovery.registrationsWithMeta(WS_GATEWAY_METADATA, { metadataOnly: true })) {
|
|
11
11
|
const path = meta.path ?? "";
|
|
12
12
|
if (typeof meta.binding !== "string" || gateways.has(path)) continue;
|
|
13
13
|
gateways.set(path, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"binding-gateways.js","names":[],"sources":["../../src/websocket/binding-gateways.ts"],"sourcesContent":["import type { Container, DiscoveryService } from '@velajs/vela/module-kit';\nimport {\n WS_GATEWAY_METADATA,\n WS_SERVER,\n type WebSocketGatewayOptions,\n} from '@velajs/vela/websocket';\nimport { reportDiagnostic } from '../diagnostics';\n\n/** A gateway whose rooms live in Durable Objects: its path and namespace binding. */\nexport interface BindingGateway {\n path: string;\n binding: string;\n /** The gateway class name, for diagnostics. */\n name: string;\n}\n\n/**\n * The application's gateways that name a `binding`, in discovery order, once\n * per path. Read from decorator metadata, so lifecycle hooks can use it.\n */\nexport function bindingGateways(discovery: DiscoveryService): BindingGateway[] {\n const gateways = new Map<string, BindingGateway>();\n for (const { metatype, meta } of discovery.
|
|
1
|
+
{"version":3,"file":"binding-gateways.js","names":[],"sources":["../../src/websocket/binding-gateways.ts"],"sourcesContent":["import type { Container, DiscoveryService } from '@velajs/vela/module-kit';\nimport {\n WS_GATEWAY_METADATA,\n WS_SERVER,\n type WebSocketGatewayOptions,\n} from '@velajs/vela/websocket';\nimport { reportDiagnostic } from '../diagnostics';\n\n/** A gateway whose rooms live in Durable Objects: its path and namespace binding. */\nexport interface BindingGateway {\n path: string;\n binding: string;\n /** The gateway class name, for diagnostics. */\n name: string;\n}\n\n/**\n * The application's gateways that name a `binding`, in discovery order, once\n * per path. Read from decorator metadata, so lifecycle hooks can use it.\n */\nexport function bindingGateways(discovery: DiscoveryService): BindingGateway[] {\n const gateways = new Map<string, BindingGateway>();\n for (const { metatype, meta } of discovery.registrationsWithMeta<WebSocketGatewayOptions>(\n WS_GATEWAY_METADATA,\n { metadataOnly: true },\n )) {\n const path = meta.path ?? '';\n if (typeof meta.binding !== 'string' || gateways.has(path)) continue;\n gateways.set(path, {\n path,\n binding: meta.binding,\n name: metatype.name,\n });\n }\n return [...gateways.values()];\n}\n\n/**\n * `WebSocketModule` mounts the Worker's upgrade routes. An application with a\n * binding-backed gateway but without that module answers its upgrades with\n * 404, so report each such gateway through the diagnostics policy.\n */\nexport function reportUnservedGateways(container: Container, discovery: DiscoveryService): void {\n if (container.has(WS_SERVER)) return;\n for (const { name, binding, path } of bindingGateways(discovery)) {\n reportDiagnostic(\n container,\n `[vela] ${name} is a @WebSocketGateway with binding '${binding}', but the application ` +\n `does not import WebSocketModule.forRoot() from @velajs/vela/websocket, so upgrades ` +\n `to '${path}' answer 404 instead of reaching its Durable Object.`,\n );\n }\n}\n"],"mappings":";;;;;;;AAoBA,SAAgB,gBAAgB,WAA+C;CAC7E,MAAM,2BAAW,IAAI,IAA4B;CACjD,KAAK,MAAM,EAAE,UAAU,UAAU,UAAU,sBACzC,qBACA,EAAE,cAAc,KAAK,CACvB,GAAG;EACD,MAAM,OAAO,KAAK,QAAQ;EAC1B,IAAI,OAAO,KAAK,YAAY,YAAY,SAAS,IAAI,IAAI,GAAG;EAC5D,SAAS,IAAI,MAAM;GACjB;GACA,SAAS,KAAK;GACd,MAAM,SAAS;EACjB,CAAC;CACH;CACA,OAAO,CAAC,GAAG,SAAS,OAAO,CAAC;AAC9B;;;;;;AAOA,SAAgB,uBAAuB,WAAsB,WAAmC;CAC9F,IAAI,UAAU,IAAI,SAAS,GAAG;CAC9B,KAAK,MAAM,EAAE,MAAM,SAAS,UAAU,gBAAgB,SAAS,GAC7D,iBACE,WACA,UAAU,KAAK,wCAAwC,QAAQ,gHAEtD,KAAK,qDAChB;AAEJ"}
|