@webpieces/core-util 0.4.763 → 0.4.766

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/core-util",
3
- "version": "0.4.763",
3
+ "version": "0.4.766",
4
4
  "description": "Utility functions for WebPieces - works in browser and Node.js",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -24,6 +24,8 @@ export declare const METADATA_KEYS: {
24
24
  ENDPOINT_CALLER: string;
25
25
  /** Per-method @MaskLog spec (which DTO fields the LogApiCall path masks). */
26
26
  MASK_LOG: string;
27
+ /** Per-method opt-in metadata for publishing an RPC endpoint as an MCP tool. */
28
+ MCP_TOOLS: string;
27
29
  };
28
30
  /**
29
31
  * WHAT TRIGGERS an endpoint at runtime — the single fact that decides how the runtime architecture
@@ -54,6 +54,8 @@ exports.METADATA_KEYS = {
54
54
  ENDPOINT_CALLER: external_caller_1.ENDPOINT_CALLER_KEY,
55
55
  /** Per-method @MaskLog spec (which DTO fields the LogApiCall path masks). */
56
56
  MASK_LOG: 'webpieces:mask-log',
57
+ /** Per-method opt-in metadata for publishing an RPC endpoint as an MCP tool. */
58
+ MCP_TOOLS: 'webpieces:mcp-tools',
57
59
  };
