@hypequery/protocol 0.27.0 → 0.29.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.
Files changed (74) hide show
  1. package/dist/cache-preimages/cache-preimages.d.ts.map +1 -1
  2. package/dist/cache-preimages/cache-preimages.js +22 -0
  3. package/dist/deployments/codec.d.ts +8 -0
  4. package/dist/deployments/codec.d.ts.map +1 -1
  5. package/dist/deployments/codec.js +11 -1
  6. package/dist/deployments/events.d.ts +10 -0
  7. package/dist/deployments/events.d.ts.map +1 -0
  8. package/dist/deployments/events.js +59 -0
  9. package/dist/deployments/index.d.ts +8 -4
  10. package/dist/deployments/index.d.ts.map +1 -1
  11. package/dist/deployments/index.js +5 -2
  12. package/dist/deployments/sql-source-analysis.d.ts +29 -0
  13. package/dist/deployments/sql-source-analysis.d.ts.map +1 -0
  14. package/dist/deployments/sql-source-analysis.js +264 -0
  15. package/dist/deployments/sql-source.d.ts +8 -0
  16. package/dist/deployments/sql-source.d.ts.map +1 -0
  17. package/dist/deployments/sql-source.js +107 -0
  18. package/dist/deployments/types.d.ts +41 -1
  19. package/dist/deployments/types.d.ts.map +1 -1
  20. package/dist/deployments/validate.d.ts +19 -0
  21. package/dist/deployments/validate.d.ts.map +1 -1
  22. package/dist/deployments/validate.js +162 -4
  23. package/dist/event-operations/index.d.ts +6 -0
  24. package/dist/event-operations/index.d.ts.map +1 -0
  25. package/dist/event-operations/index.js +4 -0
  26. package/dist/event-operations/limits.d.ts +17 -0
  27. package/dist/event-operations/limits.d.ts.map +1 -0
  28. package/dist/event-operations/limits.js +21 -0
  29. package/dist/event-operations/predicates.d.ts +4 -0
  30. package/dist/event-operations/predicates.d.ts.map +1 -0
  31. package/dist/event-operations/predicates.js +10 -0
  32. package/dist/event-operations/records.d.ts +9 -0
  33. package/dist/event-operations/records.d.ts.map +1 -0
  34. package/dist/event-operations/records.js +55 -0
  35. package/dist/event-operations/types.d.ts +69 -0
  36. package/dist/event-operations/types.d.ts.map +1 -0
  37. package/dist/event-operations/types.js +1 -0
  38. package/dist/event-operations/validate.d.ts +11 -0
  39. package/dist/event-operations/validate.d.ts.map +1 -0
  40. package/dist/event-operations/validate.js +220 -0
  41. package/dist/event-operations/window.d.ts +8 -0
  42. package/dist/event-operations/window.d.ts.map +1 -0
  43. package/dist/event-operations/window.js +23 -0
  44. package/dist/expressions/calculations.d.ts +103 -0
  45. package/dist/expressions/calculations.d.ts.map +1 -0
  46. package/dist/expressions/calculations.js +9 -0
  47. package/dist/expressions/index.d.ts +3 -0
  48. package/dist/expressions/index.d.ts.map +1 -1
  49. package/dist/expressions/index.js +2 -0
  50. package/dist/expressions/relative-dates.d.ts +31 -0
  51. package/dist/expressions/relative-dates.d.ts.map +1 -0
  52. package/dist/expressions/relative-dates.js +38 -0
  53. package/dist/expressions/types.d.ts +24 -1
  54. package/dist/expressions/types.d.ts.map +1 -1
  55. package/dist/expressions/validate-calculations.d.ts +41 -0
  56. package/dist/expressions/validate-calculations.d.ts.map +1 -0
  57. package/dist/expressions/validate-calculations.js +397 -0
  58. package/dist/expressions/validate.d.ts.map +1 -1
  59. package/dist/expressions/validate.js +80 -4
  60. package/dist/index.d.ts +10 -5
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +6 -2
  63. package/dist/invocations/index.d.ts +1 -1
  64. package/dist/invocations/index.d.ts.map +1 -1
  65. package/dist/invocations/types.d.ts +13 -3
  66. package/dist/invocations/types.d.ts.map +1 -1
  67. package/dist/invocations/validate.d.ts.map +1 -1
  68. package/dist/invocations/validate.js +58 -2
  69. package/dist/visibility/resolve.d.ts +4 -4
  70. package/dist/visibility/resolve.d.ts.map +1 -1
  71. package/dist/visibility/resolve.js +12 -4
  72. package/dist/visibility/types.d.ts +6 -0
  73. package/dist/visibility/types.d.ts.map +1 -1
  74. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"cache-preimages.d.ts","sourceRoot":"","sources":["../../src/cache-preimages/cache-preimages.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,iCAAiC,EACjC,8BAA8B,EAC/B,MAAM,YAAY,CAAC;AAQpB,qBAAa,0BAA2B,SAAQ,KAAK;IACnD,QAAQ,CAAC,IAAI,EAAE,8BAA8B,CAAC;gBAElC,IAAI,EAAE,8BAA8B;CAOjD;AAwBD;;;;GAIG;AACH,wBAAgB,+BAA+B,CAAC,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE5F;AA0ED;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,iCAAiC,GAAG,MAAM,CAmB7F"}
1
+ {"version":3,"file":"cache-preimages.d.ts","sourceRoot":"","sources":["../../src/cache-preimages/cache-preimages.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACV,iCAAiC,EACjC,8BAA8B,EAC/B,MAAM,YAAY,CAAC;AAQpB,qBAAa,0BAA2B,SAAQ,KAAK;IACnD,QAAQ,CAAC,IAAI,EAAE,8BAA8B,CAAC;gBAElC,IAAI,EAAE,8BAA8B;CAOjD;AAwBD;;;;GAIG;AACH,wBAAgB,+BAA+B,CAAC,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE5F;AA6FD;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,iCAAiC,GAAG,MAAM,CAmB7F"}
@@ -58,6 +58,15 @@ function compareUtf8(left, right) {
58
58
  }
59
59
  return a.byteLength - b.byteLength;
60
60
  }
