@dashai/sdk 0.9.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -13
- package/dist/auth/client.cjs +23 -1
- package/dist/auth/client.cjs.map +1 -1
- package/dist/auth/client.d.cts +30 -5
- package/dist/auth/client.d.ts +30 -5
- package/dist/auth/client.js +23 -1
- package/dist/auth/client.js.map +1 -1
- package/dist/auth/middleware.cjs +11 -1
- package/dist/auth/middleware.cjs.map +1 -1
- package/dist/auth/middleware.js +11 -1
- package/dist/auth/middleware.js.map +1 -1
- package/dist/auth/server.cjs +36 -7
- package/dist/auth/server.cjs.map +1 -1
- package/dist/auth/server.js +36 -7
- package/dist/auth/server.js.map +1 -1
- package/dist/auth/types.cjs.map +1 -1
- package/dist/auth/types.d.cts +13 -0
- package/dist/auth/types.d.ts +13 -0
- package/dist/auth/types.js.map +1 -1
- package/dist/deps/index.cjs +82 -7
- package/dist/deps/index.cjs.map +1 -1
- package/dist/deps/index.d.cts +28 -10
- package/dist/deps/index.d.ts +28 -10
- package/dist/deps/index.js +81 -8
- package/dist/deps/index.js.map +1 -1
- package/dist/index-BsSFz58g.d.cts +431 -0
- package/dist/index-BsSFz58g.d.ts +431 -0
- package/dist/index.cjs +318 -25
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +66 -53
- package/dist/index.d.ts +66 -53
- package/dist/index.js +313 -26
- package/dist/index.js.map +1 -1
- package/dist/query/index.cjs +158 -2
- package/dist/query/index.cjs.map +1 -1
- package/dist/query/index.d.cts +7 -7
- package/dist/query/index.d.ts +7 -7
- package/dist/query/index.js +158 -2
- package/dist/query/index.js.map +1 -1
- package/dist/react/index.d.cts +1 -1
- package/dist/react/index.d.ts +1 -1
- package/dist/{types-DXsbCVkb.d.cts → types-CkAfiS4k.d.cts} +106 -38
- package/dist/{types-DXsbCVkb.d.ts → types-CkAfiS4k.d.ts} +106 -38
- package/dist/uses/index.cjs +147 -0
- package/dist/uses/index.cjs.map +1 -0
- package/dist/uses/index.d.cts +1 -0
- package/dist/uses/index.d.ts +1 -0
- package/dist/uses/index.js +142 -0
- package/dist/uses/index.js.map +1 -0
- package/package.json +6 -1
- package/dist/errors-BV75u7b9.d.cts +0 -207
- package/dist/errors-BV75u7b9.d.ts +0 -207
package/dist/deps/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/data/deps.ts","../../src/data/errors.ts"],"names":[],"mappings":";AA2CA,IAAM,iBAAA,GAAoB,2BAAA;AAO1B,IAAM,gBAAA,GAAmB,2BAAA;AAEzB,SAAS,wBAAwB,IAAA,EAAoB;AACnD,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,CAAC,iBAAA,CAAkB,IAAA,CAAK,IAAI,CAAA,EAAG;AAC7D,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uCAAuC,IAAI,CAAA,wHAAA;AAAA,KAC7C;AAAA,EACF;AACF;AAEA,SAAS,qBAAqB,IAAA,EAAoB;AAChD,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,CAAC,gBAAA,CAAiB,IAAA,CAAK,IAAI,CAAA,EAAG;AAC5D,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,oCAAoC,IAAI,CAAA,mEAAA;AAAA,KAC1C;AAAA,EACF;AACF;AASO,SAAS,QAAA,CAAS,WAA0B,YAAA,EAA4B;AAC7E,EAAA,uBAAA,CAAwB,YAAY,CAAA;AAEpC,EAAA,OAAO;AAAA,IACL,GAAwB,SAAA,EAA6C;AACnE,MAAA,oBAAA,CAAqB,SAAS,CAAA;AAC9B,MAAA,OAAO,uBAAA,CAA6B,SAAA,EAAW,YAAA,EAAc,SAAS,CAAA;AAAA,IACxE;AAAA,GACF;AACF;AAOA,SAAS,uBAAA,CACP,SAAA,EACA,YAAA,EACA,SAAA,EAC0B;AAM1B,EAAA,MAAM,IAAA,GAAO,CAAA,MAAA,EAAS,YAAY,CAA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query plane — see\n * `dashwise-devops-docs/plans/modules-sdk-query-v1.md` §6.2.\n *\n * The factory is intentionally a thin wrapper around the existing\n * {@link HttpTransport}: cross-module reads target a parallel URL\n * shape (`/deps/<provider>/db/<table>/list` instead of\n * `/db/<table>/list`) but otherwise behave identically — same JSON\n * body, same {@link Page} envelope, same {@link DashwiseError} model.\n * No new transport, no new auth flow, no new caching.\n *\n * Cross-module **writes** are deliberately omitted: the returned\n * {@link ReadOnlyTableClient} has no `create` / `update` / `delete`.\n * See plan §4.3 — writes flow through provider-published actions in\n * a later phase, never as direct mutations across the trust boundary.\n *\n * Slug validation runs client-side as a fail-fast check so a typo\n * doesn't reach the backend as a 404 from a malformed URL. The\n * authoritative check is server-side: the backend re-validates\n * provider existence + contract coverage on every call.\n */\n\nimport type { HttpTransport } from './http.js';\nimport type {\n BaseRow,\n Deps,\n ListOpts,\n Page,\n ReadOnlyTableClient,\n} from './types.js';\n\n/**\n * Module-slug character set matches the backend manifest validator's\n * `MODULE_SLUG_REGEX` exactly: kebab-case, 2-63 chars, starts with a\n * letter, ends with letter/digit, no leading/trailing dash.\n *\n * Mirrored here (not imported from the backend) because the SDK is\n * published independently — pulling backend code in would couple\n * release cycles. If the backend's regex changes, the SDK's mirror\n * must update in lockstep; covered by an integration test.\n */\nconst MODULE_SLUG_REGEX = /^[a-z][a-z0-9-]*[a-z0-9]$/;\n\n/**\n * Table-slug character set matches the backend's `SLUG_REGEX`: snake_case,\n * 2-63 chars, starts with a letter, ends with letter/digit. Same\n * mirror-vs-import tradeoff as {@link MODULE_SLUG_REGEX}.\n */\nconst TABLE_SLUG_REGEX = /^[a-z][a-z0-9_]*[a-z0-9]$/;\n\nfunction assertValidProviderSlug(slug: string): void {\n if (typeof slug !== 'string' || !MODULE_SLUG_REGEX.test(slug)) {\n throw new Error(\n `@dashai/sdk: invalid provider slug \"${slug}\". Provider slugs are the dependency module's slug (kebab-case, e.g. \"crm-app\"); must match /^[a-z][a-z0-9-]*[a-z0-9]$/.`,\n );\n }\n}\n\nfunction assertValidTableSlug(slug: string): void {\n if (typeof slug !== 'string' || !TABLE_SLUG_REGEX.test(slug)) {\n throw new Error(\n `@dashai/sdk: invalid table slug \"${slug}\". Table slugs must match /^[a-z][a-z0-9_]*[a-z0-9]$/ (snake_case).`,\n );\n }\n}\n\n/**\n * Build a {@link Deps} accessor for `providerSlug`. Validates the\n * slug shape eagerly; defers everything else to the backend.\n *\n * Exported for use by `createClient()` in `./client.ts`. Not part\n * of the public API directly — consumers reach it via `client.deps(...)`.\n */\nexport function makeDeps(transport: HttpTransport, providerSlug: string): Deps {\n assertValidProviderSlug(providerSlug);\n\n return {\n db<Row extends BaseRow>(tableSlug: string): ReadOnlyTableClient<Row> {\n assertValidTableSlug(tableSlug);\n return makeBorrowedTableClient<Row>(transport, providerSlug, tableSlug);\n },\n };\n}\n\n/**\n * Internal: produce a {@link ReadOnlyTableClient} for one specific\n * `(providerSlug, tableSlug)` pair. Closure captures the transport +\n * the URL root so the public methods are tiny.\n */\nfunction makeBorrowedTableClient<Row extends BaseRow>(\n transport: HttpTransport,\n providerSlug: string,\n tableSlug: string,\n): ReadOnlyTableClient<Row> {\n // URL shape mirrors the owned-table CRUD pipeline but interpolates\n // the provider's slug between the installation root + the table\n // segment: `/deps/<provider>/db/<table>/...`. The full URL after\n // the transport's base prefix is therefore\n // `<baseUrl>/api/modules/<installationId>/deps/<provider>/db/<table>/<op>`.\n const root = `/deps/${providerSlug}/db/${tableSlug}`;\n\n return {\n async list(opts?: ListOpts<Row>): Promise<Page<Row>> {\n const body = opts ?? {};\n const result = await transport.request<Page<Row>>('POST', `${root}/list`, body);\n // Same defense-in-depth shape coercion as the owned-table client:\n // if the backend ever responds with a bare array (older endpoint\n // version, proxy stripping the envelope, etc.), wrap it so the\n // consumer always sees `{ rows, ... }`.\n if (Array.isArray(result)) {\n return {\n rows: result as Row[],\n total: result.length,\n limit: body.limit ?? result.length,\n offset: body.offset ?? 0,\n };\n }\n return result;\n },\n\n async get(id: number): Promise<Row> {\n return transport.request<Row>('GET', `${root}/${id}`);\n },\n };\n}\n","/**\n * Error model for @dashai/sdk.\n *\n * The backend speaks a structured error envelope:\n *\n * {\n * \"code\": \"ROW_NOT_FOUND\",\n * \"message\": \"Row 123 not found in tasks\",\n * \"retriable\": false,\n * \"context\": { ... }\n * }\n *\n * This module wraps that envelope in a typed `DashwiseError` plus a small\n * set of subclasses for the codes consumers most commonly want to branch\n * on (network errors, auth failures, row-not-found, contract violations).\n *\n * Anything not matched by a specific subclass becomes a plain\n * `DashwiseError` carrying the raw `code`. Branch on `.code` for codes\n * we don't have a class for; use `instanceof` for the common cases.\n */\n\n/**\n * Known error codes. Not exhaustive — the backend emits many codes\n * specific to individual modules / endpoints. Use these constants when\n * you want compile-time safety; otherwise treat `err.code` as a string.\n *\n * The list is curated to the codes a module author is most likely to\n * branch on. Adding a new code here is a non-breaking change.\n */\nexport const DashwiseErrorCode = {\n // Auth / authz\n UNAUTHENTICATED: 'UNAUTHENTICATED',\n FORBIDDEN: 'FORBIDDEN',\n TOKEN_EXPIRED: 'TOKEN_EXPIRED',\n INSTALLATION_NOT_FOUND: 'INSTALLATION_NOT_FOUND',\n INSTALLATION_MODE_UNSUPPORTED: 'INSTALLATION_MODE_UNSUPPORTED',\n // Contract enforcement\n CONTRACT_VIOLATION: 'CONTRACT_VIOLATION',\n FIELD_NOT_READABLE: 'FIELD_NOT_READABLE',\n FILTER_OP_UNKNOWN: 'FILTER_OP_UNKNOWN',\n OPERATION_NOT_ALLOWED: 'OPERATION_NOT_ALLOWED',\n // Cross-module dependencies (Phase 1 of the SDK query plane —\n // see dashwise-devops-docs/plans/modules-sdk-query-v1.md).\n // Surfaced when reading borrowed tables via `client.deps(slug)`.\n DEPENDENCY_NOT_DECLARED: 'DEPENDENCY_NOT_DECLARED',\n TABLE_NOT_IN_CONTRACT: 'TABLE_NOT_IN_CONTRACT',\n PROVIDER_TABLE_MISSING: 'PROVIDER_TABLE_MISSING',\n OPERATION_NOT_ALLOWED_BY_PROVIDER: 'OPERATION_NOT_ALLOWED_BY_PROVIDER',\n // Query-plane joins (Phase 3 — see\n // dashwise-devops-docs/plans/modules-sdk-query-v1-p3-execution.md).\n // Surfaced when `.join('<slug>')` / `.leftJoin('<slug>')` can't\n // resolve the target. Pre-declared in slice 3.1 so slice 3.2's\n // backend translator can emit them through fromBackendEnvelope\n // without an SDK roundtrip.\n LINK_FIELD_NOT_FOUND: 'LINK_FIELD_NOT_FOUND',\n NOT_A_LINK_FIELD: 'NOT_A_LINK_FIELD',\n JOIN_NOT_LINKED: 'JOIN_NOT_LINKED',\n // Cross-module actions (Phase 7 slice 7.3a — see\n // dashwise-devops-docs/plans/modules-sdk-query-v1-p7-cross-module-writes.md).\n // Surfaced when `qb.deps.<dep>.actions.<name>(input)` (generated\n // factory) dispatches against the new backend endpoint\n // `POST :installationId/deps/:providerSlug/actions/:actionName`.\n // Slice 7.2b ships the backend emitter; slice 7.3a (this slice)\n // reserves the codes + maps them to DepActionError in the SDK.\n ACTION_NOT_EXPOSED: 'ACTION_NOT_EXPOSED',\n ACTION_NOT_DECLARED: 'ACTION_NOT_DECLARED',\n ACTION_INPUT_INVALID: 'ACTION_INPUT_INVALID',\n ACTION_OUTPUT_INVALID: 'ACTION_OUTPUT_INVALID',\n ACTION_RATE_LIMITED: 'ACTION_RATE_LIMITED',\n ACTION_EXECUTION_FAILED: 'ACTION_EXECUTION_FAILED',\n // Data plane\n ROW_NOT_FOUND: 'ROW_NOT_FOUND',\n TABLE_NOT_FOUND: 'TABLE_NOT_FOUND',\n VALIDATION_FAILED: 'VALIDATION_FAILED',\n ROW_LIMIT_EXCEEDED: 'ROW_LIMIT_EXCEEDED',\n STORAGE_LIMIT_EXCEEDED: 'STORAGE_LIMIT_EXCEEDED',\n // Outbound / runtime\n OUTBOUND_NOT_ALLOWED: 'OUTBOUND_NOT_ALLOWED',\n OUTBOUND_CONCURRENCY_LIMITED: 'OUTBOUND_CONCURRENCY_LIMITED',\n // Transport\n NETWORK_ERROR: 'NETWORK_ERROR',\n TIMEOUT: 'TIMEOUT',\n // Server\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n} as const;\n\nexport type DashwiseErrorCode = (typeof DashwiseErrorCode)[keyof typeof DashwiseErrorCode];\n\n/**\n * Base class for every error thrown by @dashai/sdk. Carries the\n * structured envelope from the backend (or a synthetic one for\n * client-side failures like network errors / timeouts).\n *\n * Always thrown — never returned as a value. The async client methods\n * `.list()` / `.get()` etc. reject with one of these on failure.\n */\nexport class DashwiseError extends Error {\n readonly code: string;\n readonly status: number;\n readonly retriable: boolean;\n readonly context: Record<string, unknown> | undefined;\n /**\n * Backend-issued trace anchor (Phase 6 slice 6.2, 2026-05-19).\n * Mirrors the `x-request-id` response header. Populated whenever\n * the backend's `RuntimeQueryController` (or any future endpoint\n * that echoes the header) is the origin of this error. `null` when\n * the failure is client-side (NetworkError / TimeoutError — the\n * request never reached the server, so there's no server-issued\n * ID to surface).\n *\n * Use this as a debugging trace anchor when filing a bug against a\n * specific failed query — the matching row in `module_query_log`\n * carries the full backend context (ast_hash, error_code,\n * duration_ms, etc.).\n */\n readonly requestId: string | null;\n\n constructor(\n code: string,\n message: string,\n options: {\n status?: number;\n retriable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n /**\n * Phase 6 slice 6.2: backend `x-request-id` response header,\n * captured by the transport before throwing. Pass `undefined`\n * (or omit) for client-side errors that never hit the server.\n */\n requestId?: string | null;\n } = {},\n ) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n this.status = options.status ?? 0;\n this.retriable = options.retriable ?? false;\n this.context = options.context;\n this.requestId = options.requestId ?? null;\n if (options.cause !== undefined) {\n // Node 18+ and modern browsers support Error.cause natively.\n // Use a property assignment because `super({ cause })` is awkward\n // when the base class only takes a string.\n (this as { cause?: unknown }).cause = options.cause;\n }\n }\n}\n\n/** Network-level failure (DNS, connection refused, TLS, fetch threw). */\nexport class NetworkError extends DashwiseError {\n constructor(message: string, cause?: unknown) {\n super(DashwiseErrorCode.NETWORK_ERROR, message, { retriable: true, cause });\n }\n}\n\n/** Request exceeded the configured timeout (`timeoutMs`). */\nexport class TimeoutError extends DashwiseError {\n constructor(message: string, timeoutMs: number) {\n super(DashwiseErrorCode.TIMEOUT, message, {\n retriable: true,\n context: { timeout_ms: timeoutMs },\n });\n }\n}\n\n/** 401 — token missing/invalid. */\nexport class UnauthenticatedError extends DashwiseError {\n constructor(message = 'Authentication required', requestId: string | null = null) {\n super(DashwiseErrorCode.UNAUTHENTICATED, message, { status: 401, requestId });\n }\n}\n\n/** 403 — caller lacks the role/scope for this operation. */\nexport class ForbiddenError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.FORBIDDEN, message, { status: 403, context, requestId });\n }\n}\n\n/** 404 — `GET /db/<table>/<id>` for a missing or soft-deleted row. */\nexport class RowNotFoundError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.ROW_NOT_FOUND, message, { status: 404, context, requestId });\n }\n}\n\n/**\n * Schema-level rejection: dep contract violated, table not exposed, field\n * not readable, filter op not allowed. Covers the family of \"you asked for\n * something the manifest doesn't permit\" errors.\n */\nexport class ContractViolationError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.CONTRACT_VIOLATION, message, {\n status: 403,\n context,\n requestId,\n });\n }\n}\n\n/** 422-ish — request body failed validation. Inspect `context` for field-level errors. */\nexport class ValidationError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.VALIDATION_FAILED, message, {\n status: 400,\n context,\n requestId,\n });\n }\n}\n\n// ── Cross-module dependency errors ─────────────────────────────────────\n//\n// Surfaced when calling `client.deps(slug).db<Row>(table).<op>(...)`.\n// Each subclass preserves the original backend `code` (unlike the older\n// `ContractViolationError` which collapses several codes onto a single\n// `CONTRACT_VIOLATION` string — that's a known wart we don't replicate\n// in new subclasses). Branch on `instanceof` for the common cases;\n// inspect `err.code` if you need to distinguish the two contract-error\n// codes (`DEPENDENCY_NOT_DECLARED` vs `TABLE_NOT_IN_CONTRACT`).\n\n/**\n * 404 — the caller's `module.json#dependencies` doesn't declare a\n * dependency on the requested provider module, OR the declared dep\n * exists but its `reads[]` block doesn't include the requested table.\n *\n * Either way the fix is on the **caller's** side: update the manifest\n * to declare the dep / add the table to `reads[]`, then re-publish.\n *\n * Covers both `DEPENDENCY_NOT_DECLARED` and `TABLE_NOT_IN_CONTRACT` —\n * inspect `err.code` to distinguish if you need different UX per case.\n */\nexport class DependencyContractError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, { status: 404, context, requestId });\n }\n}\n\n/**\n * 404 — the provider's physical table no longer exists. This means the\n * provider published a version that dropped the table while the\n * consumer's installation still pinned the old contract. Recovery is\n * on the **provider's** side (republish with the table) or the\n * workspace admin's (downgrade the provider, or upgrade the consumer\n * to a version whose `dependencies[]` no longer references it).\n */\nexport class ProviderTableMissingError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.PROVIDER_TABLE_MISSING, message, {\n status: 404,\n context,\n requestId,\n });\n }\n}\n\n/**\n * 403 — the provider's `exposes.operations.<verb>.allowed` is explicitly\n * `false` for the requested verb. Distinct from `OPERATION_NOT_ALLOWED`\n * (which is the **owner's** own-table policy) — `OPERATION_NOT_ALLOWED_BY_PROVIDER`\n * is the provider opting out of letting depending modules use a verb.\n *\n * No caller-side fix; either the provider needs to flip the gate, or\n * the consumer needs to find a different way to satisfy the use case.\n */\nexport class OperationNotAllowedByProviderError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.OPERATION_NOT_ALLOWED_BY_PROVIDER, message, {\n status: 403,\n context,\n requestId,\n });\n }\n}\n\n// ── Join errors (Phase 3) ──────────────────────────────────────────────\n//\n// Surfaced when `.join('<slug>')` / `.leftJoin('<slug>')` on the\n// generated `qb` builder can't resolve the target against the\n// manifest. Pre-declared in slice 3.1; raised by the backend\n// translator in slice 3.2. Same one-subclass-with-preserved-code\n// pattern as DependencyContractError so authors can switch on\n// `err.code` for the three sub-cases:\n//\n// LINK_FIELD_NOT_FOUND `.join('xyz')` where `xyz` isn't a field\n// on the source table. Fix: pass an\n// explicit `on` argument, or correct the slug.\n//\n// NOT_A_LINK_FIELD `.join('title')` where `title` exists on\n// the source table but its type isn't\n// `link_row`. Fix: use a real link field,\n// or pass explicit `on`.\n//\n// JOIN_NOT_LINKED `.join('sibling_table')` where the target\n// is a sibling table but no link field\n// bridges them. Fix: pass explicit `on`.\n\n/**\n * 400 — `.join()` / `.leftJoin()` referenced a target the manifest\n * can't resolve. Covers the three sub-cases above; inspect\n * `err.code` to distinguish.\n *\n * Author-side fix in every case: either correct the slug, or pass\n * an explicit `on` argument to bypass link-field inference.\n */\nexport class JoinError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, { status: 400, context, requestId });\n }\n}\n\n// ── Cross-module action errors (Phase 7 slice 7.3a, 2026-05-20) ──────\n//\n// Surfaced by the codegen-emitted `qb.deps.<dep>.actions.<name>(input)`\n// factory when the backend's cross-module dispatch\n// (`CrossModuleActionService.dispatch()`) rejects. Six sub-cases all\n// covered by `DepActionError`; inspect `err.code` to discriminate.\n//\n// ACTION_NOT_EXPOSED 403 — provider's manifest doesn't expose\n// the action, OR visibility='private'.\n// Recovery: provider author needs to\n// publish a version that exposes it.\n// ACTION_NOT_DECLARED 403 — consumer's manifest doesn't list\n// the action in dependencies[].actions[].\n// Recovery: add it + republish.\n// ACTION_INPUT_INVALID 400 — input fails Ajv against the\n// provider's declared input schema.\n// Recovery: fix the call site (typical\n// with stale codegen + drift).\n// ACTION_OUTPUT_INVALID 500 — provider returned a value that fails\n// the declared output schema. This is a\n// PROVIDER-author bug; consumer can\n// only file an issue.\n// ACTION_RATE_LIMITED 429 — per-actor or per-caller-installation\n// rate limit exceeded. Retry with\n// backoff after Retry-After (slice 7.4).\n// ACTION_EXECUTION_FAILED 200-envelope — action body threw, timed out,\n// or OOM-ed. Provider-author bug;\n// trace surfaced in err.context.trace.\n\n/**\n * Single subclass for every cross-module action failure. The code\n * (and HTTP status) varies per sub-case; the wrapping class lets\n * consumers `catch (e) { if (e instanceof DepActionError) {...} }`\n * regardless of which sub-case fired.\n */\nexport class DepActionError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n status: number,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, {\n status,\n retriable: code === DashwiseErrorCode.ACTION_RATE_LIMITED,\n context,\n requestId,\n });\n }\n}\n\n// ── Factory: backend envelope → typed error ────────────────────────────\n\ninterface BackendErrorEnvelope {\n code?: string;\n message?: string;\n retriable?: boolean;\n context?: Record<string, unknown>;\n}\n\n/**\n * Build a typed `DashwiseError` from the backend's response envelope.\n *\n * The mapping picks the most specific subclass for codes we have a class\n * for; everything else becomes a plain `DashwiseError` carrying the raw\n * code. This keeps the type set small while still letting consumers\n * branch on string codes when they want to.\n *\n * Phase 6 slice 6.2 (2026-05-19): accepts an optional `requestId` —\n * the backend's `x-request-id` response header — and threads it onto\n * every produced error so consumers can use it as a debugging trace\n * anchor. Default `null` for backward compat; the transport always\n * passes it through.\n */\nexport function fromBackendEnvelope(\n status: number,\n envelope: BackendErrorEnvelope | null,\n requestId: string | null = null,\n): DashwiseError {\n const code = envelope?.code ?? codeFromStatus(status);\n const message = envelope?.message ?? `HTTP ${status}`;\n const context = envelope?.context;\n\n switch (code) {\n case DashwiseErrorCode.UNAUTHENTICATED:\n case DashwiseErrorCode.TOKEN_EXPIRED:\n return new UnauthenticatedError(message, requestId);\n case DashwiseErrorCode.FORBIDDEN:\n return new ForbiddenError(message, context, requestId);\n case DashwiseErrorCode.ROW_NOT_FOUND:\n return new RowNotFoundError(message, context, requestId);\n case DashwiseErrorCode.CONTRACT_VIOLATION:\n case DashwiseErrorCode.FIELD_NOT_READABLE:\n case DashwiseErrorCode.FILTER_OP_UNKNOWN:\n case DashwiseErrorCode.OPERATION_NOT_ALLOWED:\n return new ContractViolationError(message, context, requestId);\n case DashwiseErrorCode.VALIDATION_FAILED:\n return new ValidationError(message, context, requestId);\n case DashwiseErrorCode.DEPENDENCY_NOT_DECLARED:\n case DashwiseErrorCode.TABLE_NOT_IN_CONTRACT:\n return new DependencyContractError(code, message, context, requestId);\n case DashwiseErrorCode.PROVIDER_TABLE_MISSING:\n return new ProviderTableMissingError(message, context, requestId);\n case DashwiseErrorCode.OPERATION_NOT_ALLOWED_BY_PROVIDER:\n return new OperationNotAllowedByProviderError(message, context, requestId);\n case DashwiseErrorCode.LINK_FIELD_NOT_FOUND:\n case DashwiseErrorCode.NOT_A_LINK_FIELD:\n case DashwiseErrorCode.JOIN_NOT_LINKED:\n return new JoinError(code, message, context, requestId);\n case DashwiseErrorCode.ACTION_NOT_EXPOSED:\n case DashwiseErrorCode.ACTION_NOT_DECLARED:\n return new DepActionError(code, message, 403, context, requestId);\n case DashwiseErrorCode.ACTION_INPUT_INVALID:\n return new DepActionError(code, message, 400, context, requestId);\n case DashwiseErrorCode.ACTION_OUTPUT_INVALID:\n return new DepActionError(code, message, 500, context, requestId);\n case DashwiseErrorCode.ACTION_RATE_LIMITED:\n return new DepActionError(code, message, 429, context, requestId);\n case DashwiseErrorCode.ACTION_EXECUTION_FAILED:\n // ACTION_EXECUTION_FAILED arrives as a 200 envelope from the\n // backend (the host succeeded; the action body crashed). The\n // _callAction helper unwraps the envelope and synthesizes this\n // via the factory call — status 200 reflects \"the transport was\n // fine; the failure is in the application layer\".\n return new DepActionError(code, message, 200, context, requestId);\n default:\n return new DashwiseError(code, message, {\n status,\n retriable: envelope?.retriable ?? false,\n context,\n requestId,\n });\n }\n}\n\nfunction codeFromStatus(status: number): string {\n if (status === 401) return DashwiseErrorCode.UNAUTHENTICATED;\n if (status === 403) return DashwiseErrorCode.FORBIDDEN;\n if (status === 404) return DashwiseErrorCode.ROW_NOT_FOUND;\n if (status >= 500) return DashwiseErrorCode.INTERNAL_ERROR;\n return 'HTTP_ERROR';\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/data/deps.ts","../../src/data/errors.ts"],"names":[],"mappings":";AA2DA,IAAM,iBAAA,GAAoB,2BAAA;AAO1B,IAAM,gBAAA,GAAmB,2BAAA;AAEzB,SAAS,wBAAwB,IAAA,EAAoB;AACnD,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,CAAC,iBAAA,CAAkB,IAAA,CAAK,IAAI,CAAA,EAAG;AAC7D,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uCAAuC,IAAI,CAAA,wHAAA;AAAA,KAC7C;AAAA,EACF;AACF;AAEA,SAAS,qBAAqB,IAAA,EAAoB;AAChD,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,CAAC,gBAAA,CAAiB,IAAA,CAAK,IAAI,CAAA,EAAG;AAC5D,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,oCAAoC,IAAI,CAAA,mEAAA;AAAA,KAC1C;AAAA,EACF;AACF;AASO,SAAS,QAAA,CAAS,WAA0B,YAAA,EAA4B;AAC7E,EAAA,uBAAA,CAAwB,YAAY,CAAA;AAEpC,EAAA,OAAO;AAAA,IACL,GAAwB,SAAA,EAA6C;AACnE,MAAA,oBAAA,CAAqB,SAAS,CAAA;AAC9B,MAAA,OAAO,uBAAA,CAA6B,SAAA,EAAW,YAAA,EAAc,SAAS,CAAA;AAAA,IACxE;AAAA,GACF;AACF;AAOA,SAAS,uBAAA,CACP,SAAA,EACA,YAAA,EACA,SAAA,EAC0B;AAI1B,EAAA,MAAM,UAAA,GAAa,CAAA,MAAA,EAAS,Y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AAA,CAAM,iBAAA,CAAkB,aAAa,OAAA,EAAS;AAAA,MAC5C,MAAA,EAAQ,GAAA;AAAA,MACR,OAAA;AAAA,MACA;AAAA,KACD,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,QAAA,GAA+B;AACjC,IAAA,MAAM,CAAA,GAAI,KAAK,OAAA,EAAS,QAAA;AACxB,IAAA,OAAO,OAAO,CAAA,KAAM,QAAA,GAAW,CAAA,GAAI,MAAA;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,KAAA,GAA4B;AAC9B,IAAA,MAAM,CAAA,GAAI,KAAK,OAAA,EAAS,KAAA;AACxB,IAAA,OAAO,OAAO,CAAA,KAAM,QAAA,GAAW,CAAA,GAAI,MAAA;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,MAAA,GAA6B;AAC/B,IAAA,MAAM,CAAA,GAAI,KAAK,OAAA,EAAS,MAAA;AACxB,IAAA,OAAO,OAAO,CAAA,KAAM,QAAA,GAAW,CAAA,GAAI,MAAA;AAAA,EACrC;AACF","file":"index.js","sourcesContent":["/**\n * Borrowed-table accessor: `client.deps(providerSlug).db<Row>(tableSlug)`.\n *\n * Phase 1 of the SDK query plane — see\n * `dashwise-devops-docs/plans/modules-sdk-query-v1.md` §6.2.\n *\n * The factory is intentionally a thin wrapper around the existing\n * {@link HttpTransport}. Phase 2 wire protocol (contract W1) split the\n * cross-module read surface by verb:\n *\n * - `.list()` compiles to a Query AST with a `dep` table ref and posts\n * to the unified `/query` endpoint — EXACTLY mirroring the owned-\n * table client (which also routes `.list()` through `/query`). The\n * backend's `executeDep` resolves the consumer's declared-dep\n * contract + field projection and returns the same {@link Page}\n * envelope owned-table reads produce. No filter/sort/pagination\n * serialization lives here — the AST carries it, the backend\n * translates it, so there is a single source of truth for query\n * semantics.\n * - `.get(id)` hits the REST route `GET /deps/<provider>/tables/<table>/<id>`\n * (the query plane has no by-id representation). The backend returns\n * a `{ row, fields }` envelope; we unwrap `.row`.\n *\n * Same {@link DashwiseError} model on both paths — the contract error\n * codes (`DEPENDENCY_NOT_DECLARED`, `TABLE_NOT_IN_CONTRACT`,\n * `PROVIDER_TABLE_MISSING`, `OPERATION_NOT_ALLOWED_BY_PROVIDER`) surface\n * identically whether they come back from `/query` or `/deps/.../tables/...`.\n * No new transport, no new auth flow, no new caching.\n *\n * Cross-module **writes** are deliberately omitted: the returned\n * {@link ReadOnlyTableClient} has no `create` / `update` / `delete`.\n * See plan §4.3 — writes flow through provider-published actions in\n * a later phase, never as direct mutations across the trust boundary.\n *\n * Slug validation runs client-side as a fail-fast check so a typo\n * doesn't reach the backend as a 404 from a malformed URL. The\n * authoritative check is server-side: the backend re-validates\n * provider existence + contract coverage on every call.\n */\n\nimport type { HttpTransport } from './http.js';\nimport type {\n BaseRow,\n Deps,\n ListOpts,\n Page,\n ReadOnlyTableClient,\n} from './types.js';\n\n/**\n * Module-slug character set matches the backend manifest validator's\n * `MODULE_SLUG_REGEX` exactly: kebab-case, 2-63 chars, starts with a\n * letter, ends with letter/digit, no leading/trailing dash.\n *\n * Mirrored here (not imported from the backend) because the SDK is\n * published independently — pulling backend code in would couple\n * release cycles. If the backend's regex changes, the SDK's mirror\n * must update in lockstep; covered by an integration test.\n */\nconst MODULE_SLUG_REGEX = /^[a-z][a-z0-9-]*[a-z0-9]$/;\n\n/**\n * Table-slug character set matches the backend's `SLUG_REGEX`: snake_case,\n * 2-63 chars, starts with a letter, ends with letter/digit. Same\n * mirror-vs-import tradeoff as {@link MODULE_SLUG_REGEX}.\n */\nconst TABLE_SLUG_REGEX = /^[a-z][a-z0-9_]*[a-z0-9]$/;\n\nfunction assertValidProviderSlug(slug: string): void {\n if (typeof slug !== 'string' || !MODULE_SLUG_REGEX.test(slug)) {\n throw new Error(\n `@dashai/sdk: invalid provider slug \"${slug}\". Provider slugs are the dependency module's slug (kebab-case, e.g. \"crm-app\"); must match /^[a-z][a-z0-9-]*[a-z0-9]$/.`,\n );\n }\n}\n\nfunction assertValidTableSlug(slug: string): void {\n if (typeof slug !== 'string' || !TABLE_SLUG_REGEX.test(slug)) {\n throw new Error(\n `@dashai/sdk: invalid table slug \"${slug}\". Table slugs must match /^[a-z][a-z0-9_]*[a-z0-9]$/ (snake_case).`,\n );\n }\n}\n\n/**\n * Build a {@link Deps} accessor for `providerSlug`. Validates the\n * slug shape eagerly; defers everything else to the backend.\n *\n * Exported for use by `createClient()` in `./client.ts`. Not part\n * of the public API directly — consumers reach it via `client.deps(...)`.\n */\nexport function makeDeps(transport: HttpTransport, providerSlug: string): Deps {\n assertValidProviderSlug(providerSlug);\n\n return {\n db<Row extends BaseRow>(tableSlug: string): ReadOnlyTableClient<Row> {\n assertValidTableSlug(tableSlug);\n return makeBorrowedTableClient<Row>(transport, providerSlug, tableSlug);\n },\n };\n}\n\n/**\n * Internal: produce a {@link ReadOnlyTableClient} for one specific\n * `(providerSlug, tableSlug)` pair. Closure captures the transport +\n * the provider/table slugs so the public methods are tiny.\n */\nfunction makeBorrowedTableClient<Row extends BaseRow>(\n transport: HttpTransport,\n providerSlug: string,\n tableSlug: string,\n): ReadOnlyTableClient<Row> {\n // Per-id REST route (contract W1): the full URL after the transport's\n // `/api/module-api` base prefix is\n // `<baseUrl>/api/module-api/deps/<provider>/tables/<table>/<id>`.\n const tablesRoot = `/deps/${providerSlug}/tables/${tableSlug}`;\n\n return {\n async list(opts?: ListOpts<Row>): Promise<Page<Row>> {\n // Phase 2 wire protocol (W1): `.list()` compiles to a Query AST\n // with a `dep` table ref and posts to the unified `/query`\n // endpoint — identical to how the owned-table client routes its\n // `.list()`, only the `from` ref differs (`kind: 'dep'` +\n // provider module slug instead of `kind: 'owned'`). The backend's\n // `executeDep` enforces the consumer's declared-dep contract +\n // field projection and returns the same `Page<Row>` envelope.\n //\n // Why route through /query instead of the REST list route: the\n // owned-table client already made this choice, so cross-module\n // reads inherit every query-plane improvement (observability,\n // slow-query hooks, future caching) for free, and the filter /\n // sort / pagination semantics have a single translation site\n // (the backend), not a re-implementation of the Baserow\n // query-param encoding here.\n const ast: Record<string, unknown> = {\n v: 1,\n from: { kind: 'dep', module: providerSlug, slug: tableSlug },\n };\n if (opts?.filter !== undefined) ast.where = opts.filter;\n if (opts?.sort !== undefined && opts.sort.length > 0) {\n ast.orderBy = opts.sort;\n }\n if (typeof opts?.limit === 'number') ast.limit = opts.limit;\n if (typeof opts?.offset === 'number') ast.offset = opts.offset;\n\n const result = await transport.request<Page<Row>>('POST', '/query', { ast });\n // Defence in depth: same Page-envelope coercion the owned-table\n // client uses — if a proxy ever strips the envelope to a bare\n // array, wrap it so the consumer always sees `{ rows, ... }`.\n if (Array.isArray(result)) {\n return {\n rows: result as Row[],\n total: result.length,\n limit: opts?.limit ?? result.length,\n offset: opts?.offset ?? 0,\n };\n }\n return result;\n },\n\n async get(id: number): Promise<Row> {\n // Contract W1: `GET /deps/<provider>/tables/<table>/<id>` returns\n // a `{ row, fields }` envelope (the query plane has no by-id\n // representation). Unwrap `.row` so the consumer gets the bare\n // typed row — matching the owned-table `.get()` shape.\n const result = await transport.request<{ row: Row } | Row>(\n 'GET',\n `${tablesRoot}/${id}`,\n );\n if (result && typeof result === 'object' && 'row' in result) {\n return (result as { row: Row }).row;\n }\n // Defence in depth: tolerate a bare row (proxy stripping the\n // envelope / future shape drift), mirroring the list fallback.\n return result as Row;\n },\n };\n}\n","/**\n * Error model for @dashai/sdk.\n *\n * The backend speaks a structured error envelope:\n *\n * {\n * \"code\": \"ROW_NOT_FOUND\",\n * \"message\": \"Row 123 not found in tasks\",\n * \"retriable\": false,\n * \"context\": { ... }\n * }\n *\n * This module wraps that envelope in a typed `DashwiseError` plus a small\n * set of subclasses for the codes consumers most commonly want to branch\n * on (network errors, auth failures, row-not-found, contract violations).\n *\n * Anything not matched by a specific subclass becomes a plain\n * `DashwiseError` carrying the raw `code`. Branch on `.code` for codes\n * we don't have a class for; use `instanceof` for the common cases.\n */\n\n/**\n * Known error codes. Not exhaustive — the backend emits many codes\n * specific to individual modules / endpoints. Use these constants when\n * you want compile-time safety; otherwise treat `err.code` as a string.\n *\n * The list is curated to the codes a module author is most likely to\n * branch on. Adding a new code here is a non-breaking change.\n */\nexport const DashwiseErrorCode = {\n // Auth / authz\n UNAUTHENTICATED: 'UNAUTHENTICATED',\n FORBIDDEN: 'FORBIDDEN',\n TOKEN_EXPIRED: 'TOKEN_EXPIRED',\n INSTALLATION_NOT_FOUND: 'INSTALLATION_NOT_FOUND',\n INSTALLATION_MODE_UNSUPPORTED: 'INSTALLATION_MODE_UNSUPPORTED',\n // Contract enforcement\n CONTRACT_VIOLATION: 'CONTRACT_VIOLATION',\n FIELD_NOT_READABLE: 'FIELD_NOT_READABLE',\n FILTER_OP_UNKNOWN: 'FILTER_OP_UNKNOWN',\n OPERATION_NOT_ALLOWED: 'OPERATION_NOT_ALLOWED',\n // Cross-module dependencies (Phase 1 of the SDK query plane —\n // see dashwise-devops-docs/plans/modules-sdk-query-v1.md).\n // Surfaced when reading borrowed tables via `client.deps(slug)`.\n DEPENDENCY_NOT_DECLARED: 'DEPENDENCY_NOT_DECLARED',\n TABLE_NOT_IN_CONTRACT: 'TABLE_NOT_IN_CONTRACT',\n PROVIDER_TABLE_MISSING: 'PROVIDER_TABLE_MISSING',\n OPERATION_NOT_ALLOWED_BY_PROVIDER: 'OPERATION_NOT_ALLOWED_BY_PROVIDER',\n // Cross-module dependency PARK state (Phase 3 modules-platform-v2 —\n // dependency connect/bind lifecycle). Surfaced at RUNTIME (409) when a\n // module reads a borrowed table (`client.deps(slug)` / `qb.deps.<slug>`)\n // or invokes a dep action whose `module_dependencies` row is currently\n // `status='unbound'` — the dependency is declared but not connected to a\n // provider installation (no provider in the workspace, version mismatch,\n // manually unbound, provider uninstalled, etc.). The consumer app should\n // render a \"connect your provider\" state rather than treating this as a\n // hard failure. `err.context` carries `{ provider, range, reason }`.\n DEP_UNBOUND: 'DEP_UNBOUND',\n // Workspace-table `uses` plane (Phase 4 modules-platform-v2 — the\n // declared/portable path for a module to read+write a WORKSPACE table\n // the workspace already owns, as opposed to `deps` = another module's\n // tables). Surfaced at RUNTIME against `client.uses(slug)` /\n // `qb.uses.<slug>` / the `POST /api/module-api/uses/:slug/...` REST\n // plane. The BINDING is the grant on this plane (for sandbox AND\n // api_key auth alike — a kind-local key does NOT bypass it):\n // - USES_UNBOUND 409 — the `uses` slot is declared but its\n // `module_table_bindings` row isn't `status='bound'` (never bound,\n // ambiguous match, no match, table trashed, ops widened pending\n // re-consent, manually unbound). `err.context` carries\n // `{ uses_slug, reason }`. Recoverable: a workspace admin binds a\n // table (`dashwise bind <uses_slug>`), then the read succeeds.\n // - USES_OP_NOT_ALLOWED 403 — the operation isn't in the binding's\n // enforcement set (manifest `ops` ∩ `consented_ops`). `err.context`\n // carries `{ uses_slug, op }`. Fix: widen the manifest ops +\n // re-consent (re-bind), or the admin re-binds to consent.\n // - CONTRACT_FIELD_MISSING 409 — a field the binding maps no longer\n // exists on the physical table (schema drift). `err.context`\n // carries `{ uses_slug, field }`. The binding is best-effort parked\n // on detection; an admin re-binds to a table that has the field.\n USES_UNBOUND: 'USES_UNBOUND',\n USES_OP_NOT_ALLOWED: 'USES_OP_NOT_ALLOWED',\n CONTRACT_FIELD_MISSING: 'CONTRACT_FIELD_MISSING',\n // `uses`-plane query joins are NOT supported in v1 — a\n // `qb.uses.<slug>.join(...)` / cross-plane join is rejected with a\n // typed 400. (Joins WITH a uses table as a target are v2 territory.)\n USES_JOIN_UNSUPPORTED: 'USES_JOIN_UNSUPPORTED',\n // Query-plane joins (Phase 3 — see\n // dashwise-devops-docs/plans/modules-sdk-query-v1-p3-execution.md).\n // Surfaced when `.join('<slug>')` / `.leftJoin('<slug>')` can't\n // resolve the target. Pre-declared in slice 3.1 so slice 3.2's\n // backend translator can emit them through fromBackendEnvelope\n // without an SDK roundtrip.\n LINK_FIELD_NOT_FOUND: 'LINK_FIELD_NOT_FOUND',\n NOT_A_LINK_FIELD: 'NOT_A_LINK_FIELD',\n JOIN_NOT_LINKED: 'JOIN_NOT_LINKED',\n // Cross-module actions (Phase 7 slice 7.3a — see\n // dashwise-devops-docs/plans/modules-sdk-query-v1-p7-cross-module-writes.md).\n // Surfaced when `qb.deps.<dep>.actions.<name>(input)` (generated\n // factory) dispatches against the backend endpoint\n // `POST /api/module-api/deps/:providerSlug/actions/:actionName`.\n // Slice 7.2b ships the backend emitter; slice 7.3a (this slice)\n // reserves the codes + maps them to DepActionError in the SDK.\n ACTION_NOT_EXPOSED: 'ACTION_NOT_EXPOSED',\n ACTION_NOT_DECLARED: 'ACTION_NOT_DECLARED',\n ACTION_INPUT_INVALID: 'ACTION_INPUT_INVALID',\n ACTION_OUTPUT_INVALID: 'ACTION_OUTPUT_INVALID',\n ACTION_RATE_LIMITED: 'ACTION_RATE_LIMITED',\n ACTION_EXECUTION_FAILED: 'ACTION_EXECUTION_FAILED',\n // Data plane\n ROW_NOT_FOUND: 'ROW_NOT_FOUND',\n TABLE_NOT_FOUND: 'TABLE_NOT_FOUND',\n VALIDATION_FAILED: 'VALIDATION_FAILED',\n ROW_LIMIT_EXCEEDED: 'ROW_LIMIT_EXCEEDED',\n STORAGE_LIMIT_EXCEEDED: 'STORAGE_LIMIT_EXCEEDED',\n // Outbound / runtime\n OUTBOUND_NOT_ALLOWED: 'OUTBOUND_NOT_ALLOWED',\n OUTBOUND_CONCURRENCY_LIMITED: 'OUTBOUND_CONCURRENCY_LIMITED',\n // Transport\n NETWORK_ERROR: 'NETWORK_ERROR',\n TIMEOUT: 'TIMEOUT',\n // Server\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n} as const;\n\nexport type DashwiseErrorCode = (typeof DashwiseErrorCode)[keyof typeof DashwiseErrorCode];\n\n/**\n * Base class for every error thrown by @dashai/sdk. Carries the\n * structured envelope from the backend (or a synthetic one for\n * client-side failures like network errors / timeouts).\n *\n * Always thrown — never returned as a value. The async client methods\n * `.list()` / `.get()` etc. reject with one of these on failure.\n */\nexport class DashwiseError extends Error {\n readonly code: string;\n readonly status: number;\n readonly retriable: boolean;\n readonly context: Record<string, unknown> | undefined;\n /**\n * Backend-issued trace anchor (Phase 6 slice 6.2, 2026-05-19).\n * Mirrors the `x-request-id` response header. Populated whenever\n * the backend's `RuntimeQueryController` (or any future endpoint\n * that echoes the header) is the origin of this error. `null` when\n * the failure is client-side (NetworkError / TimeoutError — the\n * request never reached the server, so there's no server-issued\n * ID to surface).\n *\n * Use this as a debugging trace anchor when filing a bug against a\n * specific failed query — the matching row in `module_query_log`\n * carries the full backend context (ast_hash, error_code,\n * duration_ms, etc.).\n */\n readonly requestId: string | null;\n\n constructor(\n code: string,\n message: string,\n options: {\n status?: number;\n retriable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n /**\n * Phase 6 slice 6.2: backend `x-request-id` response header,\n * captured by the transport before throwing. Pass `undefined`\n * (or omit) for client-side errors that never hit the server.\n */\n requestId?: string | null;\n } = {},\n ) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n this.status = options.status ?? 0;\n this.retriable = options.retriable ?? false;\n this.context = options.context;\n this.requestId = options.requestId ?? null;\n if (options.cause !== undefined) {\n // Node 18+ and modern browsers support Error.cause natively.\n // Use a property assignment because `super({ cause })` is awkward\n // when the base class only takes a string.\n (this as { cause?: unknown }).cause = options.cause;\n }\n }\n}\n\n/** Network-level failure (DNS, connection refused, TLS, fetch threw). */\nexport class NetworkError extends DashwiseError {\n constructor(message: string, cause?: unknown) {\n super(DashwiseErrorCode.NETWORK_ERROR, message, { retriable: true, cause });\n }\n}\n\n/** Request exceeded the configured timeout (`timeoutMs`). */\nexport class TimeoutError extends DashwiseError {\n constructor(message: string, timeoutMs: number) {\n super(DashwiseErrorCode.TIMEOUT, message, {\n retriable: true,\n context: { timeout_ms: timeoutMs },\n });\n }\n}\n\n/** 401 — token missing/invalid. */\nexport class UnauthenticatedError extends DashwiseError {\n constructor(message = 'Authentication required', requestId: string | null = null) {\n super(DashwiseErrorCode.UNAUTHENTICATED, message, { status: 401, requestId });\n }\n}\n\n/** 403 — caller lacks the role/scope for this operation. */\nexport class ForbiddenError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.FORBIDDEN, message, { status: 403, context, requestId });\n }\n}\n\n/** 404 — `GET /db/<table>/<id>` for a missing or soft-deleted row. */\nexport class RowNotFoundError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.ROW_NOT_FOUND, message, { status: 404, context, requestId });\n }\n}\n\n/**\n * Schema-level rejection: dep contract violated, table not exposed, field\n * not readable, filter op not allowed. Covers the family of \"you asked for\n * something the manifest doesn't permit\" errors.\n */\nexport class ContractViolationError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.CONTRACT_VIOLATION, message, {\n status: 403,\n context,\n requestId,\n });\n }\n}\n\n/** 422-ish — request body failed validation. Inspect `context` for field-level errors. */\nexport class ValidationError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.VALIDATION_FAILED, message, {\n status: 400,\n context,\n requestId,\n });\n }\n}\n\n// ── Cross-module dependency errors ─────────────────────────────────────\n//\n// Surfaced when calling `client.deps(slug).db<Row>(table).<op>(...)`.\n// Each subclass preserves the original backend `code` (unlike the older\n// `ContractViolationError` which collapses several codes onto a single\n// `CONTRACT_VIOLATION` string — that's a known wart we don't replicate\n// in new subclasses). Branch on `instanceof` for the common cases;\n// inspect `err.code` if you need to distinguish the two contract-error\n// codes (`DEPENDENCY_NOT_DECLARED` vs `TABLE_NOT_IN_CONTRACT`).\n\n/**\n * 404 — the caller's `module.json#dependencies` doesn't declare a\n * dependency on the requested provider module, OR the declared dep\n * exists but its `reads[]` block doesn't include the requested table.\n *\n * Either way the fix is on the **caller's** side: update the manifest\n * to declare the dep / add the table to `reads[]`, then re-publish.\n *\n * Covers both `DEPENDENCY_NOT_DECLARED` and `TABLE_NOT_IN_CONTRACT` —\n * inspect `err.code` to distinguish if you need different UX per case.\n */\nexport class DependencyContractError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, { status: 404, context, requestId });\n }\n}\n\n/**\n * 404 — the provider's physical table no longer exists. This means the\n * provider published a version that dropped the table while the\n * consumer's installation still pinned the old contract. Recovery is\n * on the **provider's** side (republish with the table) or the\n * workspace admin's (downgrade the provider, or upgrade the consumer\n * to a version whose `dependencies[]` no longer references it).\n */\nexport class ProviderTableMissingError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.PROVIDER_TABLE_MISSING, message, {\n status: 404,\n context,\n requestId,\n });\n }\n}\n\n/**\n * 403 — the provider's `exposes.operations.<verb>.allowed` is explicitly\n * `false` for the requested verb. Distinct from `OPERATION_NOT_ALLOWED`\n * (which is the **owner's** own-table policy) — `OPERATION_NOT_ALLOWED_BY_PROVIDER`\n * is the provider opting out of letting depending modules use a verb.\n *\n * No caller-side fix; either the provider needs to flip the gate, or\n * the consumer needs to find a different way to satisfy the use case.\n */\nexport class OperationNotAllowedByProviderError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.OPERATION_NOT_ALLOWED_BY_PROVIDER, message, {\n status: 403,\n context,\n requestId,\n });\n }\n}\n\n/**\n * The vocabulary of `unbound_reason` values a parked dependency can\n * carry, surfaced in {@link DepUnboundError.reason}. Mirrors the\n * backend's `module_dependencies.unbound_reason` enum (Phase 3\n * modules-platform-v2). Not exhaustive by design — treat `.reason` as a\n * string and branch on these constants when you want compile-time\n * safety. Adding a new reason is a non-breaking change.\n *\n * Resolve/bind-time reasons (why the dep never bound):\n * - `MISSING_DEPENDENCY` no install of the provider module in the workspace\n * - `DEPENDENCY_VERSION_MISMATCH` an install exists but its version is outside the declared range\n * - `PROVIDER_VERSION_RECORD_MISSING` the provider's version row is gone (data-integrity edge)\n * - `EXPOSES_MISSING` the provider no longer exposes a table/field the dep reads\n * - `EXPOSES_PRIVATE` the exposed surface is `private` to the consumer\n * - `ACTION_NOT_EXPOSED` a declared dep action isn't exposed by the provider (Rule #11)\n * - `PROVIDER_NOT_PRODUCTION` kind hygiene: a production consumer can only bind a production provider\n *\n * Lifecycle reasons (the dep bound once, then got parked):\n * - `MANUALLY_UNBOUND` a workspace admin ran `deps unbind` / the unbind endpoint\n * - `PROVIDER_UPGRADE_BROKE_CONTRACT` a provider upgrade (with `force`) broke this consumer's contract\n * - `PROVIDER_UNINSTALLED` the provider was uninstalled with `park_consumers`\n */\nexport const DepUnboundReason = {\n MISSING_DEPENDENCY: 'MISSING_DEPENDENCY',\n DEPENDENCY_VERSION_MISMATCH: 'DEPENDENCY_VERSION_MISMATCH',\n PROVIDER_VERSION_RECORD_MISSING: 'PROVIDER_VERSION_RECORD_MISSING',\n EXPOSES_MISSING: 'EXPOSES_MISSING',\n EXPOSES_PRIVATE: 'EXPOSES_PRIVATE',\n ACTION_NOT_EXPOSED: 'ACTION_NOT_EXPOSED',\n PROVIDER_NOT_PRODUCTION: 'PROVIDER_NOT_PRODUCTION',\n MANUALLY_UNBOUND: 'MANUALLY_UNBOUND',\n PROVIDER_UPGRADE_BROKE_CONTRACT: 'PROVIDER_UPGRADE_BROKE_CONTRACT',\n PROVIDER_UNINSTALLED: 'PROVIDER_UNINSTALLED',\n} as const;\n\nexport type DepUnboundReason =\n (typeof DepUnboundReason)[keyof typeof DepUnboundReason];\n\n/**\n * 409 — a runtime read (borrowed-table `list` / `get`, query-plane\n * `qb.deps.<slug>.<table>`, or a cross-module action) targeted a\n * dependency whose `module_dependencies` row is `status='unbound'`\n * (Phase 3 modules-platform-v2 dependency connect lifecycle).\n *\n * \"Unbound\" means the dependency is *declared* in the consumer's\n * manifest but not *connected* to a provider installation. It happens\n * when the resolver PARKED the dep at install/apply time (no provider\n * in the workspace, version mismatch, exposes/action coverage gap) or\n * when the dependency was later parked (manually unbound, provider\n * upgrade broke the contract, provider uninstalled).\n *\n * This is a *recoverable* state, not a bug in the consumer. Catch it and\n * render a \"connect your provider\" prompt — a workspace admin resolves it\n * by installing/binding the provider (`dashwise deps bind <slug>` or the\n * `POST /api/installations/:id/dependencies/:providerSlug/bind` endpoint).\n * Once bound, the same read succeeds with no code change.\n *\n * Convenience accessors ({@link DepUnboundError.provider},\n * {@link DepUnboundError.range}, {@link DepUnboundError.reason}) read the\n * backend's `context: { provider, range, reason }` so callers don't have\n * to reach into `err.context` by hand.\n *\n * @example\n * ```ts\n * import { DepUnboundError } from '@dashai/sdk';\n *\n * try {\n * const contacts = await client.deps('crm').db<ContactRow>('contacts').list();\n * // …or the typed builder: await qb.deps.crm.contacts.execute();\n * } catch (err) {\n * if (err instanceof DepUnboundError) {\n * // Declared but not connected — show a connect-your-provider CTA.\n * return <ConnectProvider provider={err.provider} range={err.range} reason={err.reason} />;\n * }\n * throw err;\n * }\n * ```\n */\nexport class DepUnboundError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.DEP_UNBOUND, message, {\n status: 409,\n context,\n requestId,\n });\n }\n\n /**\n * The provider module slug the parked dependency points at (kebab-case,\n * e.g. `crm`). Read from `context.provider`; `undefined` if the backend\n * omitted it.\n */\n get provider(): string | undefined {\n const v = this.context?.provider;\n return typeof v === 'string' ? v : undefined;\n }\n\n /**\n * The SemVer range the consumer's manifest declared for this dependency\n * (e.g. `^1.2.0`). Read from `context.range`; `undefined` if omitted.\n */\n get range(): string | undefined {\n const v = this.context?.range;\n return typeof v === 'string' ? v : undefined;\n }\n\n /**\n * Why the dependency is unbound — one of {@link DepUnboundReason} (but\n * typed as `string` for forward-compat with reasons the backend may add).\n * Read from `context.reason`; `undefined` if omitted.\n */\n get reason(): string | undefined {\n const v = this.context?.reason;\n return typeof v === 'string' ? v : undefined;\n }\n}\n\n// ── Workspace-table `uses` errors (Phase 4 modules-platform-v2) ────────\n//\n// The `uses` plane lets a module read+write a WORKSPACE table the\n// workspace already owns — the declared, portable counterpart to the\n// ad-hoc numeric-tableId Data Hub bridge. A module declares an ABSTRACT\n// contract in `module.json#uses[].tables[]` (slug + fields + abstract\n// types + ops); at install/bind time that slot is BOUND to a physical\n// workspace table via a `field_map` (declared field → physical field id).\n// The binding IS the grant: even a kind-local `dwk_` key can't touch a\n// uses table until its slot is bound.\n//\n// Surfaced against `client.uses(slug).db<Row>(table)` /\n// `qb.uses.<slug>.<table>` / the REST plane at\n// `POST /api/module-api/uses/:usesSlug/rows/...`. Same\n// preserve-the-code, convenience-accessor pattern as DepUnboundError.\n\n/**\n * The vocabulary of `reason` values a parked `uses` binding can carry,\n * surfaced in {@link UsesUnboundError.reason}. Mirrors the backend's\n * `module_table_bindings` unbound_reason enum for this plane\n * (Phase 4 modules-platform-v2). Not exhaustive by design — treat\n * `.reason` as a string; branch on these constants for compile-time\n * safety. Adding a new reason is non-breaking.\n *\n * - `NOT_BOUND_YET` the slot has never been bound (declared\n * but no workspace table connected yet)\n * - `AMBIGUOUS_MATCH` auto-match found >1 candidate table; a\n * human must pick one (`dashwise bind`)\n * - `NO_MATCH` auto-match found no candidate table\n * - `TABLE_DELETED` the bound table was trashed (or a mapped\n * field drifted away) → the row parked\n * - `OPS_WIDENED_PENDING_CONSENT` the manifest widened `ops` beyond what\n * was consented at bind time; re-bind to\n * refresh consent\n * - `MANUALLY_UNBOUND` a workspace admin ran `dashwise unbind`\n */\nexport const UsesUnboundReason = {\n NOT_BOUND_YET: 'NOT_BOUND_YET',\n AMBIGUOUS_MATCH: 'AMBIGUOUS_MATCH',\n NO_MATCH: 'NO_MATCH',\n TABLE_DELETED: 'TABLE_DELETED',\n OPS_WIDENED_PENDING_CONSENT: 'OPS_WIDENED_PENDING_CONSENT',\n MANUALLY_UNBOUND: 'MANUALLY_UNBOUND',\n} as const;\n\nexport type UsesUnboundReason =\n (typeof UsesUnboundReason)[keyof typeof UsesUnboundReason];\n\n/**\n * 409 — a runtime read/write against a `uses` table whose\n * `module_table_bindings` row is not `status='bound'` (Phase 4\n * modules-platform-v2 workspace-table binding lifecycle).\n *\n * \"Unbound\" means the workspace-table slot is *declared* in the module's\n * manifest `uses` block but not *connected* to a physical workspace\n * table. It happens when install-time auto-match parked the slot (no\n * candidate / ambiguous candidates / a write contract that never\n * auto-binds), the bound table was later trashed, the manifest widened\n * `ops` beyond consent, or an admin manually unbound it.\n *\n * A *recoverable* state, not a bug. Catch it and render a \"connect a\n * table\" prompt — a workspace admin resolves it by binding a workspace\n * table to the slot (`dashwise bind <uses_slug>` / the\n * `PUT /api/installations/:id/bindings/:usesSlug` endpoint). Once bound,\n * the same call succeeds with no code change.\n *\n * Convenience accessors read the backend's `context: { uses_slug, reason }`.\n *\n * @example\n * ```ts\n * import { UsesUnboundError } from '@dashai/sdk';\n *\n * try {\n * const staff = await client.uses('employees').db<EmployeeRow>('employees').list();\n * // …or the typed builder: await qb.uses.employees.execute();\n * } catch (err) {\n * if (err instanceof UsesUnboundError) {\n * return <BindWorkspaceTable slot={err.usesSlug} reason={err.reason} />;\n * }\n * throw err;\n * }\n * ```\n */\nexport class UsesUnboundError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.USES_UNBOUND, message, {\n status: 409,\n context,\n requestId,\n });\n }\n\n /**\n * The manifest `uses[].tables[].slug` of the unbound slot (kebab-case,\n * e.g. `employees`). Read from `context.uses_slug`; `undefined` if the\n * backend omitted it.\n */\n get usesSlug(): string | undefined {\n const v = this.context?.uses_slug;\n return typeof v === 'string' ? v : undefined;\n }\n\n /**\n * Why the slot is unbound — one of {@link UsesUnboundReason} (typed as\n * `string` for forward-compat with reasons the backend may add). Read\n * from `context.reason`; `undefined` if omitted.\n */\n get reason(): string | undefined {\n const v = this.context?.reason;\n return typeof v === 'string' ? v : undefined;\n }\n}\n\n/**\n * 403 — a `uses`-plane operation that isn't in the binding's enforced\n * operation set (the manifest's declared `ops` INTERSECT the admin's\n * `consented_ops` at bind time). E.g. the manifest declares\n * `ops: ['read','update']` but the admin consented only to `read` when\n * binding, so an `update` is rejected.\n *\n * Fix: either narrow the call to a consented op, or widen the manifest\n * `ops` + have an admin re-bind (which refreshes `consented_ops`).\n *\n * `err.op` / `err.usesSlug` read the backend's `context: { uses_slug, op }`.\n */\nexport class UsesOpNotAllowedError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.USES_OP_NOT_ALLOWED, message, {\n status: 403,\n context,\n requestId,\n });\n }\n\n /** The `uses` slot slug the rejected op targeted. Read from `context.uses_slug`. */\n get usesSlug(): string | undefined {\n const v = this.context?.uses_slug;\n return typeof v === 'string' ? v : undefined;\n }\n\n /**\n * The operation that was rejected — one of `create` / `read` /\n * `update` / `delete`. Read from `context.op`; `undefined` if omitted.\n */\n get op(): string | undefined {\n const v = this.context?.op;\n return typeof v === 'string' ? v : undefined;\n }\n}\n\n/**\n * 409 — a field the `uses` binding's `field_map` points at no longer\n * exists on the physical workspace table (schema drift: the table owner\n * deleted or renamed the column after the bind). The backend best-effort\n * parks the binding (reason `TABLE_DELETED`/field-drift) on detection.\n *\n * Recovery is the workspace admin's: re-bind the slot to a table that\n * still has the field, or re-map the field (`dashwise bind <uses_slug>\n * --map <usesField>=<physicalField>`).\n *\n * `err.field` / `err.usesSlug` read the backend's\n * `context: { uses_slug, field }`.\n */\nexport class ContractFieldMissingError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.CONTRACT_FIELD_MISSING, message, {\n status: 409,\n context,\n requestId,\n });\n }\n\n /** The `uses` slot slug whose contract broke. Read from `context.uses_slug`. */\n get usesSlug(): string | undefined {\n const v = this.context?.uses_slug;\n return typeof v === 'string' ? v : undefined;\n }\n\n /**\n * The declared field slug (the `uses` side name) whose mapped physical\n * field is gone. Read from `context.field`; `undefined` if omitted.\n */\n get field(): string | undefined {\n const v = this.context?.field;\n return typeof v === 'string' ? v : undefined;\n }\n}\n\n// ── Join errors (Phase 3) ──────────────────────────────────────────────\n//\n// Surfaced when `.join('<slug>')` / `.leftJoin('<slug>')` on the\n// generated `qb` builder can't resolve the target against the\n// manifest. Pre-declared in slice 3.1; raised by the backend\n// translator in slice 3.2. Same one-subclass-with-preserved-code\n// pattern as DependencyContractError so authors can switch on\n// `err.code` for the three sub-cases:\n//\n// LINK_FIELD_NOT_FOUND `.join('xyz')` where `xyz` isn't a field\n// on the source table. Fix: pass an\n// explicit `on` argument, or correct the slug.\n//\n// NOT_A_LINK_FIELD `.join('title')` where `title` exists on\n// the source table but its type isn't\n// `link_row`. Fix: use a real link field,\n// or pass explicit `on`.\n//\n// JOIN_NOT_LINKED `.join('sibling_table')` where the target\n// is a sibling table but no link field\n// bridges them. Fix: pass explicit `on`.\n\n/**\n * 400 — `.join()` / `.leftJoin()` referenced a target the manifest\n * can't resolve. Covers the three sub-cases above; inspect\n * `err.code` to distinguish.\n *\n * Author-side fix in every case: either correct the slug, or pass\n * an explicit `on` argument to bypass link-field inference.\n */\nexport class JoinError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, { status: 400, context, requestId });\n }\n}\n\n// ── Cross-module action errors (Phase 7 slice 7.3a, 2026-05-20) ──────\n//\n// Surfaced by the codegen-emitted `qb.deps.<dep>.actions.<name>(input)`\n// factory when the backend's cross-module dispatch\n// (`CrossModuleActionService.dispatch()`) rejects. Six sub-cases all\n// covered by `DepActionError`; inspect `err.code` to discriminate.\n//\n// ACTION_NOT_EXPOSED 403 — provider's manifest doesn't expose\n// the action, OR visibility='private'.\n// Recovery: provider author needs to\n// publish a version that exposes it.\n// ACTION_NOT_DECLARED 403 — consumer's manifest doesn't list\n// the action in dependencies[].actions[].\n// Recovery: add it + republish.\n// ACTION_INPUT_INVALID 400 — input fails Ajv against the\n// provider's declared input schema.\n// Recovery: fix the call site (typical\n// with stale codegen + drift).\n// ACTION_OUTPUT_INVALID 500 — provider returned a value that fails\n// the declared output schema. This is a\n// PROVIDER-author bug; consumer can\n// only file an issue.\n// ACTION_RATE_LIMITED 429 — per-actor or per-caller-installation\n// rate limit exceeded. Retry with\n// backoff after Retry-After (slice 7.4).\n// ACTION_EXECUTION_FAILED 200-envelope — action body threw, timed out,\n// or OOM-ed. Provider-author bug;\n// trace surfaced in err.context.trace.\n\n/**\n * Single subclass for every cross-module action failure. The code\n * (and HTTP status) varies per sub-case; the wrapping class lets\n * consumers `catch (e) { if (e instanceof DepActionError) {...} }`\n * regardless of which sub-case fired.\n */\nexport class DepActionError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n status: number,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, {\n status,\n retriable: code === DashwiseErrorCode.ACTION_RATE_LIMITED,\n context,\n requestId,\n });\n }\n}\n\n// ── Factory: backend envelope → typed error ────────────────────────────\n\ninterface BackendErrorEnvelope {\n code?: string;\n message?: string;\n retriable?: boolean;\n context?: Record<string, unknown>;\n}\n\n/**\n * Build a typed `DashwiseError` from the backend's response envelope.\n *\n * The mapping picks the most specific subclass for codes we have a class\n * for; everything else becomes a plain `DashwiseError` carrying the raw\n * code. This keeps the type set small while still letting consumers\n * branch on string codes when they want to.\n *\n * Phase 6 slice 6.2 (2026-05-19): accepts an optional `requestId` —\n * the backend's `x-request-id` response header — and threads it onto\n * every produced error so consumers can use it as a debugging trace\n * anchor. Default `null` for backward compat; the transport always\n * passes it through.\n */\nexport function fromBackendEnvelope(\n status: number,\n envelope: BackendErrorEnvelope | null,\n requestId: string | null = null,\n): DashwiseError {\n const code = envelope?.code ?? codeFromStatus(status);\n const message = envelope?.message ?? `HTTP ${status}`;\n const context = envelope?.context;\n\n switch (code) {\n case DashwiseErrorCode.UNAUTHENTICATED:\n case DashwiseErrorCode.TOKEN_EXPIRED:\n return new UnauthenticatedError(message, requestId);\n case DashwiseErrorCode.FORBIDDEN:\n return new ForbiddenError(message, context, requestId);\n case DashwiseErrorCode.ROW_NOT_FOUND:\n return new RowNotFoundError(message, context, requestId);\n case DashwiseErrorCode.CONTRACT_VIOLATION:\n case DashwiseErrorCode.FIELD_NOT_READABLE:\n case DashwiseErrorCode.FILTER_OP_UNKNOWN:\n case DashwiseErrorCode.OPERATION_NOT_ALLOWED:\n return new ContractViolationError(message, context, requestId);\n case DashwiseErrorCode.VALIDATION_FAILED:\n return new ValidationError(message, context, requestId);\n case DashwiseErrorCode.DEPENDENCY_NOT_DECLARED:\n case DashwiseErrorCode.TABLE_NOT_IN_CONTRACT:\n return new DependencyContractError(code, message, context, requestId);\n case DashwiseErrorCode.PROVIDER_TABLE_MISSING:\n return new ProviderTableMissingError(message, context, requestId);\n case DashwiseErrorCode.OPERATION_NOT_ALLOWED_BY_PROVIDER:\n return new OperationNotAllowedByProviderError(message, context, requestId);\n case DashwiseErrorCode.DEP_UNBOUND:\n return new DepUnboundError(message, context, requestId);\n case DashwiseErrorCode.USES_UNBOUND:\n return new UsesUnboundError(message, context, requestId);\n case DashwiseErrorCode.USES_OP_NOT_ALLOWED:\n return new UsesOpNotAllowedError(message, context, requestId);\n case DashwiseErrorCode.CONTRACT_FIELD_MISSING:\n return new ContractFieldMissingError(message, context, requestId);\n case DashwiseErrorCode.LINK_FIELD_NOT_FOUND:\n case DashwiseErrorCode.NOT_A_LINK_FIELD:\n case DashwiseErrorCode.JOIN_NOT_LINKED:\n // `uses`-plane joins are unsupported in v1; the backend emits a 400\n // with this code. Map to JoinError so it lands in the same\n // \"your join can't be resolved\" family (code preserved for `err.code`).\n case DashwiseErrorCode.USES_JOIN_UNSUPPORTED:\n return new JoinError(code, message, context, requestId);\n case DashwiseErrorCode.ACTION_NOT_EXPOSED:\n case DashwiseErrorCode.ACTION_NOT_DECLARED:\n return new DepActionError(code, message, 403, context, requestId);\n case DashwiseErrorCode.ACTION_INPUT_INVALID:\n return new DepActionError(code, message, 400, context, requestId);\n case DashwiseErrorCode.ACTION_OUTPUT_INVALID:\n return new DepActionError(code, message, 500, context, requestId);\n case DashwiseErrorCode.ACTION_RATE_LIMITED:\n return new DepActionError(code, message, 429, context, requestId);\n case DashwiseErrorCode.ACTION_EXECUTION_FAILED:\n // ACTION_EXECUTION_FAILED arrives as a 200 envelope from the\n // backend (the host succeeded; the action body crashed). The\n // _callAction helper unwraps the envelope and synthesizes this\n // via the factory call — status 200 reflects \"the transport was\n // fine; the failure is in the application layer\".\n return new DepActionError(code, message, 200, context, requestId);\n default:\n return new DashwiseError(code, message, {\n status,\n retriable: envelope?.retriable ?? false,\n context,\n requestId,\n });\n }\n}\n\nfunction codeFromStatus(status: number): string {\n if (status === 401) return DashwiseErrorCode.UNAUTHENTICATED;\n if (status === 403) return DashwiseErrorCode.FORBIDDEN;\n if (status === 404) return DashwiseErrorCode.ROW_NOT_FOUND;\n if (status >= 500) return DashwiseErrorCode.INTERNAL_ERROR;\n return 'HTTP_ERROR';\n}\n"]}
|
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error model for @dashai/sdk.
|
|
3
|
+
*
|
|
4
|
+
* The backend speaks a structured error envelope:
|
|
5
|
+
*
|
|
6
|
+
* {
|
|
7
|
+
* "code": "ROW_NOT_FOUND",
|
|
8
|
+
* "message": "Row 123 not found in tasks",
|
|
9
|
+
* "retriable": false,
|
|
10
|
+
* "context": { ... }
|
|
11
|
+
* }
|
|
12
|
+
*
|
|
13
|
+
* This module wraps that envelope in a typed `DashwiseError` plus a small
|
|
14
|
+
* set of subclasses for the codes consumers most commonly want to branch
|
|
15
|
+
* on (network errors, auth failures, row-not-found, contract violations).
|
|
16
|
+
*
|
|
17
|
+
* Anything not matched by a specific subclass becomes a plain
|
|
18
|
+
* `DashwiseError` carrying the raw `code`. Branch on `.code` for codes
|
|
19
|
+
* we don't have a class for; use `instanceof` for the common cases.
|
|
20
|
+
*/
|
|
21
|
+
/**
|
|
22
|
+
* Known error codes. Not exhaustive — the backend emits many codes
|
|
23
|
+
* specific to individual modules / endpoints. Use these constants when
|
|
24
|
+
* you want compile-time safety; otherwise treat `err.code` as a string.
|
|
25
|
+
*
|
|
26
|
+
* The list is curated to the codes a module author is most likely to
|
|
27
|
+
* branch on. Adding a new code here is a non-breaking change.
|
|
28
|
+
*/
|
|
29
|
+
declare const DashwiseErrorCode: {
|
|
30
|
+
readonly UNAUTHENTICATED: "UNAUTHENTICATED";
|
|
31
|
+
readonly FORBIDDEN: "FORBIDDEN";
|
|
32
|
+
readonly TOKEN_EXPIRED: "TOKEN_EXPIRED";
|
|
33
|
+
readonly INSTALLATION_NOT_FOUND: "INSTALLATION_NOT_FOUND";
|
|
34
|
+
readonly INSTALLATION_MODE_UNSUPPORTED: "INSTALLATION_MODE_UNSUPPORTED";
|
|
35
|
+
readonly CONTRACT_VIOLATION: "CONTRACT_VIOLATION";
|
|
36
|
+
readonly FIELD_NOT_READABLE: "FIELD_NOT_READABLE";
|
|
37
|
+
readonly FILTER_OP_UNKNOWN: "FILTER_OP_UNKNOWN";
|
|
38
|
+
readonly OPERATION_NOT_ALLOWED: "OPERATION_NOT_ALLOWED";
|
|
39
|
+
readonly DEPENDENCY_NOT_DECLARED: "DEPENDENCY_NOT_DECLARED";
|
|
40
|
+
readonly TABLE_NOT_IN_CONTRACT: "TABLE_NOT_IN_CONTRACT";
|
|
41
|
+
readonly PROVIDER_TABLE_MISSING: "PROVIDER_TABLE_MISSING";
|
|
42
|
+
readonly OPERATION_NOT_ALLOWED_BY_PROVIDER: "OPERATION_NOT_ALLOWED_BY_PROVIDER";
|
|
43
|
+
readonly DEP_UNBOUND: "DEP_UNBOUND";
|
|
44
|
+
readonly USES_UNBOUND: "USES_UNBOUND";
|
|
45
|
+
readonly USES_OP_NOT_ALLOWED: "USES_OP_NOT_ALLOWED";
|
|
46
|
+
readonly CONTRACT_FIELD_MISSING: "CONTRACT_FIELD_MISSING";
|
|
47
|
+
readonly USES_JOIN_UNSUPPORTED: "USES_JOIN_UNSUPPORTED";
|
|
48
|
+
readonly LINK_FIELD_NOT_FOUND: "LINK_FIELD_NOT_FOUND";
|
|
49
|
+
readonly NOT_A_LINK_FIELD: "NOT_A_LINK_FIELD";
|
|
50
|
+
readonly JOIN_NOT_LINKED: "JOIN_NOT_LINKED";
|
|
51
|
+
readonly ACTION_NOT_EXPOSED: "ACTION_NOT_EXPOSED";
|
|
52
|
+
readonly ACTION_NOT_DECLARED: "ACTION_NOT_DECLARED";
|
|
53
|
+
readonly ACTION_INPUT_INVALID: "ACTION_INPUT_INVALID";
|
|
54
|
+
readonly ACTION_OUTPUT_INVALID: "ACTION_OUTPUT_INVALID";
|
|
55
|
+
readonly ACTION_RATE_LIMITED: "ACTION_RATE_LIMITED";
|
|
56
|
+
readonly ACTION_EXECUTION_FAILED: "ACTION_EXECUTION_FAILED";
|
|
57
|
+
readonly ROW_NOT_FOUND: "ROW_NOT_FOUND";
|
|
58
|
+
readonly TABLE_NOT_FOUND: "TABLE_NOT_FOUND";
|
|
59
|
+
readonly VALIDATION_FAILED: "VALIDATION_FAILED";
|
|
60
|
+
readonly ROW_LIMIT_EXCEEDED: "ROW_LIMIT_EXCEEDED";
|
|
61
|
+
readonly STORAGE_LIMIT_EXCEEDED: "STORAGE_LIMIT_EXCEEDED";
|
|
62
|
+
readonly OUTBOUND_NOT_ALLOWED: "OUTBOUND_NOT_ALLOWED";
|
|
63
|
+
readonly OUTBOUND_CONCURRENCY_LIMITED: "OUTBOUND_CONCURRENCY_LIMITED";
|
|
64
|
+
readonly NETWORK_ERROR: "NETWORK_ERROR";
|
|
65
|
+
readonly TIMEOUT: "TIMEOUT";
|
|
66
|
+
readonly INTERNAL_ERROR: "INTERNAL_ERROR";
|
|
67
|
+
};
|
|
68
|
+
type DashwiseErrorCode = (typeof DashwiseErrorCode)[keyof typeof DashwiseErrorCode];
|
|
69
|
+
/**
|
|
70
|
+
* Base class for every error thrown by @dashai/sdk. Carries the
|
|
71
|
+
* structured envelope from the backend (or a synthetic one for
|
|
72
|
+
* client-side failures like network errors / timeouts).
|
|
73
|
+
*
|
|
74
|
+
* Always thrown — never returned as a value. The async client methods
|
|
75
|
+
* `.list()` / `.get()` etc. reject with one of these on failure.
|
|
76
|
+
*/
|
|
77
|
+
declare class DashwiseError extends Error {
|
|
78
|
+
readonly code: string;
|
|
79
|
+
readonly status: number;
|
|
80
|
+
readonly retriable: boolean;
|
|
81
|
+
readonly context: Record<string, unknown> | undefined;
|
|
82
|
+
/**
|
|
83
|
+
* Backend-issued trace anchor (Phase 6 slice 6.2, 2026-05-19).
|
|
84
|
+
* Mirrors the `x-request-id` response header. Populated whenever
|
|
85
|
+
* the backend's `RuntimeQueryController` (or any future endpoint
|
|
86
|
+
* that echoes the header) is the origin of this error. `null` when
|
|
87
|
+
* the failure is client-side (NetworkError / TimeoutError — the
|
|
88
|
+
* request never reached the server, so there's no server-issued
|
|
89
|
+
* ID to surface).
|
|
90
|
+
*
|
|
91
|
+
* Use this as a debugging trace anchor when filing a bug against a
|
|
92
|
+
* specific failed query — the matching row in `module_query_log`
|
|
93
|
+
* carries the full backend context (ast_hash, error_code,
|
|
94
|
+
* duration_ms, etc.).
|
|
95
|
+
*/
|
|
96
|
+
readonly requestId: string | null;
|
|
97
|
+
constructor(code: string, message: string, options?: {
|
|
98
|
+
status?: number;
|
|
99
|
+
retriable?: boolean;
|
|
100
|
+
context?: Record<string, unknown>;
|
|
101
|
+
cause?: unknown;
|
|
102
|
+
/**
|
|
103
|
+
* Phase 6 slice 6.2: backend `x-request-id` response header,
|
|
104
|
+
* captured by the transport before throwing. Pass `undefined`
|
|
105
|
+
* (or omit) for client-side errors that never hit the server.
|
|
106
|
+
*/
|
|
107
|
+
requestId?: string | null;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
/** Network-level failure (DNS, connection refused, TLS, fetch threw). */
|
|
111
|
+
declare class NetworkError extends DashwiseError {
|
|
112
|
+
constructor(message: string, cause?: unknown);
|
|
113
|
+
}
|
|
114
|
+
/** Request exceeded the configured timeout (`timeoutMs`). */
|
|
115
|
+
declare class TimeoutError extends DashwiseError {
|
|
116
|
+
constructor(message: string, timeoutMs: number);
|
|
117
|
+
}
|
|
118
|
+
/** 401 — token missing/invalid. */
|
|
119
|
+
declare class UnauthenticatedError extends DashwiseError {
|
|
120
|
+
constructor(message?: string, requestId?: string | null);
|
|
121
|
+
}
|
|
122
|
+
/** 403 — caller lacks the role/scope for this operation. */
|
|
123
|
+
declare class ForbiddenError extends DashwiseError {
|
|
124
|
+
constructor(message: string, context?: Record<string, unknown>, requestId?: string | null);
|
|
125
|
+
}
|
|
126
|
+
/** 404 — `GET /db/<table>/<id>` for a missing or soft-deleted row. */
|
|
127
|
+
declare class RowNotFoundError extends DashwiseError {
|
|
128
|
+
constructor(message: string, context?: Record<string, unknown>, requestId?: string | null);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Schema-level rejection: dep contract violated, table not exposed, field
|
|
132
|
+
* not readable, filter op not allowed. Covers the family of "you asked for
|
|
133
|
+
* something the manifest doesn't permit" errors.
|
|
134
|
+
*/
|
|
135
|
+
declare class ContractViolationError extends DashwiseError {
|
|
136
|
+
constructor(message: string, context?: Record<string, unknown>, requestId?: string | null);
|
|
137
|
+
}
|
|
138
|
+
/** 422-ish — request body failed validation. Inspect `context` for field-level errors. */
|
|
139
|
+
declare class ValidationError extends DashwiseError {
|
|
140
|
+
constructor(message: string, context?: Record<string, unknown>, requestId?: string | null);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* 404 — the caller's `module.json#dependencies` doesn't declare a
|
|
144
|
+
* dependency on the requested provider module, OR the declared dep
|
|
145
|
+
* exists but its `reads[]` block doesn't include the requested table.
|
|
146
|
+
*
|
|
147
|
+
* Either way the fix is on the **caller's** side: update the manifest
|
|
148
|
+
* to declare the dep / add the table to `reads[]`, then re-publish.
|
|
149
|
+
*
|
|
150
|
+
* Covers both `DEPENDENCY_NOT_DECLARED` and `TABLE_NOT_IN_CONTRACT` —
|
|
151
|
+
* inspect `err.code` to distinguish if you need different UX per case.
|
|
152
|
+
*/
|
|
153
|
+
declare class DependencyContractError extends DashwiseError {
|
|
154
|
+
constructor(code: string, message: string, context?: Record<string, unknown>, requestId?: string | null);
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* 404 — the provider's physical table no longer exists. This means the
|
|
158
|
+
* provider published a version that dropped the table while the
|
|
159
|
+
* consumer's installation still pinned the old contract. Recovery is
|
|
160
|
+
* on the **provider's** side (republish with the table) or the
|
|
161
|
+
* workspace admin's (downgrade the provider, or upgrade the consumer
|
|
162
|
+
* to a version whose `dependencies[]` no longer references it).
|
|
163
|
+
*/
|
|
164
|
+
declare class ProviderTableMissingError extends DashwiseError {
|
|
165
|
+
constructor(message: string, context?: Record<string, unknown>, requestId?: string | null);
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* 403 — the provider's `exposes.operations.<verb>.allowed` is explicitly
|
|
169
|
+
* `false` for the requested verb. Distinct from `OPERATION_NOT_ALLOWED`
|
|
170
|
+
* (which is the **owner's** own-table policy) — `OPERATION_NOT_ALLOWED_BY_PROVIDER`
|
|
171
|
+
* is the provider opting out of letting depending modules use a verb.
|
|
172
|
+
*
|
|
173
|
+
* No caller-side fix; either the provider needs to flip the gate, or
|
|
174
|
+
* the consumer needs to find a different way to satisfy the use case.
|
|
175
|
+
*/
|
|
176
|
+
declare class OperationNotAllowedByProviderError extends DashwiseError {
|
|
177
|
+
constructor(message: string, context?: Record<string, unknown>, requestId?: string | null);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* The vocabulary of `unbound_reason` values a parked dependency can
|
|
181
|
+
* carry, surfaced in {@link DepUnboundError.reason}. Mirrors the
|
|
182
|
+
* backend's `module_dependencies.unbound_reason` enum (Phase 3
|
|
183
|
+
* modules-platform-v2). Not exhaustive by design — treat `.reason` as a
|
|
184
|
+
* string and branch on these constants when you want compile-time
|
|
185
|
+
* safety. Adding a new reason is a non-breaking change.
|
|
186
|
+
*
|
|
187
|
+
* Resolve/bind-time reasons (why the dep never bound):
|
|
188
|
+
* - `MISSING_DEPENDENCY` no install of the provider module in the workspace
|
|
189
|
+
* - `DEPENDENCY_VERSION_MISMATCH` an install exists but its version is outside the declared range
|
|
190
|
+
* - `PROVIDER_VERSION_RECORD_MISSING` the provider's version row is gone (data-integrity edge)
|
|
191
|
+
* - `EXPOSES_MISSING` the provider no longer exposes a table/field the dep reads
|
|
192
|
+
* - `EXPOSES_PRIVATE` the exposed surface is `private` to the consumer
|
|
193
|
+
* - `ACTION_NOT_EXPOSED` a declared dep action isn't exposed by the provider (Rule #11)
|
|
194
|
+
* - `PROVIDER_NOT_PRODUCTION` kind hygiene: a production consumer can only bind a production provider
|
|
195
|
+
*
|
|
196
|
+
* Lifecycle reasons (the dep bound once, then got parked):
|
|
197
|
+
* - `MANUALLY_UNBOUND` a workspace admin ran `deps unbind` / the unbind endpoint
|
|
198
|
+
* - `PROVIDER_UPGRADE_BROKE_CONTRACT` a provider upgrade (with `force`) broke this consumer's contract
|
|
199
|
+
* - `PROVIDER_UNINSTALLED` the provider was uninstalled with `park_consumers`
|
|
200
|
+
*/
|
|
201
|
+
declare const DepUnboundReason: {
|
|
202
|
+
readonly MISSING_DEPENDENCY: "MISSING_DEPENDENCY";
|
|
203
|
+
readonly DEPENDENCY_VERSION_MISMATCH: "DEPENDENCY_VERSION_MISMATCH";
|
|
204
|
+
readonly PROVIDER_VERSION_RECORD_MISSING: "PROVIDER_VERSION_RECORD_MISSING";
|
|
205
|
+
readonly EXPOSES_MISSING: "EXPOSES_MISSING";
|
|
206
|
+
readonly EXPOSES_PRIVATE: "EXPOSES_PRIVATE";
|
|
207
|
+
readonly ACTION_NOT_EXPOSED: "ACTION_NOT_EXPOSED";
|
|
208
|
+
readonly PROVIDER_NOT_PRODUCTION: "PROVIDER_NOT_PRODUCTION";
|
|
209
|
+
readonly MANUALLY_UNBOUND: "MANUALLY_UNBOUND";
|
|
210
|
+
readonly PROVIDER_UPGRADE_BROKE_CONTRACT: "PROVIDER_UPGRADE_BROKE_CONTRACT";
|
|
211
|
+
readonly PROVIDER_UNINSTALLED: "PROVIDER_UNINSTALLED";
|
|
212
|
+
};
|
|
213
|
+
type DepUnboundReason = (typeof DepUnboundReason)[keyof typeof DepUnboundReason];
|
|
214
|
+
/**
|
|
215
|
+
* 409 — a runtime read (borrowed-table `list` / `get`, query-plane
|
|
216
|
+
* `qb.deps.<slug>.<table>`, or a cross-module action) targeted a
|
|
217
|
+
* dependency whose `module_dependencies` row is `status='unbound'`
|
|
218
|
+
* (Phase 3 modules-platform-v2 dependency connect lifecycle).
|
|
219
|
+
*
|
|
220
|
+
* "Unbound" means the dependency is *declared* in the consumer's
|
|
221
|
+
* manifest but not *connected* to a provider installation. It happens
|
|
222
|
+
* when the resolver PARKED the dep at install/apply time (no provider
|
|
223
|
+
* in the workspace, version mismatch, exposes/action coverage gap) or
|
|
224
|
+
* when the dependency was later parked (manually unbound, provider
|
|
225
|
+
* upgrade broke the contract, provider uninstalled).
|
|
226
|
+
*
|
|
227
|
+
* This is a *recoverable* state, not a bug in the consumer. Catch it and
|
|
228
|
+
* render a "connect your provider" prompt — a workspace admin resolves it
|
|
229
|
+
* by installing/binding the provider (`dashwise deps bind <slug>` or the
|
|
230
|
+
* `POST /api/installations/:id/dependencies/:providerSlug/bind` endpoint).
|
|
231
|
+
* Once bound, the same read succeeds with no code change.
|
|
232
|
+
*
|
|
233
|
+
* Convenience accessors ({@link DepUnboundError.provider},
|
|
234
|
+
* {@link DepUnboundError.range}, {@link DepUnboundError.reason}) read the
|
|
235
|
+
* backend's `context: { provider, range, reason }` so callers don't have
|
|
236
|
+
* to reach into `err.context` by hand.
|
|
237
|
+
*
|
|
238
|
+
* @example
|
|
239
|
+
* ```ts
|
|
240
|
+
* import { DepUnboundError } from '@dashai/sdk';
|
|
241
|
+
*
|
|
242
|
+
* try {
|
|
243
|
+
* const contacts = await client.deps('crm').db<ContactRow>('contacts').list();
|
|
244
|
+
* // …or the typed builder: await qb.deps.crm.contacts.execute();
|
|
245
|
+
* } catch (err) {
|
|
246
|
+
* if (err instanceof DepUnboundError) {
|
|
247
|
+
* // Declared but not connected — show a connect-your-provider CTA.
|
|
248
|
+
* return <ConnectProvider provider={err.provider} range={err.range} reason={err.reason} />;
|
|
249
|
+
* }
|
|
250
|
+
* throw err;
|
|
251
|
+
* }
|
|
252
|
+
* ```
|
|
253
|
+
*/
|
|
254
|
+
declare class DepUnboundError extends DashwiseError {
|
|
255
|
+
constructor(message: string, context?: Record<string, unknown>, requestId?: string | null);
|
|
256
|
+
/**
|
|
257
|
+
* The provider module slug the parked dependency points at (kebab-case,
|
|
258
|
+
* e.g. `crm`). Read from `context.provider`; `undefined` if the backend
|
|
259
|
+
* omitted it.
|
|
260
|
+
*/
|
|
261
|
+
get provider(): string | undefined;
|
|
262
|
+
/**
|
|
263
|
+
* The SemVer range the consumer's manifest declared for this dependency
|
|
264
|
+
* (e.g. `^1.2.0`). Read from `context.range`; `undefined` if omitted.
|
|
265
|
+
*/
|
|
266
|
+
get range(): string | undefined;
|
|
267
|
+
/**
|
|
268
|
+
* Why the dependency is unbound — one of {@link DepUnboundReason} (but
|
|
269
|
+
* typed as `string` for forward-compat with reasons the backend may add).
|
|
270
|
+
* Read from `context.reason`; `undefined` if omitted.
|
|
271
|
+
*/
|
|
272
|
+
get reason(): string | undefined;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* The vocabulary of `reason` values a parked `uses` binding can carry,
|
|
276
|
+
* surfaced in {@link UsesUnboundError.reason}. Mirrors the backend's
|
|
277
|
+
* `module_table_bindings` unbound_reason enum for this plane
|
|
278
|
+
* (Phase 4 modules-platform-v2). Not exhaustive by design — treat
|
|
279
|
+
* `.reason` as a string; branch on these constants for compile-time
|
|
280
|
+
* safety. Adding a new reason is non-breaking.
|
|
281
|
+
*
|
|
282
|
+
* - `NOT_BOUND_YET` the slot has never been bound (declared
|
|
283
|
+
* but no workspace table connected yet)
|
|
284
|
+
* - `AMBIGUOUS_MATCH` auto-match found >1 candidate table; a
|
|
285
|
+
* human must pick one (`dashwise bind`)
|
|
286
|
+
* - `NO_MATCH` auto-match found no candidate table
|
|
287
|
+
* - `TABLE_DELETED` the bound table was trashed (or a mapped
|
|
288
|
+
* field drifted away) → the row parked
|
|
289
|
+
* - `OPS_WIDENED_PENDING_CONSENT` the manifest widened `ops` beyond what
|
|
290
|
+
* was consented at bind time; re-bind to
|
|
291
|
+
* refresh consent
|
|
292
|
+
* - `MANUALLY_UNBOUND` a workspace admin ran `dashwise unbind`
|
|
293
|
+
*/
|
|
294
|
+
declare const UsesUnboundReason: {
|
|
295
|
+
readonly NOT_BOUND_YET: "NOT_BOUND_YET";
|
|
296
|
+
readonly AMBIGUOUS_MATCH: "AMBIGUOUS_MATCH";
|
|
297
|
+
readonly NO_MATCH: "NO_MATCH";
|
|
298
|
+
readonly TABLE_DELETED: "TABLE_DELETED";
|
|
299
|
+
readonly OPS_WIDENED_PENDING_CONSENT: "OPS_WIDENED_PENDING_CONSENT";
|
|
300
|
+
readonly MANUALLY_UNBOUND: "MANUALLY_UNBOUND";
|
|
301
|
+
};
|
|
302
|
+
type UsesUnboundReason = (typeof UsesUnboundReason)[keyof typeof UsesUnboundReason];
|
|
303
|
+
/**
|
|
304
|
+
* 409 — a runtime read/write against a `uses` table whose
|
|
305
|
+
* `module_table_bindings` row is not `status='bound'` (Phase 4
|
|
306
|
+
* modules-platform-v2 workspace-table binding lifecycle).
|
|
307
|
+
*
|
|
308
|
+
* "Unbound" means the workspace-table slot is *declared* in the module's
|
|
309
|
+
* manifest `uses` block but not *connected* to a physical workspace
|
|
310
|
+
* table. It happens when install-time auto-match parked the slot (no
|
|
311
|
+
* candidate / ambiguous candidates / a write contract that never
|
|
312
|
+
* auto-binds), the bound table was later trashed, the manifest widened
|
|
313
|
+
* `ops` beyond consent, or an admin manually unbound it.
|
|
314
|
+
*
|
|
315
|
+
* A *recoverable* state, not a bug. Catch it and render a "connect a
|
|
316
|
+
* table" prompt — a workspace admin resolves it by binding a workspace
|
|
317
|
+
* table to the slot (`dashwise bind <uses_slug>` / the
|
|
318
|
+
* `PUT /api/installations/:id/bindings/:usesSlug` endpoint). Once bound,
|
|
319
|
+
* the same call succeeds with no code change.
|
|
320
|
+
*
|
|
321
|
+
* Convenience accessors read the backend's `context: { uses_slug, reason }`.
|
|
322
|
+
*
|
|
323
|
+
* @example
|
|
324
|
+
* ```ts
|
|
325
|
+
* import { UsesUnboundError } from '@dashai/sdk';
|
|
326
|
+
*
|
|
327
|
+
* try {
|
|
328
|
+
* const staff = await client.uses('employees').db<EmployeeRow>('employees').list();
|
|
329
|
+
* // …or the typed builder: await qb.uses.employees.execute();
|
|
330
|
+
* } catch (err) {
|
|
331
|
+
* if (err instanceof UsesUnboundError) {
|
|
332
|
+
* return <BindWorkspaceTable slot={err.usesSlug} reason={err.reason} />;
|
|
333
|
+
* }
|
|
334
|
+
* throw err;
|
|
335
|
+
* }
|
|
336
|
+
* ```
|
|
337
|
+
*/
|
|
338
|
+
declare class UsesUnboundError extends DashwiseError {
|
|
339
|
+
constructor(message: string, context?: Record<string, unknown>, requestId?: string | null);
|
|
340
|
+
/**
|
|
341
|
+
* The manifest `uses[].tables[].slug` of the unbound slot (kebab-case,
|
|
342
|
+
* e.g. `employees`). Read from `context.uses_slug`; `undefined` if the
|
|
343
|
+
* backend omitted it.
|
|
344
|
+
*/
|
|
345
|
+
get usesSlug(): string | undefined;
|
|
346
|
+
/**
|
|
347
|
+
* Why the slot is unbound — one of {@link UsesUnboundReason} (typed as
|
|
348
|
+
* `string` for forward-compat with reasons the backend may add). Read
|
|
349
|
+
* from `context.reason`; `undefined` if omitted.
|
|
350
|
+
*/
|
|
351
|
+
get reason(): string | undefined;
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* 403 — a `uses`-plane operation that isn't in the binding's enforced
|
|
355
|
+
* operation set (the manifest's declared `ops` INTERSECT the admin's
|
|
356
|
+
* `consented_ops` at bind time). E.g. the manifest declares
|
|
357
|
+
* `ops: ['read','update']` but the admin consented only to `read` when
|
|
358
|
+
* binding, so an `update` is rejected.
|
|
359
|
+
*
|
|
360
|
+
* Fix: either narrow the call to a consented op, or widen the manifest
|
|
361
|
+
* `ops` + have an admin re-bind (which refreshes `consented_ops`).
|
|
362
|
+
*
|
|
363
|
+
* `err.op` / `err.usesSlug` read the backend's `context: { uses_slug, op }`.
|
|
364
|
+
*/
|
|
365
|
+
declare class UsesOpNotAllowedError extends DashwiseError {
|
|
366
|
+
constructor(message: string, context?: Record<string, unknown>, requestId?: string | null);
|
|
367
|
+
/** The `uses` slot slug the rejected op targeted. Read from `context.uses_slug`. */
|
|
368
|
+
get usesSlug(): string | undefined;
|
|
369
|
+
/**
|
|
370
|
+
* The operation that was rejected — one of `create` / `read` /
|
|
371
|
+
* `update` / `delete`. Read from `context.op`; `undefined` if omitted.
|
|
372
|
+
*/
|
|
373
|
+
get op(): string | undefined;
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* 409 — a field the `uses` binding's `field_map` points at no longer
|
|
377
|
+
* exists on the physical workspace table (schema drift: the table owner
|
|
378
|
+
* deleted or renamed the column after the bind). The backend best-effort
|
|
379
|
+
* parks the binding (reason `TABLE_DELETED`/field-drift) on detection.
|
|
380
|
+
*
|
|
381
|
+
* Recovery is the workspace admin's: re-bind the slot to a table that
|
|
382
|
+
* still has the field, or re-map the field (`dashwise bind <uses_slug>
|
|
383
|
+
* --map <usesField>=<physicalField>`).
|
|
384
|
+
*
|
|
385
|
+
* `err.field` / `err.usesSlug` read the backend's
|
|
386
|
+
* `context: { uses_slug, field }`.
|
|
387
|
+
*/
|
|
388
|
+
declare class ContractFieldMissingError extends DashwiseError {
|
|
389
|
+
constructor(message: string, context?: Record<string, unknown>, requestId?: string | null);
|
|
390
|
+
/** The `uses` slot slug whose contract broke. Read from `context.uses_slug`. */
|
|
391
|
+
get usesSlug(): string | undefined;
|
|
392
|
+
/**
|
|
393
|
+
* The declared field slug (the `uses` side name) whose mapped physical
|
|
394
|
+
* field is gone. Read from `context.field`; `undefined` if omitted.
|
|
395
|
+
*/
|
|
396
|
+
get field(): string | undefined;
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* 400 — `.join()` / `.leftJoin()` referenced a target the manifest
|
|
400
|
+
* can't resolve. Covers the three sub-cases above; inspect
|
|
401
|
+
* `err.code` to distinguish.
|
|
402
|
+
*
|
|
403
|
+
* Author-side fix in every case: either correct the slug, or pass
|
|
404
|
+
* an explicit `on` argument to bypass link-field inference.
|
|
405
|
+
*/
|
|
406
|
+
declare class JoinError extends DashwiseError {
|
|
407
|
+
constructor(code: string, message: string, context?: Record<string, unknown>, requestId?: string | null);
|
|
408
|
+
}
|
|
409
|
+
interface BackendErrorEnvelope {
|
|
410
|
+
code?: string;
|
|
411
|
+
message?: string;
|
|
412
|
+
retriable?: boolean;
|
|
413
|
+
context?: Record<string, unknown>;
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Build a typed `DashwiseError` from the backend's response envelope.
|
|
417
|
+
*
|
|
418
|
+
* The mapping picks the most specific subclass for codes we have a class
|
|
419
|
+
* for; everything else becomes a plain `DashwiseError` carrying the raw
|
|
420
|
+
* code. This keeps the type set small while still letting consumers
|
|
421
|
+
* branch on string codes when they want to.
|
|
422
|
+
*
|
|
423
|
+
* Phase 6 slice 6.2 (2026-05-19): accepts an optional `requestId` —
|
|
424
|
+
* the backend's `x-request-id` response header — and threads it onto
|
|
425
|
+
* every produced error so consumers can use it as a debugging trace
|
|
426
|
+
* anchor. Default `null` for backward compat; the transport always
|
|
427
|
+
* passes it through.
|
|
428
|
+
*/
|
|
429
|
+
declare function fromBackendEnvelope(status: number, envelope: BackendErrorEnvelope | null, requestId?: string | null): DashwiseError;
|
|
430
|
+
|
|
431
|
+
export { ContractFieldMissingError as C, DepUnboundError as D, ForbiddenError as F, JoinError as J, NetworkError as N, OperationNotAllowedByProviderError as O, ProviderTableMissingError as P, RowNotFoundError as R, TimeoutError as T, UnauthenticatedError as U, ValidationError as V, DepUnboundReason as a, DependencyContractError as b, ContractViolationError as c, DashwiseError as d, DashwiseErrorCode as e, UsesOpNotAllowedError as f, UsesUnboundError as g, UsesUnboundReason as h, fromBackendEnvelope as i };
|