58
60
  /**
59
61
  * @ApiPath(basePath) - Class decorator that marks a class as an API definition
@@ -1 +1 @@
1
- {"version":3,"file":"decorators.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/decorators.ts"],"names":[],"mappings":";;;AA+GA,0BAcC;AAsDD,4BA2CC;AAoBD,0BAUC;AAOD,kCAIC;AAsCD,oCAOC;AAgBD,8BAEC;AAQD,sCAEC;AAaD,gCAEC;AASD,gDAEC;AAgCD,sCAEC;AAuDD,oCAEC;AA8BD,0CAEC;AASD,gCAEC;AAMD,oCAEC;AAOD,4CAEC;AAWD,0CAEC;AAMD,gDAIC;AASD,8FAcC;AAOD,gCAEC;AAOD,8B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AC3C,CAAC,CAAC,SAAS,UAAU,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CACX,iCAAiC,QAAQ,IAAI;YACzC,gFAAgF;YAChF,kEAAkE;YAClE,gDAAgD,CACvD,CAAC;IACN,CAAC;AACL,CAAC","sourcesContent":["import 'reflect-metadata';\nimport { MaskSpec, MaskMode } from './LogFieldMask';\nimport {\n DEFAULT_CALLER_KIND,\n ENDPOINT_CALLER_KEY,\n ExternalCaller,\n ExternalSystemKind,\n getEndpointCaller,\n} from './external-caller';\n// The TYPE layer these decorators attach — split out for file size only (see auth-mode.ts).\nimport { ApiKeyCredentials, AuthMeta, AuthMode, JwtRequirement } from './auth-mode';\n\n/**\n * Metadata keys for storing API routing information.\n * These keys are used by both server-side (routing) and client-side (client generation).\n */\nexport const METADATA_KEYS = {\n API_PATH: 'webpieces:api-path',\n ENDPOINTS: 'webpieces:endpoints',\n AUTH_META: 'webpieces:auth-meta',\n /** Method names carrying one of the canonical authorization decorators. */\n AUTH_METHODS: 'webpieces:auth-methods',\n /** 'rpc' (default, sync request/response) vs 'pubsub' (fire-and-forget cloud task). */\n API_KIND: 'webpieces:api-kind',\n /** Per-method Cloud Tasks queue-name override (set via @Queue). */\n QUEUE_OVERRIDE: 'webpieces:queue-override',\n /** Per-method @Endpoint options (e.g. formPost), parallel to ENDPOINTS. */\n ENDPOINT_OPTIONS: 'webpieces:endpoint-options',\n /** Per-method @Endpoint trigger kind (rpc | cloudtasks | cron | external), parallel to ENDPOINTS. */\n ENDPOINT_KIND: 'webpieces:endpoint-kind',\n /** Per-method declared external CALLER (only for kind 'external'), parallel to ENDPOINTS. */\n ENDPOINT_CALLER: ENDPOINT_CALLER_KEY,\n /** Per-method @MaskLog spec (which DTO fields the LogApiCall path masks). */\n MASK_LOG: 'webpieces:mask-log',\n};\n\n/**\n * WHAT TRIGGERS an endpoint at runtime — the single fact that decides how the runtime architecture\n * graph draws it, and which Terraform resource must exist for it to ever fire:\n *\n * - `rpc` — a caller in this repo (or a browser) calls it synchronously. A direct arrow.\n * - `cloudtasks` — a producer ENQUEUES it; Cloud Tasks delivers it later. Drawn producer → queue →\n * consumer, one queue node per METHOD (see {@link Queue}). Producer and consumer\n * being the SAME service is legal and common — the queue decouples them.\n * - `cron` — a scheduler fires it on a clock. Nothing in-repo calls it; drawn hanging off a\n * clock symbol. Backed by a Cloud Scheduler job.\n * - `external` — a system OUTSIDE this repo drives it (a GCP Pub/Sub push subscription, a Twilio\n * or Gmail webhook). Drawn as an inbound dashed arrow from that system.\n *\n * Declared PER METHOD, because one api class routinely mixes them: an admin contract can have\n * caller-driven endpoints AND a nightly cron sweep. A class-level marker cannot express that, which\n * is exactly why the graph could not tell these apart before.\n */\nexport type EndpointKind = 'rpc' | 'cloudtasks' | 'cron' | 'external';\n\n/**\n * Options for a single @Endpoint. Kept in a metadata map PARALLEL to ENDPOINTS so the existing\n * `Record<methodName, path>` shape every consumer iterates stays unchanged.\n */\nexport interface EndpointOptions {\n /**\n * Parse the request body as application/x-www-form-urlencoded (flat key→value) instead of JSON.\n * For EXTERNAL webhooks (e.g. Twilio) that post form-encoded. The request DTO must be FLAT —\n * urlencoded has no nesting (unlike JSON). Default false = JSON.\n */\n formPost?: boolean;\n\n /**\n * RETAIN the verbatim request bytes + the absolute url the sender addressed, so an\n * {@link WpAuthWebhook} hook can verify a vendor signature over them (see `RawRequest`).\n *\n * Opt-in PER ENDPOINT, sitting beside `formPost` and for the same reason: the cost lands on the\n * handful of webhook routes rather than on every request in the process. It is retention, not\n * new buffering — the express adapter already accumulates the whole body, it simply threw it\n * away once it had parsed a DTO.\n *\n * REQUIRED by `@WpAuthWebhook`, checked at wiring time (see\n * {@link assertEveryWebhookEndpointRetainsRawBody}) rather than left to fail as a 401 in\n * production: a hook with nothing to verify is a misconfiguration, not a bad request.\n *\n * Combines with `formPost` — `{ formPost: true, rawBody: true }` is the Twilio case, where the\n * hook needs the bytes and the url while the controller still wants the flat parsed DTO.\n */\n rawBody?: boolean;\n}\n\n/**\n * Options for an `external` @Endpoint: everything {@link EndpointOptions} carries, PLUS a REQUIRED\n * declaration of WHO is calling. See {@link Endpoint} for why, `external-caller.ts` for identity.\n */\nexport interface ExternalEndpointOptions extends EndpointOptions {\n /** The outside system that posts here (`'twilio'`) — the graph node IDENTITY, not display text. */\n calledBy: string;\n /** What that caller IS; picks the node's shape. Defaults to `'saas'` (see DEFAULT_CALLER_KIND). */\n callerKind?: ExternalSystemKind;\n}\n\n/**\n * @ApiPath(basePath) - Class decorator that marks a class as an API definition\n * and sets the base path for all endpoints.\n *\n * Usage:\n * ```typescript\n * @ApiPath('/api/save')\n * abstract class SaveApi {\n * @WpAuthJwt({ roles: ['admin'] })\n * @Endpoint('/item', 'rpc')\n * save(request: SaveRequest): Promise<SaveResponse> { ... }\n * }\n * ```\n */\nexport function ApiPath(basePath: string): ClassDecorator {\n return (target: Function) => {\n if (Reflect.hasMetadata('webpieces:ipc-api-id', target)) {\n throw new Error(\n `Class ${target.name || 'Unknown'} cannot combine @ApiPath with @WpInternal.`,\n );\n }\n Reflect.defineMetadata(METADATA_KEYS.API_PATH, basePath, target);\n\n // Initialize endpoints map if not exists\n if (!Reflect.hasMetadata(METADATA_KEYS.ENDPOINTS, target)) {\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINTS, {}, target);\n }\n };\n}\n\n/**\n * @Endpoint(path, kind, options?) - Method decorator that registers a POST endpoint at the given\n * path and declares WHAT TRIGGERS it.\n *\n * All endpoints are POST-only (matching gRPC/thrift style).\n *\n * Usage:\n * ```typescript\n * @Endpoint('/item', 'rpc')\n * save(request: SaveRequest): Promise<SaveResponse> { ... }\n *\n * // enqueued by a producer, delivered later by Cloud Tasks:\n * @Endpoint('/send', 'cloudtasks')\n * send(request: SendRequest): Promise<void> { ... }\n *\n * // fired by Cloud Scheduler on a clock, called by nobody in this repo:\n * @Endpoint('/nightly', 'cron')\n * nightly(request: NightlyRequest): Promise<void> { ... }\n *\n * // EXTERNAL webhook posting application/x-www-form-urlencoded (e.g. Twilio):\n * @Endpoint('/hook', 'external', { formPost: true, calledBy: 'twilio' })\n * inbound(request: InboundRequest): Promise<InboundResponse> { ... }\n * ```\n *\n * `kind` is REQUIRED and deliberately positional: it makes every pre-existing single-argument\n * `@Endpoint('/x')` a COMPILE error rather than something a lint rule has to chase, so no endpoint\n * can slip into the runtime architecture graph with its trigger left to guesswork. See\n * {@link EndpointKind} for what each value draws and which Terraform resource backs it.\n *\n * `calledBy` is REQUIRED for `external` FOR EXACTLY THE SAME REASON, enforced by the overloads below:\n * the one box on the runtime graph whose whole job is to say who calls us from outside could only\n * restate OUR OWN contract name, because nothing in the source ever said who the caller was. This is\n * BREAKING for published consumers, intentionally — an existing `@Endpoint(p, 'external', {...})`\n * stops compiling until it names its caller. Migration is one property; see the migration note in\n * `external-caller.ts`. Non-`external` endpoints are completely unaffected.\n *\n * The path write to ENDPOINTS is UNCHANGED (every consumer iterates `[methodName, path]`); kind,\n * options and caller ride PARALLEL ENDPOINT_KIND / ENDPOINT_OPTIONS / ENDPOINT_CALLER maps.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function Endpoint(\n path: string,\n kind: 'external',\n options: ExternalEndpointOptions,\n): MethodDecorator;\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function Endpoint(\n path: string,\n kind: Exclude<EndpointKind, 'external'>,\n options?: EndpointOptions,\n): MethodDecorator;\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function Endpoint(\n path: string,\n kind: EndpointKind,\n options: EndpointOptions = {},\n): MethodDecorator {\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any, propertyKey: string | symbol, _descriptor: PropertyDescriptor) => {\n const metadataTarget = typeof target === 'function' ? target : target.constructor;\n\n const endpoints: Record<string, string> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINTS, metadataTarget) || {};\n\n endpoints[propertyKey as string] = path;\n\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINTS, endpoints, metadataTarget);\n\n const kinds: Record<string, EndpointKind> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_KIND, metadataTarget) || {};\n kinds[propertyKey as string] = kind;\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINT_KIND, kinds, metadataTarget);\n\n const opts: Record<string, EndpointOptions> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_OPTIONS, metadataTarget) || {};\n opts[propertyKey as string] = options;\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINT_OPTIONS, opts, metadataTarget);\n\n // ONLY for 'external', mirroring how a queue name is recorded only for the kinds that HAVE\n // a queue: a caller on an rpc endpoint would be a fact about nothing.\n const declared = options as ExternalEndpointOptions;\n if (\n kind !== 'external' ||\n typeof declared.calledBy !== 'string' ||\n declared.calledBy === ''\n )\n return;\n const callers: Record<string, ExternalCaller> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_CALLER, metadataTarget) || {};\n callers[propertyKey as string] = new ExternalCaller(\n declared.callerKind ?? DEFAULT_CALLER_KIND,\n declared.calledBy,\n );\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINT_CALLER, callers, metadataTarget);\n };\n}\n\n/**\n * @MaskLog(fields) - declare which fields of THIS method's request/response DTOs the\n * {@link LogApiCallImpl} logging path must mask, so a secret riding on a DTO (an OAuth refresh token, an\n * id-token JWT) is never written to the logs in cleartext. The REAL value still travels on the wire\n * untouched — masking lives in the logging path only.\n *\n * ```typescript\n * @Endpoint('/account', 'rpc')\n * @MaskLog({ refreshToken: 'full', accessToken: 'last4', credential: 'full' })\n * getEmailAccount(request: GetEmailAccountRequest): Promise<GetEmailAccountResponse> { ... }\n * ```\n *\n * Matching is by field NAME at any depth (nested objects + array elements), so\n * `response.account.refreshToken` is masked. Declared on the SHARED api contract, so BOTH the client\n * `[API-client-*]` and server `[API-server-*]` lines mask it. The spec is read ONCE at route-build\n * time and rides {@link RouteMetadata.mask}, so an unmasked method pays nothing at call time.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function MaskLog(fields: Record<string, MaskMode>): MethodDecorator {\n const spec = new MaskSpec(fields);\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any, propertyKey: string | symbol, _descriptor: PropertyDescriptor) => {\n const metadataTarget = typeof target === 'function' ? target : target.constructor;\n const specs: Record<string, MaskSpec> =\n Reflect.getMetadata(METADATA_KEYS.MASK_LOG, metadataTarget) || {};\n specs[propertyKey as string] = spec;\n Reflect.defineMetadata(METADATA_KEYS.MASK_LOG, specs, metadataTarget);\n };\n}\n\n/**\n * The @MaskLog spec for one method, or undefined if the method declared none (the common case — the\n * caller then logs the DTO verbatim on the plain JSON.stringify fast path).\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpointOptions\nexport function getMaskSpec(apiClass: Function, methodName: string): MaskSpec | undefined {\n const specs: Record<string, MaskSpec> =\n Reflect.getMetadata(METADATA_KEYS.MASK_LOG, apiClass) || {};\n return specs[methodName];\n}\n\n/**\n * Shared implementation for every auth decorator. Authorization is deliberately\n * method-only: a class-level default is too easy to miss when reviewing one endpoint.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nfunction defineAuthMode(mode: AuthMode): MethodDecorator {\n const authMeta = new AuthMeta(mode);\n\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any, propertyKey?: string | symbol, _descriptor?: PropertyDescriptor) => {\n if (propertyKey === undefined) {\n throw new Error(\n 'Authorization decorators are method-only; annotate every @Endpoint explicitly.',\n );\n }\n const metadataTarget = typeof target === 'function' ? target : target.constructor;\n if (Reflect.hasMetadata('webpieces:ipc-api-id', metadataTarget)) {\n throw new Error(\n `Internal API ${metadataTarget.name || 'Unknown'} cannot use HTTP authorization decorators.`,\n );\n }\n validateNoConflictingDecorators(metadataTarget, propertyKey as string);\n Reflect.defineMetadata(METADATA_KEYS.AUTH_META, authMeta, metadataTarget, propertyKey);\n const methods = new Set<string>(\n Reflect.getMetadata(METADATA_KEYS.AUTH_METHODS, metadataTarget) || [],\n );\n methods.add(propertyKey as string);\n Reflect.defineMetadata(METADATA_KEYS.AUTH_METHODS, [...methods], metadataTarget);\n };\n}\n\n/**\n * @WpAuthPublic(reason) - endpoint intentionally requires no authentication.\n * The non-empty reason makes anonymous exposure an explicit review decision.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthPublic(reason: string): MethodDecorator {\n if (typeof reason !== 'string' || reason.trim() === '') {\n throw new Error(\n '@WpAuthPublic requires a non-empty reason explaining why anonymous access is required.',\n );\n }\n return defineAuthMode({ kind: 'public' });\n}\n\n/**\n * @WpAuthJwt(requirement) - THE user-facing JWT decorator, covering the whole user-JWT axis: the\n * compiler-enforced role decision ({@link JwtRoles}) plus app-defined fields ({@link JwtRequirement}).\n *\n * ```typescript\n * @WpAuthJwt({ roles: ['admin', 'editor'] }) // any-of\n * @WpAuthJwt({ allRolesAllowed: true, inOrg: true }) // wide + an app rule enforced by authorizeJwt\n * ```\n *\n * It absorbed the former `@Auth(requirement)` — same argument, same AuthMode, so two spellings of one\n * decision. One decorator per credential kind now: `@WpAuthPublic` / `@WpAuthJwt` / `@WpAuthOidc` /\n * `@WpAuthSharedSecret` / `@WpAuthLocalOnly`.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthJwt(requirement: JwtRequirement): MethodDecorator {\n return defineAuthMode({ kind: 'jwt', requirement });\n}\n\n/**\n * The roles an endpoint accepts, or [] when it accepts every authenticated user. The ONE reader of\n * the {@link JwtRoles} union, so no caller has to re-derive \"does absent mean wide?\" — a question\n * whose two plausible answers is how the widest grant kept hiding behind an absent field.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getAuthMode\nexport function rolesRequired(requirement: JwtRequirement): readonly string[] {\n return requirement.allRolesAllowed === true ? [] : requirement.roles;\n}\n\n/**\n * @WpAuthOidc(...callers) - Google OIDC service-to-service auth (Cloud Tasks delivery / cross-service\n * RPC). `callers` is an OPTIONAL app-level allow-list of caller service accounts.\n *\n * NO args = TRUST THE EDGE: accept any genuine Google-signed OIDC caller, because a PRIVATE Cloud\n * Run service's edge already gates WHO via `run.invoker` IAM (managed in terraform — one source of\n * truth, no hand-synced list in code). If the service is actually PUBLIC, the verifier logs a loud\n * warning (it can't be the gate then). Pass explicit SAs (`@WpAuthOidc('svc-a')`) only when you want\n * an additional app-level allow-list as defense-in-depth.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthOidc(...callers: string[]): MethodDecorator {\n return defineAuthMode({ kind: 'oidc', callers });\n}\n\n/**\n * @WpAuthSharedSecret(key) - constant-time compare of an inbound header against the secret bound for\n * `key`. `key` is a LOOKUP KEY (not an env var): the server looks up its accepted {@link SharedSecrets}\n * by this key, and each client looks up the value it sends by the SAME key (see {@link Secrets}).\n * For internal callers that cannot mint OIDC tokens.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthSharedSecret(key: string): MethodDecorator {\n return defineAuthMode({ kind: 'shared-secret', secretKey: key });\n}\n\n/**\n * @WpAuthWebhook(name) - an OUTSIDE vendor signed this request in its OWN scheme; the app's bound\n * `WebhookAuthCallback` proves it. THE mode for every signed inbound webhook — Sentry, GitHub, Stripe, Slack,\n * Twilio — none of which fits the other kinds: no vendor mints Google OIDC tokens, and none sends its\n * secret (they all send a DERIVATION over the request), so `@WpAuthPublic` was the only reachable posture\n * and `calledBy: 'sentry'` stayed a claim rather than a fact.\n *\n * ```typescript\n * @WpAuthWebhook('sentry')\n * @Endpoint('/hook/sentry/issue', 'external', { calledBy: 'sentry', rawBody: true })\n * abstract notify(request: SentryIssueHook): Promise<HookAck>;\n * ```\n *\n * `name` is a bare STRING resolved through DI in the server's container, exactly as\n * `@WpAuthOidc('gmail-push')` already is — never a function reference. An api contract is level 0: a\n * direct reference to a verifier would invert the dependency graph and drag a vendor SDK into the\n * browser bundle that imports the same contract.\n *\n * THE FRAMEWORK IMPLEMENTS NO VENDOR CRYPTO, deliberately. Every vendor ships an official validator\n * (`twilio.validateRequest`, `stripe.webhooks.constructEvent`, `@octokit/webhooks-methods`) and every\n * vendor revises its scheme (Twilio added `bodySHA256` for JSON bodies; Stripe versions its header).\n * Reimplementing five of those is signing up to track five security changelogs forever and to be\n * wrong at the moment being wrong matters. The framework hands the hook enough of the raw request to\n * call the vendor's own library — hence the REQUIRED `{ rawBody: true }` (see\n * {@link EndpointOptions.rawBody}), which is checked at wiring time.\n *\n * FAILS CLOSED: with no `WebhookAuthCallback` bound, every `@WpAuthWebhook` endpoint 401s, matching `JwtHook`.\n * Silently allowing an unverified webhook is the one default that must not exist.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthWebhook(name: string): MethodDecorator {\n return defineAuthMode({ kind: 'webhook', name });\n}\n\n/**\n * @WpAuthApiKey(regime, credentials) - a CUSTOMER holds the credential. The app's bound `ApiKeyHook`\n * authenticates the inbound request against its own datastore and returns the `ContextTuple` entries\n * the framework seeds into `RequestContext`. THE mode for a partner-facing contract consumed by other\n * companies' codebases (POS vendors, back-office platforms, ETL pipelines).\n *\n * ```typescript\n * @WpAuthApiKey('onetablet-partner', [\n * { in: 'header', name: 'x-api-key', description: 'The key issued to your integration.' },\n * { in: 'header', name: 'x-organization-id', description: 'Which of your organizations to act on.' },\n * ])\n * @ApiPath('/management/v1')\n * abstract class ManagementApi { ... }\n * ```\n *\n * `regime` is a bare STRING selecting WHICH key regime this route belongs to, exactly as\n * `@WpAuthSharedSecret(key)` and `@WpAuthWebhook(vendor)` already are — one hook serves several regimes,\n * and an api contract is level 0, so it never references a verifier directly.\n *\n * `credentials` DECLARES where the credential rides ({@link ApiKeyCredential}), so a spec generator\n * reading route auth metadata can emit `components.securitySchemes` instead of a human hand-writing\n * them into a manifest. It is a NON-EMPTY, ORDERED list rather than one credential because a real\n * regime authenticates a PAIR — the key names a customer, a second header names which of that\n * customer's organizations the request acts on, and a mismatch is a 401. Its OpenAPI form is two\n * schemes plus ONE security-requirement object holding BOTH keys (an AND); a LIST of two objects\n * would mean \"either alone suffices\", which is a load-bearing difference a single-credential shape\n * cannot even express. ORDER IS SIGNIFICANT and preserved: it is the order the credentials are\n * presented in the published document.\n *\n * The list can never be EMPTY — a contract that declares a key regime and then names no credential\n * would generate a document with no security block, which is the exact silent failure this argument\n * exists to remove. That is a compile error, not a runtime throw (see {@link JwtRoles}'s non-empty\n * tuple, the same device for the same reason).\n *\n * WHY IT IS NOT `@WpAuthSharedSecret`. Shared-secret declares that AN INTERNAL SERVICE is on the other\n * end, so the framework BELIEVES the trusted context headers that caller forwarded (see\n * `DestinationTrust.forAuthMode` and `AuthFilter.verifiesCaller`). A customer is not an internal\n * service: declaring a partner endpoint `@WpAuthSharedSecret` would let that partner assert someone\n * else's org id on the wire and have it admitted — a privilege escalation. `apikey` therefore sits\n * with `jwt` on the caller-NOT-verified side, where an inbound trusted header is admitted only when\n * the hook independently derived the SAME value.\n *\n * WHY THE HOOK SEES THE REQUEST, NOT ONE TOKEN. A real key regime checks the key TOGETHER WITH a\n * second header (the organization it is acting for), and `JwtHook.parseJwt` — handed one pre-extracted\n * token from one header — physically cannot. `ApiKeyHook.verifyApiKey(regime, request)` gets the whole\n * inbound request instead, so the app owns which headers carry the credential and validates them as a\n * PAIR. `credentials` does NOT change that: the framework reads no header from it and performs no\n * extraction. It is DECLARATION for readers of the contract, and enforcement stays entirely the hook's.\n *\n * FAILS CLOSED: with no `ApiKeyHook` bound, every `@WpAuthApiKey` endpoint 401s, matching `JwtHook` and\n * `WebhookAuthCallback`.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthApiKey(regime: string, credentials: ApiKeyCredentials): MethodDecorator {\n return defineAuthMode({ kind: 'apikey', regime, credentials });\n}\n\n/**\n * @WpAuthLocalOnly() - this endpoint exists ONLY on a developer's machine. Off-local it is not\n * registered as a route at all, and if it is somehow reached it 404s. Method-only, like every\n * authorization decorator, so every endpoint's posture is visible at the method.\n *\n * ```typescript\n * @WpAuthLocalOnly()\n * @Endpoint('/logs', 'rpc')\n * sendBatch(request: SendLogBatchRequest): Promise<SendLogBatchResponse> { ... }\n * ```\n *\n * WHY IT IS AN AUTH MODE AND NOT A ROUTE-MODULE `if`. Apps hand-rolled this in TWO places kept in\n * sync by a comment: a route module that registered the route only locally, PLUS a\n * `if (env !== 'local') throw new ApiForbiddenError(...)` at the top of the handler. Neither half\n * was visible on the CONTRACT, so nothing reading the api — a human, a generated client, or an\n * agent — could tell this endpoint from a `@WpAuthPublic` one. Both halves are the framework's job now,\n * driven by this ONE declaration on the contract, which is where every other \"who may call this\"\n * fact already lives.\n *\n * It is DELIBERATELY a peer of @WpAuthPublic / @WpAuthJwt / @WpAuthOidc / @WpAuthSharedSecret / @WpAuthApiKey rather than an\n * option on one of them: one decorator per credential kind, and \"local-only\" is a different kind of\n * gate — it authenticates nobody, it excludes an entire environment.\n *\n * HOW \"local\" IS DECIDED: {@link RuntimeLocality}, declared once at startup (a REQUIRED input to\n * `RuntimeSetupOptions`). Undeclared means DEPLOYED, so a forgotten wiring call refuses the endpoint\n * rather than exposing it.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthLocalOnly(): MethodDecorator {\n return defineAuthMode({ kind: 'local-only' });\n}\n\n// ============================================================\n// Helper functions\n// ============================================================\n\n/**\n * Get the base path from @ApiPath decorator.\n */\nexport function getApiPath(apiClass: Function): string | undefined {\n return Reflect.getMetadata(METADATA_KEYS.API_PATH, apiClass);\n}\n\n/**\n * Get all endpoints from @Endpoint decorators.\n * Returns a record of methodName -> endpoint path.\n */\nexport function getEndpoints(apiClass: Function): Record<string, string> | undefined {\n return Reflect.getMetadata(METADATA_KEYS.ENDPOINTS, apiClass);\n}\n\n/**\n * Every method's declared trigger kind, as `methodName -> kind`. Parallel to {@link getEndpoints}.\n * Empty for a class carrying no @Endpoint at all.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function getEndpointKinds(apiClass: Function): Record<string, EndpointKind> {\n return Reflect.getMetadata(METADATA_KEYS.ENDPOINT_KIND, apiClass) || {};\n}\n\n/**\n * What triggers ONE method, or undefined when the method carries no @Endpoint.\n *\n * Defaults to nothing rather than to 'rpc': `kind` is a required argument, so a missing entry means\n * \"this is not an endpoint\", never \"an endpoint that forgot to say\". Silently defaulting here would\n * put an undeclared cron or webhook back into the graph as a normal rpc call — the exact blindness\n * the required argument exists to remove.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function getEndpointKind(apiClass: Function, methodName: string): EndpointKind | undefined {\n return getEndpointKinds(apiClass)[methodName];\n}\n\n/**\n * Get the @Endpoint options for one method (empty object if the method had no options).\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function getEndpointOptions(apiClass: Function, methodName: string): EndpointOptions {\n const opts: Record<string, EndpointOptions> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_OPTIONS, apiClass) || {};\n return opts[methodName] ?? {};\n}\n\n/**\n * Fail-fast at wiring time when an `external` endpoint declared no caller. The {@link Endpoint}\n * overloads already make that a COMPILE error; this is the backstop for the ways TS is bypassed —\n * a JS caller, an `as any` options object, a hand-rolled Reflect.defineMetadata.\n * @throws Error naming the first external endpoint with no `calledBy`.\n */\n// webpieces-disable no-function-outside-class -- wiring-time assert, sibling of assertEveryEndpointHasAuthMode\nexport function assertEveryExternalEndpointDeclaresCaller(apiClass: Function): void {\n const kinds = getEndpointKinds(apiClass);\n for (const methodName of Object.keys(kinds)) {\n if (\n kinds[methodName] !== 'external' ||\n getEndpointCaller(apiClass, methodName) !== undefined\n )\n continue;\n throw new Error(\n `External endpoint '${methodName}' in ${apiClass.name || 'Unknown'} declares no caller. Say WHO ` +\n `posts to it: @Endpoint(path, 'external', { calledBy: '<vendor>' }) — the runtime architecture ` +\n `graph cannot name an inbound caller it was never told about.`,\n );\n }\n}\n\n/**\n * True when the method's @Endpoint declared `{ formPost: true }` — its body is\n * application/x-www-form-urlencoded (flat), not JSON.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function isFormPost(apiClass: Function, methodName: string): boolean {\n return getEndpointOptions(apiClass, methodName).formPost === true;\n}\n\n/**\n * True when the method's @Endpoint declared `{ rawBody: true }` — the transport must retain the\n * verbatim bytes + absolute url for an {@link WpAuthWebhook} hook to verify.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of isFormPost\nexport function isRawBody(apiClass: Function, methodName: string): boolean {\n return getEndpointOptions(apiClass, methodName).rawBody === true;\n}\n\n/**\n * Fail-fast at wiring time when an `@WpAuthWebhook` endpoint did not ask the transport to keep the\n * bytes it is supposed to verify. A hook with nothing to verify is a MISCONFIGURATION, and it must\n * surface at startup, naming the fix — not as a 401 in production on exactly the traffic the endpoint\n * exists for.\n *\n * This pairing is a runtime assert rather than a type because the two halves live on DIFFERENT\n * decorators (`@WpAuthWebhook` and `@Endpoint`), and no union over one decorator's argument can say\n * anything about the other's.\n *\n * @throws Error naming the first `@WpAuthWebhook` endpoint missing `{ rawBody: true }`.\n */\n// webpieces-disable no-function-outside-class -- wiring-time assert, sibling of assertEveryEndpointHasAuthMode\nexport function assertEveryWebhookEndpointRetainsRawBody(apiClass: Function): void {\n const endpoints = getEndpoints(apiClass) || {};\n for (const methodName of Object.keys(endpoints)) {\n if (\n getAuthMode(apiClass, methodName)?.kind !== 'webhook' ||\n isRawBody(apiClass, methodName)\n )\n continue;\n throw new Error(\n `Endpoint '${methodName}' in ${apiClass.name || 'Unknown'} is @WpAuthWebhook but its @Endpoint ` +\n `does not declare { rawBody: true }. A webhook hook verifies a signature over the bytes and ` +\n `the url the SENDER transmitted, and without that option the transport parses the body and ` +\n `throws them away — leaving the hook nothing to check.`,\n );\n }\n}\n\n/**\n * Check if a class has @ApiPath decorator.\n */\nexport function isApiPath(apiClass: Function): boolean {\n return Reflect.hasMetadata(METADATA_KEYS.API_PATH, apiClass);\n}\n\n/**\n * Get method-level auth metadata. Class-level authorization is forbidden.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader paired with the decorator API\nexport function getAuthMeta(apiClass: Function, methodName: string): AuthMeta | undefined {\n return Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass, methodName);\n}\n\n/**\n * Get the auth mode for a method, or undefined.\n * Convenience wrapper over getAuthMeta for callers that only want the mode.\n */\n// webpieces-disable no-function-outside-class -- typed convenience reader over getAuthMeta\nexport function getAuthMode(apiClass: Function, methodName: string): AuthMode | undefined {\n return getAuthMeta(apiClass, methodName)?.mode;\n}\n\n/**\n * The ONE prescription for \"this endpoint declares no auth\", shared by the two places that raise it\n * (here and http-routing's ApiRoutingFactory) because they had drifted into teaching different menus.\n * A message teaching an incomplete API is the same defect as an API with two spellings: whichever menu\n * the caller hits becomes the API they believe exists. It leads with the ROLE-GATED member on purpose —\n * the first thing offered should not be the widest grant.\n */\nexport const MISSING_AUTH_DECORATOR_FIX =\n \"Add one of @WpAuthJwt({roles: ['admin']}) / @WpAuthJwt({allRolesAllowed: true}) / \" +\n '@WpAuthOidc(...callers) / @WpAuthSharedSecret(key) / ' +\n \"@WpAuthWebhook('vendor') / @WpAuthApiKey('regime', [{in: 'header', name: 'x-api-key'}]) / \" +\n \"@WpAuthLocalOnly() / @WpAuthPublic('why anonymous access is required') to \" +\n 'the method.';\n\n/**\n * Fail-fast at wiring time if any endpoint lacks an auth mode. Both the server\n * (ApiRoutingFactory) and the task/rpc clients call this so a missing auth\n * decorator is a startup error, never a silent open endpoint.\n * @throws Error naming the first endpoint with no auth decorator, via {@link MISSING_AUTH_DECORATOR_FIX}.\n */\nexport function assertEveryEndpointHasAuthMode(apiClass: Function): void {\n const apiName = apiClass.name || 'Unknown';\n const endpoints = getEndpoints(apiClass) || {};\n for (const methodName of Object.keys(endpoints)) {\n if (!getAuthMeta(apiClass, methodName)) {\n throw new Error(\n `Endpoint '${methodName}' in ${apiName} has no auth decorator. ` +\n MISSING_AUTH_DECORATOR_FIX,\n );\n }\n }\n}\n\n/**\n * Validate that a class/method doesn't have conflicting auth decorators.\n * @throws Error if multiple auth decorators are found on the same target.\n */\n// webpieces-disable no-function-outside-class -- shared decorator metadata validation\nexport function validateNoConflictingDecorators(\n apiClass: Function,\n methodName: string | undefined,\n): void {\n const existing = methodName\n ? Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass, methodName)\n : Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass);\n\n if (existing) {\n const targetName = apiClass.name || 'Unknown';\n const location = methodName\n ? `method '${methodName}' of ${targetName}`\n : `class ${targetName}`;\n throw new Error(\n `Conflicting auth decorator on ${location}. ` +\n `Only one of @WpAuthJwt({...}) / @WpAuthOidc(...) / @WpAuthSharedSecret(...) / ` +\n `@WpAuthWebhook(...) / @WpAuthApiKey(...) / @WpAuthLocalOnly() / ` +\n `@WpAuthPublic('reason') is allowed per target.`,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"decorators.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/decorators.ts"],"names":[],"mappings":";;;AAiHA,0BAcC;AAsDD,4BA2CC;AAoBD,0BAUC;AAOD,kCAIC;AAsCD,oCAOC;AAgBD,8BAEC;AAQD,sCAEC;AAaD,gCAEC;AASD,gDAEC;AAgCD,sCAEC;AAuDD,oCAEC;AA8BD,0CAEC;AASD,gCAEC;AAMD,oCAEC;AAOD,4CAEC;AAWD,0CAEC;AAMD,gDAIC;AASD,8FAcC;AAOD,gCAEC;AAOD,8BAEC;AAeD,4FAeC;AAKD,8BAEC;AAMD,kCAEC;AAOD,kCAEC;AAsBD,wEAWC;AAOD,0EAoBC;AArrBD,4BAA0B;AAC1B,iDAAoD;AACpD,uDAM2B;AAC3B,4FAA4F;AAC5F,2CAAoF;AAEpF;;;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AgD,CACvD,CAAC;IACN,CAAC;AACL,CAAC","sourcesContent":["import 'reflect-metadata';\nimport { MaskSpec, MaskMode } from './LogFieldMask';\nimport {\n DEFAULT_CALLER_KIND,\n ENDPOINT_CALLER_KEY,\n ExternalCaller,\n ExternalSystemKind,\n getEndpointCaller,\n} from './external-caller';\n// The TYPE layer these decorators attach — split out for file size only (see auth-mode.ts).\nimport { ApiKeyCredentials, AuthMeta, AuthMode, JwtRequirement } from './auth-mode';\n\n/**\n * Metadata keys for storing API routing information.\n * These keys are used by both server-side (routing) and client-side (client generation).\n */\nexport const METADATA_KEYS = {\n API_PATH: 'webpieces:api-path',\n ENDPOINTS: 'webpieces:endpoints',\n AUTH_META: 'webpieces:auth-meta',\n /** Method names carrying one of the canonical authorization decorators. */\n AUTH_METHODS: 'webpieces:auth-methods',\n /** 'rpc' (default, sync request/response) vs 'pubsub' (fire-and-forget cloud task). */\n API_KIND: 'webpieces:api-kind',\n /** Per-method Cloud Tasks queue-name override (set via @Queue). */\n QUEUE_OVERRIDE: 'webpieces:queue-override',\n /** Per-method @Endpoint options (e.g. formPost), parallel to ENDPOINTS. */\n ENDPOINT_OPTIONS: 'webpieces:endpoint-options',\n /** Per-method @Endpoint trigger kind (rpc | cloudtasks | cron | external), parallel to ENDPOINTS. */\n ENDPOINT_KIND: 'webpieces:endpoint-kind',\n /** Per-method declared external CALLER (only for kind 'external'), parallel to ENDPOINTS. */\n ENDPOINT_CALLER: ENDPOINT_CALLER_KEY,\n /** Per-method @MaskLog spec (which DTO fields the LogApiCall path masks). */\n MASK_LOG: 'webpieces:mask-log',\n /** Per-method opt-in metadata for publishing an RPC endpoint as an MCP tool. */\n MCP_TOOLS: 'webpieces:mcp-tools',\n};\n\n/**\n * WHAT TRIGGERS an endpoint at runtime — the single fact that decides how the runtime architecture\n * graph draws it, and which Terraform resource must exist for it to ever fire:\n *\n * - `rpc` — a caller in this repo (or a browser) calls it synchronously. A direct arrow.\n * - `cloudtasks` — a producer ENQUEUES it; Cloud Tasks delivers it later. Drawn producer → queue →\n * consumer, one queue node per METHOD (see {@link Queue}). Producer and consumer\n * being the SAME service is legal and common — the queue decouples them.\n * - `cron` — a scheduler fires it on a clock. Nothing in-repo calls it; drawn hanging off a\n * clock symbol. Backed by a Cloud Scheduler job.\n * - `external` — a system OUTSIDE this repo drives it (a GCP Pub/Sub push subscription, a Twilio\n * or Gmail webhook). Drawn as an inbound dashed arrow from that system.\n *\n * Declared PER METHOD, because one api class routinely mixes them: an admin contract can have\n * caller-driven endpoints AND a nightly cron sweep. A class-level marker cannot express that, which\n * is exactly why the graph could not tell these apart before.\n */\nexport type EndpointKind = 'rpc' | 'cloudtasks' | 'cron' | 'external';\n\n/**\n * Options for a single @Endpoint. Kept in a metadata map PARALLEL to ENDPOINTS so the existing\n * `Record<methodName, path>` shape every consumer iterates stays unchanged.\n */\nexport interface EndpointOptions {\n /**\n * Parse the request body as application/x-www-form-urlencoded (flat key→value) instead of JSON.\n * For EXTERNAL webhooks (e.g. Twilio) that post form-encoded. The request DTO must be FLAT —\n * urlencoded has no nesting (unlike JSON). Default false = JSON.\n */\n formPost?: boolean;\n\n /**\n * RETAIN the verbatim request bytes + the absolute url the sender addressed, so an\n * {@link WpAuthWebhook} hook can verify a vendor signature over them (see `RawRequest`).\n *\n * Opt-in PER ENDPOINT, sitting beside `formPost` and for the same reason: the cost lands on the\n * handful of webhook routes rather than on every request in the process. It is retention, not\n * new buffering — the express adapter already accumulates the whole body, it simply threw it\n * away once it had parsed a DTO.\n *\n * REQUIRED by `@WpAuthWebhook`, checked at wiring time (see\n * {@link assertEveryWebhookEndpointRetainsRawBody}) rather than left to fail as a 401 in\n * production: a hook with nothing to verify is a misconfiguration, not a bad request.\n *\n * Combines with `formPost` — `{ formPost: true, rawBody: true }` is the Twilio case, where the\n * hook needs the bytes and the url while the controller still wants the flat parsed DTO.\n */\n rawBody?: boolean;\n}\n\n/**\n * Options for an `external` @Endpoint: everything {@link EndpointOptions} carries, PLUS a REQUIRED\n * declaration of WHO is calling. See {@link Endpoint} for why, `external-caller.ts` for identity.\n */\nexport interface ExternalEndpointOptions extends EndpointOptions {\n /** The outside system that posts here (`'twilio'`) — the graph node IDENTITY, not display text. */\n calledBy: string;\n /** What that caller IS; picks the node's shape. Defaults to `'saas'` (see DEFAULT_CALLER_KIND). */\n callerKind?: ExternalSystemKind;\n}\n\n/**\n * @ApiPath(basePath) - Class decorator that marks a class as an API definition\n * and sets the base path for all endpoints.\n *\n * Usage:\n * ```typescript\n * @ApiPath('/api/save')\n * abstract class SaveApi {\n * @WpAuthJwt({ roles: ['admin'] })\n * @Endpoint('/item', 'rpc')\n * save(request: SaveRequest): Promise<SaveResponse> { ... }\n * }\n * ```\n */\nexport function ApiPath(basePath: string): ClassDecorator {\n return (target: Function) => {\n if (Reflect.hasMetadata('webpieces:ipc-api-id', target)) {\n throw new Error(\n `Class ${target.name || 'Unknown'} cannot combine @ApiPath with @WpInternal.`,\n );\n }\n Reflect.defineMetadata(METADATA_KEYS.API_PATH, basePath, target);\n\n // Initialize endpoints map if not exists\n if (!Reflect.hasMetadata(METADATA_KEYS.ENDPOINTS, target)) {\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINTS, {}, target);\n }\n };\n}\n\n/**\n * @Endpoint(path, kind, options?) - Method decorator that registers a POST endpoint at the given\n * path and declares WHAT TRIGGERS it.\n *\n * All endpoints are POST-only (matching gRPC/thrift style).\n *\n * Usage:\n * ```typescript\n * @Endpoint('/item', 'rpc')\n * save(request: SaveRequest): Promise<SaveResponse> { ... }\n *\n * // enqueued by a producer, delivered later by Cloud Tasks:\n * @Endpoint('/send', 'cloudtasks')\n * send(request: SendRequest): Promise<void> { ... }\n *\n * // fired by Cloud Scheduler on a clock, called by nobody in this repo:\n * @Endpoint('/nightly', 'cron')\n * nightly(request: NightlyRequest): Promise<void> { ... }\n *\n * // EXTERNAL webhook posting application/x-www-form-urlencoded (e.g. Twilio):\n * @Endpoint('/hook', 'external', { formPost: true, calledBy: 'twilio' })\n * inbound(request: InboundRequest): Promise<InboundResponse> { ... }\n * ```\n *\n * `kind` is REQUIRED and deliberately positional: it makes every pre-existing single-argument\n * `@Endpoint('/x')` a COMPILE error rather than something a lint rule has to chase, so no endpoint\n * can slip into the runtime architecture graph with its trigger left to guesswork. See\n * {@link EndpointKind} for what each value draws and which Terraform resource backs it.\n *\n * `calledBy` is REQUIRED for `external` FOR EXACTLY THE SAME REASON, enforced by the overloads below:\n * the one box on the runtime graph whose whole job is to say who calls us from outside could only\n * restate OUR OWN contract name, because nothing in the source ever said who the caller was. This is\n * BREAKING for published consumers, intentionally — an existing `@Endpoint(p, 'external', {...})`\n * stops compiling until it names its caller. Migration is one property; see the migration note in\n * `external-caller.ts`. Non-`external` endpoints are completely unaffected.\n *\n * The path write to ENDPOINTS is UNCHANGED (every consumer iterates `[methodName, path]`); kind,\n * options and caller ride PARALLEL ENDPOINT_KIND / ENDPOINT_OPTIONS / ENDPOINT_CALLER maps.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function Endpoint(\n path: string,\n kind: 'external',\n options: ExternalEndpointOptions,\n): MethodDecorator;\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function Endpoint(\n path: string,\n kind: Exclude<EndpointKind, 'external'>,\n options?: EndpointOptions,\n): MethodDecorator;\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function Endpoint(\n path: string,\n kind: EndpointKind,\n options: EndpointOptions = {},\n): MethodDecorator {\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any, propertyKey: string | symbol, _descriptor: PropertyDescriptor) => {\n const metadataTarget = typeof target === 'function' ? target : target.constructor;\n\n const endpoints: Record<string, string> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINTS, metadataTarget) || {};\n\n endpoints[propertyKey as string] = path;\n\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINTS, endpoints, metadataTarget);\n\n const kinds: Record<string, EndpointKind> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_KIND, metadataTarget) || {};\n kinds[propertyKey as string] = kind;\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINT_KIND, kinds, metadataTarget);\n\n const opts: Record<string, EndpointOptions> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_OPTIONS, metadataTarget) || {};\n opts[propertyKey as string] = options;\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINT_OPTIONS, opts, metadataTarget);\n\n // ONLY for 'external', mirroring how a queue name is recorded only for the kinds that HAVE\n // a queue: a caller on an rpc endpoint would be a fact about nothing.\n const declared = options as ExternalEndpointOptions;\n if (\n kind !== 'external' ||\n typeof declared.calledBy !== 'string' ||\n declared.calledBy === ''\n )\n return;\n const callers: Record<string, ExternalCaller> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_CALLER, metadataTarget) || {};\n callers[propertyKey as string] = new ExternalCaller(\n declared.callerKind ?? DEFAULT_CALLER_KIND,\n declared.calledBy,\n );\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINT_CALLER, callers, metadataTarget);\n };\n}\n\n/**\n * @MaskLog(fields) - declare which fields of THIS method's request/response DTOs the\n * {@link LogApiCallImpl} logging path must mask, so a secret riding on a DTO (an OAuth refresh token, an\n * id-token JWT) is never written to the logs in cleartext. The REAL value still travels on the wire\n * untouched — masking lives in the logging path only.\n *\n * ```typescript\n * @Endpoint('/account', 'rpc')\n * @MaskLog({ refreshToken: 'full', accessToken: 'last4', credential: 'full' })\n * getEmailAccount(request: GetEmailAccountRequest): Promise<GetEmailAccountResponse> { ... }\n * ```\n *\n * Matching is by field NAME at any depth (nested objects + array elements), so\n * `response.account.refreshToken` is masked. Declared on the SHARED api contract, so BOTH the client\n * `[API-client-*]` and server `[API-server-*]` lines mask it. The spec is read ONCE at route-build\n * time and rides {@link RouteMetadata.mask}, so an unmasked method pays nothing at call time.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function MaskLog(fields: Record<string, MaskMode>): MethodDecorator {\n const spec = new MaskSpec(fields);\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any, propertyKey: string | symbol, _descriptor: PropertyDescriptor) => {\n const metadataTarget = typeof target === 'function' ? target : target.constructor;\n const specs: Record<string, MaskSpec> =\n Reflect.getMetadata(METADATA_KEYS.MASK_LOG, metadataTarget) || {};\n specs[propertyKey as string] = spec;\n Reflect.defineMetadata(METADATA_KEYS.MASK_LOG, specs, metadataTarget);\n };\n}\n\n/**\n * The @MaskLog spec for one method, or undefined if the method declared none (the common case — the\n * caller then logs the DTO verbatim on the plain JSON.stringify fast path).\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpointOptions\nexport function getMaskSpec(apiClass: Function, methodName: string): MaskSpec | undefined {\n const specs: Record<string, MaskSpec> =\n Reflect.getMetadata(METADATA_KEYS.MASK_LOG, apiClass) || {};\n return specs[methodName];\n}\n\n/**\n * Shared implementation for every auth decorator. Authorization is deliberately\n * method-only: a class-level default is too easy to miss when reviewing one endpoint.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nfunction defineAuthMode(mode: AuthMode): MethodDecorator {\n const authMeta = new AuthMeta(mode);\n\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any, propertyKey?: string | symbol, _descriptor?: PropertyDescriptor) => {\n if (propertyKey === undefined) {\n throw new Error(\n 'Authorization decorators are method-only; annotate every @Endpoint explicitly.',\n );\n }\n const metadataTarget = typeof target === 'function' ? target : target.constructor;\n if (Reflect.hasMetadata('webpieces:ipc-api-id', metadataTarget)) {\n throw new Error(\n `Internal API ${metadataTarget.name || 'Unknown'} cannot use HTTP authorization decorators.`,\n );\n }\n validateNoConflictingDecorators(metadataTarget, propertyKey as string);\n Reflect.defineMetadata(METADATA_KEYS.AUTH_META, authMeta, metadataTarget, propertyKey);\n const methods = new Set<string>(\n Reflect.getMetadata(METADATA_KEYS.AUTH_METHODS, metadataTarget) || [],\n );\n methods.add(propertyKey as string);\n Reflect.defineMetadata(METADATA_KEYS.AUTH_METHODS, [...methods], metadataTarget);\n };\n}\n\n/**\n * @WpAuthPublic(reason) - endpoint intentionally requires no authentication.\n * The non-empty reason makes anonymous exposure an explicit review decision.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthPublic(reason: string): MethodDecorator {\n if (typeof reason !== 'string' || reason.trim() === '') {\n throw new Error(\n '@WpAuthPublic requires a non-empty reason explaining why anonymous access is required.',\n );\n }\n return defineAuthMode({ kind: 'public' });\n}\n\n/**\n * @WpAuthJwt(requirement) - THE user-facing JWT decorator, covering the whole user-JWT axis: the\n * compiler-enforced role decision ({@link JwtRoles}) plus app-defined fields ({@link JwtRequirement}).\n *\n * ```typescript\n * @WpAuthJwt({ roles: ['admin', 'editor'] }) // any-of\n * @WpAuthJwt({ allRolesAllowed: true, inOrg: true }) // wide + an app rule enforced by authorizeJwt\n * ```\n *\n * It absorbed the former `@Auth(requirement)` — same argument, same AuthMode, so two spellings of one\n * decision. One decorator per credential kind now: `@WpAuthPublic` / `@WpAuthJwt` / `@WpAuthOidc` /\n * `@WpAuthSharedSecret` / `@WpAuthLocalOnly`.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthJwt(requirement: JwtRequirement): MethodDecorator {\n return defineAuthMode({ kind: 'jwt', requirement });\n}\n\n/**\n * The roles an endpoint accepts, or [] when it accepts every authenticated user. The ONE reader of\n * the {@link JwtRoles} union, so no caller has to re-derive \"does absent mean wide?\" — a question\n * whose two plausible answers is how the widest grant kept hiding behind an absent field.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getAuthMode\nexport function rolesRequired(requirement: JwtRequirement): readonly string[] {\n return requirement.allRolesAllowed === true ? [] : requirement.roles;\n}\n\n/**\n * @WpAuthOidc(...callers) - Google OIDC service-to-service auth (Cloud Tasks delivery / cross-service\n * RPC). `callers` is an OPTIONAL app-level allow-list of caller service accounts.\n *\n * NO args = TRUST THE EDGE: accept any genuine Google-signed OIDC caller, because a PRIVATE Cloud\n * Run service's edge already gates WHO via `run.invoker` IAM (managed in terraform — one source of\n * truth, no hand-synced list in code). If the service is actually PUBLIC, the verifier logs a loud\n * warning (it can't be the gate then). Pass explicit SAs (`@WpAuthOidc('svc-a')`) only when you want\n * an additional app-level allow-list as defense-in-depth.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthOidc(...callers: string[]): MethodDecorator {\n return defineAuthMode({ kind: 'oidc', callers });\n}\n\n/**\n * @WpAuthSharedSecret(key) - constant-time compare of an inbound header against the secret bound for\n * `key`. `key` is a LOOKUP KEY (not an env var): the server looks up its accepted {@link SharedSecrets}\n * by this key, and each client looks up the value it sends by the SAME key (see {@link Secrets}).\n * For internal callers that cannot mint OIDC tokens.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthSharedSecret(key: string): MethodDecorator {\n return defineAuthMode({ kind: 'shared-secret', secretKey: key });\n}\n\n/**\n * @WpAuthWebhook(name) - an OUTSIDE vendor signed this request in its OWN scheme; the app's bound\n * `WebhookAuthCallback` proves it. THE mode for every signed inbound webhook — Sentry, GitHub, Stripe, Slack,\n * Twilio — none of which fits the other kinds: no vendor mints Google OIDC tokens, and none sends its\n * secret (they all send a DERIVATION over the request), so `@WpAuthPublic` was the only reachable posture\n * and `calledBy: 'sentry'` stayed a claim rather than a fact.\n *\n * ```typescript\n * @WpAuthWebhook('sentry')\n * @Endpoint('/hook/sentry/issue', 'external', { calledBy: 'sentry', rawBody: true })\n * abstract notify(request: SentryIssueHook): Promise<HookAck>;\n * ```\n *\n * `name` is a bare STRING resolved through DI in the server's container, exactly as\n * `@WpAuthOidc('gmail-push')` already is — never a function reference. An api contract is level 0: a\n * direct reference to a verifier would invert the dependency graph and drag a vendor SDK into the\n * browser bundle that imports the same contract.\n *\n * THE FRAMEWORK IMPLEMENTS NO VENDOR CRYPTO, deliberately. Every vendor ships an official validator\n * (`twilio.validateRequest`, `stripe.webhooks.constructEvent`, `@octokit/webhooks-methods`) and every\n * vendor revises its scheme (Twilio added `bodySHA256` for JSON bodies; Stripe versions its header).\n * Reimplementing five of those is signing up to track five security changelogs forever and to be\n * wrong at the moment being wrong matters. The framework hands the hook enough of the raw request to\n * call the vendor's own library — hence the REQUIRED `{ rawBody: true }` (see\n * {@link EndpointOptions.rawBody}), which is checked at wiring time.\n *\n * FAILS CLOSED: with no `WebhookAuthCallback` bound, every `@WpAuthWebhook` endpoint 401s, matching `JwtHook`.\n * Silently allowing an unverified webhook is the one default that must not exist.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthWebhook(name: string): MethodDecorator {\n return defineAuthMode({ kind: 'webhook', name });\n}\n\n/**\n * @WpAuthApiKey(regime, credentials) - a CUSTOMER holds the credential. The app's bound `ApiKeyHook`\n * authenticates the inbound request against its own datastore and returns the `ContextTuple` entries\n * the framework seeds into `RequestContext`. THE mode for a partner-facing contract consumed by other\n * companies' codebases (POS vendors, back-office platforms, ETL pipelines).\n *\n * ```typescript\n * @WpAuthApiKey('onetablet-partner', [\n * { in: 'header', name: 'x-api-key', description: 'The key issued to your integration.' },\n * { in: 'header', name: 'x-organization-id', description: 'Which of your organizations to act on.' },\n * ])\n * @ApiPath('/management/v1')\n * abstract class ManagementApi { ... }\n * ```\n *\n * `regime` is a bare STRING selecting WHICH key regime this route belongs to, exactly as\n * `@WpAuthSharedSecret(key)` and `@WpAuthWebhook(vendor)` already are — one hook serves several regimes,\n * and an api contract is level 0, so it never references a verifier directly.\n *\n * `credentials` DECLARES where the credential rides ({@link ApiKeyCredential}), so a spec generator\n * reading route auth metadata can emit `components.securitySchemes` instead of a human hand-writing\n * them into a manifest. It is a NON-EMPTY, ORDERED list rather than one credential because a real\n * regime authenticates a PAIR — the key names a customer, a second header names which of that\n * customer's organizations the request acts on, and a mismatch is a 401. Its OpenAPI form is two\n * schemes plus ONE security-requirement object holding BOTH keys (an AND); a LIST of two objects\n * would mean \"either alone suffices\", which is a load-bearing difference a single-credential shape\n * cannot even express. ORDER IS SIGNIFICANT and preserved: it is the order the credentials are\n * presented in the published document.\n *\n * The list can never be EMPTY — a contract that declares a key regime and then names no credential\n * would generate a document with no security block, which is the exact silent failure this argument\n * exists to remove. That is a compile error, not a runtime throw (see {@link JwtRoles}'s non-empty\n * tuple, the same device for the same reason).\n *\n * WHY IT IS NOT `@WpAuthSharedSecret`. Shared-secret declares that AN INTERNAL SERVICE is on the other\n * end, so the framework BELIEVES the trusted context headers that caller forwarded (see\n * `DestinationTrust.forAuthMode` and `AuthFilter.verifiesCaller`). A customer is not an internal\n * service: declaring a partner endpoint `@WpAuthSharedSecret` would let that partner assert someone\n * else's org id on the wire and have it admitted — a privilege escalation. `apikey` therefore sits\n * with `jwt` on the caller-NOT-verified side, where an inbound trusted header is admitted only when\n * the hook independently derived the SAME value.\n *\n * WHY THE HOOK SEES THE REQUEST, NOT ONE TOKEN. A real key regime checks the key TOGETHER WITH a\n * second header (the organization it is acting for), and `JwtHook.parseJwt` — handed one pre-extracted\n * token from one header — physically cannot. `ApiKeyHook.verifyApiKey(regime, request)` gets the whole\n * inbound request instead, so the app owns which headers carry the credential and validates them as a\n * PAIR. `credentials` does NOT change that: the framework reads no header from it and performs no\n * extraction. It is DECLARATION for readers of the contract, and enforcement stays entirely the hook's.\n *\n * FAILS CLOSED: with no `ApiKeyHook` bound, every `@WpAuthApiKey` endpoint 401s, matching `JwtHook` and\n * `WebhookAuthCallback`.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthApiKey(regime: string, credentials: ApiKeyCredentials): MethodDecorator {\n return defineAuthMode({ kind: 'apikey', regime, credentials });\n}\n\n/**\n * @WpAuthLocalOnly() - this endpoint exists ONLY on a developer's machine. Off-local it is not\n * registered as a route at all, and if it is somehow reached it 404s. Method-only, like every\n * authorization decorator, so every endpoint's posture is visible at the method.\n *\n * ```typescript\n * @WpAuthLocalOnly()\n * @Endpoint('/logs', 'rpc')\n * sendBatch(request: SendLogBatchRequest): Promise<SendLogBatchResponse> { ... }\n * ```\n *\n * WHY IT IS AN AUTH MODE AND NOT A ROUTE-MODULE `if`. Apps hand-rolled this in TWO places kept in\n * sync by a comment: a route module that registered the route only locally, PLUS a\n * `if (env !== 'local') throw new ApiForbiddenError(...)` at the top of the handler. Neither half\n * was visible on the CONTRACT, so nothing reading the api — a human, a generated client, or an\n * agent — could tell this endpoint from a `@WpAuthPublic` one. Both halves are the framework's job now,\n * driven by this ONE declaration on the contract, which is where every other \"who may call this\"\n * fact already lives.\n *\n * It is DELIBERATELY a peer of @WpAuthPublic / @WpAuthJwt / @WpAuthOidc / @WpAuthSharedSecret / @WpAuthApiKey rather than an\n * option on one of them: one decorator per credential kind, and \"local-only\" is a different kind of\n * gate — it authenticates nobody, it excludes an entire environment.\n *\n * HOW \"local\" IS DECIDED: {@link RuntimeLocality}, declared once at startup (a REQUIRED input to\n * `RuntimeSetupOptions`). Undeclared means DEPLOYED, so a forgotten wiring call refuses the endpoint\n * rather than exposing it.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function WpAuthLocalOnly(): MethodDecorator {\n return defineAuthMode({ kind: 'local-only' });\n}\n\n// ============================================================\n// Helper functions\n// ============================================================\n\n/**\n * Get the base path from @ApiPath decorator.\n */\nexport function getApiPath(apiClass: Function): string | undefined {\n return Reflect.getMetadata(METADATA_KEYS.API_PATH, apiClass);\n}\n\n/**\n * Get all endpoints from @Endpoint decorators.\n * Returns a record of methodName -> endpoint path.\n */\nexport function getEndpoints(apiClass: Function): Record<string, string> | undefined {\n return Reflect.getMetadata(METADATA_KEYS.ENDPOINTS, apiClass);\n}\n\n/**\n * Every method's declared trigger kind, as `methodName -> kind`. Parallel to {@link getEndpoints}.\n * Empty for a class carrying no @Endpoint at all.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function getEndpointKinds(apiClass: Function): Record<string, EndpointKind> {\n return Reflect.getMetadata(METADATA_KEYS.ENDPOINT_KIND, apiClass) || {};\n}\n\n/**\n * What triggers ONE method, or undefined when the method carries no @Endpoint.\n *\n * Defaults to nothing rather than to 'rpc': `kind` is a required argument, so a missing entry means\n * \"this is not an endpoint\", never \"an endpoint that forgot to say\". Silently defaulting here would\n * put an undeclared cron or webhook back into the graph as a normal rpc call — the exact blindness\n * the required argument exists to remove.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function getEndpointKind(apiClass: Function, methodName: string): EndpointKind | undefined {\n return getEndpointKinds(apiClass)[methodName];\n}\n\n/**\n * Get the @Endpoint options for one method (empty object if the method had no options).\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function getEndpointOptions(apiClass: Function, methodName: string): EndpointOptions {\n const opts: Record<string, EndpointOptions> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_OPTIONS, apiClass) || {};\n return opts[methodName] ?? {};\n}\n\n/**\n * Fail-fast at wiring time when an `external` endpoint declared no caller. The {@link Endpoint}\n * overloads already make that a COMPILE error; this is the backstop for the ways TS is bypassed —\n * a JS caller, an `as any` options object, a hand-rolled Reflect.defineMetadata.\n * @throws Error naming the first external endpoint with no `calledBy`.\n */\n// webpieces-disable no-function-outside-class -- wiring-time assert, sibling of assertEveryEndpointHasAuthMode\nexport function assertEveryExternalEndpointDeclaresCaller(apiClass: Function): void {\n const kinds = getEndpointKinds(apiClass);\n for (const methodName of Object.keys(kinds)) {\n if (\n kinds[methodName] !== 'external' ||\n getEndpointCaller(apiClass, methodName) !== undefined\n )\n continue;\n throw new Error(\n `External endpoint '${methodName}' in ${apiClass.name || 'Unknown'} declares no caller. Say WHO ` +\n `posts to it: @Endpoint(path, 'external', { calledBy: '<vendor>' }) — the runtime architecture ` +\n `graph cannot name an inbound caller it was never told about.`,\n );\n }\n}\n\n/**\n * True when the method's @Endpoint declared `{ formPost: true }` — its body is\n * application/x-www-form-urlencoded (flat), not JSON.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function isFormPost(apiClass: Function, methodName: string): boolean {\n return getEndpointOptions(apiClass, methodName).formPost === true;\n}\n\n/**\n * True when the method's @Endpoint declared `{ rawBody: true }` — the transport must retain the\n * verbatim bytes + absolute url for an {@link WpAuthWebhook} hook to verify.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of isFormPost\nexport function isRawBody(apiClass: Function, methodName: string): boolean {\n return getEndpointOptions(apiClass, methodName).rawBody === true;\n}\n\n/**\n * Fail-fast at wiring time when an `@WpAuthWebhook` endpoint did not ask the transport to keep the\n * bytes it is supposed to verify. A hook with nothing to verify is a MISCONFIGURATION, and it must\n * surface at startup, naming the fix — not as a 401 in production on exactly the traffic the endpoint\n * exists for.\n *\n * This pairing is a runtime assert rather than a type because the two halves live on DIFFERENT\n * decorators (`@WpAuthWebhook` and `@Endpoint`), and no union over one decorator's argument can say\n * anything about the other's.\n *\n * @throws Error naming the first `@WpAuthWebhook` endpoint missing `{ rawBody: true }`.\n */\n// webpieces-disable no-function-outside-class -- wiring-time assert, sibling of assertEveryEndpointHasAuthMode\nexport function assertEveryWebhookEndpointRetainsRawBody(apiClass: Function): void {\n const endpoints = getEndpoints(apiClass) || {};\n for (const methodName of Object.keys(endpoints)) {\n if (\n getAuthMode(apiClass, methodName)?.kind !== 'webhook' ||\n isRawBody(apiClass, methodName)\n )\n continue;\n throw new Error(\n `Endpoint '${methodName}' in ${apiClass.name || 'Unknown'} is @WpAuthWebhook but its @Endpoint ` +\n `does not declare { rawBody: true }. A webhook hook verifies a signature over the bytes and ` +\n `the url the SENDER transmitted, and without that option the transport parses the body and ` +\n `throws them away — leaving the hook nothing to check.`,\n );\n }\n}\n\n/**\n * Check if a class has @ApiPath decorator.\n */\nexport function isApiPath(apiClass: Function): boolean {\n return Reflect.hasMetadata(METADATA_KEYS.API_PATH, apiClass);\n}\n\n/**\n * Get method-level auth metadata. Class-level authorization is forbidden.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader paired with the decorator API\nexport function getAuthMeta(apiClass: Function, methodName: string): AuthMeta | undefined {\n return Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass, methodName);\n}\n\n/**\n * Get the auth mode for a method, or undefined.\n * Convenience wrapper over getAuthMeta for callers that only want the mode.\n */\n// webpieces-disable no-function-outside-class -- typed convenience reader over getAuthMeta\nexport function getAuthMode(apiClass: Function, methodName: string): AuthMode | undefined {\n return getAuthMeta(apiClass, methodName)?.mode;\n}\n\n/**\n * The ONE prescription for \"this endpoint declares no auth\", shared by the two places that raise it\n * (here and http-routing's ApiRoutingFactory) because they had drifted into teaching different menus.\n * A message teaching an incomplete API is the same defect as an API with two spellings: whichever menu\n * the caller hits becomes the API they believe exists. It leads with the ROLE-GATED member on purpose —\n * the first thing offered should not be the widest grant.\n */\nexport const MISSING_AUTH_DECORATOR_FIX =\n \"Add one of @WpAuthJwt({roles: ['admin']}) / @WpAuthJwt({allRolesAllowed: true}) / \" +\n '@WpAuthOidc(...callers) / @WpAuthSharedSecret(key) / ' +\n \"@WpAuthWebhook('vendor') / @WpAuthApiKey('regime', [{in: 'header', name: 'x-api-key'}]) / \" +\n \"@WpAuthLocalOnly() / @WpAuthPublic('why anonymous access is required') to \" +\n 'the method.';\n\n/**\n * Fail-fast at wiring time if any endpoint lacks an auth mode. Both the server\n * (ApiRoutingFactory) and the task/rpc clients call this so a missing auth\n * decorator is a startup error, never a silent open endpoint.\n * @throws Error naming the first endpoint with no auth decorator, via {@link MISSING_AUTH_DECORATOR_FIX}.\n */\nexport function assertEveryEndpointHasAuthMode(apiClass: Function): void {\n const apiName = apiClass.name || 'Unknown';\n const endpoints = getEndpoints(apiClass) || {};\n for (const methodName of Object.keys(endpoints)) {\n if (!getAuthMeta(apiClass, methodName)) {\n throw new Error(\n `Endpoint '${methodName}' in ${apiName} has no auth decorator. ` +\n MISSING_AUTH_DECORATOR_FIX,\n );\n }\n }\n}\n\n/**\n * Validate that a class/method doesn't have conflicting auth decorators.\n * @throws Error if multiple auth decorators are found on the same target.\n */\n// webpieces-disable no-function-outside-class -- shared decorator metadata validation\nexport function validateNoConflictingDecorators(\n apiClass: Function,\n methodName: string | undefined,\n): void {\n const existing = methodName\n ? Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass, methodName)\n : Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass);\n\n if (existing) {\n const targetName = apiClass.name || 'Unknown';\n const location = methodName\n ? `method '${methodName}' of ${targetName}`\n : `class ${targetName}`;\n throw new Error(\n `Conflicting auth decorator on ${location}. ` +\n `Only one of @WpAuthJwt({...}) / @WpAuthOidc(...) / @WpAuthSharedSecret(...) / ` +\n `@WpAuthWebhook(...) / @WpAuthApiKey(...) / @WpAuthLocalOnly() / ` +\n `@WpAuthPublic('reason') is allowed per target.`,\n );\n }\n}\n"]}
package/src/index.d.ts CHANGED
@@ -22,6 +22,10 @@ export { WpInternal, WpIpcEndpoint, isInternalApi, getIpcApiId, getIpcEndpoints,
22
22
  export type { IpcApiType, IpcEndpointKind, IpcEndpointOptions } from './ipc/IpcDecorators';
23
23
  export { RouteMetadata } from './http/RouteMetadata';
24
24
  export type { EndpointKind, EndpointOptions, ExternalEndpointOptions } from './http/decorators';
25
+ export { WpMcpTool, WpMcpToolHints, WpMcpToolMetadata, getWpMcpTools, } from './mcp/McpMetadata';
26
+ export type { WpMcpMethodDecorator, WpMcpToolOptions } from './mcp/McpMetadata';
27
+ export { WpDto, WpDtoField, WpDtoFieldOptions, WpDtoFieldMetadata, WpResponseDto, ApiJsonSchema, DtoValidationFailure, DtoSchemaBuilder, } from './mcp/DtoSchema';
28
+ export type { DtoClass, DtoArrayItem, DtoValue } from './mcp/DtoSchema';
25
29
  export { AuthMeta } from './http/auth-mode';
26
30
  export type { AuthMode, ApiKeyCredential, ApiKeyCredentials, JwtRoles, JwtRequirement, } from './http/auth-mode';
27
31
  export { Rpc, PubSub, Queue, ENDPOINT_KINDS_BY_API_KIND, getApiKind, assertApiKind, assertPubSubConventions, getQueueName, } from './http/api-kind';
package/src/index.js CHANGED
@@ -9,8 +9,8 @@
9
9
  */
10
10
  Object.defineProperty(exports, "__esModule", { value: true });
11
11
  exports.assertInternalApi = exports.getIpcMaskSpec = exports.getIpcEndpointKind = exports.getIpcEndpoints = exports.getIpcApiId = exports.isInternalApi = exports.WpIpcEndpoint = exports.WpInternal = exports.METADATA_KEYS = exports.validateNoConflictingDecorators = exports.assertEveryWebhookEndpointRetainsRawBody = exports.assertEveryExternalEndpointDeclaresCaller = exports.assertEveryEndpointHasAuthMode = exports.getAuthMode = exports.getAuthMeta = exports.isApiPath = exports.isRawBody = exports.isFormPost = exports.getMaskSpec = exports.getEndpointKinds = exports.getEndpointKind = exports.getEndpointOptions = exports.getEndpoints = exports.getApiPath = exports.MaskLog = exports.WpAuthLocalOnly = exports.WpAuthApiKey = exports.WpAuthWebhook = exports.WpAuthSharedSecret = exports.WpAuthOidc = exports.MISSING_AUTH_DECORATOR_FIX = exports.rolesRequired = exports.WpAuthJwt = exports.WpAuthPublic = exports.Endpoint = exports.ApiPath = exports.GCP_LOG_BUDGET_BYTES = exports.MAX_GCP_LOG_BYTES = exports.LogChunkInfo = exports.LogChunkerImpl = exports.LogChunker = exports.LogManager = exports.ConsoleLoggerFactory = exports.ConsoleLogger = exports.DESIGN_METADATA_KEYS = exports.isDocumentDesign = exports.DocumentDesign = exports.ContextTuple = exports.ContextKey = exports.toError = void 0;
12
- exports.ContextMgr = exports.DestinationTrust = exports.WebpiecesCoreHeaders = exports.templateDeriver = exports.WEBPIECES_DEFAULT_FAILURE_CLASSIFIER = exports.WebpiecesDefaultFailureClassifier = exports.KeyedFailureClassifier = exports.HttpResponseDto = exports.HttpResponseStatus = exports.HttpHeader = exports.RuntimeLocality = exports.ServiceInfo = exports.ApiCallTimeoutError = exports.CallContext = exports.CallDeadline = exports.CallRegistry = exports.ClientRegistry = exports.HeaderRegistry = exports.DateTimeUtil = exports.TimeUtil = exports.DateUtil = exports.InstantUtil = exports.NetworkRejectClassifier = exports.NO_REG_CODE = exports.WRONG_COMPANY = exports.WRONG_DOMAIN = exports.EMAIL_NOT_CONFIRMED = exports.NOT_APPROVED = exports.WRONG_LOGIN = exports.WRONG_LOGIN_TYPE = exports.ENTITY_NOT_FOUND = exports.SECRETS = exports.Secrets = exports.getEndpointCaller = exports.isExternalSystemKind = exports.ExternalCaller = exports.DEFAULT_CALLER_KIND = exports.EXTERNAL_SYSTEM_KINDS = exports.getQueueName = exports.assertPubSubConventions = exports.assertApiKind = exports.getApiKind = exports.ENDPOINT_KINDS_BY_API_KIND = exports.Queue = exports.PubSub = exports.Rpc = exports.AuthMeta = exports.RouteMetadata = exports.IPC_METADATA_KEYS = exports.assertNotInternalApi = void 0;
13
- exports.ApiErrorHttpStatus = exports.ApiErrorPayload = exports.ApiErrorCodec = exports.ApiEndpointNotFoundError = exports.ApiConnectionError = exports.ApiDependencyBackoffError = exports.ApiUnauthorizedError = exports.ApiBadRequestError = exports.ApiEndUserError = exports.ApiRequestTimeoutError = exports.ApiForbiddenError = exports.ApiRateLimitedError = exports.ApiImplementationError = exports.ApiDependencyTimeoutError = exports.ApiUnavailableError = exports.ApiDependencyError = exports.ApiNotFoundError = exports.ApiError = exports.FilterChain = exports.Filter = exports.SerializedError = exports.SerializedMap = exports.RecordSerializer = exports.getDoNotRecordFields = exports.DoNotRecord = exports.RecordedTestCase = exports.RecordedError = exports.RecordedEndpoint = exports.RecorderKeys = exports.ApiMethodInfo = exports.LOG_API_CALL_LOGGER_NAME = exports.ApiCallLogNameImpl = exports.ApiCallLogName = exports.ApiCallInfo = exports.MaskSpec = exports.LogApiCallImpl = void 0;
12
+ exports.ApiCallTimeoutError = exports.CallContext = exports.CallDeadline = exports.CallRegistry = exports.ClientRegistry = exports.HeaderRegistry = exports.DateTimeUtil = exports.TimeUtil = exports.DateUtil = exports.InstantUtil = exports.NetworkRejectClassifier = exports.NO_REG_CODE = exports.WRONG_COMPANY = exports.WRONG_DOMAIN = exports.EMAIL_NOT_CONFIRMED = exports.NOT_APPROVED = exports.WRONG_LOGIN = exports.WRONG_LOGIN_TYPE = exports.ENTITY_NOT_FOUND = exports.SECRETS = exports.Secrets = exports.getEndpointCaller = exports.isExternalSystemKind = exports.ExternalCaller = exports.DEFAULT_CALLER_KIND = exports.EXTERNAL_SYSTEM_KINDS = exports.getQueueName = exports.assertPubSubConventions = exports.assertApiKind = exports.getApiKind = exports.ENDPOINT_KINDS_BY_API_KIND = exports.Queue = exports.PubSub = exports.Rpc = exports.AuthMeta = exports.DtoSchemaBuilder = exports.DtoValidationFailure = exports.ApiJsonSchema = exports.WpResponseDto = exports.WpDtoFieldMetadata = exports.WpDtoFieldOptions = exports.WpDtoField = exports.WpDto = exports.getWpMcpTools = exports.WpMcpToolMetadata = exports.WpMcpToolHints = exports.WpMcpTool = exports.RouteMetadata = exports.IPC_METADATA_KEYS = exports.assertNotInternalApi = void 0;
13
+ exports.ApiErrorHttpStatus = exports.ApiErrorPayload = exports.ApiErrorCodec = exports.ApiEndpointNotFoundError = exports.ApiConnectionError = exports.ApiDependencyBackoffError = exports.ApiUnauthorizedError = exports.ApiBadRequestError = exports.ApiEndUserError = exports.ApiRequestTimeoutError = exports.ApiForbiddenError = exports.ApiRateLimitedError = exports.ApiImplementationError = exports.ApiDependencyTimeoutError = exports.ApiUnavailableError = exports.ApiDependencyError = exports.ApiNotFoundError = exports.ApiError = exports.FilterChain = exports.Filter = exports.SerializedError = exports.SerializedMap = exports.RecordSerializer = exports.getDoNotRecordFields = exports.DoNotRecord = exports.RecordedTestCase = exports.RecordedError = exports.RecordedEndpoint = exports.RecorderKeys = exports.ApiMethodInfo = exports.LOG_API_CALL_LOGGER_NAME = exports.ApiCallLogNameImpl = exports.ApiCallLogName = exports.ApiCallInfo = exports.MaskSpec = exports.LogApiCallImpl = exports.ContextMgr = exports.DestinationTrust = exports.WebpiecesCoreHeaders = exports.templateDeriver = exports.WEBPIECES_DEFAULT_FAILURE_CLASSIFIER = exports.WebpiecesDefaultFailureClassifier = exports.KeyedFailureClassifier = exports.HttpResponseDto = exports.HttpResponseStatus = exports.HttpHeader = exports.RuntimeLocality = exports.ServiceInfo = void 0;
14
14
  var errorUtils_1 = require("./lib/errorUtils");
15
15
  Object.defineProperty(exports, "toError", { enumerable: true, get: function () { return errorUtils_1.toError; } });
16
16
  var ContextKey_1 = require("./ContextKey");
@@ -86,6 +86,20 @@ Object.defineProperty(exports, "IPC_METADATA_KEYS", { enumerable: true, get: fun
86
86
  // The runtime representation of ONE route (split out of decorators.ts for file size only).
87
87
  var RouteMetadata_1 = require("./http/RouteMetadata");
88
88
  Object.defineProperty(exports, "RouteMetadata", { enumerable: true, get: function () { return RouteMetadata_1.RouteMetadata; } });
89
+ var McpMetadata_1 = require("./mcp/McpMetadata");
90
+ Object.defineProperty(exports, "WpMcpTool", { enumerable: true, get: function () { return McpMetadata_1.WpMcpTool; } });
91
+ Object.defineProperty(exports, "WpMcpToolHints", { enumerable: true, get: function () { return McpMetadata_1.WpMcpToolHints; } });
92
+ Object.defineProperty(exports, "WpMcpToolMetadata", { enumerable: true, get: function () { return McpMetadata_1.WpMcpToolMetadata; } });
93
+ Object.defineProperty(exports, "getWpMcpTools", { enumerable: true, get: function () { return McpMetadata_1.getWpMcpTools; } });
94
+ var DtoSchema_1 = require("./mcp/DtoSchema");
95
+ Object.defineProperty(exports, "WpDto", { enumerable: true, get: function () { return DtoSchema_1.WpDto; } });
96
+ Object.defineProperty(exports, "WpDtoField", { enumerable: true, get: function () { return DtoSchema_1.WpDtoField; } });
97
+ Object.defineProperty(exports, "WpDtoFieldOptions", { enumerable: true, get: function () { return DtoSchema_1.WpDtoFieldOptions; } });
98
+ Object.defineProperty(exports, "WpDtoFieldMetadata", { enumerable: true, get: function () { return DtoSchema_1.WpDtoFieldMetadata; } });
99
+ Object.defineProperty(exports, "WpResponseDto", { enumerable: true, get: function () { return DtoSchema_1.WpResponseDto; } });
100
+ Object.defineProperty(exports, "ApiJsonSchema", { enumerable: true, get: function () { return DtoSchema_1.ApiJsonSchema; } });
101
+ Object.defineProperty(exports, "DtoValidationFailure", { enumerable: true, get: function () { return DtoSchema_1.DtoValidationFailure; } });
102
+ Object.defineProperty(exports, "DtoSchemaBuilder", { enumerable: true, get: function () { return DtoSchema_1.DtoSchemaBuilder; } });
89
103
  // The TYPE layer of the auth surface — likewise split out of decorators.ts for file size only.
90
104
  var auth_mode_1 = require("./http/auth-mode");
91
105
  Object.defineProperty(exports, "AuthMeta", { enumerable: true, get: function () { return auth_mode_1.AuthMeta; } });
package/src/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/core/core-util/src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;;;AAEH,+CAA2C;AAAlC,qGAAA,OAAO,OAAA;AAChB,2CAA0C;AAAjC,wGAAA,UAAU,OAAA;AAOnB,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AAErB,+EAA+E;AAC/E,kFAAkF;AAClF,yCAAyC;AACzC,mDAA0F;AAAjF,gHAAA,cAAc,OAAA;AAAE,kHAAA,gBAAgB,OAAA;AAAE,sHAAA,oBAAoB,OAAA;AAO/D,yDAAwD;AAA/C,8GAAA,aAAa,OAAA;AACtB,uEAAsE;AAA7D,4HAAA,oBAAoB,OAAA;AAC7B,mDAAkD;AAAzC,wGAAA,UAAU,OAAA;AACnB,mDAM8B;AAL1B,wGAAA,UAAU,OAAA;AACV,4GAAA,cAAc,OAAA;AACd,0GAAA,YAAY,OAAA;AACZ,+GAAA,iBAAiB,OAAA;AACjB,kHAAA,oBAAoB,OAAA;AAGxB,8DAA8D;AAC9D,sEAAsE;AACtE,qEAAqE;AACrE,uEAAuE;AACvE,kEAAkE;AAElE,4BAA4B;AAC5B,gDA8B2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GAAkG;AAClG,wFAAwF;AACxF,2CAA0C;AAAjC,gGAAA,MAAM,OAAA;AAEf,qDAAoD;AAA3C,0GAAA,WAAW,OAAA;AAEpB,mCAkBkB;AAjBd,kGAAA,QAAQ,OAAA;AACR,0GAAA,gBAAgB,OAAA;AAChB,4GAAA,kBAAkB,OAAA;AAClB,6GAAA,mBAAmB,OAAA;AACnB,mHAAA,yBAAyB,OAAA;AACzB,gHAAA,sBAAsB,OAAA;AACtB,6GAAA,mBAAmB,OAAA;AACnB,2GAAA,iBAAiB,OAAA;AACjB,gHAAA,sBAAsB,OAAA;AACtB,yGAAA,eAAe,OAAA;AACf,4GAAA,kBAAkB,OAAA;AAClB,8GAAA,oBAAoB,OAAA;AACpB,mHAAA,yBAAyB,OAAA;AACzB,4GAAA,kBAAkB,OAAA;AAClB,kHAAA,wBAAwB,OAAA;AACxB,uGAAA,aAAa,OAAA;AACb,yGAAA,eAAe,OAAA;AAGnB,gEAA+D;AAAtD,wHAAA,kBAAkB,OAAA","sourcesContent":["/**\n * @webpieces/core-util\n *\n * Utility functions for WebPieces applications.\n * This package works in both browser and Node.js environments.\n *\n * @packageDocumentation\n */\n\nexport { toError } from './lib/errorUtils';\nexport { ContextKey } from './ContextKey';\nexport type {\n AnyContextKey,\n AnyTrustedContextKey,\n AnyUntrustedContextKey,\n Trust,\n} from './ContextKey';\nexport { ContextTuple } from './ContextTuple';\n\n// @DocumentDesign — DI-design-root marker. Applies to ANY project kind (server\n// controllers AND library impl classes), so it lives here (browser + Node) rather\n// than in a server-only routing package.\nexport { DocumentDesign, isDocumentDesign, DESIGN_METADATA_KEYS } from './DocumentDesign';\n\n// Logging (merged from former @webpieces/wp-logging).\n// Pluggable logging interface + a browser-safe console default; apps plug in\n// bunyan/winston/pino/etc. via LogManager.setFactory(...). Browser + Node.\nexport type { Logger, LogLevel } from './logging/Logger';\nexport type { LoggerFactory } from './logging/LoggerFactory';\nexport { ConsoleLogger } from './logging/ConsoleLogger';\nexport { ConsoleLoggerFactory } from './logging/ConsoleLoggerFactory';\nexport { LogManager } from './logging/LogManager';\nexport {\n LogChunker,\n LogChunkerImpl,\n LogChunkInfo,\n MAX_GCP_LOG_BYTES,\n GCP_LOG_BUDGET_BYTES,\n} from './logging/LogChunker';\n\n// HTTP API contract (merged from former @webpieces/http-api).\n// Shared HTTP API definition consumed by both client and server: REST\n// decorators, the API error taxonomy, datetime DTOs, platform-header\n// registry/readers, ValidateImplementation, and the test-case recorder\n// contract. Pure definitions — express-free, browser + Node safe.\n\n// API definition decorators\nexport {\n ApiPath,\n Endpoint,\n // Auth mode decorators (clean service-to-service + user JWT model)\n WpAuthPublic,\n WpAuthJwt,\n rolesRequired,\n MISSING_AUTH_DECORATOR_FIX,\n WpAuthOidc,\n WpAuthSharedSecret,\n WpAuthWebhook,\n WpAuthApiKey,\n WpAuthLocalOnly,\n MaskLog,\n getApiPath,\n getEndpoints,\n getEndpointOptions,\n getEndpointKind,\n getEndpointKinds,\n getMaskSpec,\n isFormPost,\n isRawBody,\n isApiPath,\n getAuthMeta,\n getAuthMode,\n assertEveryEndpointHasAuthMode,\n assertEveryExternalEndpointDeclaresCaller,\n assertEveryWebhookEndpointRetainsRawBody,\n validateNoConflictingDecorators,\n METADATA_KEYS,\n} from './http/decorators';\nexport {\n WpInternal,\n WpIpcEndpoint,\n isInternalApi,\n getIpcApiId,\n getIpcEndpoints,\n getIpcEndpointKind,\n getIpcMaskSpec,\n assertInternalApi,\n assertNotInternalApi,\n IPC_METADATA_KEYS,\n} from './ipc/IpcDecorators';\nexport type { IpcApiType, IpcEndpointKind, IpcEndpointOptions } from './ipc/IpcDecorators';\n// The runtime representation of ONE route (split out of decorators.ts for file size only).\nexport { RouteMetadata } from './http/RouteMetadata';\nexport type { EndpointKind, EndpointOptions, ExternalEndpointOptions } from './http/decorators';\n// The TYPE layer of the auth surface — likewise split out of decorators.ts for file size only.\nexport { AuthMeta } from './http/auth-mode';\nexport type {\n AuthMode,\n ApiKeyCredential,\n ApiKeyCredentials,\n JwtRoles,\n JwtRequirement,\n} from './http/auth-mode';\n// API kind (RPC vs PubSub/Cloud Tasks) + queue naming. Split out of decorators.ts for file size only;\n// one-way dependency api-kind -> decorators, and the barrel keeps the surface identical.\nexport {\n Rpc,\n PubSub,\n Queue,\n ENDPOINT_KINDS_BY_API_KIND,\n getApiKind,\n assertApiKind,\n assertPubSubConventions,\n getQueueName,\n} from './http/api-kind';\nexport type { ApiKind } from './http/api-kind';\n// WHO calls an `external` endpoint — the caller declaration @Endpoint(..., 'external', {calledBy})\n// requires, and the reader for it.\nexport {\n EXTERNAL_SYSTEM_KINDS,\n DEFAULT_CALLER_KIND,\n ExternalCaller,\n isExternalSystemKind,\n getEndpointCaller,\n} from './http/external-caller';\nexport type { ExternalSystemKind } from './http/external-caller';\n// Client-side shared-secret store (the value THIS service sends per @WpAuthSharedSecret key).\nexport { Secrets, SECRETS } from './http/Secrets';\n\n// Type validators\nexport { ValidateImplementation } from './http/validators';\n\n// Authentication subtype constants.\nexport {\n ENTITY_NOT_FOUND,\n WRONG_LOGIN_TYPE,\n WRONG_LOGIN,\n NOT_APPROVED,\n EMAIL_NOT_CONFIRMED,\n WRONG_DOMAIN,\n WRONG_COMPANY,\n NO_REG_CODE,\n} from './errors';\n\nexport { NetworkRejectClassifier } from './http/networkReject';\n\n// Date/Time DTOs and Utilities (inspired by Java Time / JSR-310)\nexport {\n InstantDto,\n DateDto,\n TimeDto,\n DateTimeDto,\n InstantUtil,\n DateUtil,\n TimeUtil,\n DateTimeUtil,\n} from './http/datetime';\n\n// Context keys + registry (the global magic-context header system)\nexport { HeaderRegistry } from './http/HeaderRegistry';\nexport { ClientRegistry } from './http/ClientRegistry';\nexport { CallRegistry } from './http/CallRegistry';\nexport { CallDeadline } from './http/CallDeadline';\nexport { CallContext } from './http/CallStrategy';\nexport type { Attempt, CallStrategy } from './http/CallStrategy';\nexport { ApiCallTimeoutError } from './http/ApiCallTimeoutError';\nexport type { ServiceUrlDeriver } from './http/ClientRegistry';\n\n// \"What service am I\" — set once at startup, read by the logging backends and by\n// RequestContextHeaders (to stamp requestIdSource on ids this service mints).\nexport { ServiceInfo } from './http/ServiceInfo';\n// \"Where am I running\" — declared once at startup (setupRuntime, from RuntimeSetupOptions.locality).\n// The ONE input to @WpAuthLocalOnly enforcement. Undeclared reads as DEPLOYED (fail safe).\nexport { RuntimeLocality } from './http/RuntimeLocality';\nexport type { Locality } from './http/RuntimeLocality';\n// The ENTIRE HTTP response as pure data — the ONE form both transports (express, fetch) are\n// normalised into, so an ErrorTranslators implementation is written once and serves both.\nexport { HttpHeader, HttpResponseStatus, HttpResponseDto } from './http/HttpResponseDto';\n// Pluggable, bidirectional error translation (app exception <-> the WHOLE response). Set on\n// ClientRegistry at startup; consulted before the built-in webpieces mapping on BOTH sides.\nexport type { ErrorTranslators } from './http/ErrorTranslators';\n// Pluggable per-client failure classification (is a thrown API-call error a real failure or an\n// expected non-failure?). Registered on ClientRegistry at startup; consulted by LogApiCall.\nexport type { FailureClassifier } from './http/FailureClassifier';\nexport { KeyedFailureClassifier } from './http/FailureClassifier';\nexport {\n WebpiecesDefaultFailureClassifier,\n WEBPIECES_DEFAULT_FAILURE_CLASSIFIER,\n} from './http/WebpiecesDefaultFailureClassifier';\nexport { templateDeriver } from './http/templateDeriver';\nexport { WebpiecesCoreHeaders } from './http/WebpiecesCoreHeaders';\nexport { ContextReader } from './http/ContextReader';\n\n// The OUTBOUND half of the trust model: whether a TRUSTED context key may ride to the endpoint being\n// called. Built ONLY from the destination endpoint's AuthMode — see the class doc.\nexport { DestinationTrust } from './http/DestinationTrust';\n\n// BROWSER-ONLY outbound-header propagation (app-held store + registry -> outbound HTTP headers).\n// Only @webpieces/http-client-browser may name it; the server reads RequestContext directly via\n// RequestContextHeaders in the Node-only @webpieces/core-context.\nexport { ContextMgr } from './http/ContextMgr';\n\n// API-call logging helper (uses LogManager above). NOT a singleton: construct one per environment\n// with that environment's ApiCallContext — `new LogApiCallImpl(new RequestContextApiCallContext())`\n// on node, `new LogApiCallImpl(new BrowserApiCallContext())` in a browser.\nexport { LogApiCallImpl } from './http/LogApiCall';\n\n// Opt-in field masking for the LogApiCall log path — declare per-api sensitive fields so secrets\n// (OAuth refresh tokens, id-token JWTs) are masked in the logs while the real value stays on the wire.\nexport { MaskSpec } from './http/LogFieldMask';\nexport type { MaskMode } from './http/LogFieldMask';\n\n// The structured `api` tag + the context-writer seam LogApiCall stamps through. The Node\n// RequestContext-backed impl lives in @webpieces/core-context, the browser one in\n// @webpieces/http-client-browser; each is CONSTRUCTED by its package, never installed globally.\nexport { ApiCallInfo } from './http/ApiCallInfo';\nexport type { ApiType, ApiResult } from './http/ApiCallInfo';\n// Console-render bridge: turns LogApiCall's [LogApiCall] bracket into [API.{side}.{phase}] locally.\nexport {\n ApiCallLogName,\n ApiCallLogNameImpl,\n LOG_API_CALL_LOGGER_NAME,\n} from './http/ApiCallLogName';\nexport { ApiMethodInfo } from './http/ApiMethodInfo';\nexport type { ApiSide } from './http/ApiMethodInfo';\nexport type { ApiCallContext } from './http/ApiCallContext';\n\n// Test-case recording contract (impl lives in http-server; hooks in http-client)\nexport { TestCaseRecorder, RecorderKeys } from './http/recorder/TestCaseRecorder';\nexport {\n RecordedEndpoint,\n RecordedError,\n RecordedTestCase,\n} from './http/recorder/RecordedEndpoint';\nexport { DoNotRecord, getDoNotRecordFields } from './http/recorder/DoNotRecord';\nexport { RecordSerializer, SerializedMap, SerializedError } from './http/recorder/RecordSerializer';\n\n// ---------------------------------------------------------------------------------------------\n// Filter-chain primitives, shared by BOTH chains: the inbound server chain\n// (`Filter<MethodMeta, WpResponse<unknown>>`, @webpieces/http-routing) and the outbound client\n// chain (`Filter<ClientRequest, Response>`, @webpieces/http-client-core). Declared once, here, in\n// the package both depend on — see the class doc for why a second pair would be a shim.\nexport { Filter } from './filters/Filter';\nexport type { Service } from './filters/Filter';\nexport { FilterChain } from './filters/FilterChain';\n\nexport {\n ApiError,\n ApiNotFoundError,\n ApiDependencyError,\n ApiUnavailableError,\n ApiDependencyTimeoutError,\n ApiImplementationError,\n ApiRateLimitedError,\n ApiForbiddenError,\n ApiRequestTimeoutError,\n ApiEndUserError,\n ApiBadRequestError,\n ApiUnauthorizedError,\n ApiDependencyBackoffError,\n ApiConnectionError,\n ApiEndpointNotFoundError,\n ApiErrorCodec,\n ApiErrorPayload,\n} from './errors';\nexport type { ApiErrorKind } from './errors';\nexport { ApiErrorHttpStatus } from './http/ApiErrorHttpStatus';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/core/core-util/src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;;;AAEH,+CAA2C;AAAlC,qGAAA,OAAO,OAAA;AAChB,2CAA0C;AAAjC,wGAAA,UAAU,OAAA;AAOnB,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AAErB,+EAA+E;AAC/E,kFAAkF;AAClF,yCAAyC;AACzC,mDAA0F;AAAjF,gHAAA,cAAc,OAAA;AAAE,kHAAA,gBAAgB,OAAA;AAAE,sHAAA,oBAAoB,OAAA;AAO/D,yDAAwD;AAA/C,8GAAA,aAAa,OAAA;AACtB,uEAAsE;AAA7D,4HAAA,oBAAoB,OAAA;AAC7B,mDAAkD;AAAzC,wGAAA,UAAU,OAAA;AACnB,mDAM8B;AAL1B,wGAAA,UAAU,OAAA;AACV,4GAAA,cAAc,OAAA;AACd,0GAAA,YAAY,OAAA;AACZ,+GAAA,iBAAiB,OAAA;AACjB,kHAAA,oBAAoB,OAAA;AAGxB,8DAA8D;AAC9D,sEAAsE;AACtE,qEAAqE;AACrE,uEAAuE;AACvE,kEAAkE;AAElE,4BAA4B;AAC5B,gDA8B2B;AA7BvB,qGAAA,OAAO,OAAA;AACP,sGAAA,QAAQ,OAAA;AACR,mEAAmE;AACnE,0GAAA,YAAY,OAAA;AACZ,uGAAA,SAAS,OAAA;AACT,2GAAA,aAAa,OAAA;AACb,wHAAA,0BAA0B,OAAA;AAC1B,wGAAA,UAAU,OA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C1C,qEAAoG;AAA3F,oHAAA,gBAAgB,OAAA;AAAE,iHAAA,aAAa,OAAA;AAAE,mHAAA,eAAe,OAAA;AAEzD,gGAAgG;AAChG,2EAA2E;AAC3E,+FAA+F;AAC/F,kGAAkG;AAClG,wFAAwF;AACxF,2CAA0C;AAAjC,gGAAA,MAAM,OAAA;AAEf,qDAAoD;AAA3C,0GAAA,WAAW,OAAA;AAEpB,mCAkBkB;AAjBd,kGAAA,QAAQ,OAAA;AACR,0GAAA,gBAAgB,OAAA;AAChB,4GAAA,kBAAkB,OAAA;AAClB,6GAAA,mBAAmB,OAAA;AACnB,mHAAA,yBAAyB,OAAA;AACzB,gHAAA,sBAAsB,OAAA;AACtB,6GAAA,mBAAmB,OAAA;AACnB,2GAAA,iBAAiB,OAAA;AACjB,gHAAA,sBAAsB,OAAA;AACtB,yGAAA,eAAe,OAAA;AACf,4GAAA,kBAAkB,OAAA;AAClB,8GAAA,oBAAoB,OAAA;AACpB,mHAAA,yBAAyB,OAAA;AACzB,4GAAA,kBAAkB,OAAA;AAClB,kHAAA,wBAAwB,OAAA;AACxB,uGAAA,aAAa,OAAA;AACb,yGAAA,eAAe,OAAA;AAGnB,gEAA+D;AAAtD,wHAAA,kBAAkB,OAAA","sourcesContent":["/**\n * @webpieces/core-util\n *\n * Utility functions for WebPieces applications.\n * This package works in both browser and Node.js environments.\n *\n * @packageDocumentation\n */\n\nexport { toError } from './lib/errorUtils';\nexport { ContextKey } from './ContextKey';\nexport type {\n AnyContextKey,\n AnyTrustedContextKey,\n AnyUntrustedContextKey,\n Trust,\n} from './ContextKey';\nexport { ContextTuple } from './ContextTuple';\n\n// @DocumentDesign — DI-design-root marker. Applies to ANY project kind (server\n// controllers AND library impl classes), so it lives here (browser + Node) rather\n// than in a server-only routing package.\nexport { DocumentDesign, isDocumentDesign, DESIGN_METADATA_KEYS } from './DocumentDesign';\n\n// Logging (merged from former @webpieces/wp-logging).\n// Pluggable logging interface + a browser-safe console default; apps plug in\n// bunyan/winston/pino/etc. via LogManager.setFactory(...). Browser + Node.\nexport type { Logger, LogLevel } from './logging/Logger';\nexport type { LoggerFactory } from './logging/LoggerFactory';\nexport { ConsoleLogger } from './logging/ConsoleLogger';\nexport { ConsoleLoggerFactory } from './logging/ConsoleLoggerFactory';\nexport { LogManager } from './logging/LogManager';\nexport {\n LogChunker,\n LogChunkerImpl,\n LogChunkInfo,\n MAX_GCP_LOG_BYTES,\n GCP_LOG_BUDGET_BYTES,\n} from './logging/LogChunker';\n\n// HTTP API contract (merged from former @webpieces/http-api).\n// Shared HTTP API definition consumed by both client and server: REST\n// decorators, the API error taxonomy, datetime DTOs, platform-header\n// registry/readers, ValidateImplementation, and the test-case recorder\n// contract. Pure definitions — express-free, browser + Node safe.\n\n// API definition decorators\nexport {\n ApiPath,\n Endpoint,\n // Auth mode decorators (clean service-to-service + user JWT model)\n WpAuthPublic,\n WpAuthJwt,\n rolesRequired,\n MISSING_AUTH_DECORATOR_FIX,\n WpAuthOidc,\n WpAuthSharedSecret,\n WpAuthWebhook,\n WpAuthApiKey,\n WpAuthLocalOnly,\n MaskLog,\n getApiPath,\n getEndpoints,\n getEndpointOptions,\n getEndpointKind,\n getEndpointKinds,\n getMaskSpec,\n isFormPost,\n isRawBody,\n isApiPath,\n getAuthMeta,\n getAuthMode,\n assertEveryEndpointHasAuthMode,\n assertEveryExternalEndpointDeclaresCaller,\n assertEveryWebhookEndpointRetainsRawBody,\n validateNoConflictingDecorators,\n METADATA_KEYS,\n} from './http/decorators';\nexport {\n WpInternal,\n WpIpcEndpoint,\n isInternalApi,\n getIpcApiId,\n getIpcEndpoints,\n getIpcEndpointKind,\n getIpcMaskSpec,\n assertInternalApi,\n assertNotInternalApi,\n IPC_METADATA_KEYS,\n} from './ipc/IpcDecorators';\nexport type { IpcApiType, IpcEndpointKind, IpcEndpointOptions } from './ipc/IpcDecorators';\n// The runtime representation of ONE route (split out of decorators.ts for file size only).\nexport { RouteMetadata } from './http/RouteMetadata';\nexport type { EndpointKind, EndpointOptions, ExternalEndpointOptions } from './http/decorators';\nexport {\n WpMcpTool,\n WpMcpToolHints,\n WpMcpToolMetadata,\n getWpMcpTools,\n} from './mcp/McpMetadata';\nexport type { WpMcpMethodDecorator, WpMcpToolOptions } from './mcp/McpMetadata';\nexport {\n WpDto,\n WpDtoField,\n WpDtoFieldOptions,\n WpDtoFieldMetadata,\n WpResponseDto,\n ApiJsonSchema,\n DtoValidationFailure,\n DtoSchemaBuilder,\n} from './mcp/DtoSchema';\nexport type { DtoClass, DtoArrayItem, DtoValue } from './mcp/DtoSchema';\n// The TYPE layer of the auth surface — likewise split out of decorators.ts for file size only.\nexport { AuthMeta } from './http/auth-mode';\nexport type {\n AuthMode,\n ApiKeyCredential,\n ApiKeyCredentials,\n JwtRoles,\n JwtRequirement,\n} from './http/auth-mode';\n// API kind (RPC vs PubSub/Cloud Tasks) + queue naming. Split out of decorators.ts for file size only;\n// one-way dependency api-kind -> decorators, and the barrel keeps the surface identical.\nexport {\n Rpc,\n PubSub,\n Queue,\n ENDPOINT_KINDS_BY_API_KIND,\n getApiKind,\n assertApiKind,\n assertPubSubConventions,\n getQueueName,\n} from './http/api-kind';\nexport type { ApiKind } from './http/api-kind';\n// WHO calls an `external` endpoint — the caller declaration @Endpoint(..., 'external', {calledBy})\n// requires, and the reader for it.\nexport {\n EXTERNAL_SYSTEM_KINDS,\n DEFAULT_CALLER_KIND,\n ExternalCaller,\n isExternalSystemKind,\n getEndpointCaller,\n} from './http/external-caller';\nexport type { ExternalSystemKind } from './http/external-caller';\n// Client-side shared-secret store (the value THIS service sends per @WpAuthSharedSecret key).\nexport { Secrets, SECRETS } from './http/Secrets';\n\n// Type validators\nexport { ValidateImplementation } from './http/validators';\n\n// Authentication subtype constants.\nexport {\n ENTITY_NOT_FOUND,\n WRONG_LOGIN_TYPE,\n WRONG_LOGIN,\n NOT_APPROVED,\n EMAIL_NOT_CONFIRMED,\n WRONG_DOMAIN,\n WRONG_COMPANY,\n NO_REG_CODE,\n} from './errors';\n\nexport { NetworkRejectClassifier } from './http/networkReject';\n\n// Date/Time DTOs and Utilities (inspired by Java Time / JSR-310)\nexport {\n InstantDto,\n DateDto,\n TimeDto,\n DateTimeDto,\n InstantUtil,\n DateUtil,\n TimeUtil,\n DateTimeUtil,\n} from './http/datetime';\n\n// Context keys + registry (the global magic-context header system)\nexport { HeaderRegistry } from './http/HeaderRegistry';\nexport { ClientRegistry } from './http/ClientRegistry';\nexport { CallRegistry } from './http/CallRegistry';\nexport { CallDeadline } from './http/CallDeadline';\nexport { CallContext } from './http/CallStrategy';\nexport type { Attempt, CallStrategy } from './http/CallStrategy';\nexport { ApiCallTimeoutError } from './http/ApiCallTimeoutError';\nexport type { ServiceUrlDeriver } from './http/ClientRegistry';\n\n// \"What service am I\" — set once at startup, read by the logging backends and by\n// RequestContextHeaders (to stamp requestIdSource on ids this service mints).\nexport { ServiceInfo } from './http/ServiceInfo';\n// \"Where am I running\" — declared once at startup (setupRuntime, from RuntimeSetupOptions.locality).\n// The ONE input to @WpAuthLocalOnly enforcement. Undeclared reads as DEPLOYED (fail safe).\nexport { RuntimeLocality } from './http/RuntimeLocality';\nexport type { Locality } from './http/RuntimeLocality';\n// The ENTIRE HTTP response as pure data — the ONE form both transports (express, fetch) are\n// normalised into, so an ErrorTranslators implementation is written once and serves both.\nexport { HttpHeader, HttpResponseStatus, HttpResponseDto } from './http/HttpResponseDto';\n// Pluggable, bidirectional error translation (app exception <-> the WHOLE response). Set on\n// ClientRegistry at startup; consulted before the built-in webpieces mapping on BOTH sides.\nexport type { ErrorTranslators } from './http/ErrorTranslators';\n// Pluggable per-client failure classification (is a thrown API-call error a real failure or an\n// expected non-failure?). Registered on ClientRegistry at startup; consulted by LogApiCall.\nexport type { FailureClassifier } from './http/FailureClassifier';\nexport { KeyedFailureClassifier } from './http/FailureClassifier';\nexport {\n WebpiecesDefaultFailureClassifier,\n WEBPIECES_DEFAULT_FAILURE_CLASSIFIER,\n} from './http/WebpiecesDefaultFailureClassifier';\nexport { templateDeriver } from './http/templateDeriver';\nexport { WebpiecesCoreHeaders } from './http/WebpiecesCoreHeaders';\nexport { ContextReader } from './http/ContextReader';\n\n// The OUTBOUND half of the trust model: whether a TRUSTED context key may ride to the endpoint being\n// called. Built ONLY from the destination endpoint's AuthMode — see the class doc.\nexport { DestinationTrust } from './http/DestinationTrust';\n\n// BROWSER-ONLY outbound-header propagation (app-held store + registry -> outbound HTTP headers).\n// Only @webpieces/http-client-browser may name it; the server reads RequestContext directly via\n// RequestContextHeaders in the Node-only @webpieces/core-context.\nexport { ContextMgr } from './http/ContextMgr';\n\n// API-call logging helper (uses LogManager above). NOT a singleton: construct one per environment\n// with that environment's ApiCallContext — `new LogApiCallImpl(new RequestContextApiCallContext())`\n// on node, `new LogApiCallImpl(new BrowserApiCallContext())` in a browser.\nexport { LogApiCallImpl } from './http/LogApiCall';\n\n// Opt-in field masking for the LogApiCall log path — declare per-api sensitive fields so secrets\n// (OAuth refresh tokens, id-token JWTs) are masked in the logs while the real value stays on the wire.\nexport { MaskSpec } from './http/LogFieldMask';\nexport type { MaskMode } from './http/LogFieldMask';\n\n// The structured `api` tag + the context-writer seam LogApiCall stamps through. The Node\n// RequestContext-backed impl lives in @webpieces/core-context, the browser one in\n// @webpieces/http-client-browser; each is CONSTRUCTED by its package, never installed globally.\nexport { ApiCallInfo } from './http/ApiCallInfo';\nexport type { ApiType, ApiResult } from './http/ApiCallInfo';\n// Console-render bridge: turns LogApiCall's [LogApiCall] bracket into [API.{side}.{phase}] locally.\nexport {\n ApiCallLogName,\n ApiCallLogNameImpl,\n LOG_API_CALL_LOGGER_NAME,\n} from './http/ApiCallLogName';\nexport { ApiMethodInfo } from './http/ApiMethodInfo';\nexport type { ApiSide } from './http/ApiMethodInfo';\nexport type { ApiCallContext } from './http/ApiCallContext';\n\n// Test-case recording contract (impl lives in http-server; hooks in http-client)\nexport { TestCaseRecorder, RecorderKeys } from './http/recorder/TestCaseRecorder';\nexport {\n RecordedEndpoint,\n RecordedError,\n RecordedTestCase,\n} from './http/recorder/RecordedEndpoint';\nexport { DoNotRecord, getDoNotRecordFields } from './http/recorder/DoNotRecord';\nexport { RecordSerializer, SerializedMap, SerializedError } from './http/recorder/RecordSerializer';\n\n// ---------------------------------------------------------------------------------------------\n// Filter-chain primitives, shared by BOTH chains: the inbound server chain\n// (`Filter<MethodMeta, WpResponse<unknown>>`, @webpieces/http-routing) and the outbound client\n// chain (`Filter<ClientRequest, Response>`, @webpieces/http-client-core). Declared once, here, in\n// the package both depend on — see the class doc for why a second pair would be a shim.\nexport { Filter } from './filters/Filter';\nexport type { Service } from './filters/Filter';\nexport { FilterChain } from './filters/FilterChain';\n\nexport {\n ApiError,\n ApiNotFoundError,\n ApiDependencyError,\n ApiUnavailableError,\n ApiDependencyTimeoutError,\n ApiImplementationError,\n ApiRateLimitedError,\n ApiForbiddenError,\n ApiRequestTimeoutError,\n ApiEndUserError,\n ApiBadRequestError,\n ApiUnauthorizedError,\n ApiDependencyBackoffError,\n ApiConnectionError,\n ApiEndpointNotFoundError,\n ApiErrorCodec,\n ApiErrorPayload,\n} from './errors';\nexport type { ApiErrorKind } from './errors';\nexport { ApiErrorHttpStatus } from './http/ApiErrorHttpStatus';\n"]}
@@ -0,0 +1,70 @@
1
+ import 'reflect-metadata';
2
+ export type DtoClass = abstract new (...args: any[]) => unknown;
3
+ export type DtoArrayItem = 'string' | 'number' | 'integer' | 'boolean' | DtoClass;
4
+ /** Runtime values accepted at the DTO validation boundary. */
5
+ export type DtoValue = object | string | number | boolean | null;
6
+ /** Additive field metadata; the scalar/object type itself comes from `design:type`. */
7
+ export declare class WpDtoFieldOptions {
8
+ readonly description: string;
9
+ /** Required/optional is explicit because TypeScript erases `?` at runtime. */
10
+ readonly required: boolean;
11
+ /** Required for arrays because TypeScript erases their element type. */
12
+ readonly arrayItems?: DtoArrayItem | undefined;
13
+ /** A reflected Number is otherwise emitted as JSON Schema `number`. */
14
+ readonly integer: boolean;
15
+ readonly minimum?: number | undefined;
16
+ readonly maximum?: number | undefined;
17
+ readonly enumValues?: readonly [string, ...string[]] | undefined;
18
+ constructor(description: string,
19
+ /** Required/optional is explicit because TypeScript erases `?` at runtime. */
20
+ required: boolean,
21
+ /** Required for arrays because TypeScript erases their element type. */
22
+ arrayItems?: DtoArrayItem | undefined,
23
+ /** A reflected Number is otherwise emitted as JSON Schema `number`. */
24
+ integer?: boolean, minimum?: number | undefined, maximum?: number | undefined, enumValues?: readonly [string, ...string[]] | undefined);
25
+ }
26
+ export declare class WpDtoFieldMetadata {
27
+ readonly propertyKey: string;
28
+ readonly options: WpDtoFieldOptions;
29
+ constructor(propertyKey: string, options: WpDtoFieldOptions);
30
+ }
31
+ /** The JSON Schema subset emitted for Webpieces API DTOs. */
32
+ export declare class ApiJsonSchema {
33
+ type?: 'object' | 'string' | 'number' | 'integer' | 'boolean' | 'array';
34
+ description?: string;
35
+ properties?: Record<string, ApiJsonSchema>;
36
+ required?: string[];
37
+ additionalProperties?: boolean;
38
+ items?: ApiJsonSchema;
39
+ enum?: string[];
40
+ minimum?: number;
41
+ maximum?: number;
42
+ constructor(type?: 'object' | 'string' | 'number' | 'integer' | 'boolean' | 'array');
43
+ }
44
+ /** A validation result safe to show to an API caller/model. */
45
+ export declare class DtoValidationFailure {
46
+ readonly message: string;
47
+ constructor(message: string);
48
+ }
49
+ /** Marks a request/response class as a schema-bearing DTO, including intentionally empty DTOs. */
50
+ export declare function WpDto(): ClassDecorator;
51
+ /** Adds documentation and runtime-only shape facts to a DTO property. */
52
+ export declare function WpDtoField(options: WpDtoFieldOptions): PropertyDecorator;
53
+ /** Declares an async API method's response DTO because reflection sees Promise, not its generic. */
54
+ export declare function WpResponseDto(responseDto: () => DtoClass): MethodDecorator;
55
+ /** Builds and validates the same DTO schema used for MCP input and structured output. */
56
+ export declare class DtoSchemaBuilder {
57
+ requestClassOf(apiClass: Function, methodName: string): DtoClass;
58
+ responseClassOf(apiClass: Function, methodName: string): DtoClass;
59
+ build(dtoClass: DtoClass): ApiJsonSchema;
60
+ validate(dtoClass: DtoClass, value: DtoValue): DtoValidationFailure | undefined;
61
+ private buildAt;
62
+ private fieldSchema;
63
+ private validateOptions;
64
+ private itemSchema;
65
+ private validateAt;
66
+ private validateField;
67
+ private validateArray;
68
+ private fields;
69
+ private requireDto;
70
+ }
@@ -0,0 +1,294 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DtoSchemaBuilder = exports.DtoValidationFailure = exports.ApiJsonSchema = exports.WpDtoFieldMetadata = exports.WpDtoFieldOptions = void 0;
4
+ exports.WpDto = WpDto;
5
+ exports.WpDtoField = WpDtoField;
6
+ exports.WpResponseDto = WpResponseDto;
7
+ require("reflect-metadata");
8
+ const DTO_MARKER = 'webpieces:dto-schema';
9
+ const DTO_FIELDS = 'webpieces:dto-fields';
10
+ const RESPONSE_DTOS = 'webpieces:response-dtos';
11
+ /** Additive field metadata; the scalar/object type itself comes from `design:type`. */
12
+ class WpDtoFieldOptions {
13
+ description;
14
+ required;
15
+ arrayItems;
16
+ integer;
17
+ minimum;
18
+ maximum;
19
+ enumValues;
20
+ constructor(description,
21
+ /** Required/optional is explicit because TypeScript erases `?` at runtime. */
22
+ required,
23
+ /** Required for arrays because TypeScript erases their element type. */
24
+ arrayItems,
25
+ /** A reflected Number is otherwise emitted as JSON Schema `number`. */
26
+ integer = false, minimum, maximum, enumValues) {
27
+ this.description = description;
28
+ this.required = required;
29
+ this.arrayItems = arrayItems;
30
+ this.integer = integer;
31
+ this.minimum = minimum;
32
+ this.maximum = maximum;
33
+ this.enumValues = enumValues;
34
+ }
35
+ }
36
+ exports.WpDtoFieldOptions = WpDtoFieldOptions;
37
+ class WpDtoFieldMetadata {
38
+ propertyKey;
39
+ options;
40
+ constructor(propertyKey, options) {
41
+ this.propertyKey = propertyKey;
42
+ this.options = options;
43
+ }
44
+ }
45
+ exports.WpDtoFieldMetadata = WpDtoFieldMetadata;
46
+ /** The JSON Schema subset emitted for Webpieces API DTOs. */
47
+ class ApiJsonSchema {
48
+ type;
49
+ description;
50
+ properties;
51
+ required;
52
+ additionalProperties;
53
+ items;
54
+ enum;
55
+ minimum;
56
+ maximum;
57
+ constructor(type) {
58
+ this.type = type;
59
+ }
60
+ }
61
+ exports.ApiJsonSchema = ApiJsonSchema;
62
+ /** A validation result safe to show to an API caller/model. */
63
+ class DtoValidationFailure {
64
+ message;
65
+ constructor(message) {
66
+ this.message = message;
67
+ }
68
+ }
69
+ exports.DtoValidationFailure = DtoValidationFailure;
70
+ /** Marks a request/response class as a schema-bearing DTO, including intentionally empty DTOs. */
71
+ // webpieces-disable no-function-outside-class -- decorator factories are inherently module-scope
72
+ function WpDto() {
73
+ return (target) => Reflect.defineMetadata(DTO_MARKER, true, target);
74
+ }
75
+ /** Adds documentation and runtime-only shape facts to a DTO property. */
76
+ // webpieces-disable no-function-outside-class -- decorator factories are inherently module-scope
77
+ function WpDtoField(options) {
78
+ if (options.description.trim() === '') {
79
+ throw new Error('@WpDtoField requires non-empty field documentation.');
80
+ }
81
+ return (target, propertyKey) => {
82
+ const dtoClass = target.constructor;
83
+ const fields = Reflect.getMetadata(DTO_FIELDS, dtoClass) ?? {};
84
+ const name = String(propertyKey);
85
+ fields[name] = new WpDtoFieldMetadata(name, options);
86
+ Reflect.defineMetadata(DTO_FIELDS, fields, dtoClass);
87
+ };
88
+ }
89
+ /** Declares an async API method's response DTO because reflection sees Promise, not its generic. */
90
+ // webpieces-disable no-function-outside-class -- decorator factories are inherently module-scope
91
+ function WpResponseDto(responseDto) {
92
+ return (target, propertyKey) => {
93
+ const apiClass = target.constructor;
94
+ const responses = Reflect.getMetadata(RESPONSE_DTOS, apiClass) ?? {};
95
+ responses[String(propertyKey)] = responseDto;
96
+ Reflect.defineMetadata(RESPONSE_DTOS, responses, apiClass);
97
+ };
98
+ }
99
+ /** Builds and validates the same DTO schema used for MCP input and structured output. */
100
+ class DtoSchemaBuilder {
101
+ requestClassOf(apiClass, methodName) {
102
+ // webpieces-disable no-any-unknown -- reflect-metadata returns erased runtime constructor tokens
103
+ const params = Reflect.getMetadata('design:paramtypes', apiClass.prototype, methodName);
104
+ if (!params || params.length !== 1) {
105
+ throw new Error(`${apiClass.name}.${methodName} must take exactly one @WpDto request class to be an MCP tool.`);
106
+ }
107
+ return params[0];
108
+ }
109
+ responseClassOf(apiClass, methodName) {
110
+ const responses = Reflect.getMetadata(RESPONSE_DTOS, apiClass) ?? {};
111
+ const response = responses[methodName];
112
+ if (!response) {
113
+ throw new Error(`${apiClass.name}.${methodName} must declare @WpResponseDto(() => ResponseClass) before MCP exposure.`);
114
+ }
115
+ return response();
116
+ }
117
+ build(dtoClass) {
118
+ return this.buildAt(dtoClass, new Set());
119
+ }
120
+ validate(dtoClass, value) {
121
+ return this.validateAt(dtoClass, value, '$');
122
+ }
123
+ buildAt(dtoClass, parents) {
124
+ this.requireDto(dtoClass);
125
+ if (parents.has(dtoClass)) {
126
+ throw new Error(`Recursive DTO ${dtoClass.name} cannot use an inline MCP schema.`);
127
+ }
128
+ const nextParents = new Set(parents);
129
+ nextParents.add(dtoClass);
130
+ const schema = new ApiJsonSchema('object');
131
+ schema.properties = {};
132
+ schema.additionalProperties = false;
133
+ const required = [];
134
+ for (const field of this.fields(dtoClass)) {
135
+ schema.properties[field.propertyKey] = this.fieldSchema(dtoClass, field, nextParents);
136
+ if (field.options.required)
137
+ required.push(field.propertyKey);
138
+ }
139
+ if (required.length > 0)
140
+ schema.required = required;
141
+ return schema;
142
+ }
143
+ fieldSchema(dtoClass, field, parents) {
144
+ // webpieces-disable no-any-unknown -- reflect-metadata returns an erased constructor token
145
+ const reflected = Reflect.getMetadata('design:type', dtoClass.prototype, field.propertyKey);
146
+ if (!reflected)
147
+ throw new Error(`No reflected type for ${dtoClass.name}.${field.propertyKey}.`);
148
+ const options = field.options;
149
+ this.validateOptions(dtoClass, field, reflected);
150
+ let schema;
151
+ switch (reflected.name) {
152
+ case 'String':
153
+ schema = new ApiJsonSchema('string');
154
+ break;
155
+ case 'Number':
156
+ schema = new ApiJsonSchema(options.integer ? 'integer' : 'number');
157
+ break;
158
+ case 'Boolean':
159
+ schema = new ApiJsonSchema('boolean');
160
+ break;
161
+ case 'Array':
162
+ if (!options.arrayItems) {
163
+ throw new Error(`${dtoClass.name}.${field.propertyKey} must declare arrayItems.`);
164
+ }
165
+ schema = new ApiJsonSchema('array');
166
+ schema.items = this.itemSchema(options.arrayItems, parents);
167
+ break;
168
+ default:
169
+ schema = this.buildAt(reflected, parents);
170
+ }
171
+ schema.description = options.description;
172
+ if (options.minimum !== undefined)
173
+ schema.minimum = options.minimum;
174
+ if (options.maximum !== undefined)
175
+ schema.maximum = options.maximum;
176
+ if (options.enumValues)
177
+ schema.enum = [...options.enumValues];
178
+ return schema;
179
+ }
180
+ validateOptions(dtoClass, field, reflected) {
181
+ const label = `${dtoClass.name}.${field.propertyKey}`;
182
+ const options = field.options;
183
+ if (reflected.name !== 'Array' && options.arrayItems) {
184
+ throw new Error(`${label} declares arrayItems but is not an array.`);
185
+ }
186
+ if (reflected.name !== 'Number' &&
187
+ (options.integer || options.minimum !== undefined || options.maximum !== undefined)) {
188
+ throw new Error(`${label} declares numeric constraints but is not a number.`);
189
+ }
190
+ if (options.minimum !== undefined && options.maximum !== undefined && options.minimum > options.maximum) {
191
+ throw new Error(`${label} minimum cannot exceed maximum.`);
192
+ }
193
+ if (options.enumValues && reflected.name !== 'String') {
194
+ throw new Error(`${label} enumValues require a string field.`);
195
+ }
196
+ }
197
+ itemSchema(item, parents) {
198
+ if (typeof item !== 'string')
199
+ return this.buildAt(item, parents);
200
+ return new ApiJsonSchema(item === 'integer' ? 'integer' : item);
201
+ }
202
+ validateAt(dtoClass, value, path) {
203
+ this.requireDto(dtoClass);
204
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
205
+ return new DtoValidationFailure(`${path} must be an object`);
206
+ }
207
+ const fields = this.fields(dtoClass);
208
+ const known = new Set(fields.map((field) => field.propertyKey));
209
+ for (const key of Object.keys(value)) {
210
+ if (!known.has(key))
211
+ return new DtoValidationFailure(`${path}.${key} is not allowed`);
212
+ }
213
+ for (const field of fields) {
214
+ const fieldValue = Object.getOwnPropertyDescriptor(value, field.propertyKey)?.value;
215
+ if (fieldValue === undefined) {
216
+ if (field.options.required) {
217
+ return new DtoValidationFailure(`${path}.${field.propertyKey} is required`);
218
+ }
219
+ continue;
220
+ }
221
+ const failure = this.validateField(dtoClass, field, fieldValue, `${path}.${field.propertyKey}`);
222
+ if (failure)
223
+ return failure;
224
+ }
225
+ return undefined;
226
+ }
227
+ validateField(dtoClass, field, value, path) {
228
+ // webpieces-disable no-any-unknown -- reflect-metadata returns an erased constructor token
229
+ const reflected = Reflect.getMetadata('design:type', dtoClass.prototype, field.propertyKey);
230
+ const expected = reflected?.name;
231
+ if (expected === 'Array')
232
+ return this.validateArray(field.options, value, path);
233
+ if (expected === 'String') {
234
+ if (typeof value !== 'string')
235
+ return new DtoValidationFailure(`${path} must be a string`);
236
+ if (field.options.enumValues && !field.options.enumValues.includes(value)) {
237
+ return new DtoValidationFailure(`${path} must be one of: ${field.options.enumValues.join(', ')}`);
238
+ }
239
+ return undefined;
240
+ }
241
+ if (expected === 'Number') {
242
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
243
+ return new DtoValidationFailure(`${path} must be a number`);
244
+ }
245
+ if (field.options.integer && !Number.isInteger(value)) {
246
+ return new DtoValidationFailure(`${path} must be an integer`);
247
+ }
248
+ if (field.options.minimum !== undefined && value < field.options.minimum) {
249
+ return new DtoValidationFailure(`${path} must be >= ${field.options.minimum}`);
250
+ }
251
+ if (field.options.maximum !== undefined && value > field.options.maximum) {
252
+ return new DtoValidationFailure(`${path} must be <= ${field.options.maximum}`);
253
+ }
254
+ return undefined;
255
+ }
256
+ if (expected === 'Boolean') {
257
+ return typeof value === 'boolean'
258
+ ? undefined
259
+ : new DtoValidationFailure(`${path} must be a boolean`);
260
+ }
261
+ return this.validateAt(reflected, value, path);
262
+ }
263
+ validateArray(options, value, path) {
264
+ if (!Array.isArray(value))
265
+ return new DtoValidationFailure(`${path} must be an array`);
266
+ if (!options.arrayItems)
267
+ return new DtoValidationFailure(`${path} has no item type`);
268
+ for (let index = 0; index < value.length; index += 1) {
269
+ const item = value[index];
270
+ if (typeof options.arrayItems !== 'string') {
271
+ const nested = this.validateAt(options.arrayItems, item, `${path}[${index}]`);
272
+ if (nested)
273
+ return nested;
274
+ continue;
275
+ }
276
+ const wanted = options.arrayItems === 'integer' ? 'number' : options.arrayItems;
277
+ if (typeof item !== wanted || (options.arrayItems === 'integer' && !Number.isInteger(item))) {
278
+ return new DtoValidationFailure(`${path}[${index}] must be ${options.arrayItems}`);
279
+ }
280
+ }
281
+ return undefined;
282
+ }
283
+ fields(dtoClass) {
284
+ const fields = Reflect.getMetadata(DTO_FIELDS, dtoClass) ?? {};
285
+ return Object.values(fields);
286
+ }
287
+ requireDto(dtoClass) {
288
+ if (!Reflect.getMetadata(DTO_MARKER, dtoClass)) {
289
+ throw new Error(`${dtoClass.name} must be decorated with @WpDto() for schema generation.`);
290
+ }
291
+ }
292
+ }
293
+ exports.DtoSchemaBuilder = DtoSchemaBuilder;
294
+ //# sourceMappingURL=DtoSchema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DtoSchema.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/mcp/DtoSchema.ts"],"names":[],"mappings":";;;AA2DA,sBAEC;AAID,gCAYC;AAID,sCAQC;AAzFD,4BAA0B;AAE1B,MAAM,UAAU,GAAG,sBAAsB,CAAC;AAC1C,MAAM,UAAU,GAAG,sBAAsB,CAAC;AAC1C,MAAM,aAAa,GAAG,yBAAyB,CAAC;AAQhD,uFAAuF;AACvF,MAAa,iBAAiB;IAEN;IAEA;IAEA;IAEA;IACA;IACA;IACA;IAVpB,YACoB,WAAmB;IACnC,8EAA8E;IAC9D,QAAiB;IACjC,wEAAwE;IACxD,UAAyB;IACzC,uEAAuE;IACvD,UAAmB,KAAK,EACx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K,MAAM,IAAI,CAAC,OAAO,CAAC,UAAU,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;gBAC1F,OAAO,IAAI,oBAAoB,CAAC,GAAG,IAAI,IAAI,KAAK,aAAa,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;YACvF,CAAC;QACL,CAAC;QACD,OAAO,SAAS,CAAC;IACrB,CAAC;IAEO,MAAM,CAAC,QAAkB;QAC7B,MAAM,MAAM,GACR,OAAO,CAAC,WAAW,CAAC,UAAU,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC;QACpD,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACjC,CAAC;IAEO,UAAU,CAAC,QAAkB;QACjC,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,UAAU,EAAE,QAAQ,CAAC,EAAE,CAAC;YAC7C,MAAM,IAAI,KAAK,CAAC,GAAG,QAAQ,CAAC,IAAI,yDAAyD,CAAC,CAAC;QAC/F,CAAC;IACL,CAAC;CACJ;AArOD,4CAqOC","sourcesContent":["import 'reflect-metadata';\n\nconst DTO_MARKER = 'webpieces:dto-schema';\nconst DTO_FIELDS = 'webpieces:dto-fields';\nconst RESPONSE_DTOS = 'webpieces:response-dtos';\n\n// webpieces-disable no-any-unknown -- abstract class tokens necessarily erase constructor parameters\nexport type DtoClass = abstract new (...args: any[]) => unknown;\nexport type DtoArrayItem = 'string' | 'number' | 'integer' | 'boolean' | DtoClass;\n/** Runtime values accepted at the DTO validation boundary. */\nexport type DtoValue = object | string | number | boolean | null;\n\n/** Additive field metadata; the scalar/object type itself comes from `design:type`. */\nexport class WpDtoFieldOptions {\n constructor(\n public readonly description: string,\n /** Required/optional is explicit because TypeScript erases `?` at runtime. */\n public readonly required: boolean,\n /** Required for arrays because TypeScript erases their element type. */\n public readonly arrayItems?: DtoArrayItem,\n /** A reflected Number is otherwise emitted as JSON Schema `number`. */\n public readonly integer: boolean = false,\n public readonly minimum?: number,\n public readonly maximum?: number,\n public readonly enumValues?: readonly [string, ...string[]],\n ) {}\n}\n\nexport class WpDtoFieldMetadata {\n constructor(\n public readonly propertyKey: string,\n public readonly options: WpDtoFieldOptions,\n ) {}\n}\n\n/** The JSON Schema subset emitted for Webpieces API DTOs. */\nexport class ApiJsonSchema {\n type?: 'object' | 'string' | 'number' | 'integer' | 'boolean' | 'array';\n description?: string;\n properties?: Record<string, ApiJsonSchema>;\n required?: string[];\n additionalProperties?: boolean;\n items?: ApiJsonSchema;\n enum?: string[];\n minimum?: number;\n maximum?: number;\n\n constructor(type?: 'object' | 'string' | 'number' | 'integer' | 'boolean' | 'array') {\n this.type = type;\n }\n}\n\n/** A validation result safe to show to an API caller/model. */\nexport class DtoValidationFailure {\n constructor(public readonly message: string) {}\n}\n\n/** Marks a request/response class as a schema-bearing DTO, including intentionally empty DTOs. */\n// webpieces-disable no-function-outside-class -- decorator factories are inherently module-scope\nexport function WpDto(): ClassDecorator {\n return (target: Function): void => Reflect.defineMetadata(DTO_MARKER, true, target);\n}\n\n/** Adds documentation and runtime-only shape facts to a DTO property. */\n// webpieces-disable no-function-outside-class -- decorator factories are inherently module-scope\nexport function WpDtoField(options: WpDtoFieldOptions): PropertyDecorator {\n if (options.description.trim() === '') {\n throw new Error('@WpDtoField requires non-empty field documentation.');\n }\n return (target: object, propertyKey: string | symbol): void => {\n const dtoClass = target.constructor;\n const fields: Record<string, WpDtoFieldMetadata> =\n Reflect.getMetadata(DTO_FIELDS, dtoClass) ?? {};\n const name = String(propertyKey);\n fields[name] = new WpDtoFieldMetadata(name, options);\n Reflect.defineMetadata(DTO_FIELDS, fields, dtoClass);\n };\n}\n\n/** Declares an async API method's response DTO because reflection sees Promise, not its generic. */\n// webpieces-disable no-function-outside-class -- decorator factories are inherently module-scope\nexport function WpResponseDto(responseDto: () => DtoClass): MethodDecorator {\n return (target: object, propertyKey: string | symbol): void => {\n const apiClass = target.constructor;\n const responses: Record<string, () => DtoClass> =\n Reflect.getMetadata(RESPONSE_DTOS, apiClass) ?? {};\n responses[String(propertyKey)] = responseDto;\n Reflect.defineMetadata(RESPONSE_DTOS, responses, apiClass);\n };\n}\n\n/** Builds and validates the same DTO schema used for MCP input and structured output. */\nexport class DtoSchemaBuilder {\n requestClassOf(apiClass: Function, methodName: string): DtoClass {\n // webpieces-disable no-any-unknown -- reflect-metadata returns erased runtime constructor tokens\n const params = Reflect.getMetadata('design:paramtypes', apiClass.prototype, methodName) as\n | DtoClass[]\n | undefined;\n if (!params || params.length !== 1) {\n throw new Error(\n `${apiClass.name}.${methodName} must take exactly one @WpDto request class to be an MCP tool.`,\n );\n }\n return params[0];\n }\n\n responseClassOf(apiClass: Function, methodName: string): DtoClass {\n const responses: Record<string, () => DtoClass> =\n Reflect.getMetadata(RESPONSE_DTOS, apiClass) ?? {};\n const response = responses[methodName];\n if (!response) {\n throw new Error(\n `${apiClass.name}.${methodName} must declare @WpResponseDto(() => ResponseClass) before MCP exposure.`,\n );\n }\n return response();\n }\n\n build(dtoClass: DtoClass): ApiJsonSchema {\n return this.buildAt(dtoClass, new Set<DtoClass>());\n }\n\n validate(dtoClass: DtoClass, value: DtoValue): DtoValidationFailure | undefined {\n return this.validateAt(dtoClass, value, '$');\n }\n\n private buildAt(dtoClass: DtoClass, parents: Set<DtoClass>): ApiJsonSchema {\n this.requireDto(dtoClass);\n if (parents.has(dtoClass)) {\n throw new Error(`Recursive DTO ${dtoClass.name} cannot use an inline MCP schema.`);\n }\n const nextParents = new Set(parents);\n nextParents.add(dtoClass);\n const schema = new ApiJsonSchema('object');\n schema.properties = {};\n schema.additionalProperties = false;\n const required: string[] = [];\n for (const field of this.fields(dtoClass)) {\n schema.properties[field.propertyKey] = this.fieldSchema(dtoClass, field, nextParents);\n if (field.options.required) required.push(field.propertyKey);\n }\n if (required.length > 0) schema.required = required;\n return schema;\n }\n\n private fieldSchema(\n dtoClass: DtoClass,\n field: WpDtoFieldMetadata,\n parents: Set<DtoClass>,\n ): ApiJsonSchema {\n // webpieces-disable no-any-unknown -- reflect-metadata returns an erased constructor token\n const reflected = Reflect.getMetadata(\n 'design:type',\n dtoClass.prototype,\n field.propertyKey,\n ) as DtoClass | undefined;\n if (!reflected) throw new Error(`No reflected type for ${dtoClass.name}.${field.propertyKey}.`);\n const options = field.options;\n this.validateOptions(dtoClass, field, reflected);\n let schema: ApiJsonSchema;\n switch (reflected.name) {\n case 'String':\n schema = new ApiJsonSchema('string');\n break;\n case 'Number':\n schema = new ApiJsonSchema(options.integer ? 'integer' : 'number');\n break;\n case 'Boolean':\n schema = new ApiJsonSchema('boolean');\n break;\n case 'Array':\n if (!options.arrayItems) {\n throw new Error(`${dtoClass.name}.${field.propertyKey} must declare arrayItems.`);\n }\n schema = new ApiJsonSchema('array');\n schema.items = this.itemSchema(options.arrayItems, parents);\n break;\n default:\n schema = this.buildAt(reflected, parents);\n }\n schema.description = options.description;\n if (options.minimum !== undefined) schema.minimum = options.minimum;\n if (options.maximum !== undefined) schema.maximum = options.maximum;\n if (options.enumValues) schema.enum = [...options.enumValues];\n return schema;\n }\n\n private validateOptions(\n dtoClass: DtoClass,\n field: WpDtoFieldMetadata,\n reflected: DtoClass,\n ): void {\n const label = `${dtoClass.name}.${field.propertyKey}`;\n const options = field.options;\n if (reflected.name !== 'Array' && options.arrayItems) {\n throw new Error(`${label} declares arrayItems but is not an array.`);\n }\n if (\n reflected.name !== 'Number' &&\n (options.integer || options.minimum !== undefined || options.maximum !== undefined)\n ) {\n throw new Error(`${label} declares numeric constraints but is not a number.`);\n }\n if (options.minimum !== undefined && options.maximum !== undefined && options.minimum > options.maximum) {\n throw new Error(`${label} minimum cannot exceed maximum.`);\n }\n if (options.enumValues && reflected.name !== 'String') {\n throw new Error(`${label} enumValues require a string field.`);\n }\n }\n\n private itemSchema(item: DtoArrayItem, parents: Set<DtoClass>): ApiJsonSchema {\n if (typeof item !== 'string') return this.buildAt(item, parents);\n return new ApiJsonSchema(item === 'integer' ? 'integer' : item);\n }\n\n private validateAt(\n dtoClass: DtoClass,\n value: DtoValue,\n path: string,\n ): DtoValidationFailure | undefined {\n this.requireDto(dtoClass);\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return new DtoValidationFailure(`${path} must be an object`);\n }\n const fields = this.fields(dtoClass);\n const known = new Set(fields.map((field: WpDtoFieldMetadata) => field.propertyKey));\n for (const key of Object.keys(value)) {\n if (!known.has(key)) return new DtoValidationFailure(`${path}.${key} is not allowed`);\n }\n for (const field of fields) {\n const fieldValue = Object.getOwnPropertyDescriptor(value, field.propertyKey)?.value;\n if (fieldValue === undefined) {\n if (field.options.required) {\n return new DtoValidationFailure(`${path}.${field.propertyKey} is required`);\n }\n continue;\n }\n const failure = this.validateField(dtoClass, field, fieldValue, `${path}.${field.propertyKey}`);\n if (failure) return failure;\n }\n return undefined;\n }\n\n private validateField(\n dtoClass: DtoClass,\n field: WpDtoFieldMetadata,\n value: DtoValue,\n path: string,\n ): DtoValidationFailure | undefined {\n // webpieces-disable no-any-unknown -- reflect-metadata returns an erased constructor token\n const reflected = Reflect.getMetadata(\n 'design:type',\n dtoClass.prototype,\n field.propertyKey,\n ) as DtoClass;\n const expected = reflected?.name;\n if (expected === 'Array') return this.validateArray(field.options, value, path);\n if (expected === 'String') {\n if (typeof value !== 'string') return new DtoValidationFailure(`${path} must be a string`);\n if (field.options.enumValues && !field.options.enumValues.includes(value)) {\n return new DtoValidationFailure(`${path} must be one of: ${field.options.enumValues.join(', ')}`);\n }\n return undefined;\n }\n if (expected === 'Number') {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n return new DtoValidationFailure(`${path} must be a number`);\n }\n if (field.options.integer && !Number.isInteger(value)) {\n return new DtoValidationFailure(`${path} must be an integer`);\n }\n if (field.options.minimum !== undefined && value < field.options.minimum) {\n return new DtoValidationFailure(`${path} must be >= ${field.options.minimum}`);\n }\n if (field.options.maximum !== undefined && value > field.options.maximum) {\n return new DtoValidationFailure(`${path} must be <= ${field.options.maximum}`);\n }\n return undefined;\n }\n if (expected === 'Boolean') {\n return typeof value === 'boolean'\n ? undefined\n : new DtoValidationFailure(`${path} must be a boolean`);\n }\n return this.validateAt(reflected, value, path);\n }\n\n private validateArray(\n options: WpDtoFieldOptions,\n value: DtoValue,\n path: string,\n ): DtoValidationFailure | undefined {\n if (!Array.isArray(value)) return new DtoValidationFailure(`${path} must be an array`);\n if (!options.arrayItems) return new DtoValidationFailure(`${path} has no item type`);\n for (let index = 0; index < value.length; index += 1) {\n const item = value[index];\n if (typeof options.arrayItems !== 'string') {\n const nested = this.validateAt(options.arrayItems, item, `${path}[${index}]`);\n if (nested) return nested;\n continue;\n }\n const wanted = options.arrayItems === 'integer' ? 'number' : options.arrayItems;\n if (typeof item !== wanted || (options.arrayItems === 'integer' && !Number.isInteger(item))) {\n return new DtoValidationFailure(`${path}[${index}] must be ${options.arrayItems}`);\n }\n }\n return undefined;\n }\n\n private fields(dtoClass: DtoClass): WpDtoFieldMetadata[] {\n const fields: Record<string, WpDtoFieldMetadata> =\n Reflect.getMetadata(DTO_FIELDS, dtoClass) ?? {};\n return Object.values(fields);\n }\n\n private requireDto(dtoClass: DtoClass): void {\n if (!Reflect.getMetadata(DTO_MARKER, dtoClass)) {\n throw new Error(`${dtoClass.name} must be decorated with @WpDto() for schema generation.`);\n }\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const McpMetadata_1 = require("./McpMetadata");
5
+ const DtoSchema_1 = require("./DtoSchema");
6
+ const invalidEmptyEnum = new DtoSchema_1.WpDtoFieldOptions('invalid enum', true, undefined, false, undefined, undefined,
7
+ // @ts-expect-error enumValues must contain at least one allowed string
8
+ []);
9
+ class InvalidMcpContract {
10
+ // @ts-expect-error read-only tools cannot also claim to be destructive
11
+ invalid() {
12
+ throw new Error('contract only');
13
+ }
14
+ }
15
+ tslib_1.__decorate([
16
+ (0, McpMetadata_1.WpMcpTool)({
17
+ name: 'invalid',
18
+ description: 'This declaration must never compile.',
19
+ readOnlyHint: true,
20
+ destructiveHint: true,
21
+ idempotentHint: true,
22
+ openWorldHint: false,
23
+ }),
24
+ tslib_1.__metadata("design:type", Function),
25
+ tslib_1.__metadata("design:paramtypes", []),
26
+ tslib_1.__metadata("design:returntype", Promise)
27
+ ], InvalidMcpContract.prototype, "invalid", null);
28
+ class InvalidMcpArities {
29
+ // @ts-expect-error MCP tools require exactly one request DTO
30
+ zero() {
31
+ throw new Error('contract only');
32
+ }
33
+ // @ts-expect-error MCP tools require exactly one request DTO
34
+ multi(_first, _second) {
35
+ throw new Error('contract only');
36
+ }
37
+ }
38
+ tslib_1.__decorate([
39
+ (0, McpMetadata_1.WpMcpTool)({
40
+ name: 'zero-arity',
41
+ description: 'This declaration must never compile.',
42
+ readOnlyHint: true,
43
+ idempotentHint: true,
44
+ openWorldHint: false,
45
+ }),
46
+ tslib_1.__metadata("design:type", Function),
47
+ tslib_1.__metadata("design:paramtypes", []),
48
+ tslib_1.__metadata("design:returntype", Promise)
49
+ ], InvalidMcpArities.prototype, "zero", null);
50
+ tslib_1.__decorate([
51
+ (0, McpMetadata_1.WpMcpTool)({
52
+ name: 'multi-arity',
53
+ description: 'This declaration must never compile.',
54
+ readOnlyHint: true,
55
+ idempotentHint: true,
56
+ openWorldHint: false,
57
+ }),
58
+ tslib_1.__metadata("design:type", Function),
59
+ tslib_1.__metadata("design:paramtypes", [Object, Object]),
60
+ tslib_1.__metadata("design:returntype", Promise)
61
+ ], InvalidMcpArities.prototype, "multi", null);
62
+ void InvalidMcpContract;
63
+ void InvalidMcpArities;
64
+ void invalidEmptyEnum;
65
+ //# sourceMappingURL=McpCompileAssertions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"McpCompileAssertions.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/mcp/McpCompileAssertions.ts"],"names":[],"mappings":";;;AAAA,+CAA0C;AAC1C,2CAAgD;AAEhD,MAAM,gBAAgB,GAAG,IAAI,6BAAiB,CAC1C,cAAc,EACd,IAAI,EACJ,SAAS,EACT,KAAK,EACL,SAAS,EACT,SAAS;AACT,uEAAuE;AACvE,EAAE,CACL,CAAC;AAEF,MAAe,kBAAkB;IAC7B,uEAAuE;IASvE,OAAO;QACH,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACrC,CAAC;CACJ;AAHG;IARC,IAAA,uBAAS,EAAC;QACP,IAAI,EAAE,SAAS;QACf,WAAW,EAAE,sCAAsC;QACnD,YAAY,EAAE,IAAI;QAClB,eAAe,EAAE,IAAI;QACrB,cAAc,EAAE,IAAI;QACpB,aAAa,EAAE,KAAK;KACvB,CAAC;;;;iDAGD;AAGL,MAAe,iBAAiB;IAC5B,6DAA6D;IAQ7D,IAAI;QACA,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACrC,CAAC;IAED,6DAA6D;IAQ7D,KAAK,CAAC,MAAc,EAAE,OAAe;QACjC,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACrC,CAAC;CACJ;AAfG;IAPC,IAAA,uBAAS,EAAC;QACP,IAAI,EAAE,YAAY;QAClB,WAAW,EAAE,sCAAsC;QACnD,YAAY,EAAE,IAAI;QAClB,cAAc,EAAE,IAAI;QACpB,aAAa,EAAE,KAAK;KACvB,CAAC;;;;6CAGD;AAUD;IAPC,IAAA,uBAAS,EAAC;QACP,IAAI,EAAE,aAAa;QACnB,WAAW,EAAE,sCAAsC;QACnD,YAAY,EAAE,IAAI;QAClB,cAAc,EAAE,IAAI;QACpB,aAAa,EAAE,KAAK;KACvB,CAAC;;;;8CAGD;AAGL,KAAK,kBAAkB,CAAC;AACxB,KAAK,iBAAiB,CAAC;AACvB,KAAK,gBAAgB,CAAC","sourcesContent":["import { WpMcpTool } from './McpMetadata';\nimport { WpDtoFieldOptions } from './DtoSchema';\n\nconst invalidEmptyEnum = new WpDtoFieldOptions(\n 'invalid enum',\n true,\n undefined,\n false,\n undefined,\n undefined,\n // @ts-expect-error enumValues must contain at least one allowed string\n [],\n);\n\nabstract class InvalidMcpContract {\n // @ts-expect-error read-only tools cannot also claim to be destructive\n @WpMcpTool({\n name: 'invalid',\n description: 'This declaration must never compile.',\n readOnlyHint: true,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n })\n invalid(): Promise<void> {\n throw new Error('contract only');\n }\n}\n\nabstract class InvalidMcpArities {\n // @ts-expect-error MCP tools require exactly one request DTO\n @WpMcpTool({\n name: 'zero-arity',\n description: 'This declaration must never compile.',\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n })\n zero(): Promise<object> {\n throw new Error('contract only');\n }\n\n // @ts-expect-error MCP tools require exactly one request DTO\n @WpMcpTool({\n name: 'multi-arity',\n description: 'This declaration must never compile.',\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n })\n multi(_first: object, _second: object): Promise<object> {\n throw new Error('contract only');\n }\n}\n\nvoid InvalidMcpContract;\nvoid InvalidMcpArities;\nvoid invalidEmptyEnum;\n"]}
@@ -0,0 +1,51 @@
1
+ import 'reflect-metadata';
2
+ /** The immutable hints MCP clients use when deciding whether and how to call a tool. */
3
+ export declare class WpMcpToolHints {
4
+ readonly readOnlyHint: boolean;
5
+ readonly destructiveHint: boolean;
6
+ readonly idempotentHint: boolean;
7
+ readonly openWorldHint: boolean;
8
+ constructor(readOnlyHint: boolean, destructiveHint: boolean, idempotentHint: boolean, openWorldHint: boolean);
9
+ }
10
+ type CommonToolOptions = {
11
+ /** Stable protocol name. Renaming this breaks saved agent workflows. */
12
+ name: string;
13
+ /** Tool-level documentation published verbatim by tools/list. */
14
+ description: string;
15
+ idempotentHint: boolean;
16
+ openWorldHint: boolean;
17
+ };
18
+ type ReadOnlyToolOptions = CommonToolOptions & {
19
+ readOnlyHint: true;
20
+ destructiveHint?: never;
21
+ };
22
+ type MutatingToolOptions = CommonToolOptions & {
23
+ readOnlyHint: false;
24
+ destructiveHint: boolean;
25
+ };
26
+ /** Compiler-enforced exposure: a read-only tool cannot also claim to be destructive. */
27
+ export type WpMcpToolOptions = ReadOnlyToolOptions | MutatingToolOptions;
28
+ type AsyncObjectMethod = (...args: never[]) => Promise<object>;
29
+ type ExactOneParameter<TMethod extends AsyncObjectMethod> = Parameters<TMethod>['length'] extends 1 ? object : never;
30
+ type ExactOneMethodDescriptor<TMethod extends AsyncObjectMethod> = TypedPropertyDescriptor<TMethod> & ExactOneParameter<TMethod>;
31
+ /** Method decorator restricted to one request DTO and one async response DTO. */
32
+ export type WpMcpMethodDecorator = <TMethod extends AsyncObjectMethod>(target: object, propertyKey: string | symbol, descriptor: ExactOneMethodDescriptor<TMethod>) => void;
33
+ /** Runtime metadata for one explicitly exposed endpoint. */
34
+ export declare class WpMcpToolMetadata {
35
+ readonly methodName: string;
36
+ readonly name: string;
37
+ readonly description: string;
38
+ readonly hints: WpMcpToolHints;
39
+ constructor(methodName: string, name: string, description: string, hints: WpMcpToolHints);
40
+ }
41
+ /**
42
+ * Explicitly publishes an existing `@Endpoint(..., 'rpc')` method as an MCP tool.
43
+ *
44
+ * This annotation owns tool-level documentation only. Input/output field documentation and JSON
45
+ * Schema come from the request/response DTO metadata. The endpoint's `@WpAuth*` annotation remains
46
+ * the sole runtime authorization policy.
47
+ */
48
+ export declare function WpMcpTool(options: WpMcpToolOptions): WpMcpMethodDecorator;
49
+ /** Returns only methods explicitly opted in through {@link WpMcpTool}. */
50
+ export declare function getWpMcpTools(apiClass: Function): WpMcpToolMetadata[];
51
+ export {};
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WpMcpToolMetadata = exports.WpMcpToolHints = void 0;
4
+ exports.WpMcpTool = WpMcpTool;
5
+ exports.getWpMcpTools = getWpMcpTools;
6
+ require("reflect-metadata");
7
+ const decorators_1 = require("../http/decorators");
8
+ /** The immutable hints MCP clients use when deciding whether and how to call a tool. */
9
+ class WpMcpToolHints {
10
+ readOnlyHint;
11
+ destructiveHint;
12
+ idempotentHint;
13
+ openWorldHint;
14
+ constructor(readOnlyHint, destructiveHint, idempotentHint, openWorldHint) {
15
+ this.readOnlyHint = readOnlyHint;
16
+ this.destructiveHint = destructiveHint;
17
+ this.idempotentHint = idempotentHint;
18
+ this.openWorldHint = openWorldHint;
19
+ }
20
+ }
21
+ exports.WpMcpToolHints = WpMcpToolHints;
22
+ /** Runtime metadata for one explicitly exposed endpoint. */
23
+ class WpMcpToolMetadata {
24
+ methodName;
25
+ name;
26
+ description;
27
+ hints;
28
+ constructor(methodName, name, description, hints) {
29
+ this.methodName = methodName;
30
+ this.name = name;
31
+ this.description = description;
32
+ this.hints = hints;
33
+ }
34
+ }
35
+ exports.WpMcpToolMetadata = WpMcpToolMetadata;
36
+ /**
37
+ * Explicitly publishes an existing `@Endpoint(..., 'rpc')` method as an MCP tool.
38
+ *
39
+ * This annotation owns tool-level documentation only. Input/output field documentation and JSON
40
+ * Schema come from the request/response DTO metadata. The endpoint's `@WpAuth*` annotation remains
41
+ * the sole runtime authorization policy.
42
+ */
43
+ // webpieces-disable no-function-outside-class -- decorator factories are inherently module-scope
44
+ function WpMcpTool(options) {
45
+ if (options.name.trim() === '')
46
+ throw new Error('@WpMcpTool requires a non-empty stable name.');
47
+ if (options.description.trim() === '') {
48
+ throw new Error('@WpMcpTool requires non-empty tool documentation.');
49
+ }
50
+ return (target, propertyKey, _descriptor) => {
51
+ const apiClass = target.constructor;
52
+ const tools = Reflect.getMetadata(decorators_1.METADATA_KEYS.MCP_TOOLS, apiClass) ?? {};
53
+ const methodName = String(propertyKey);
54
+ tools[methodName] = new WpMcpToolMetadata(methodName, options.name, options.description, new WpMcpToolHints(options.readOnlyHint, options.readOnlyHint ? false : options.destructiveHint, options.idempotentHint, options.openWorldHint));
55
+ Reflect.defineMetadata(decorators_1.METADATA_KEYS.MCP_TOOLS, tools, apiClass);
56
+ };
57
+ }
58
+ /** Returns only methods explicitly opted in through {@link WpMcpTool}. */
59
+ // webpieces-disable no-function-outside-class -- metadata reader paired with the decorator
60
+ function getWpMcpTools(apiClass) {
61
+ const tools = Reflect.getMetadata(decorators_1.METADATA_KEYS.MCP_TOOLS, apiClass) ?? {};
62
+ return Object.values(tools);
63
+ }
64
+ //# sourceMappingURL=McpMetadata.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"McpMetadata.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/mcp/McpMetadata.ts"],"names":[],"mappings":";;;AAmEA,8BA2BC;AAID,sCAIC;AAtGD,4BAA0B;AAC1B,mDAAmD;AAEnD,wFAAwF;AACxF,MAAa,cAAc;IAEH;IACA;IACA;IACA;IAJpB,YACoB,YAAqB,EACrB,eAAwB,EACxB,cAAuB,EACvB,aAAsB;QAHtB,iBAAY,GAAZ,YAAY,CAAS;QACrB,oBAAe,GAAf,eAAe,CAAS;QACxB,mBAAc,GAAd,cAAc,CAAS;QACvB,kBAAa,GAAb,aAAa,CAAS;IACvC,CAAC;CACP;AAPD,wCAOC;AAsCD,4DAA4D;AAC5D,MAAa,iBAAiB;IAEN;IACA;IACA;IACA;IAJpB,YACoB,UAAkB,EAClB,IAAY,EACZ,WAAmB,EACnB,KAAqB;QAHrB,eAAU,GAAV,UAAU,CAAQ;QAClB,SAAI,GAAJ,IAAI,CAAQ;QACZ,gBAAW,GAAX,WAAW,CAAQ;QACnB,UAAK,GAAL,KAAK,CAAgB;IACtC,CAAC;CACP;AAPD,8CAOC;AAED;;;;;;GAMG;AACH,iGAAiG;AACjG,SAAgB,SAAS,CAAC,OAAyB;IAC/C,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IAChG,IAAI,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACpC,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;IACzE,CAAC;IACD,OAAO,CACH,MAAc,EACd,WAA4B,EAC5B,WAA8C,EAC1C,EAAE;QACN,MAAM,QAAQ,GAAG,MAAM,CAAC,WAAW,CAAC;QACpC,MAAM,KAAK,GACP,OAAO,CAAC,WAAW,CAAC,0BAAa,CAAC,SAAS,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC;QACjE,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;QACvC,KAAK,CAAC,UAAU,CAAC,GAAG,IAAI,iBAAiB,CACrC,UAAU,EACV,OAAO,CAAC,IAAI,EACZ,OAAO,CAAC,WAAW,EACnB,IAAI,cAAc,CACd,OAAO,CAAC,YAAY,EACpB,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,eAAe,EACtD,OAAO,CAAC,cAAc,EACtB,OAAO,CAAC,aAAa,CACxB,CACJ,CAAC;QACF,OAAO,CAAC,cAAc,CAAC,0BAAa,CAAC,SAAS,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;IACrE,CAAC,CAAC;AACN,CAAC;AAED,0EAA0E;AAC1E,2FAA2F;AAC3F,SAAgB,aAAa,CAAC,QAAkB;IAC5C,MAAM,KAAK,GACP,OAAO,CAAC,WAAW,CAAC,0BAAa,CAAC,SAAS,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC;IACjE,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChC,CAAC","sourcesContent":["import 'reflect-metadata';\nimport { METADATA_KEYS } from '../http/decorators';\n\n/** The immutable hints MCP clients use when deciding whether and how to call a tool. */\nexport class WpMcpToolHints {\n constructor(\n public readonly readOnlyHint: boolean,\n public readonly destructiveHint: boolean,\n public readonly idempotentHint: boolean,\n public readonly openWorldHint: boolean,\n ) {}\n}\n\ntype CommonToolOptions = {\n /** Stable protocol name. Renaming this breaks saved agent workflows. */\n name: string;\n /** Tool-level documentation published verbatim by tools/list. */\n description: string;\n idempotentHint: boolean;\n openWorldHint: boolean;\n};\n\ntype ReadOnlyToolOptions = CommonToolOptions & {\n readOnlyHint: true;\n destructiveHint?: never;\n};\n\ntype MutatingToolOptions = CommonToolOptions & {\n readOnlyHint: false;\n destructiveHint: boolean;\n};\n\n/** Compiler-enforced exposure: a read-only tool cannot also claim to be destructive. */\nexport type WpMcpToolOptions = ReadOnlyToolOptions | MutatingToolOptions;\n\ntype AsyncObjectMethod = (...args: never[]) => Promise<object>;\ntype ExactOneParameter<TMethod extends AsyncObjectMethod> = Parameters<TMethod>['length'] extends 1\n ? object\n : never;\ntype ExactOneMethodDescriptor<TMethod extends AsyncObjectMethod> = TypedPropertyDescriptor<TMethod> &\n ExactOneParameter<TMethod>;\n\n/** Method decorator restricted to one request DTO and one async response DTO. */\nexport type WpMcpMethodDecorator = <TMethod extends AsyncObjectMethod>(\n target: object,\n propertyKey: string | symbol,\n descriptor: ExactOneMethodDescriptor<TMethod>,\n) => void;\n\n/** Runtime metadata for one explicitly exposed endpoint. */\nexport class WpMcpToolMetadata {\n constructor(\n public readonly methodName: string,\n public readonly name: string,\n public readonly description: string,\n public readonly hints: WpMcpToolHints,\n ) {}\n}\n\n/**\n * Explicitly publishes an existing `@Endpoint(..., 'rpc')` method as an MCP tool.\n *\n * This annotation owns tool-level documentation only. Input/output field documentation and JSON\n * Schema come from the request/response DTO metadata. The endpoint's `@WpAuth*` annotation remains\n * the sole runtime authorization policy.\n */\n// webpieces-disable no-function-outside-class -- decorator factories are inherently module-scope\nexport function WpMcpTool(options: WpMcpToolOptions): WpMcpMethodDecorator {\n if (options.name.trim() === '') throw new Error('@WpMcpTool requires a non-empty stable name.');\n if (options.description.trim() === '') {\n throw new Error('@WpMcpTool requires non-empty tool documentation.');\n }\n return <TMethod extends AsyncObjectMethod>(\n target: object,\n propertyKey: string | symbol,\n _descriptor: ExactOneMethodDescriptor<TMethod>,\n ): void => {\n const apiClass = target.constructor;\n const tools: Record<string, WpMcpToolMetadata> =\n Reflect.getMetadata(METADATA_KEYS.MCP_TOOLS, apiClass) ?? {};\n const methodName = String(propertyKey);\n tools[methodName] = new WpMcpToolMetadata(\n methodName,\n options.name,\n options.description,\n new WpMcpToolHints(\n options.readOnlyHint,\n options.readOnlyHint ? false : options.destructiveHint,\n options.idempotentHint,\n options.openWorldHint,\n ),\n );\n Reflect.defineMetadata(METADATA_KEYS.MCP_TOOLS, tools, apiClass);\n };\n}\n\n/** Returns only methods explicitly opted in through {@link WpMcpTool}. */\n// webpieces-disable no-function-outside-class -- metadata reader paired with the decorator\nexport function getWpMcpTools(apiClass: Function): WpMcpToolMetadata[] {\n const tools: Record<string, WpMcpToolMetadata> =\n Reflect.getMetadata(METADATA_KEYS.MCP_TOOLS, apiClass) ?? {};\n return Object.values(tools);\n}\n"]}