61
+ function usesRelativeDateRange(expression) {
62
+ if (expression.kind === 'comparison')
63
+ return expression.operator === 'inDateRange';
64
+ if (expression.kind !== 'logical')
65
+ return false;
66
+ return expression.operator === 'not'
67
+ ? usesRelativeDateRange(expression.operand)
68
+ : expression.operands.some(usesRelativeDateRange);
69
+ }
61
70
  function normalizeQuery(source) {
62
71
  let query;
63
72
  try {
@@ -75,6 +84,19 @@ function normalizeQuery(source) {
75
84
  fail('HQ_CACHE_PREIMAGE_INVALID_QUERY');
76
85
  if (query.timezone !== undefined && query.timezone !== 'UTC')
77
86
  fail('HQ_CACHE_PREIMAGE_INVALID_QUERY');
87
+ // RFC 0026: calculations, limitBy and other have no portable key either.
88
+ if (query.kind === 'dataset' && ((query.calculations?.length ?? 0) > 0 || query.limitBy !== undefined || query.other !== undefined))
89
+ fail('HQ_CACHE_PREIMAGE_INVALID_QUERY');
90
+ // RFC 0029: a relative range means a different query every day, and a
91
+ // filled series has rows the preimage can't describe. Neither has a
92
+ // portable key; `fill: false` is the default and is dropped below.
93
+ if ((query.filters ?? []).some(usesRelativeDateRange))
94
+ fail('HQ_CACHE_PREIMAGE_INVALID_QUERY');
95
+ if (query.kind === 'dataset' && query.fill === true)
96
+ fail('HQ_CACHE_PREIMAGE_INVALID_QUERY');
97
+ // Without the contract a key equal to `timeField` can't be told from another.
98
+ if (query.timeKey !== undefined)
99
+ fail('HQ_CACHE_PREIMAGE_INVALID_QUERY');
78
100
  // AND-combined, so order cannot change rows; identical filters collapse.
79
101
  const filters = new Map();
80
102
  for (const filter of query.filters ?? [])
@@ -14,6 +14,14 @@ export interface PreparedProtocolDeploymentContractV3 extends Omit<PreparedProto
14
14
  export declare function prepareProtocolDeploymentContract(input: unknown, options?: ProtocolDeploymentOptions): PreparedProtocolDeploymentContract;
15
15
  /** Validates, canonically encodes, and identifies a deployment contract 3. */
16
16
  export declare function prepareProtocolDeploymentContractV3(input: unknown, options?: ProtocolDeploymentOptions): PreparedProtocolDeploymentContractV3;
17
+ /** A prepared deployment contract of any version this package reads. */
18
+ export type PreparedProtocolDeploymentContractAnyVersion = PreparedProtocolDeploymentContract | PreparedProtocolDeploymentContractV3;
19
+ /**
20
+ * Validates, canonically encodes, and identifies a deployment contract 2 or 3,
21
+ * selected by its `version`. Each version keeps its own identity domain, so a
22
+ * contract 2 artifact keeps the identity it had before contract 3 existed.
23
+ */
24
+ export declare function prepareProtocolDeploymentContractAnyVersion(input: unknown, options?: ProtocolDeploymentOptions): PreparedProtocolDeploymentContractAnyVersion;
17
25
  export declare function encodeProtocolDeploymentContract(input: unknown, options?: ProtocolDeploymentOptions): Uint8Array;
18
26
  export declare function hashProtocolDeploymentContract(input: unknown, options?: ProtocolDeploymentOptions): string;
19
27
  export declare function encodeProtocolDeploymentContractToString(input: unknown, options?: ProtocolDeploymentOptions): string;
@@ -1 +1 @@
1
- {"version":3,"file":"codec.d.ts","sourceRoot":"","sources":["../../src/deployments/codec.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,0BAA0B,EAC1B,4BAA4B,EAC5B,yBAAyB,EAC1B,MAAM,YAAY,CAAC;AAKpB,eAAO,MAAM,mCAAmC,8BAA8B,CAAC;AAC/E,4DAA4D;AAC5D,eAAO,MAAM,sCAAsC,8BAA8B,CAAC;AAElF,MAAM,WAAW,kCAAkC;IACjD,QAAQ,CAAC,QAAQ,EAAE,0BAA0B,CAAC;IAC9C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,oCACf,SAAQ,IAAI,CAAC,kCAAkC,EAAE,UAAU,CAAC;IAC5D,QAAQ,CAAC,QAAQ,EAAE,4BAA4B,CAAC;CACjD;AAYD,wBAAgB,iCAAiC,CAC/C,KAAK,EAAE,OAAO,EACd,OAAO,GAAE,yBAA8B,GACtC,kCAAkC,CAEpC;AAED,8EAA8E;AAC9E,wBAAgB,mCAAmC,CACjD,KAAK,EAAE,OAAO,EACd,OAAO,GAAE,yBAA8B,GACtC,oCAAoC,CAEtC;AAED,wBAAgB,gCAAgC,CAC9C,KAAK,EAAE,OAAO,EACd,OAAO,GAAE,yBAA8B,GACtC,UAAU,CAEZ;AAED,wBAAgB,8BAA8B,CAC5C,KAAK,EAAE,OAAO,EACd,OAAO,GAAE,yBAA8B,GACtC,MAAM,CAER;AAED,wBAAgB,wCAAwC,CACtD,KAAK,EAAE,OAAO,EACd,OAAO,GAAE,yBAA8B,GACtC,MAAM,CAER"}
1
+ {"version":3,"file":"codec.d.ts","sourceRoot":"","sources":["../../src/deployments/codec.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,0BAA0B,EAC1B,4BAA4B,EAC5B,yBAAyB,EAC1B,MAAM,YAAY,CAAC;AAKpB,eAAO,MAAM,mCAAmC,8BAA8B,CAAC;AAC/E,4DAA4D;AAC5D,eAAO,MAAM,sCAAsC,8BAA8B,CAAC;AAElF,MAAM,WAAW,kCAAkC;IACjD,QAAQ,CAAC,QAAQ,EAAE,0BAA0B,CAAC;IAC9C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,oCACf,SAAQ,IAAI,CAAC,kCAAkC,EAAE,UAAU,CAAC;IAC5D,QAAQ,CAAC,QAAQ,EAAE,4BAA4B,CAAC;CACjD;AAYD,wBAAgB,iCAAiC,CAC/C,KAAK,EAAE,OAAO,EACd,OAAO,GAAE,yBAA8B,GACtC,kCAAkC,CAEpC;AAED,8EAA8E;AAC9E,wBAAgB,mCAAmC,CACjD,KAAK,EAAE,OAAO,EACd,OAAO,GAAE,yBAA8B,GACtC,oCAAoC,CAEtC;AAED,wEAAwE;AACxE,MAAM,MAAM,4CAA4C,GACpD,kCAAkC,GAClC,oCAAoC,CAAC;AAEzC;;;;GAIG;AACH,wBAAgB,2CAA2C,CACzD,KAAK,EAAE,OAAO,EACd,OAAO,GAAE,yBAA8B,GACtC,4CAA4C,CAI9C;AAED,wBAAgB,gCAAgC,CAC9C,KAAK,EAAE,OAAO,EACd,OAAO,GAAE,yBAA8B,GACtC,UAAU,CAEZ;AAED,wBAAgB,8BAA8B,CAC5C,KAAK,EAAE,OAAO,EACd,OAAO,GAAE,yBAA8B,GACtC,MAAM,CAER;AAED,wBAAgB,wCAAwC,CACtD,KAAK,EAAE,OAAO,EACd,OAAO,GAAE,yBAA8B,GACtC,MAAM,CAER"}
@@ -1,7 +1,7 @@
1
1
  import { sha256 } from '@noble/hashes/sha2.js';
2
2
  import { bytesToHex } from '@noble/hashes/utils.js';
3
3
  import { serializeJcs } from '../values/jcs.js';
4
- import { validateProtocolDeploymentContract, validateProtocolDeploymentContractV3 } from './validate.js';
4
+ import { isContract3Envelope, validateProtocolDeploymentContract, validateProtocolDeploymentContractV3 } from './validate.js';
5
5
  const textEncoder = new TextEncoder();
6
6
  export const PROTOCOL_DEPLOYMENT_IDENTITY_DOMAIN = 'hypequery:deployment:v2\0';
7
7
  /** Identity domain for deployment contract 3 (RFC 0015). */
@@ -22,6 +22,16 @@ export function prepareProtocolDeploymentContract(input, options = {}) {
22
22
  export function prepareProtocolDeploymentContractV3(input, options = {}) {
23
23
  return identify(validateProtocolDeploymentContractV3(input, options), PROTOCOL_DEPLOYMENT_V3_IDENTITY_DOMAIN);
24
24
  }
25
+ /**
26
+ * Validates, canonically encodes, and identifies a deployment contract 2 or 3,
27
+ * selected by its `version`. Each version keeps its own identity domain, so a
28
+ * contract 2 artifact keeps the identity it had before contract 3 existed.
29
+ */
30
+ export function prepareProtocolDeploymentContractAnyVersion(input, options = {}) {
31
+ return isContract3Envelope(input)
32
+ ? prepareProtocolDeploymentContractV3(input, options)
33
+ : prepareProtocolDeploymentContract(input, options);
34
+ }
25
35
  export function encodeProtocolDeploymentContract(input, options = {}) {
26
36
  return prepareProtocolDeploymentContract(input, options).bytes;
27
37
  }
@@ -0,0 +1,10 @@
1
+ import type { ProtocolQualifiedIdentifier } from '../identifiers/index.js';
2
+ import type { ProtocolDatasetDimension, ProtocolDatasetEvents } from './types.js';
3
+ /**
4
+ * RFC 0027: an event dataset names the dimension that identifies who acted
5
+ * (`entity`) and, optionally, the one naming what happened (`event`). The
6
+ * event timestamp is always the dataset's `timeField`, so the declaration is
7
+ * checked against the dataset's own dimensions and time field.
8
+ */
9
+ export declare function validateProtocolDatasetEvents(input: unknown, path: string, dimensions: readonly ProtocolDatasetDimension[], timeField: ProtocolQualifiedIdentifier | undefined): ProtocolDatasetEvents;
10
+ //# sourceMappingURL=events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/deployments/events.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAsB,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAC/F,OAAO,KAAK,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAUlF;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAC3C,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,SAAS,wBAAwB,EAAE,EAC/C,SAAS,EAAE,2BAA2B,GAAG,SAAS,GACjD,qBAAqB,CAoCvB"}
@@ -0,0 +1,59 @@
1
+ import { parseProtocolIdentifier } from '../identifiers/index.js';
2
+ import { deploymentError } from './errors.js';
3
+ function simpleIdentifier(value, path) {
4
+ try {
5
+ return parseProtocolIdentifier(value);
6
+ }
7
+ catch {
8
+ return deploymentError('HQ_DEPLOYMENT_INVALID_IDENTIFIER', path);
9
+ }
10
+ }
11
+ /**
12
+ * RFC 0027: an event dataset names the dimension that identifies who acted
13
+ * (`entity`) and, optionally, the one naming what happened (`event`). The
14
+ * event timestamp is always the dataset's `timeField`, so the declaration is
15
+ * checked against the dataset's own dimensions and time field.
16
+ */
17
+ export function validateProtocolDatasetEvents(input, path, dimensions, timeField) {
18
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
19
+ deploymentError('HQ_DEPLOYMENT_TYPE', path);
20
+ const prototype = Object.getPrototypeOf(input);
21
+ if (prototype !== null && prototype !== Object.prototype)
22
+ deploymentError('HQ_DEPLOYMENT_UNSAFE_OBJECT', path);
23
+ const value = input;
24
+ for (const key of Reflect.ownKeys(value)) {
25
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
26
+ if (typeof key !== 'string' || !descriptor || !descriptor.enumerable || !('value' in descriptor)) {
27
+ deploymentError('HQ_DEPLOYMENT_UNSAFE_OBJECT', path);
28
+ }
29
+ if (key !== 'entity' && key !== 'event')
30
+ deploymentError('HQ_DEPLOYMENT_UNKNOWN_FIELD', `${path}.${key}`);
31
+ }
32
+ if (!Object.hasOwn(value, 'entity'))
33
+ deploymentError('HQ_DEPLOYMENT_TYPE', `${path}.entity`);
34
+ const entity = simpleIdentifier(value.entity, `${path}.entity`);
35
+ const event = value.event === undefined ? undefined : simpleIdentifier(value.event, `${path}.event`);
36
+ const byName = new Map(dimensions.map(dimension => [String(dimension.name), dimension]));
37
+ const entityDimension = byName.get(entity);
38
+ if (!entityDimension)
39
+ deploymentError('HQ_DEPLOYMENT_INVALID_REFERENCE', `${path}.entity`);
40
+ // Distinct entities are counted per group, so the entity must be a value a
41
+ // caller could group by, and not a point in time.
42
+ if (!entityDimension.groupable || (entityDimension.type !== 'string' && entityDimension.type !== 'number')) {
43
+ deploymentError('HQ_DEPLOYMENT_INVALID_VALUE', `${path}.entity`);
44
+ }
45
+ if (event !== undefined) {
46
+ const eventDimension = byName.get(event);
47
+ if (!eventDimension)
48
+ deploymentError('HQ_DEPLOYMENT_INVALID_REFERENCE', `${path}.event`);
49
+ if (!eventDimension.filterable || eventDimension.type !== 'string') {
50
+ deploymentError('HQ_DEPLOYMENT_INVALID_VALUE', `${path}.event`);
51
+ }
52
+ }
53
+ // The time field is the event timestamp: it must be one of this dataset's
54
+ // own timestamp dimensions.
55
+ const time = timeField === undefined ? undefined : byName.get(String(timeField));
56
+ if (time === undefined || time.type !== 'timestamp')
57
+ deploymentError('HQ_DEPLOYMENT_INVALID_REFERENCE', path);
58
+ return Object.freeze({ entity, ...(event === undefined ? {} : { event }) });
59
+ }
@@ -1,8 +1,12 @@
1
1
  export { ProtocolDeploymentError } from './errors.js';
2
- export { PROTOCOL_DEPLOYMENT_IDENTITY_DOMAIN, PROTOCOL_DEPLOYMENT_V3_IDENTITY_DOMAIN, encodeProtocolDeploymentContract, encodeProtocolDeploymentContractToString, hashProtocolDeploymentContract, prepareProtocolDeploymentContract, prepareProtocolDeploymentContractV3, } from './codec.js';
3
- export type { PreparedProtocolDeploymentContract, PreparedProtocolDeploymentContractV3, } from './codec.js';
2
+ export { PROTOCOL_DEPLOYMENT_IDENTITY_DOMAIN, PROTOCOL_DEPLOYMENT_V3_IDENTITY_DOMAIN, encodeProtocolDeploymentContract, encodeProtocolDeploymentContractToString, hashProtocolDeploymentContract, prepareProtocolDeploymentContract, prepareProtocolDeploymentContractAnyVersion, prepareProtocolDeploymentContractV3, } from './codec.js';
3
+ export type { PreparedProtocolDeploymentContract, PreparedProtocolDeploymentContractAnyVersion, PreparedProtocolDeploymentContractV3, } from './codec.js';
4
4
  export { DEFAULT_PROTOCOL_DEPLOYMENT_LIMITS } from './limits.js';
5
- export { checkProtocolDatasetContract, checkProtocolDeploymentContract, checkProtocolDeploymentContractV3, validateProtocolDatasetContract, validateProtocolDeploymentContract, validateProtocolDeploymentContractV3, } from './validate.js';
6
- export type { ProtocolDatasetDerivedMeasure, ProtocolDeploymentDataset, ProtocolDeploymentMeasure, ProtocolAccessPolicy, ProtocolDatasetContract, ProtocolRowResolution, ProtocolDatasetDefaults, ProtocolDatasetDimension, ProtocolDatasetFieldSource, ProtocolDatasetFieldType, ProtocolDatasetFilter, ProtocolDatasetFreshness, ProtocolDatasetLimits, ProtocolDatasetMeasure, ProtocolDatasetMetric, ProtocolDatasetRelationship, ProtocolDatasetTenantPolicy, ProtocolSemanticMetadata, ProtocolSemanticSensitivity, ProtocolDeploymentContract, ProtocolDeploymentContractV3, ProtocolDeploymentDatasetV3, ProtocolDeploymentMeasureV3, ProtocolDatasetDerivedMeasureV3, ProtocolDatasetMeasureV3, ProtocolDatasetSegment, ProtocolDatasetShiftMeasure, ProtocolDatasetWindowMeasure, ProtocolTimeInterval, ProtocolDeploymentCheckResult, ProtocolDeploymentErrorCode, ProtocolDeploymentValidationError, ProtocolDeploymentLimits, ProtocolDeploymentOptions, ProtocolEndpointPolicy, ProtocolEndpointTenantPolicy, ProtocolMetricDerivation, ProtocolMetricInput, } from './types.js';
5
+ export { checkProtocolDatasetContract, checkProtocolDeploymentContract, checkProtocolDeploymentContractV3, validateProtocolDatasetContract, validateProtocolDeploymentContract, validateProtocolDeploymentContractAnyVersion, validateProtocolDeploymentContractAtLowestVersion, validateProtocolDeploymentContractV3, } from './validate.js';
6
+ export type { ProtocolDatasetDerivedMeasure, ProtocolDeploymentDataset, ProtocolDeploymentMeasure, ProtocolAccessPolicy, ProtocolDatasetContract, ProtocolRowResolution, ProtocolDatasetEvents, ProtocolDatasetSource, ProtocolSqlSource, ProtocolSqlSourceColumn, ProtocolDatasetDefaults, ProtocolDatasetDimension, ProtocolDatasetFieldSource, ProtocolDatasetFieldType, ProtocolDatasetFilter, ProtocolDatasetFreshness, ProtocolDatasetLimits, ProtocolDatasetMeasure, ProtocolDatasetMetric, ProtocolDatasetRelationship, ProtocolDatasetTenantPolicy, ProtocolSemanticMetadata, ProtocolSemanticSensitivity, ProtocolDeploymentContract, ProtocolDeploymentContractV3, ProtocolDeploymentContractAnyVersion, ProtocolDeploymentDatasetAnyVersion, ProtocolDeploymentDatasetV3, ProtocolDeploymentMeasureV3, ProtocolDatasetDerivedMeasureV3, ProtocolDatasetMeasureV3, ProtocolDatasetSegment, ProtocolDatasetShiftMeasure, ProtocolDatasetWindowMeasure, ProtocolTimeInterval, ProtocolDeploymentCheckResult, ProtocolDeploymentErrorCode, ProtocolDeploymentValidationError, ProtocolDeploymentLimits, ProtocolDeploymentOptions, ProtocolEndpointPolicy, ProtocolEndpointTenantPolicy, ProtocolMetricDerivation, ProtocolMetricInput, } from './types.js';
7
7
  export { validateProtocolRowResolution } from './row-resolution.js';
8
+ export { validateProtocolDatasetEvents } from './events.js';
9
+ export { isProtocolSqlSource, validateProtocolSqlSource } from './sql-source.js';
10
+ export { PROTOCOL_SQL_SOURCE_MAX_BYTES, PROTOCOL_SQL_SOURCE_MAX_DEPENDENCIES, analyzeProtocolSqlSource, } from './sql-source-analysis.js';
11
+ export type { ProtocolSqlSourceAnalysis, ProtocolSqlSourceRefusal } from './sql-source-analysis.js';
8
12
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/deployments/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EACL,mCAAmC,EACnC,sCAAsC,EACtC,gCAAgC,EAChC,wCAAwC,EACxC,8BAA8B,EAC9B,iCAAiC,EACjC,mCAAmC,GACpC,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,kCAAkC,EAClC,oCAAoC,GACrC,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,kCAAkC,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EACL,4BAA4B,EAC5B,+BAA+B,EAC/B,iCAAiC,EACjC,+BAA+B,EAC/B,kCAAkC,EAClC,oCAAoC,GACrC,MAAM,eAAe,CAAC;AAEvB,YAAY,EACV,6BAA6B,EAC7B,yBAAyB,EACzB,yBAAyB,EACzB,oBAAoB,EACpB,uBAAuB,EACvB,qBAAqB,EACrB,uBAAuB,EACvB,wBAAwB,EACxB,0BAA0B,EAC1B,wBAAwB,EACxB,qBAAqB,EACrB,wBAAwB,EACxB,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,2BAA2B,EAC3B,2BAA2B,EAC3B,wBAAwB,EACxB,2BAA2B,EAC3B,0BAA0B,EAC1B,4BAA4B,EAC5B,2BAA2B,EAC3B,2BAA2B,EAC3B,+BAA+B,EAC/B,wBAAwB,EACxB,sBAAsB,EACtB,2BAA2B,EAC3B,4BAA4B,EAC5B,oBAAoB,EACpB,6BAA6B,EAC7B,2BAA2B,EAC3B,iCAAiC,EACjC,wBAAwB,EACxB,yBAAyB,EACzB,sBAAsB,EACtB,4BAA4B,EAC5B,wBAAwB,EACxB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/deployments/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EACL,mCAAmC,EACnC,sCAAsC,EACtC,gCAAgC,EAChC,wCAAwC,EACxC,8BAA8B,EAC9B,iCAAiC,EACjC,2CAA2C,EAC3C,mCAAmC,GACpC,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,kCAAkC,EAClC,4CAA4C,EAC5C,oCAAoC,GACrC,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,kCAAkC,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EACL,4BAA4B,EAC5B,+BAA+B,EAC/B,iCAAiC,EACjC,+BAA+B,EAC/B,kCAAkC,EAClC,4CAA4C,EAC5C,iDAAiD,EACjD,oCAAoC,GACrC,MAAM,eAAe,CAAC;AAEvB,YAAY,EACV,6BAA6B,EAC7B,yBAAyB,EACzB,yBAAyB,EACzB,oBAAoB,EACpB,uBAAuB,EACvB,qBAAqB,EACrB,qBAAqB,EACrB,qBAAqB,EACrB,iBAAiB,EACjB,uBAAuB,EACvB,uBAAuB,EACvB,wBAAwB,EACxB,0BAA0B,EAC1B,wBAAwB,EACxB,qBAAqB,EACrB,wBAAwB,EACxB,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,2BAA2B,EAC3B,2BAA2B,EAC3B,wBAAwB,EACxB,2BAA2B,EAC3B,0BAA0B,EAC1B,4BAA4B,EAC5B,oCAAoC,EACpC,mCAAmC,EACnC,2BAA2B,EAC3B,2BAA2B,EAC3B,+BAA+B,EAC/B,wBAAwB,EACxB,sBAAsB,EACtB,2BAA2B,EAC3B,4BAA4B,EAC5B,oBAAoB,EACpB,6BAA6B,EAC7B,2BAA2B,EAC3B,iCAAiC,EACjC,wBAAwB,EACxB,yBAAyB,EACzB,sBAAsB,EACtB,4BAA4B,EAC5B,wBAAwB,EACxB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAAE,6BAA6B,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AACjF,OAAO,EACL,6BAA6B,EAC7B,oCAAoC,EACpC,wBAAwB,GACzB,MAAM,0BAA0B,CAAC;AAClC,YAAY,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,0BAA0B,CAAC"}
@@ -1,5 +1,8 @@
1
1
  export { ProtocolDeploymentError } from './errors.js';
2
- export { PROTOCOL_DEPLOYMENT_IDENTITY_DOMAIN, PROTOCOL_DEPLOYMENT_V3_IDENTITY_DOMAIN, encodeProtocolDeploymentContract, encodeProtocolDeploymentContractToString, hashProtocolDeploymentContract, prepareProtocolDeploymentContract, prepareProtocolDeploymentContractV3, } from './codec.js';
2
+ export { PROTOCOL_DEPLOYMENT_IDENTITY_DOMAIN, PROTOCOL_DEPLOYMENT_V3_IDENTITY_DOMAIN, encodeProtocolDeploymentContract, encodeProtocolDeploymentContractToString, hashProtocolDeploymentContract, prepareProtocolDeploymentContract, prepareProtocolDeploymentContractAnyVersion, prepareProtocolDeploymentContractV3, } from './codec.js';
3
3
  export { DEFAULT_PROTOCOL_DEPLOYMENT_LIMITS } from './limits.js';
4
- export { checkProtocolDatasetContract, checkProtocolDeploymentContract, checkProtocolDeploymentContractV3, validateProtocolDatasetContract, validateProtocolDeploymentContract, validateProtocolDeploymentContractV3, } from './validate.js';
4
+ export { checkProtocolDatasetContract, checkProtocolDeploymentContract, checkProtocolDeploymentContractV3, validateProtocolDatasetContract, validateProtocolDeploymentContract, validateProtocolDeploymentContractAnyVersion, validateProtocolDeploymentContractAtLowestVersion, validateProtocolDeploymentContractV3, } from './validate.js';
5
5
  export { validateProtocolRowResolution } from './row-resolution.js';
6
+ export { validateProtocolDatasetEvents } from './events.js';
7
+ export { isProtocolSqlSource, validateProtocolSqlSource } from './sql-source.js';
8
+ export { PROTOCOL_SQL_SOURCE_MAX_BYTES, PROTOCOL_SQL_SOURCE_MAX_DEPENDENCIES, analyzeProtocolSqlSource, } from './sql-source-analysis.js';
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The RFC 0028 checker for a SQL-sourced dataset: a lexical pass with
3
+ * ClickHouse's literal rules, not a parser. Each rule refuses a construct the
4
+ * lexer can see, so nothing is ever accepted on a judgement that it looks
5
+ * harmless. Code-first datasets and contract validation share it.
6
+ */
7
+ /** Why a SQL source was refused. Stable: datasets maps each to a message. */
8
+ export type ProtocolSqlSourceRefusal = 'empty' | 'too-large' | 'invalid-character' | 'unterminated-literal' | 'multiple-statements' | 'comment' | 'placeholder' | 'not-select' | 'forbidden-clause' | 'table-function' | 'forbidden-function' | 'system-table' | 'unbalanced-parentheses' | 'unsupported-from' | 'undeclared-dependency' | 'unused-dependency';
9
+ export type ProtocolSqlSourceAnalysis = {
10
+ readonly ok: true;
11
+ /** Tables the SQL reads, unquoted and as written, in first-reference order. */
12
+ readonly tables: readonly string[];
13
+ /** The SQL reads at least one table with FINAL (RFC 0021 pinning applies). */
14
+ readonly readsFinal: boolean;
15
+ } | {
16
+ readonly ok: false;
17
+ readonly reason: ProtocolSqlSourceRefusal;
18
+ /** The word, function or table the refusal is about, when there is one. */
19
+ readonly detail?: string;
20
+ };
21
+ /** 16 KiB of UTF-8. */
22
+ export declare const PROTOCOL_SQL_SOURCE_MAX_BYTES = 16384;
23
+ export declare const PROTOCOL_SQL_SOURCE_MAX_DEPENDENCIES = 64;
24
+ /**
25
+ * Check one SQL source against RFC 0028's rules and its declared
26
+ * dependencies. Never throws.
27
+ */
28
+ export declare function analyzeProtocolSqlSource(sql: string, dependencies: readonly string[]): ProtocolSqlSourceAnalysis;
29
+ //# sourceMappingURL=sql-source-analysis.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sql-source-analysis.d.ts","sourceRoot":"","sources":["../../src/deployments/sql-source-analysis.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,6EAA6E;AAC7E,MAAM,MAAM,wBAAwB,GAChC,OAAO,GACP,WAAW,GACX,mBAAmB,GACnB,sBAAsB,GACtB,qBAAqB,GACrB,SAAS,GACT,aAAa,GACb,YAAY,GACZ,kBAAkB,GAClB,gBAAgB,GAChB,oBAAoB,GACpB,cAAc,GACd,wBAAwB,GACxB,kBAAkB,GAClB,uBAAuB,GACvB,mBAAmB,CAAC;AAExB,MAAM,MAAM,yBAAyB,GACjC;IACA,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAClB,+EAA+E;IAC/E,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,8EAA8E;IAC9E,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;CAC9B,GACC;IACA,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IACnB,QAAQ,CAAC,MAAM,EAAE,wBAAwB,CAAC;IAC1C,2EAA2E;IAC3E,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEJ,uBAAuB;AACvB,eAAO,MAAM,6BAA6B,QAAS,CAAC;AACpD,eAAO,MAAM,oCAAoC,KAAK,CAAC;AAiIvD;;;GAGG;AACH,wBAAgB,wBAAwB,CACtC,GAAG,EAAE,MAAM,EACX,YAAY,EAAE,SAAS,MAAM,EAAE,GAC9B,yBAAyB,CA8H3B"}
@@ -0,0 +1,264 @@
1
+ /**
2
+ * The RFC 0028 checker for a SQL-sourced dataset: a lexical pass with
3
+ * ClickHouse's literal rules, not a parser. Each rule refuses a construct the
4
+ * lexer can see, so nothing is ever accepted on a judgement that it looks
5
+ * harmless. Code-first datasets and contract validation share it.
6
+ */
7
+ /** 16 KiB of UTF-8. */
8
+ export const PROTOCOL_SQL_SOURCE_MAX_BYTES = 16_384;
9
+ export const PROTOCOL_SQL_SOURCE_MAX_DEPENDENCIES = 64;
10
+ const FORBIDDEN_WORDS = new Set(['SETTINGS', 'FORMAT', 'INTO', 'OUTFILE']);
11
+ /** Functions that read an object named in a string, the filesystem, or block. */
12
+ const FORBIDDEN_FUNCTIONS = new Set([
13
+ 'joinget', 'joingetornull', 'file', 'getsetting', 'getsettingordefault', 'getserversetting', 'getmacro',
14
+ 'hascolumnintable', 'catboostevaluate', 'sleep', 'sleepeachrow',
15
+ ]);
16
+ /** Statements other than SELECT. `DESC` is also a sort direction, so only a frame may not start with it. */
17
+ const STATEMENT_WORDS = new Set(['EXPLAIN', 'DESCRIBE', 'DESC', 'SHOW']);
18
+ /** Functions whose own syntax has FROM in their arguments. */
19
+ const FROM_SYNTAX_FUNCTIONS = new Set(['EXTRACT', 'SUBSTRING', 'SUBSTR', 'TRIM', 'OVERLAY']);
20
+ /** After these, a comma at the same level starts another table reference. */
21
+ const TABLE_LIST_CLAUSES = new Set(['FROM', 'JOIN', 'SAMPLE', 'ON', 'USING']);
22
+ const SYSTEM_DATABASES = new Set(['system', 'information_schema']);
23
+ /** Words that start a clause of a SELECT; a FROM-list comma only counts inside FROM. */
24
+ const CLAUSE_WORDS = new Set([
25
+ 'SELECT', 'FROM', 'WHERE', 'PREWHERE', 'GROUP', 'HAVING', 'ORDER', 'LIMIT', 'OFFSET', 'UNION', 'EXCEPT',
26
+ 'INTERSECT', 'WINDOW', 'QUALIFY', 'JOIN', 'ON', 'USING', 'WITH', 'SAMPLE', 'ARRAY',
27
+ ]);
28
+ const refuse = (reason, detail) => (Object.freeze(detail === undefined ? { ok: false, reason } : { ok: false, reason, detail }));
29
+ const isWordStart = (char) => /[A-Za-z_]/.test(char);
30
+ const isWordPart = (char) => /[A-Za-z0-9_]/.test(char);
31
+ function isForbiddenFunction(name) {
32
+ const lower = name.toLowerCase();
33
+ return lower.startsWith('dict') || FORBIDDEN_FUNCTIONS.has(lower);
34
+ }
35
+ /** Reads a quoted span starting at `start`; returns the index after it, or -1 if unterminated. */
36
+ function readQuoted(sql, start, quote) {
37
+ let text = '';
38
+ for (let index = start + 1; index < sql.length; index += 1) {
39
+ const char = sql[index];
40
+ if (char === '\\') {
41
+ if (index + 1 >= sql.length)
42
+ return undefined;
43
+ text += sql[index + 1];
44
+ index += 1;
45
+ continue;
46
+ }
47
+ if (char === quote) {
48
+ if (sql[index + 1] === quote) {
49
+ text += quote;
50
+ index += 1;
51
+ continue;
52
+ }
53
+ return { end: index + 1, text };
54
+ }
55
+ text += char;
56
+ }
57
+ return undefined;
58
+ }
59
+ function tokenize(sql) {
60
+ const tokens = [];
61
+ let index = 0;
62
+ while (index < sql.length) {
63
+ const char = sql[index];
64
+ if (char === ' ' || char === '\t' || char === '\n' || char === '\r') {
65
+ index += 1;
66
+ continue;
67
+ }
68
+ if (char === '\'' || char === '`' || char === '"') {
69
+ const quoted = readQuoted(sql, index, char);
70
+ if (!quoted)
71
+ return refuse('unterminated-literal');
72
+ tokens.push(char === '\'' ? { kind: 'string' } : { kind: 'quoted', text: quoted.text });
73
+ index = quoted.end;
74
+ continue;
75
+ }
76
+ if ((char === '-' && sql[index + 1] === '-') || (char === '/' && sql[index + 1] === '*') || char === '#') {
77
+ return refuse('comment');
78
+ }
79
+ if (char === ';')
80
+ return refuse('multiple-statements');
81
+ if (char === '{' || char === '}' || char === '$')
82
+ return refuse('placeholder', char);
83
+ if (isWordStart(char)) {
84
+ let end = index + 1;
85
+ while (end < sql.length && isWordPart(sql[end]))
86
+ end += 1;
87
+ const text = sql.slice(index, end);
88
+ tokens.push({ kind: 'word', text, upper: text.toUpperCase() });
89
+ index = end;
90
+ continue;
91
+ }
92
+ if (/[0-9]/.test(char)) {
93
+ let end = index + 1;
94
+ while (end < sql.length && /[0-9A-Za-z_.]/.test(sql[end]))
95
+ end += 1;
96
+ tokens.push({ kind: 'number' });
97
+ index = end;
98
+ continue;
99
+ }
100
+ const code = char.charCodeAt(0);
101
+ if (code < 0x21 || code > 0x7e)
102
+ return refuse('invalid-character');
103
+ tokens.push({ kind: 'punct', text: char });
104
+ index += 1;
105
+ }
106
+ return tokens;
107
+ }
108
+ const isPunct = (token, text) => token?.kind === 'punct' && token.text === text;
109
+ const isName = (token) => (token?.kind === 'word' || token?.kind === 'quoted');
110
+ const isWord = (token, upper) => token?.kind === 'word' && token.upper === upper;
111
+ /**
112
+ * Check one SQL source against RFC 0028's rules and its declared
113
+ * dependencies. Never throws.
114
+ */
115
+ export function analyzeProtocolSqlSource(sql, dependencies) {
116
+ if (sql.trim().length === 0)
117
+ return refuse('empty');
118
+ if (sql.length > PROTOCOL_SQL_SOURCE_MAX_BYTES
119
+ || new TextEncoder().encode(sql).byteLength > PROTOCOL_SQL_SOURCE_MAX_BYTES) {
120
+ return refuse('too-large');
121
+ }
122
+ for (const character of sql) {
123
+ const code = character.codePointAt(0);
124
+ if ((code <= 0x1f && code !== 0x09 && code !== 0x0a && code !== 0x0d) || code === 0x7f || (code >= 0x80 && code <= 0x9f)) {
125
+ return refuse('invalid-character');
126
+ }
127
+ }
128
+ // The TypeScript client substitutes `?` across the whole statement, literals included.
129
+ if (sql.includes('?'))
130
+ return refuse('placeholder', '?');
131
+ const lexed = tokenize(sql);
132
+ if (!Array.isArray(lexed))
133
+ return lexed;
134
+ const tokens = lexed;
135
+ if (!isWord(tokens[0], 'SELECT') && !isWord(tokens[0], 'WITH'))
136
+ return refuse('not-select');
137
+ const frames = [{ fromCall: false, clause: undefined, ctes: new Set() }];
138
+ const tables = [];
139
+ let readsFinal = false;
140
+ let pendingCte;
141
+ const resolvesToCte = (name) => frames.some(frame => frame.ctes.has(name));
142
+ /** Reads a table reference at `index`; returns the index after it, or a refusal. */
143
+ const readTable = (index) => {
144
+ const first = tokens[index];
145
+ if (isPunct(first, '(')) {
146
+ // A parenthesized table position holds a query, never a join tree or a statement.
147
+ const inner = tokens[index + 1];
148
+ return isWord(inner, 'SELECT') || isWord(inner, 'WITH') || isWord(inner, 'FROM') || isPunct(inner, '(')
149
+ ? index
150
+ : refuse('unsupported-from');
151
+ }
152
+ if (!isName(first))
153
+ return refuse('unsupported-from');
154
+ let name = first.text;
155
+ let qualified = false;
156
+ let next = index + 1;
157
+ if (isPunct(tokens[next], '.')) {
158
+ const second = tokens[next + 1];
159
+ if (!isName(second))
160
+ return refuse('unsupported-from');
161
+ name = `${name}.${second.text}`;
162
+ qualified = true;
163
+ next += 2;
164
+ }
165
+ if (isPunct(tokens[next], '.'))
166
+ return refuse('unsupported-from');
167
+ if (isPunct(tokens[next], '('))
168
+ return refuse('table-function', name);
169
+ if (qualified && SYSTEM_DATABASES.has(name.slice(0, name.indexOf('.')).toLowerCase())) {
170
+ return refuse('system-table', name);
171
+ }
172
+ if (!(!qualified && resolvesToCte(name)) && !tables.includes(name))
173
+ tables.push(name);
174
+ return next;
175
+ };
176
+ for (let index = 0; index < tokens.length; index += 1) {
177
+ const token = tokens[index];
178
+ const frame = frames[frames.length - 1];
179
+ if (token.kind === 'punct') {
180
+ if (token.text === '(') {
181
+ const inner = tokens[index + 1];
182
+ if (inner?.kind === 'word' && STATEMENT_WORDS.has(inner.upper))
183
+ return refuse('not-select', inner.upper);
184
+ const previous = tokens[index - 1];
185
+ frames.push({
186
+ fromCall: previous?.kind === 'word' && FROM_SYNTAX_FUNCTIONS.has(previous.upper),
187
+ clause: undefined,
188
+ ctes: new Set(),
189
+ ...(pendingCte?.at === index ? { defines: pendingCte.name } : {}),
190
+ });
191
+ }
192
+ else if (token.text === ')') {
193
+ if (frames.length === 1)
194
+ return refuse('unbalanced-parentheses');
195
+ const closed = frames.pop();
196
+ // ClickHouse hides a CTE from its own body, where the name reads the physical table.
197
+ if (closed.defines !== undefined)
198
+ frames[frames.length - 1].ctes.add(closed.defines);
199
+ }
200
+ else if (token.text === ',' && frame.clause !== undefined && TABLE_LIST_CLAUSES.has(frame.clause)) {
201
+ const after = readTable(index + 1);
202
+ if (typeof after !== 'number')
203
+ return after;
204
+ index = after - 1;
205
+ }
206
+ continue;
207
+ }
208
+ if (!isName(token))
209
+ continue;
210
+ if (isPunct(tokens[index + 1], '(') && isForbiddenFunction(token.text)) {
211
+ return refuse('forbidden-function', token.text);
212
+ }
213
+ // `name AS (…)` inside WITH defines a CTE, quoted or not; see `defines`.
214
+ if (!frame.fromCall && frame.clause === 'WITH' && isWord(tokens[index + 1], 'AS') && isPunct(tokens[index + 2], '(')) {
215
+ pendingCte = { name: token.text, at: index + 2 };
216
+ continue;
217
+ }
218
+ if (token.kind !== 'word')
219
+ continue;
220
+ const upper = token.upper;
221
+ if (FORBIDDEN_WORDS.has(upper) || (STATEMENT_WORDS.has(upper) && upper !== 'DESC'))
222
+ return refuse('forbidden-clause', upper);
223
+ if (upper === 'FINAL')
224
+ readsFinal = true;
225
+ // `x IN t` reads a table wherever it appears, function arguments included.
226
+ if (upper === 'IN' && isName(tokens[index + 1])) {
227
+ const after = readTable(index + 1);
228
+ if (typeof after !== 'number')
229
+ return after;
230
+ index = after - 1;
231
+ continue;
232
+ }
233
+ if (upper === 'JOIN' && isWord(tokens[index - 1], 'ARRAY')) {
234
+ frame.clause = 'ARRAY';
235
+ continue;
236
+ }
237
+ // FROM inside a function call (EXTRACT, SUBSTRING, TRIM) is not a table position.
238
+ if (upper === 'JOIN' || (upper === 'FROM' && !frame.fromCall)) {
239
+ frame.clause = upper;
240
+ const after = readTable(index + 1);
241
+ if (typeof after !== 'number')
242
+ return after;
243
+ index = after - 1;
244
+ continue;
245
+ }
246
+ if (frame.fromCall)
247
+ continue;
248
+ if (CLAUSE_WORDS.has(upper))
249
+ frame.clause = upper;
250
+ }
251
+ if (frames.length !== 1)
252
+ return refuse('unbalanced-parentheses');
253
+ for (const table of tables) {
254
+ if (!dependencies.includes(table))
255
+ return refuse('undeclared-dependency', table);
256
+ }
257
+ for (const dependency of dependencies) {
258
+ if (SYSTEM_DATABASES.has(dependency.split('.')[0].toLowerCase()))
259
+ return refuse('system-table', dependency);
260
+ if (!tables.includes(dependency))
261
+ return refuse('unused-dependency', dependency);
262
+ }
263
+ return Object.freeze({ ok: true, tables: Object.freeze(tables), readsFinal });
264
+ }
@@ -0,0 +1,8 @@
1
+ import type { ProtocolDeploymentLimits, ProtocolSqlSource } from './types.js';
2
+ /**
3
+ * Validate an RFC 0028 SQL source: its shape, then the SQL rules and the
4
+ * dependency coverage `analyzeProtocolSqlSource` checks.
5
+ */
6
+ export declare function validateProtocolSqlSource(input: unknown, path: string, limits: Readonly<ProtocolDeploymentLimits>): ProtocolSqlSource;
7
+ export declare function isProtocolSqlSource(source: unknown): source is ProtocolSqlSource;
8
+ //# sourceMappingURL=sql-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sql-source.d.ts","sourceRoot":"","sources":["../../src/deployments/sql-source.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAA4B,wBAAwB,EAAE,iBAAiB,EAA2B,MAAM,YAAY,CAAC;AAgDjI;;;GAGG;AACH,wBAAgB,yBAAyB,CACvC,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,QAAQ,CAAC,wBAAwB,CAAC,GACzC,iBAAiB,CAqCnB;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,IAAI,iBAAiB,CAEhF"}
@@ -0,0 +1,107 @@
1
+ import { ProtocolIdentifierError, parseProtocolIdentifier, parseProtocolQualifiedIdentifier } from '../identifiers/index.js';
2
+ import { deploymentError } from './errors.js';
3
+ import { PROTOCOL_SQL_SOURCE_MAX_DEPENDENCIES, analyzeProtocolSqlSource, } from './sql-source-analysis.js';
4
+ const FIELD_TYPES = new Set(['string', 'number', 'boolean', 'timestamp']);
5
+ function record(input, path) {
6
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
7
+ deploymentError('HQ_DEPLOYMENT_TYPE', path);
8
+ const prototype = Object.getPrototypeOf(input);
9
+ if (prototype !== null && prototype !== Object.prototype)
10
+ deploymentError('HQ_DEPLOYMENT_UNSAFE_OBJECT', path);
11
+ for (const key of Reflect.ownKeys(input)) {
12
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
13
+ if (typeof key !== 'string' || !descriptor?.enumerable || !('value' in descriptor)) {
14
+ deploymentError('HQ_DEPLOYMENT_UNSAFE_OBJECT', path);
15
+ }
16
+ }
17
+ return input;
18
+ }
19
+ function list(input, path, maxItems) {
20
+ if (!Array.isArray(input))
21
+ deploymentError('HQ_DEPLOYMENT_TYPE', path);
22
+ if (Object.getPrototypeOf(input) !== Array.prototype || Object.getOwnPropertySymbols(input).length > 0
23
+ || Object.keys(input).length !== input.length) {
24
+ deploymentError('HQ_DEPLOYMENT_UNSAFE_OBJECT', path);
25
+ }
26
+ if (input.length === 0)
27
+ deploymentError('HQ_DEPLOYMENT_INVALID_VALUE', path);
28
+ if (input.length > maxItems)
29
+ deploymentError('HQ_DEPLOYMENT_TOO_MANY_ITEMS', path);
30
+ // Read descriptors, never elements, so a getter is refused without running.
31
+ const descriptors = Object.getOwnPropertyDescriptors(input);
32
+ for (let index = 0; index < input.length; index += 1) {
33
+ const descriptor = descriptors[String(index)];
34
+ if (!descriptor?.enumerable || !('value' in descriptor))
35
+ deploymentError('HQ_DEPLOYMENT_UNSAFE_OBJECT', `${path}[${index}]`);
36
+ }
37
+ return input;
38
+ }
39
+ function exact(value, keys, path) {
40
+ for (const key of Object.keys(value))
41
+ if (!keys.includes(key))
42
+ deploymentError('HQ_DEPLOYMENT_UNKNOWN_FIELD', `${path}.${key}`);
43
+ for (const key of keys)
44
+ if (!Object.hasOwn(value, key))
45
+ deploymentError('HQ_DEPLOYMENT_TYPE', `${path}.${key}`);
46
+ }
47
+ function parseIdentifier(value, path, parse) {
48
+ try {
49
+ return parse(value);
50
+ }
51
+ catch (error) {
52
+ if (error instanceof ProtocolIdentifierError)
53
+ deploymentError('HQ_DEPLOYMENT_INVALID_IDENTIFIER', path);
54
+ throw error;
55
+ }
56
+ }
57
+ /**
58
+ * Validate an RFC 0028 SQL source: its shape, then the SQL rules and the
59
+ * dependency coverage `analyzeProtocolSqlSource` checks.
60
+ */
61
+ export function validateProtocolSqlSource(input, path, limits) {
62
+ const value = record(input, path);
63
+ exact(value, ['kind', 'dialect', 'sql', 'alias', 'dependencies', 'columns'], path);
64
+ if (value.kind !== 'sql')
65
+ deploymentError('HQ_DEPLOYMENT_INVALID_VALUE', `${path}.kind`);
66
+ if (value.dialect !== 'clickhouse')
67
+ deploymentError('HQ_DEPLOYMENT_INVALID_VALUE', `${path}.dialect`);
68
+ if (typeof value.sql !== 'string')
69
+ deploymentError('HQ_DEPLOYMENT_TYPE', `${path}.sql`);
70
+ const alias = parseIdentifier(value.alias, `${path}.alias`, parseProtocolIdentifier);
71
+ const dependencies = list(value.dependencies, `${path}.dependencies`, PROTOCOL_SQL_SOURCE_MAX_DEPENDENCIES)
72
+ .map((dependency, index) => parseIdentifier(dependency, `${path}.dependencies[${index}]`, parseProtocolQualifiedIdentifier));
73
+ if (new Set(dependencies).size !== dependencies.length)
74
+ deploymentError('HQ_DEPLOYMENT_INVALID_VALUE', `${path}.dependencies`);
75
+ const columns = list(value.columns, `${path}.columns`, limits.maxDatasetItems).map((item, index) => {
76
+ const columnPath = `${path}.columns[${index}]`;
77
+ const column = record(item, columnPath);
78
+ exact(column, ['name', 'type'], columnPath);
79
+ const name = parseIdentifier(column.name, `${columnPath}.name`, parseProtocolIdentifier);
80
+ if (typeof column.type !== 'string' || !FIELD_TYPES.has(column.type))
81
+ deploymentError('HQ_DEPLOYMENT_INVALID_VALUE', `${columnPath}.type`);
82
+ return Object.freeze({ name, type: column.type });
83
+ });
84
+ if (new Set(columns.map(column => column.name)).size !== columns.length) {
85
+ deploymentError('HQ_DEPLOYMENT_INVALID_VALUE', `${path}.columns`);
86
+ }
87
+ const analysis = analyzeProtocolSqlSource(value.sql, dependencies);
88
+ if (!analysis.ok) {
89
+ if (analysis.reason === 'too-large')
90
+ deploymentError('HQ_DEPLOYMENT_TOO_LARGE', `${path}.sql`);
91
+ if (analysis.reason === 'undeclared-dependency' || analysis.reason === 'unused-dependency') {
92
+ deploymentError('HQ_DEPLOYMENT_INVALID_REFERENCE', `${path}.dependencies`);
93
+ }
94
+ deploymentError('HQ_DEPLOYMENT_INVALID_VALUE', `${path}.sql`);
95
+ }
96
+ return Object.freeze({
97
+ kind: 'sql',
98
+ dialect: 'clickhouse',
99
+ sql: value.sql,
100
+ alias,
101
+ dependencies: Object.freeze(dependencies),
102
+ columns: Object.freeze(columns),
103
+ });
104
+ }
105
+ export function isProtocolSqlSource(source) {
106
+ return typeof source === 'object' && source !== null && source.kind === 'sql';
107
+ }