@szdatatalk/sqlward 0.3.0 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ SqlWard
2
+ Copyright 2026 Suzhou DataTalk Information Technology Co., Ltd. (苏州数说信息科技有限公司)
3
+
4
+ This product includes SqlWard (https://github.com/shygoly/sqlward | https://www.npmjs.com/package/@szdatatalk/sqlward), developed by Suzhou DataTalk Information Technology Co., Ltd.
package/index.d.ts CHANGED
@@ -1,18 +1,202 @@
1
+ /**
2
+ * `@szdatatalk/sqlward` — Offline, zero-Python Pure-Rust WebAssembly runtime for
3
+ * column-level SQL lineage (8 dialects), fail-closed M6 SQL security guardrails,
4
+ * transitive column ACLs, cryptographic decision receipts, and dbt/OMOP/Robot adapters.
5
+ *
6
+ * Never executes SQL and never requires a database connection.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { instantiateWasm } from "@szdatatalk/sqlward";
11
+ *
12
+ * const sw = await instantiateWasm();
13
+ * const lineage = sw.parseColumn({
14
+ * dialect: "postgres",
15
+ * sql: "INSERT INTO dws.orders (id, net) SELECT id, amount - discount FROM ods.orders",
16
+ * });
17
+ * ```
18
+ * @packageDocumentation
19
+ */
20
+
1
21
  export const PROMOTED: true;
2
- export const CONTRACT_VERSION: "0.3.0";
22
+ export const CONTRACT_VERSION: "0.3.3";
3
23
  export const MAX_WASM_INPUT_BYTES: 1048576;
24
+ export const MAX_WASM_DBT_INPUT_BYTES: 8388608;
25
+
26
+ /** Supported SQL dialects parsed offline in Rust + WebAssembly. */
27
+ export type SqlDialect =
28
+ | "postgres"
29
+ | "mysql"
30
+ | "doris"
31
+ | "starrocks"
32
+ | "oracle"
33
+ | "spark"
34
+ | "hive"
35
+ | "tsql";
4
36
 
5
37
  export interface LineageEdge {
6
38
  sourceTable: string;
7
39
  sourceColumn: string;
8
40
  targetTable: string;
9
41
  targetColumn: string;
10
- dependencyType: string;
42
+ dependencyType: "DIRECT" | "INDIRECT" | "Direct" | "Indirect" | string;
11
43
  relation: string;
12
44
  transformExpr?: string | null;
13
45
  maskingApplied?: boolean;
14
46
  }
15
47
 
48
+ export interface ParseColumnRequest {
49
+ dialect: SqlDialect | string;
50
+ sql: string;
51
+ catalogSchema?: Record<string, string[]>;
52
+ defaultSchema?: string;
53
+ preserveAsWritten?: boolean;
54
+ [key: string]: unknown;
55
+ }
56
+
57
+ export interface ParseColumnStatement {
58
+ statementIndex?: number;
59
+ status?: string;
60
+ edges: LineageEdge[];
61
+ notes?: string[];
62
+ [key: string]: unknown;
63
+ }
64
+
65
+ export interface ParseColumnResult {
66
+ status: "OK" | "INCONCLUSIVE" | "ERROR" | string;
67
+ statements: ParseColumnStatement[];
68
+ notes?: string[];
69
+ [key: string]: unknown;
70
+ }
71
+
72
+ export interface PolicyRelationMetadata {
73
+ kind: "table" | "view" | string;
74
+ sensitivityLabels?: string[];
75
+ columns?: string[];
76
+ columnLabels?: Record<string, string[]>;
77
+ viewSql?: string;
78
+ [key: string]: unknown;
79
+ }
80
+
81
+ export interface PolicySnapshot {
82
+ policyId: string;
83
+ policyVersion: string;
84
+ profile: "read-only" | "analysis" | "custom" | string;
85
+ relations: Record<string, PolicyRelationMetadata>;
86
+ deniedLabels?: string[];
87
+ enforceColumnAcl?: boolean;
88
+ allowMultipleStatements?: boolean;
89
+ allowWriteStatements?: boolean;
90
+ allowUnknownFunctions?: boolean;
91
+ allowUnknownRelations?: boolean;
92
+ allowedFunctions?: string[];
93
+ allowedRoles?: string[];
94
+ allowedTenants?: string[];
95
+ columnGrants?: Array<{
96
+ principalOrRole: string;
97
+ relation: string;
98
+ column: string;
99
+ effect: "ALLOW" | "DENY";
100
+ }>;
101
+ [key: string]: unknown;
102
+ }
103
+
104
+ export interface TrustedPrincipal {
105
+ principalId: string;
106
+ tenantId: string;
107
+ roles: string[];
108
+ }
109
+
110
+ export interface PolicyEvaluationRequest {
111
+ dialect: SqlDialect | string;
112
+ sql: string;
113
+ snapshot: PolicySnapshot;
114
+ principal: TrustedPrincipal;
115
+ caseSettingProvided?: boolean;
116
+ [key: string]: unknown;
117
+ }
118
+
119
+ export interface PolicyDecisionReport {
120
+ contractVersion: string;
121
+ decision: "ALLOW" | "DENY" | string;
122
+ parseStatus: string;
123
+ sqlHash: string;
124
+ statementCount: number;
125
+ reasonCodes: string[];
126
+ reasonDetails: string[];
127
+ diagnostics: unknown[];
128
+ [key: string]: unknown;
129
+ }
130
+
131
+ export interface DbtAnalysisRequest {
132
+ /** Raw dbt `manifest.json` string or parsed JSON object. */
133
+ manifest: Record<string, unknown> | string;
134
+ /** Optional raw dbt `catalog.json` string or parsed JSON object. */
135
+ catalog?: Record<string, unknown> | string | null;
136
+ /** Optional raw dbt `run_results.json` string or parsed JSON object. */
137
+ run_results?: Record<string, unknown> | string | null;
138
+ /** Run SQL column-level lineage extraction on compiled model SQL (default `true`). */
139
+ analyze_sql?: boolean;
140
+ analyzeSql?: boolean;
141
+ [key: string]: unknown;
142
+ }
143
+
144
+ export interface DbtProjectSnapshot {
145
+ contract_version: string;
146
+ operation: string;
147
+ status: string;
148
+ snapshot_id: string;
149
+ evidence_id: string;
150
+ dialect: string;
151
+ protected_decision_allowed: boolean;
152
+ nodes: Array<Record<string, unknown>>;
153
+ edges: {
154
+ declared: Array<Record<string, unknown>>;
155
+ inferred: Array<Record<string, unknown>>;
156
+ };
157
+ completeness: {
158
+ capability_gaps?: string[];
159
+ [key: string]: unknown;
160
+ };
161
+ diagnostics: Array<Record<string, unknown>>;
162
+ [key: string]: unknown;
163
+ }
164
+
165
+ export interface DbtDiffRequest {
166
+ base: DbtProjectSnapshot | Record<string, unknown>;
167
+ head: DbtProjectSnapshot | Record<string, unknown>;
168
+ }
169
+
170
+ export interface DbtSnapshotDiff {
171
+ contract_version: string;
172
+ operation: string;
173
+ base_snapshot_id: string;
174
+ head_snapshot_id: string;
175
+ added_nodes: string[];
176
+ removed_nodes: string[];
177
+ added_declared_edges: Array<Record<string, unknown>>;
178
+ removed_declared_edges: Array<Record<string, unknown>>;
179
+ added_inferred_edges: Array<Record<string, unknown>>;
180
+ removed_inferred_edges: Array<Record<string, unknown>>;
181
+ }
182
+
183
+ export interface DbtImpactRequest {
184
+ snapshot: DbtProjectSnapshot | Record<string, unknown>;
185
+ origin_node: string;
186
+ direction?: "downstream" | "upstream" | "both";
187
+ max_hops?: number;
188
+ }
189
+
190
+ export interface DbtImpactResult {
191
+ contract_version: string;
192
+ operation: string;
193
+ origin_node: string;
194
+ direction: string;
195
+ impacted_nodes: string[];
196
+ depth_by_node: Record<string, number>;
197
+ impacted_inferred_columns: string[];
198
+ }
199
+
16
200
  export interface EdgeComparisonReport {
17
201
  matchCount: number;
18
202
  missingInActual: string[];
@@ -32,19 +216,123 @@ export interface WasmVersionInfo {
32
216
  export interface SqlWardWasmInstance {
33
217
  promoted: true;
34
218
  maxInputBytes: number;
219
+ maxDbtInputBytes: number;
220
+
221
+ /** Return runtime version, supported dialects, and input byte ceilings. */
35
222
  versionInfo(): WasmVersionInfo;
36
- parseColumn(request: Record<string, unknown> | string): Record<string, unknown>;
37
- evaluatePolicy(request: Record<string, unknown> | string): Record<string, unknown>;
223
+
224
+ /**
225
+ * Extract deterministic column-level SQL lineage (`DIRECT` / `INDIRECT` edges) offline.
226
+ *
227
+ * @example
228
+ * ```ts
229
+ * const res = sw.parseColumn({
230
+ * dialect: "postgres",
231
+ * sql: "INSERT INTO dws.orders (id, net) SELECT id, amount - discount FROM ods.orders",
232
+ * });
233
+ * console.log(res.status, res.statements[0].edges);
234
+ * ```
235
+ */
236
+ parseColumn(request: ParseColumnRequest | string): ParseColumnResult;
237
+
238
+ /**
239
+ * Evaluate fail-closed M6 SQL security policy (read-only/analysis/custom profiles,
240
+ * write/DDL/dynamic-SQL/locking rejection, and transitive view/CTE column ACLs).
241
+ *
242
+ * @example
243
+ * ```ts
244
+ * const decision = sw.evaluatePolicy({
245
+ * dialect: "postgres",
246
+ * sql: "DELETE FROM ods.orders",
247
+ * snapshot: {
248
+ * policyId: "pol-1",
249
+ * policyVersion: "1.0.0",
250
+ * profile: "read-only",
251
+ * relations: { "ods.orders": { kind: "table", sensitivityLabels: [] } },
252
+ * },
253
+ * principal: { principalId: "u1", tenantId: "t1", roles: ["analyst"] },
254
+ * });
255
+ * // decision.decision === "DENY"
256
+ * ```
257
+ */
258
+ evaluatePolicy(request: PolicyEvaluationRequest | string): PolicyDecisionReport;
259
+
260
+ /** Compile and cache a `PolicySnapshot` in WASM memory for repeated low-latency evaluations. */
261
+ preparePolicySnapshot(request: Record<string, unknown> | string): Record<string, unknown>;
262
+
263
+ /** Evaluate SQL against a previously prepared cached policy snapshot handle. */
264
+ evaluatePolicyPrepared(request: Record<string, unknown> | string): PolicyDecisionReport;
265
+
266
+ /** Evict a cached prepared policy snapshot from WASM memory. */
267
+ evictPolicySnapshot(request: Record<string, unknown> | string): Record<string, unknown>;
268
+
269
+ /** Verify constant-time HMAC-SHA256 M6 policy decision receipts. */
38
270
  verifyReceipt(request: Record<string, unknown> | string): Record<string, unknown>;
271
+
272
+ /** Verify sealed workflow evidence bundles. */
39
273
  verifyWorkflowEvidence(bundle: Record<string, unknown> | string): Record<string, unknown>;
274
+
275
+ /** Schema-grounded column binding against a catalog snapshot (`binding-report/v1`). */
40
276
  bind(request: Record<string, unknown> | string): Record<string, unknown>;
41
- analyzeDbt(request: Record<string, unknown> | string): Record<string, unknown>;
277
+
278
+ /**
279
+ * Analyze a dbt project (`manifest.json` + optional `catalog.json` / `run_results.json`)
280
+ * in a single WASM call with automatic lossless slimming (`slim: true` by default).
281
+ * For large manifests (> 8 MiB after slimming), prefer {@link analyzeDbtBatched}.
282
+ */
283
+ analyzeDbt(request: DbtAnalysisRequest | string, options?: { slim?: boolean }): DbtProjectSnapshot;
284
+
285
+ /**
286
+ * Compute structural & column-level lineage diff between base and head dbt snapshots.
287
+ *
288
+ * @example
289
+ * ```ts
290
+ * const diff = sw.diffDbt({ base: baseSnap, head: headSnap });
291
+ * console.log(diff.added_nodes, diff.removed_inferred_edges);
292
+ * ```
293
+ */
294
+ diffDbt(request: DbtDiffRequest | string): DbtSnapshotDiff;
295
+
296
+ /**
297
+ * Compute bounded upstream/downstream blast-radius impact from a dbt node.
298
+ *
299
+ * @example
300
+ * ```ts
301
+ * const impact = sw.impactDbt({
302
+ * snapshot: headSnap,
303
+ * origin_node: "model.analytics.stg_orders",
304
+ * direction: "downstream",
305
+ * max_hops: 6,
306
+ * });
307
+ * ```
308
+ */
309
+ impactDbt(request: DbtImpactRequest | string): DbtImpactResult;
310
+
311
+ /** Re-seal canonical `snapshot_id` and `evidence_id` digests on a dbt snapshot. */
312
+ sealDbt(snapshot: DbtProjectSnapshot | Record<string, unknown> | string): DbtProjectSnapshot;
313
+
314
+ /** Profile OMOP CDM 5.4 clinical lineage (`omop-lineage-profile/v1`). */
42
315
  profileOmop(request: Record<string, unknown> | string): Record<string, unknown>;
316
+
317
+ /** Gate protected clinical column changes (`mapping-impact-analysis/v1`). */
43
318
  analyzeMappingImpact(request: Record<string, unknown> | string): Record<string, unknown>;
319
+
320
+ /** Query sealed RobotDataOps artifact lineage impact (`robot-artifact-lineage/v1`). */
44
321
  queryRobotImpact(query: Record<string, unknown> | string): Record<string, unknown>;
322
+
323
+ /** Verify offline HMAC-SHA256 control-plane entitlements (`control-plane-interop/v1`). */
45
324
  verifyInterop(request: Record<string, unknown> | string): Record<string, unknown>;
325
+
326
+ /** Retrieve ranked, sensitivity-redacted semantic schema context for Text-to-SQL prompts. */
327
+ retrieveContext(request: Record<string, unknown> | string): Record<string, unknown>;
328
+
329
+ /** Compute canonical SHA-256 lineage graph digest from column edges. */
46
330
  graphDigestFromEdges(edges: LineageEdge[] | string): string;
331
+
332
+ /** Traverse downstream impacted columns from a `(table, column)` origin. */
47
333
  impactDownstream(edges: LineageEdge[] | string, originTable: string, originColumn: string): unknown;
334
+
335
+ /** Traverse upstream source columns for a `(table, column)` target. */
48
336
  impactUpstream(edges: LineageEdge[] | string, originTable: string, originColumn: string): unknown;
49
337
  }
50
338
 
@@ -64,6 +352,8 @@ export type WasmWorkerOperation =
64
352
  | "verifyWorkflowEvidence"
65
353
  | "bind"
66
354
  | "analyzeDbt"
355
+ | "diffDbt"
356
+ | "impactDbt"
67
357
  | "profileOmop"
68
358
  | "analyzeMappingImpact"
69
359
  | "queryRobotImpact"
@@ -76,9 +366,59 @@ export function compareEdges(
76
366
  expectedDirect: Omit<LineageEdge, "dependencyType">[],
77
367
  expectedIndirect: Omit<LineageEdge, "dependencyType">[],
78
368
  ): EdgeComparisonReport;
369
+
370
+ /**
371
+ * Load and instantiate the bundled Pure-Rust `sqlward_wasm.wasm` module.
372
+ *
373
+ * @example
374
+ * ```ts
375
+ * import { instantiateWasm } from "@szdatatalk/sqlward";
376
+ *
377
+ * const sw = await instantiateWasm();
378
+ * console.log(sw.versionInfo());
379
+ * ```
380
+ */
79
381
  export function instantiateWasm(wasmSource?: string | Uint8Array | ArrayBuffer): Promise<SqlWardWasmInstance>;
382
+
383
+ /** Execute a bounded WASM operation inside an isolated Node Worker thread with timeout & AbortSignal support. */
80
384
  export function runWasmWorker(
81
385
  operation: WasmWorkerOperation,
82
386
  payload: unknown,
83
387
  options?: WasmWorkerOptions,
84
388
  ): Promise<unknown>;
389
+
390
+ /** Losslessly strip non-lineage bulk fields from a dbt `manifest.json` while keeping DAG & compiled SQL intact. */
391
+ export function slimDbtManifest(
392
+ manifest: Record<string, unknown> | string,
393
+ options?: { includeCompiledCode?: boolean; onlyModelIds?: string[] | null },
394
+ ): Record<string, unknown>;
395
+
396
+ /** Losslessly strip non-column metadata from a dbt `catalog.json`. */
397
+ export function slimDbtCatalog(
398
+ catalog: Record<string, unknown> | string | null | undefined,
399
+ ): Record<string, unknown> | null;
400
+
401
+ /**
402
+ * Analyze arbitrary-size dbt projects offline with automatic lossless manifest slimming,
403
+ * Worker batching, and bit-for-bit `snapshot_id` & `evidence_id` parity with single-shot analysis.
404
+ *
405
+ * @example
406
+ * ```ts
407
+ * import fs from "node:fs";
408
+ * import { analyzeDbtBatched } from "@szdatatalk/sqlward";
409
+ *
410
+ * const snap = await analyzeDbtBatched(
411
+ * {
412
+ * manifest: fs.readFileSync("target/manifest.json", "utf8"),
413
+ * catalog: fs.readFileSync("target/catalog.json", "utf8"),
414
+ * analyze_sql: true,
415
+ * },
416
+ * { batchSize: 50, useWorker: true },
417
+ * );
418
+ * console.log(snap.snapshot_id, snap.edges.inferred.length);
419
+ * ```
420
+ */
421
+ export function analyzeDbtBatched(
422
+ request: DbtAnalysisRequest,
423
+ options?: WasmWorkerOptions & { batchSize?: number; maxBatchBytes?: number; useWorker?: boolean },
424
+ ): Promise<DbtProjectSnapshot>;
package/index.js CHANGED
@@ -1,24 +1,151 @@
1
1
  /**
2
- * Offline Node & WASM runtime SDK (`@szdatatalk/sqlward`, v0.3.0).
2
+ * Offline Node & WASM runtime SDK (`@szdatatalk/sqlward`, v0.3.3).
3
3
  *
4
4
  * Zero Python dependency, zero compiler required at runtime, zero network access.
5
5
  * Executes `sqlward_wasm.wasm` directly in-process or inside a terminable
6
- * `node:worker_threads` Worker with 1 MiB byte bounds for 8-dialect SQL parsing,
7
- * column lineage, graph digest/impact, M6 policy/receipt/workflow verification,
8
- * and pure-Rust domain adapters (bind, dbt, OMOP, robot, interop). Never executes SQL.
6
+ * `node:worker_threads` Worker with 1 MiB byte bounds for single-SQL calls and
7
+ * 8 MiB + lossless manifest slimming + automatic model batching for dbt projects.
8
+ * Never executes SQL.
9
9
  */
10
10
 
11
+ import { createHash } from "node:crypto";
11
12
  import fs from "node:fs";
12
13
  import path from "node:path";
13
14
  import { fileURLToPath } from "node:url";
14
15
  import { Worker } from "node:worker_threads";
15
16
 
16
17
  export const PROMOTED = true;
17
- export const CONTRACT_VERSION = "0.3.0";
18
+ export const CONTRACT_VERSION = "0.3.3";
18
19
  export const MAX_WASM_INPUT_BYTES = 1_048_576;
20
+ export const MAX_WASM_DBT_INPUT_BYTES = 8 * 1_048_576;
21
+
22
+ const KNOWN_MANIFEST_KEYS = new Set([
23
+ "metadata",
24
+ "nodes",
25
+ "sources",
26
+ "macros",
27
+ "docs",
28
+ "exposures",
29
+ "metrics",
30
+ "groups",
31
+ "selectors",
32
+ "disabled",
33
+ "parent_map",
34
+ "child_map",
35
+ "group_map",
36
+ "saved_queries",
37
+ "semantic_models",
38
+ "unit_tests",
39
+ ]);
40
+ const KNOWN_CATALOG_KEYS = new Set(["metadata", "nodes", "sources", "errors"]);
41
+ const sealWasmCache = new Map();
42
+
43
+ function getCachedSealWasm(wasmPath) {
44
+ if (!sealWasmCache.has(wasmPath)) {
45
+ const p = instantiateWasm(wasmPath).catch((err) => {
46
+ sealWasmCache.delete(wasmPath);
47
+ throw err;
48
+ });
49
+ sealWasmCache.set(wasmPath, p);
50
+ }
51
+ return sealWasmCache.get(wasmPath);
52
+ }
53
+
54
+ function computeArtifactOverride(rawInput, parsedObj, knownKeys) {
55
+ let bytes;
56
+ if (typeof rawInput === "string") {
57
+ bytes = Buffer.from(rawInput, "utf8");
58
+ } else {
59
+ bytes = Buffer.from(JSON.stringify(sortJsonKeys(parsedObj)), "utf8");
60
+ }
61
+ let ignored = 0;
62
+ for (const k of Object.keys(parsedObj)) {
63
+ if (!knownKeys.has(k)) ignored += 1;
64
+ }
65
+ return {
66
+ sha256: createHash("sha256").update(bytes).digest("hex"),
67
+ size_bytes: bytes.byteLength,
68
+ ignored_additive_fields: ignored,
69
+ };
70
+ }
71
+
72
+ function collectCompiledSqlSha256(parsedManifest) {
73
+ const out = new Map();
74
+ for (const group of DBT_MANIFEST_GROUPS) {
75
+ const grp = parsedManifest[group];
76
+ if (!grp || typeof grp !== "object" || Array.isArray(grp)) continue;
77
+ for (const [uid, entry] of Object.entries(grp)) {
78
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
79
+ const c1 = typeof entry.compiled_code === "string" ? entry.compiled_code.trim() : "";
80
+ const c2 = typeof entry.compiled_sql === "string" ? entry.compiled_sql.trim() : "";
81
+ const sql = c1 || c2;
82
+ if (sql) {
83
+ out.set(uid, createHash("sha256").update(sql, "utf8").digest("hex"));
84
+ }
85
+ }
86
+ }
87
+ return out;
88
+ }
89
+
90
+ function cmpOptStr(a, b) {
91
+ const aNull = a === null || a === undefined;
92
+ const bNull = b === null || b === undefined;
93
+ if (aNull && bNull) return 0;
94
+ if (aNull) return -1;
95
+ if (bNull) return 1;
96
+ return a < b ? -1 : a > b ? 1 : 0;
97
+ }
98
+
99
+ function cmpInferredEdge(a, b) {
100
+ return (
101
+ cmpOptStr(a.namespace, b.namespace) ||
102
+ cmpOptStr(a.from_node, b.from_node) ||
103
+ cmpOptStr(a.from_relation, b.from_relation) ||
104
+ cmpOptStr(a.from_column, b.from_column) ||
105
+ cmpOptStr(a.to_node, b.to_node) ||
106
+ cmpOptStr(a.to_relation, b.to_relation) ||
107
+ cmpOptStr(a.to_column, b.to_column) ||
108
+ cmpOptStr(a.relation, b.relation) ||
109
+ cmpOptStr(a.detail, b.detail) ||
110
+ cmpOptStr(a.reason, b.reason) ||
111
+ (a.masking_applied === b.masking_applied ? 0 : a.masking_applied ? 1 : -1)
112
+ );
113
+ }
114
+
115
+ function cmpDiagnostic(a, b) {
116
+ return (
117
+ cmpOptStr(a.code, b.code) ||
118
+ cmpOptStr(a.severity, b.severity) ||
119
+ cmpOptStr(a.message, b.message) ||
120
+ cmpOptStr(a.scope_id, b.scope_id)
121
+ );
122
+ }
19
123
 
20
124
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
21
125
 
126
+ const DBT_MANIFEST_GROUPS = [
127
+ "nodes",
128
+ "sources",
129
+ "exposures",
130
+ "metrics",
131
+ "seeds",
132
+ "snapshots",
133
+ "semantic_models",
134
+ "saved_queries",
135
+ "unit_tests",
136
+ ];
137
+
138
+ const DBT_METADATA_KEYS = [
139
+ "dbt_schema_version",
140
+ "dbt_version",
141
+ "adapter_type",
142
+ "project_id",
143
+ "project_name",
144
+ "target_name",
145
+ "invocation_id",
146
+ "generated_at",
147
+ ];
148
+
22
149
  export function defaultWasmPath() {
23
150
  if (process.env.SQLWARD_WASM_PATH) {
24
151
  return process.env.SQLWARD_WASM_PATH;
@@ -42,6 +169,165 @@ export function defaultWasmPath() {
42
169
  return candidates[0];
43
170
  }
44
171
 
172
+ function parseJsonObjectInput(value, fieldName) {
173
+ if (value && typeof value === "object" && !Array.isArray(value)) {
174
+ return value;
175
+ }
176
+ if (typeof value === "string") {
177
+ const trimmed = value.trim();
178
+ if (!trimmed) {
179
+ throw new TypeError(`INVALID_ARTIFACT_JSON: ${fieldName} string is empty`);
180
+ }
181
+ let parsed;
182
+ try {
183
+ parsed = JSON.parse(trimmed);
184
+ } catch (err) {
185
+ throw new TypeError(`INVALID_ARTIFACT_JSON: ${fieldName} is not valid JSON (${err.message})`);
186
+ }
187
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
188
+ throw new TypeError(`INVALID_ARTIFACT_JSON: ${fieldName} must decode to a JSON object`);
189
+ }
190
+ return parsed;
191
+ }
192
+ throw new TypeError(
193
+ `INVALID_ARTIFACT_JSON: ${fieldName} must be a JSON object or JSON object string`,
194
+ );
195
+ }
196
+
197
+ /**
198
+ * Losslessly slim a dbt `manifest.json` (object or JSON string) by stripping
199
+ * non-lineage bloat (raw_code, descriptions, docs, macros, meta, patch_path, etc.)
200
+ * while preserving 100% of lineage, DAG, ephemeral CTE, and provenance fields.
201
+ */
202
+ export function slimDbtManifest(manifestInput, options = {}) {
203
+ const { includeCompiledCode = true, onlyModelIds = null } = options;
204
+ const src = parseJsonObjectInput(manifestInput, "manifest");
205
+ const out = {};
206
+
207
+ if (src.metadata && typeof src.metadata === "object" && !Array.isArray(src.metadata)) {
208
+ const meta = {};
209
+ for (const k of DBT_METADATA_KEYS) {
210
+ if (src.metadata[k] !== undefined && src.metadata[k] !== null) {
211
+ meta[k] = src.metadata[k];
212
+ }
213
+ }
214
+ out.metadata = meta;
215
+ }
216
+
217
+ if (src.parent_map && typeof src.parent_map === "object" && !Array.isArray(src.parent_map)) {
218
+ out.parent_map = src.parent_map;
219
+ }
220
+
221
+ const modelFilter = onlyModelIds ? new Set(onlyModelIds) : null;
222
+
223
+ for (const group of DBT_MANIFEST_GROUPS) {
224
+ const grp = src[group];
225
+ if (!grp || typeof grp !== "object" || Array.isArray(grp)) continue;
226
+ const slimGroup = {};
227
+ for (const [uid, entry] of Object.entries(grp)) {
228
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
229
+ const slim = {};
230
+ for (const k of [
231
+ "unique_id",
232
+ "resource_type",
233
+ "name",
234
+ "alias",
235
+ "identifier",
236
+ "database",
237
+ "schema",
238
+ "version",
239
+ "latest_version",
240
+ "original_file_path",
241
+ ]) {
242
+ if (entry[k] !== undefined && entry[k] !== null) slim[k] = entry[k];
243
+ }
244
+ if (entry.quoting && typeof entry.quoting === "object") {
245
+ slim.quoting = {
246
+ database: Boolean(entry.quoting.database),
247
+ schema: Boolean(entry.quoting.schema),
248
+ identifier: Boolean(entry.quoting.identifier),
249
+ };
250
+ }
251
+ if (entry.config && typeof entry.config === "object" && entry.config.materialized) {
252
+ slim.config = { materialized: entry.config.materialized };
253
+ }
254
+ if (entry.depends_on && Array.isArray(entry.depends_on.nodes)) {
255
+ slim.depends_on = { nodes: entry.depends_on.nodes };
256
+ }
257
+ if (includeCompiledCode && (!modelFilter || modelFilter.has(uid))) {
258
+ const sql = entry.compiled_code ?? entry.compiled_sql;
259
+ if (typeof sql === "string" && sql.trim().length > 0) {
260
+ slim.compiled_code = sql;
261
+ }
262
+ }
263
+ slimGroup[uid] = slim;
264
+ }
265
+ out[group] = slimGroup;
266
+ }
267
+
268
+ return out;
269
+ }
270
+
271
+ /**
272
+ * Losslessly slim a dbt `catalog.json` (object or JSON string) to only
273
+ * relation metadata and column names required for schema grounding.
274
+ */
275
+ export function slimDbtCatalog(catalogInput) {
276
+ if (catalogInput === undefined || catalogInput === null) return null;
277
+ const src = parseJsonObjectInput(catalogInput, "catalog");
278
+ const out = {};
279
+ if (src.metadata && typeof src.metadata === "object" && !Array.isArray(src.metadata)) {
280
+ const meta = {};
281
+ for (const k of DBT_METADATA_KEYS) {
282
+ if (src.metadata[k] !== undefined && src.metadata[k] !== null) {
283
+ meta[k] = src.metadata[k];
284
+ }
285
+ }
286
+ out.metadata = meta;
287
+ }
288
+ for (const group of ["nodes", "sources"]) {
289
+ const grp = src[group];
290
+ if (!grp || typeof grp !== "object" || Array.isArray(grp)) continue;
291
+ const slimGroup = {};
292
+ for (const [uid, entry] of Object.entries(grp)) {
293
+ if (!entry || typeof entry !== "object") continue;
294
+ const m = entry.metadata && typeof entry.metadata === "object" ? entry.metadata : {};
295
+ const cols = {};
296
+ if (entry.columns && typeof entry.columns === "object") {
297
+ for (const colName of Object.keys(entry.columns)) {
298
+ cols[colName] = {};
299
+ }
300
+ }
301
+ slimGroup[uid] = {
302
+ metadata: {
303
+ database: m.database ?? null,
304
+ schema: m.schema ?? null,
305
+ name: m.name ?? null,
306
+ },
307
+ columns: cols,
308
+ };
309
+ }
310
+ out[group] = slimGroup;
311
+ }
312
+ return out;
313
+ }
314
+
315
+ function sortJsonKeys(v) {
316
+ if (Array.isArray(v)) return v.map(sortJsonKeys);
317
+ if (v && typeof v === "object") {
318
+ const out = {};
319
+ for (const k of Object.keys(v).sort()) {
320
+ out[k] = sortJsonKeys(v[k]);
321
+ }
322
+ return out;
323
+ }
324
+ return v;
325
+ }
326
+
327
+ function canonicalSha256Hex(v) {
328
+ return createHash("sha256").update(JSON.stringify(sortJsonKeys(v))).digest("hex");
329
+ }
330
+
45
331
  export function edgeKey(edge) {
46
332
  return [
47
333
  edge.sourceTable,
@@ -105,16 +391,23 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
105
391
  const wasmLastPtr = ex.sw_wasm_last_ptr || ex.lk_wasm_last_ptr;
106
392
  const wasmLastLen = ex.sw_wasm_last_len || ex.lk_wasm_last_len;
107
393
  const wasmMaxInputBytes = ex.sw_wasm_max_input_bytes || ex.lk_wasm_max_input_bytes;
394
+ const wasmMaxDbtInputBytes = ex.sw_wasm_max_dbt_input_bytes;
108
395
  const wasmGraphDigest = ex.sw_wasm_graph_digest || ex.lk_wasm_graph_digest;
109
396
  const wasmImpactDownstream = ex.sw_wasm_impact_downstream || ex.lk_wasm_impact_downstream;
110
397
  const wasmImpactUpstream = ex.sw_wasm_impact_upstream || ex.lk_wasm_impact_upstream;
111
398
  const encoder = new TextEncoder();
112
399
  const decoder = new TextDecoder("utf-8", { fatal: true });
400
+ const maxDbtBytes =
401
+ typeof wasmMaxDbtInputBytes === "function"
402
+ ? Number(wasmMaxDbtInputBytes())
403
+ : MAX_WASM_DBT_INPUT_BYTES;
113
404
 
114
- function writeUtf8(str) {
405
+ function writeUtf8(str, limitBytes = MAX_WASM_INPUT_BYTES) {
115
406
  const encoded = encoder.encode(str);
116
- if (encoded.byteLength > MAX_WASM_INPUT_BYTES) {
117
- throw new RangeError("WASM_INPUT_TOO_LARGE: payload exceeds 1 MiB limit");
407
+ if (encoded.byteLength > limitBytes) {
408
+ throw new RangeError(
409
+ `WASM_INPUT_TOO_LARGE: payload (${encoded.byteLength} bytes) exceeds ${limitBytes} byte limit`,
410
+ );
118
411
  }
119
412
  if (encoded.byteLength === 0) {
120
413
  return { ptr: 0, len: 0 };
@@ -151,12 +444,12 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
151
444
  );
152
445
  }
153
446
 
154
- function callSingleJson(fn, payload) {
447
+ function callSingleJson(fn, payload, limitBytes = MAX_WASM_INPUT_BYTES) {
155
448
  if (typeof fn !== "function") {
156
- throw new Error("WASM_EXPORT_MISSING: rebuild sqlward_wasm.wasm >= 0.3.0");
449
+ throw new Error("WASM_EXPORT_MISSING: rebuild sqlward_wasm.wasm >= 0.3.1");
157
450
  }
158
451
  const json = typeof payload === "string" ? payload : JSON.stringify(payload);
159
- const buf = writeUtf8(json);
452
+ const buf = writeUtf8(json, limitBytes);
160
453
  try {
161
454
  const rc = fn(buf.ptr, buf.len);
162
455
  const text = readLastResult();
@@ -170,6 +463,7 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
170
463
  return {
171
464
  promoted: true,
172
465
  maxInputBytes: Number(wasmMaxInputBytes()),
466
+ maxDbtInputBytes: maxDbtBytes,
173
467
  versionInfo() {
174
468
  if (typeof ex.sw_wasm_version_info !== "function") {
175
469
  return { version: CONTRACT_VERSION, promoted: true, sqlParseInWasm: false };
@@ -185,6 +479,15 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
185
479
  evaluatePolicy(request) {
186
480
  return callSingleJson(ex.sw_wasm_policy_eval, request);
187
481
  },
482
+ preparePolicySnapshot(request) {
483
+ return callSingleJson(ex.sw_wasm_prepare_policy, request);
484
+ },
485
+ evaluatePolicyPrepared(request) {
486
+ return callSingleJson(ex.sw_wasm_policy_eval_prepared, request);
487
+ },
488
+ evictPolicySnapshot(request) {
489
+ return callSingleJson(ex.sw_wasm_evict_policy, request);
490
+ },
188
491
  verifyReceipt(request) {
189
492
  return callSingleJson(ex.sw_wasm_receipt_verify, request);
190
493
  },
@@ -194,8 +497,54 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
194
497
  bind(request) {
195
498
  return callSingleJson(ex.sw_wasm_bind, request);
196
499
  },
197
- analyzeDbt(request) {
198
- return callSingleJson(ex.sw_wasm_dbt_analyze, request);
500
+ analyzeDbt(request, options = {}) {
501
+ const { slim = true } = options;
502
+ let payload = request;
503
+ if (slim && request && typeof request === "object" && !Array.isArray(request)) {
504
+ const prepared = { ...request };
505
+ const existingOverrides = prepared.artifact_overrides ?? prepared.artifactOverrides;
506
+ const overrides =
507
+ existingOverrides && typeof existingOverrides === "object"
508
+ ? { ...existingOverrides }
509
+ : {};
510
+ if (prepared.manifest !== undefined) {
511
+ const parsedManifest = parseJsonObjectInput(prepared.manifest, "manifest");
512
+ if (!overrides.manifest) {
513
+ overrides.manifest = computeArtifactOverride(
514
+ prepared.manifest,
515
+ parsedManifest,
516
+ KNOWN_MANIFEST_KEYS,
517
+ );
518
+ }
519
+ prepared.manifest = slimDbtManifest(parsedManifest);
520
+ }
521
+ if (prepared.catalog !== undefined && prepared.catalog !== null) {
522
+ const parsedCatalog = parseJsonObjectInput(prepared.catalog, "catalog");
523
+ if (!overrides.catalog) {
524
+ overrides.catalog = computeArtifactOverride(
525
+ prepared.catalog,
526
+ parsedCatalog,
527
+ KNOWN_CATALOG_KEYS,
528
+ );
529
+ }
530
+ prepared.catalog = slimDbtCatalog(parsedCatalog);
531
+ }
532
+ if (Object.keys(overrides).length > 0) {
533
+ delete prepared.artifactOverrides;
534
+ prepared.artifact_overrides = overrides;
535
+ }
536
+ payload = prepared;
537
+ }
538
+ return callSingleJson(ex.sw_wasm_dbt_analyze, payload, maxDbtBytes);
539
+ },
540
+ diffDbt(request) {
541
+ return callSingleJson(ex.sw_wasm_dbt_diff, request, maxDbtBytes);
542
+ },
543
+ impactDbt(request) {
544
+ return callSingleJson(ex.sw_wasm_dbt_impact, request, maxDbtBytes);
545
+ },
546
+ sealDbt(snapshot) {
547
+ return callSingleJson(ex.sw_wasm_dbt_seal, snapshot, maxDbtBytes);
199
548
  },
200
549
  profileOmop(request) {
201
550
  return callSingleJson(ex.sw_wasm_omop_profile, request);
@@ -209,6 +558,9 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
209
558
  verifyInterop(request) {
210
559
  return callSingleJson(ex.sw_wasm_interop_verify, request);
211
560
  },
561
+ retrieveContext(request) {
562
+ return callSingleJson(ex.sw_wasm_context_retrieve, request);
563
+ },
212
564
  graphDigestFromEdges(edges) {
213
565
  const json = normalizeEdgesPayload(edges);
214
566
  const buf = writeUtf8(json);
@@ -272,10 +624,14 @@ export async function instantiateWasm(wasmSource = defaultWasmPath()) {
272
624
 
273
625
  /**
274
626
  * Execute WASM analysis inside a terminable worker thread (`AbortSignal` + `timeoutMs`).
627
+ * Worker exits after each call so WASM linear memory is fully reclaimed by the OS.
275
628
  */
276
629
  export function runWasmWorker(operation, payload, options = {}) {
277
630
  const { timeoutMs = 5000, signal, wasmPath = defaultWasmPath() } = options;
278
631
  const workerScript = path.join(__dirname, "wasm-worker.js");
632
+ const isDbtOp =
633
+ operation === "analyzeDbt" || operation === "diffDbt" || operation === "impactDbt";
634
+ const maxBytes = isDbtOp ? MAX_WASM_DBT_INPUT_BYTES : MAX_WASM_INPUT_BYTES;
279
635
 
280
636
  return new Promise((resolve, reject) => {
281
637
  if (signal?.aborted) {
@@ -288,13 +644,14 @@ export function runWasmWorker(operation, payload, options = {}) {
288
644
  : typeof payload?.edges === "string"
289
645
  ? payload.edges
290
646
  : JSON.stringify(payload ?? {});
291
- if (Buffer.byteLength(rawJson, "utf8") > MAX_WASM_INPUT_BYTES) {
292
- reject(new RangeError("WASM_INPUT_TOO_LARGE: payload exceeds 1 MiB limit"));
647
+ if (Buffer.byteLength(rawJson, "utf8") > maxBytes) {
648
+ reject(new RangeError(`WASM_INPUT_TOO_LARGE: payload exceeds ${maxBytes} byte limit`));
293
649
  return;
294
650
  }
295
651
 
296
652
  const worker = new Worker(workerScript, {
297
653
  workerData: { operation, payload, wasmPath },
654
+ execArgv: [],
298
655
  });
299
656
  let settled = false;
300
657
  let cancelReason = null;
@@ -339,3 +696,248 @@ export function runWasmWorker(operation, payload, options = {}) {
339
696
  });
340
697
  });
341
698
  }
699
+
700
+ /**
701
+ * Analyze an arbitrarily large dbt project in pure WASM via lossless manifest slimming
702
+ * plus automatic chunked SQL inference (optional per-batch Worker isolation so WASM
703
+ * linear memory never accumulates across batches).
704
+ */
705
+ export async function analyzeDbtBatched(request, options = {}) {
706
+ const {
707
+ wasmPath = defaultWasmPath(),
708
+ batchSize = 50,
709
+ maxBatchBytes = 4 * 1_048_576,
710
+ useWorker = true,
711
+ timeoutMs = 30_000,
712
+ signal,
713
+ } = options;
714
+
715
+ if (!request || typeof request !== "object" || Array.isArray(request)) {
716
+ throw new TypeError("INVALID_REQUEST: analyzeDbtBatched requires a request object");
717
+ }
718
+ const parsedManifest = parseJsonObjectInput(request.manifest, "manifest");
719
+ const parsedCatalog =
720
+ request.catalog !== undefined && request.catalog !== null
721
+ ? parseJsonObjectInput(request.catalog, "catalog")
722
+ : null;
723
+ const slimmedFull = slimDbtManifest(parsedManifest, { includeCompiledCode: true });
724
+ const slimmedCatalog = parsedCatalog !== null ? slimDbtCatalog(parsedCatalog) : null;
725
+
726
+ const existingOverrides = request.artifact_overrides ?? request.artifactOverrides;
727
+ const artifactOverrides = {
728
+ ...(existingOverrides && typeof existingOverrides === "object" ? existingOverrides : {}),
729
+ };
730
+ if (!artifactOverrides.manifest) {
731
+ artifactOverrides.manifest = computeArtifactOverride(
732
+ request.manifest,
733
+ parsedManifest,
734
+ KNOWN_MANIFEST_KEYS,
735
+ );
736
+ }
737
+ if (parsedCatalog !== null && !artifactOverrides.catalog) {
738
+ artifactOverrides.catalog = computeArtifactOverride(
739
+ request.catalog,
740
+ parsedCatalog,
741
+ KNOWN_CATALOG_KEYS,
742
+ );
743
+ }
744
+
745
+ const analyzeSql = request.analyze_sql ?? request.analyzeSql ?? true;
746
+ const sqlModelIds = [];
747
+ if (analyzeSql && slimmedFull.nodes && typeof slimmedFull.nodes === "object") {
748
+ for (const [uid, entry] of Object.entries(slimmedFull.nodes)) {
749
+ const rtype = entry.resource_type || "model";
750
+ const isEph = entry.config?.materialized === "ephemeral";
751
+ const sql = entry.compiled_code || entry.compiled_sql;
752
+ if (rtype === "model" && !isEph && typeof sql === "string" && sql.trim().length > 0) {
753
+ sqlModelIds.push(uid);
754
+ }
755
+ }
756
+ }
757
+ sqlModelIds.sort();
758
+
759
+ const {
760
+ manifest: _m,
761
+ catalog: _c,
762
+ analyzeSql: _as1,
763
+ analyze_sql: _as2,
764
+ runResults: reqRunResultsCamel,
765
+ run_results: reqRunResultsSnake,
766
+ modelIds: _mi1,
767
+ model_ids: _mi2,
768
+ artifactOverrides: _ao1,
769
+ artifact_overrides: _ao2,
770
+ ...restReq
771
+ } = request;
772
+ const runResultsVal = reqRunResultsSnake ?? reqRunResultsCamel ?? null;
773
+
774
+ const baseReq = {
775
+ ...restReq,
776
+ manifest: slimmedFull,
777
+ ...(slimmedCatalog !== null ? { catalog: slimmedCatalog } : {}),
778
+ ...(runResultsVal !== null ? { run_results: runResultsVal } : {}),
779
+ artifact_overrides: artifactOverrides,
780
+ analyze_sql: analyzeSql,
781
+ };
782
+
783
+ const singleBytes = Buffer.byteLength(JSON.stringify(baseReq), "utf8");
784
+ const execOne = async (payload) => {
785
+ if (useWorker) {
786
+ return runWasmWorker("analyzeDbt", payload, { wasmPath, timeoutMs, signal });
787
+ }
788
+ const wasm = await instantiateWasm(wasmPath);
789
+ return wasm.analyzeDbt(payload, { slim: false });
790
+ };
791
+
792
+ if (!analyzeSql || (sqlModelIds.length <= batchSize && singleBytes <= maxBatchBytes)) {
793
+ return execOne(baseReq);
794
+ }
795
+
796
+ // Pass 1: DAG skeleton without compiled_code (fast, tiny linear memory footprint),
797
+ // anchored to the original raw artifact provenance overrides.
798
+ const skeletonManifest = slimDbtManifest(parsedManifest, { includeCompiledCode: false });
799
+ const skeleton = await execOne({
800
+ ...restReq,
801
+ manifest: skeletonManifest,
802
+ ...(slimmedCatalog !== null ? { catalog: slimmedCatalog } : {}),
803
+ ...(runResultsVal !== null ? { run_results: runResultsVal } : {}),
804
+ artifact_overrides: artifactOverrides,
805
+ analyze_sql: false,
806
+ });
807
+
808
+ // Preserve compiled_sql_sha256 for ALL nodes (including ephemeral models, snapshots, tests)
809
+ const compiledSqlShaByUid = collectCompiledSqlSha256(parsedManifest);
810
+
811
+ // Pass 2: Partition SQL models into bounded batches (both count & byte capped)
812
+ const batches = [];
813
+ let current = [];
814
+ let currentSqlBytes = 0;
815
+ const skeletonBytes = Buffer.byteLength(JSON.stringify(skeletonManifest), "utf8");
816
+ const catalogBytes = slimmedCatalog
817
+ ? Buffer.byteLength(JSON.stringify(slimmedCatalog), "utf8")
818
+ : 0;
819
+ const fixedOverhead = skeletonBytes + catalogBytes + 16_384;
820
+ const sqlBudgetPerBatch = Math.max(256 * 1024, maxBatchBytes - fixedOverhead);
821
+
822
+ for (const uid of sqlModelIds) {
823
+ const sqlLen = Buffer.byteLength(slimmedFull.nodes[uid].compiled_code || "", "utf8");
824
+ if (
825
+ current.length > 0 &&
826
+ (current.length >= batchSize || currentSqlBytes + sqlLen > sqlBudgetPerBatch)
827
+ ) {
828
+ batches.push(current);
829
+ current = [];
830
+ currentSqlBytes = 0;
831
+ }
832
+ current.push(uid);
833
+ currentSqlBytes += sqlLen;
834
+ }
835
+ if (current.length > 0) batches.push(current);
836
+
837
+ const inferredMap = new Map();
838
+ const diagMap = new Map();
839
+ const scopeMap = new Map();
840
+ const nodePatchMap = new Map();
841
+
842
+ for (const d of skeleton.diagnostics || []) {
843
+ diagMap.set(`${d.code}|${d.severity}|${d.scope_id ?? ""}|${d.message}`, d);
844
+ }
845
+
846
+ for (const batchIds of batches) {
847
+ const batchManifest = slimDbtManifest(parsedManifest, {
848
+ includeCompiledCode: true,
849
+ onlyModelIds: batchIds,
850
+ });
851
+ const part = await execOne({
852
+ ...restReq,
853
+ manifest: batchManifest,
854
+ ...(slimmedCatalog !== null ? { catalog: slimmedCatalog } : {}),
855
+ run_results: null,
856
+ sources: null,
857
+ analyze_sql: true,
858
+ model_ids: batchIds,
859
+ });
860
+
861
+ for (const e of part.edges?.inferred || []) {
862
+ const k = JSON.stringify([
863
+ e.from_node,
864
+ e.from_relation,
865
+ e.from_column,
866
+ e.to_node,
867
+ e.to_relation,
868
+ e.to_column,
869
+ e.relation,
870
+ e.detail,
871
+ e.reason,
872
+ e.masking_applied,
873
+ ]);
874
+ inferredMap.set(k, e);
875
+ }
876
+ for (const d of part.diagnostics || []) {
877
+ diagMap.set(`${d.code}|${d.severity}|${d.scope_id ?? ""}|${d.message}`, d);
878
+ }
879
+ for (const s of part.completeness?.scopes || []) {
880
+ scopeMap.set(s.scope_id, s);
881
+ }
882
+ for (const n of part.nodes || []) {
883
+ if (batchIds.includes(n.unique_id)) {
884
+ nodePatchMap.set(n.unique_id, {
885
+ compiled_sql_sha256: n.compiled_sql_sha256,
886
+ ephemeral_resolution: n.ephemeral_resolution,
887
+ });
888
+ }
889
+ }
890
+ }
891
+
892
+ // Merge deterministically back into skeleton
893
+ const mergedNodes = (skeleton.nodes || []).map((n) => {
894
+ const patch = nodePatchMap.get(n.unique_id);
895
+ const fullSha = compiledSqlShaByUid.get(n.unique_id) ?? null;
896
+ if (patch) {
897
+ return {
898
+ ...n,
899
+ ...patch,
900
+ compiled_sql_sha256: patch.compiled_sql_sha256 ?? fullSha,
901
+ };
902
+ }
903
+ return fullSha !== null ? { ...n, compiled_sql_sha256: fullSha } : n;
904
+ });
905
+ const mergedInferred = [...inferredMap.values()].sort(cmpInferredEdge);
906
+ const mergedDiagnostics = [...diagMap.values()].sort(cmpDiagnostic);
907
+ const mergedScopes = [...scopeMap.values()].sort((a, b) =>
908
+ a.scope_id < b.scope_id ? -1 : a.scope_id > b.scope_id ? 1 : 0,
909
+ );
910
+
911
+ const hasErrors = mergedDiagnostics.some((d) => d.severity === "ERROR");
912
+ const hasInconclusive =
913
+ mergedScopes.some((s) => s.level === "inconclusive") ||
914
+ mergedDiagnostics.some((d) => d.severity === "INCONCLUSIVE");
915
+ const catalogPresent = Boolean(skeleton.completeness?.catalog_present);
916
+ const capabilityGaps = catalogPresent ? [] : ["CATALOG_ABSENT"];
917
+
918
+ const mergedEdges = {
919
+ declared: skeleton.edges?.declared || [],
920
+ inferred: mergedInferred,
921
+ };
922
+ const mergedCompleteness = {
923
+ ...skeleton.completeness,
924
+ overall: hasInconclusive ? "inconclusive" : catalogPresent ? "complete" : "partial",
925
+ requires_caller_acceptance: hasInconclusive || !catalogPresent,
926
+ capability_gaps: capabilityGaps,
927
+ scopes: mergedScopes,
928
+ };
929
+ const mergedSnapshot = {
930
+ ...skeleton,
931
+ status: hasErrors ? "ERROR" : hasInconclusive ? "INCONCLUSIVE" : "OK",
932
+ nodes: mergedNodes,
933
+ edges: mergedEdges,
934
+ completeness: mergedCompleteness,
935
+ diagnostics: mergedDiagnostics,
936
+ protected_decision_allowed: !hasErrors && !hasInconclusive && catalogPresent,
937
+ };
938
+
939
+ // Seal in-process with Rust WASM (2–5 ms, zero Worker spawn overhead) so canonical sorting,
940
+ // float serialization, snapshot_id, and evidence_id match single-shot byte-for-byte.
941
+ const sealWasm = await getCachedSealWasm(wasmPath);
942
+ return sealWasm.sealDbt(mergedSnapshot);
943
+ }
package/package.json CHANGED
@@ -1,7 +1,16 @@
1
1
  {
2
2
  "name": "@szdatatalk/sqlward",
3
- "version": "0.3.0",
3
+ "version": "0.3.3",
4
4
  "license": "Apache-2.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/shygoly/sqlward.git",
8
+ "directory": "packages/wasm"
9
+ },
10
+ "homepage": "https://github.com/shygoly/sqlward#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/shygoly/sqlward/issues"
13
+ },
5
14
  "description": "Zero-Python WASM runtime for SqlWard: 8-dialect SQL lineage, M6 security policy, receipts, and dbt/OMOP/Robot/M5 adapters",
6
15
  "type": "module",
7
16
  "main": "index.js",
@@ -18,7 +27,8 @@
18
27
  "wasm-worker.js",
19
28
  "wasm/sqlward_wasm.wasm",
20
29
  "README.md",
21
- "LICENSE"
30
+ "LICENSE",
31
+ "NOTICE"
22
32
  ],
23
33
  "keywords": [
24
34
  "szdatatalk",
@@ -37,7 +47,7 @@
37
47
  "access": "public"
38
48
  },
39
49
  "scripts": {
40
- "stage-wasm": "node -e \"const fs=require('fs'),p=require('path');const dst=p.resolve('wasm/sqlward_wasm.wasm');const srcs=[p.resolve('../../native/target/wasm32-unknown-unknown/release/sqlward_wasm.wasm'),p.resolve('../../evidence/phase2/artifacts/wasm/sqlward_wasm.wasm')];const src=srcs.find((s)=>fs.existsSync(s));if(src){fs.mkdirSync(p.dirname(dst),{recursive:true});fs.copyFileSync(src,dst);}if(!fs.existsSync(dst)){throw new Error('Missing wasm/sqlward_wasm.wasm; build sqlward-wasm first');}const lic=p.resolve('../../LICENSE');if(fs.existsSync(lic))fs.copyFileSync(lic,p.resolve('LICENSE'));\"",
50
+ "stage-wasm": "node -e \"const fs=require('fs'),p=require('path');const dst=p.resolve('wasm/sqlward_wasm.wasm');const srcs=[p.resolve('../../native/target/wasm32-unknown-unknown/release/sqlward_wasm.wasm'),p.resolve('../../evidence/phase2/artifacts/wasm/sqlward_wasm.wasm')];const src=srcs.find((s)=>fs.existsSync(s));if(src){fs.mkdirSync(p.dirname(dst),{recursive:true});fs.copyFileSync(src,dst);}if(!fs.existsSync(dst)){throw new Error('Missing wasm/sqlward_wasm.wasm; build sqlward-wasm first');}for(const f of ['LICENSE','NOTICE']){const s=p.resolve('../../'+f);if(fs.existsSync(s))fs.copyFileSync(s,p.resolve(f));}\"",
41
51
  "prepack": "npm run stage-wasm",
42
52
  "test": "node --test test/contract.test.js"
43
53
  },
Binary file
package/wasm-worker.js CHANGED
@@ -29,6 +29,10 @@ async function main() {
29
29
  result = wasm.bind(payload);
30
30
  } else if (operation === "analyzeDbt") {
31
31
  result = wasm.analyzeDbt(payload);
32
+ } else if (operation === "diffDbt") {
33
+ result = wasm.diffDbt(payload);
34
+ } else if (operation === "impactDbt") {
35
+ result = wasm.impactDbt(payload);
32
36
  } else if (operation === "profileOmop") {
33
37
  result = wasm.profileOmop(payload);
34
38
  } else if (operation === "analyzeMappingImpact") {
@@ -37,6 +41,8 @@ async function main() {
37
41
  result = wasm.queryRobotImpact(payload);
38
42
  } else if (operation === "verifyInterop") {
39
43
  result = wasm.verifyInterop(payload);
44
+ } else if (operation === "retrieveContext") {
45
+ result = wasm.retrieveContext(payload);
40
46
  } else {
41
47
  throw new Error(`unsupported WASM worker operation: ${operation}`);
42
48
  }