@hypequery/datasets 0.30.0 → 0.32.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 (46) hide show
  1. package/dist/client-contract/build-from-deployment.d.ts +8 -0
  2. package/dist/client-contract/build-from-deployment.d.ts.map +1 -1
  3. package/dist/client-contract/build-from-deployment.js +1 -1
  4. package/dist/client-contract/deployment-annotations.d.ts +8 -2
  5. package/dist/client-contract/deployment-annotations.d.ts.map +1 -1
  6. package/dist/client-contract/deployment-annotations.js +37 -7
  7. package/dist/cloud-publication.d.ts +37 -0
  8. package/dist/cloud-publication.d.ts.map +1 -0
  9. package/dist/cloud-publication.js +46 -0
  10. package/dist/cloud-publishing.d.ts +14 -1
  11. package/dist/cloud-publishing.d.ts.map +1 -1
  12. package/dist/cloud-publishing.js +16 -0
  13. package/dist/codegen/cloud-source.d.ts +8 -0
  14. package/dist/codegen/cloud-source.d.ts.map +1 -0
  15. package/dist/codegen/cloud-source.js +90 -0
  16. package/dist/codegen/dataset-source.d.ts +19 -0
  17. package/dist/codegen/dataset-source.d.ts.map +1 -0
  18. package/dist/codegen/dataset-source.js +223 -0
  19. package/dist/codegen/errors.d.ts +11 -0
  20. package/dist/codegen/errors.d.ts.map +1 -0
  21. package/dist/codegen/errors.js +15 -0
  22. package/dist/codegen/formula-source.d.ts +8 -0
  23. package/dist/codegen/formula-source.d.ts.map +1 -0
  24. package/dist/codegen/formula-source.js +83 -0
  25. package/dist/codegen/index.d.ts +28 -0
  26. package/dist/codegen/index.d.ts.map +1 -0
  27. package/dist/codegen/index.js +67 -0
  28. package/dist/codegen/utils/declaration-order.d.ts +9 -0
  29. package/dist/codegen/utils/declaration-order.d.ts.map +1 -0
  30. package/dist/codegen/utils/declaration-order.js +28 -0
  31. package/dist/codegen/utils/member-order.d.ts +17 -0
  32. package/dist/codegen/utils/member-order.d.ts.map +1 -0
  33. package/dist/codegen/utils/member-order.js +52 -0
  34. package/dist/codegen/utils/naming.d.ts +7 -0
  35. package/dist/codegen/utils/naming.d.ts.map +1 -0
  36. package/dist/codegen/utils/naming.js +22 -0
  37. package/dist/codegen/utils/source-writer.d.ts +35 -0
  38. package/dist/codegen/utils/source-writer.d.ts.map +1 -0
  39. package/dist/codegen/utils/source-writer.js +121 -0
  40. package/dist/index.d.ts +2 -0
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +1 -0
  43. package/dist/utils/agent-catalog-projection.d.ts +9 -0
  44. package/dist/utils/agent-catalog-projection.d.ts.map +1 -1
  45. package/dist/utils/agent-catalog-projection.js +18 -3
  46. package/package.json +11 -3
@@ -21,6 +21,14 @@ export interface BuildClientContractOptions {
21
21
  * turns them on; advertising one the host drops would return the wrong rows.
22
22
  */
23
23
  readonly capabilities?: ClientContractCapabilities;
24
+ /**
25
+ * Also advertise each field's synonyms, examples, format, unit and currency
26
+ * in its annotations. Validators released before these members existed reject
27
+ * them, so a live discovery route turns this on only for a request whose
28
+ * `x-hypequery-client-features` header asks for them
29
+ * (`acceptsClientFieldMetadata` from `@hypequery/protocol`). Off by default.
30
+ */
31
+ readonly fieldMetadata?: boolean;
24
32
  }
25
33
  export interface ClientContractCapabilities {
26
34
  /** Accepts `having` predicates on measures. */
@@ -1 +1 @@
1
- {"version":3,"file":"build-from-deployment.d.ts","sourceRoot":"","sources":["../../src/client-contract/build-from-deployment.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,8BAA8B,EACnC,KAAK,0BAA0B,EAC/B,KAAK,yBAAyB,EAC/B,MAAM,qBAAqB,CAAC;AAI7B,OAAO,EAAmD,KAAK,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAEtH,MAAM,WAAW,0BAA0B;IACzC,+EAA+E;IAC/E,QAAQ,CAAC,OAAO,CAAC,EAAE,qBAAqB,CAAC;IACzC;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,uGAAuG;IACvG,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAClD,8DAA8D;IAC9D,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,GAAG,YAAY,CAAC;IACvC,mEAAmE;IACnE,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,yBAAyB,KAAK,OAAO,CAAC;IACnE;;;;;OAKG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,0BAA0B,CAAC;CACpD;AAED,MAAM,WAAW,0BAA0B;IACzC,+CAA+C;IAC/C,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B,yDAAyD;IACzD,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B;AA4DD;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,0BAA0B,EACpC,OAAO,GAAE,0BAA+B,GACvC,8BAA8B,CAchC"}
1
+ {"version":3,"file":"build-from-deployment.d.ts","sourceRoot":"","sources":["../../src/client-contract/build-from-deployment.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,8BAA8B,EACnC,KAAK,0BAA0B,EAC/B,KAAK,yBAAyB,EAC/B,MAAM,qBAAqB,CAAC;AAI7B,OAAO,EAAmD,KAAK,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAEtH,MAAM,WAAW,0BAA0B;IACzC,+EAA+E;IAC/E,QAAQ,CAAC,OAAO,CAAC,EAAE,qBAAqB,CAAC;IACzC;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,uGAAuG;IACvG,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAClD,8DAA8D;IAC9D,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,GAAG,YAAY,CAAC;IACvC,mEAAmE;IACnE,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,yBAAyB,KAAK,OAAO,CAAC;IACnE;;;;;OAKG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,0BAA0B,CAAC;IACnD;;;;;;OAMG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,OAAO,CAAC;CAClC;AAED,MAAM,WAAW,0BAA0B;IACzC,+CAA+C;IAC/C,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B,yDAAyD;IACzD,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B;AA8DD;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,0BAA0B,EACpC,OAAO,GAAE,0BAA+B,GACvC,8BAA8B,CAchC"}
@@ -31,7 +31,7 @@ function endpointDescriptor(dataset, options, profile) {
31
31
  throw new Error(`Client export: dataset "${dataset.name}" selects ${defaultMeasures.length} measures by default, `
32
32
  + `more than the host's measure budget of ${limits.maxMeasures}. Raise the budget, or set the dataset's limits.maxMeasures.`);
33
33
  }
34
- const annotations = endpointAnnotations(dataset, Object.keys(dimensions), Object.keys(measures));
34
+ const annotations = endpointAnnotations(dataset, Object.keys(dimensions), Object.keys(measures), options.fieldMetadata === true);
35
35
  return {
36
36
  id: dataset.name,
37
37
  kind: 'dataset',
@@ -1,6 +1,12 @@
1
1
  import type { ClientEndpointAnnotations, ProtocolDeploymentDataset } from '@hypequery/protocol';
2
2
  /** Fold whitespace runs so multi-line definitions stay advertisable; omit blank text. */
3
3
  export declare function annotationText(value: string | undefined): string | undefined;
4
- /** Group text from the dataset; field text for each advertised dimension and measure. */
5
- export declare function endpointAnnotations(dataset: ProtocolDeploymentDataset, dimensions: readonly string[], measures: readonly string[]): ClientEndpointAnnotations | undefined;
4
+ /** Folded, non-blank, first-occurrence items; omitted when none remain. */
5
+ export declare function annotationList(values: readonly string[] | undefined): string[] | undefined;
6
+ /**
7
+ * Group text from the dataset; field text for each advertised dimension and
8
+ * measure. With `fieldMetadata`, fields also carry their synonyms, examples,
9
+ * format, unit and currency.
10
+ */
11
+ export declare function endpointAnnotations(dataset: ProtocolDeploymentDataset, dimensions: readonly string[], measures: readonly string[], fieldMetadata?: boolean): ClientEndpointAnnotations | undefined;
6
12
  //# sourceMappingURL=deployment-annotations.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"deployment-annotations.d.ts","sourceRoot":"","sources":["../../src/client-contract/deployment-annotations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,yBAAyB,EAEzB,yBAAyB,EAC1B,MAAM,qBAAqB,CAAC;AAE7B,yFAAyF;AACzF,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAI5E;AASD,yFAAyF;AACzF,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,yBAAyB,EAClC,UAAU,EAAE,SAAS,MAAM,EAAE,EAC7B,QAAQ,EAAE,SAAS,MAAM,EAAE,GAC1B,yBAAyB,GAAG,SAAS,CAgBvC"}
1
+ {"version":3,"file":"deployment-annotations.d.ts","sourceRoot":"","sources":["../../src/client-contract/deployment-annotations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,yBAAyB,EAEzB,yBAAyB,EAE1B,MAAM,qBAAqB,CAAC;AAE7B,yFAAyF;AACzF,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAI5E;AAED,2EAA2E;AAC3E,wBAAgB,cAAc,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,GAAG,MAAM,EAAE,GAAG,SAAS,CAI1F;AAwBD;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,yBAAyB,EAClC,UAAU,EAAE,SAAS,MAAM,EAAE,EAC7B,QAAQ,EAAE,SAAS,MAAM,EAAE,EAC3B,aAAa,UAAQ,GACpB,yBAAyB,GAAG,SAAS,CAgBvC"}
@@ -5,22 +5,52 @@ export function annotationText(value) {
5
5
  const folded = value.split(/\s+/).filter(Boolean).join(' ');
6
6
  return folded.trim() ? folded : undefined;
7
7
  }
8
- function fieldAnnotation(definition) {
8
+ /** Folded, non-blank, first-occurrence items; omitted when none remain. */
9
+ export function annotationList(values) {
10
+ if (values === undefined)
11
+ return undefined;
12
+ const items = [...new Set(values.flatMap(value => annotationText(value) ?? []))];
13
+ return items.length ? items : undefined;
14
+ }
15
+ function fieldAnnotation(definition, fieldMetadata) {
16
+ const node = {};
9
17
  const label = annotationText(definition.label);
10
18
  const description = annotationText(definition.description);
11
- if (label === undefined && description === undefined)
12
- return undefined;
13
- return { ...(label !== undefined ? { label } : {}), ...(description !== undefined ? { description } : {}) };
19
+ if (label !== undefined)
20
+ node.label = label;
21
+ if (description !== undefined)
22
+ node.description = description;
23
+ if (fieldMetadata) {
24
+ const synonyms = annotationList(definition.synonyms);
25
+ const examples = annotationList(definition.examples);
26
+ const format = annotationText(definition.format);
27
+ const unit = annotationText(definition.unit);
28
+ if (synonyms !== undefined)
29
+ node.synonyms = synonyms;
30
+ if (examples !== undefined)
31
+ node.examples = examples;
32
+ if (format !== undefined)
33
+ node.format = format;
34
+ if (unit !== undefined)
35
+ node.unit = unit;
36
+ if (definition.currency !== undefined)
37
+ node.currency = definition.currency;
38
+ }
39
+ return Object.keys(node).length ? node : undefined;
14
40
  }
15
- /** Group text from the dataset; field text for each advertised dimension and measure. */
16
- export function endpointAnnotations(dataset, dimensions, measures) {
41
+ /**
42
+ * Group text from the dataset; field text for each advertised dimension and
43
+ * measure. With `fieldMetadata`, fields also carry their synonyms, examples,
44
+ * format, unit and currency.
45
+ */
46
+ export function endpointAnnotations(dataset, dimensions, measures, fieldMetadata = false) {
17
47
  const advertised = [
18
48
  ...dataset.dimensions.filter(item => dimensions.includes(item.name)),
19
49
  ...dataset.measures.filter(item => measures.includes(item.name)),
20
50
  ];
21
51
  // Object.fromEntries defines each name as an own key, `__proto__` included.
22
52
  const fields = Object.fromEntries(advertised.flatMap(definition => {
23
- const node = fieldAnnotation(definition);
53
+ const node = fieldAnnotation(definition, fieldMetadata);
24
54
  return node ? [[definition.name, node]] : [];
25
55
  }));
26
56
  const description = annotationText(dataset.description);
@@ -0,0 +1,37 @@
1
+ import { type ProtocolBusinessContext, type ProtocolDeploymentContract } from '@hypequery/protocol';
2
+ /** Business context as authored in code: the document without its header. */
3
+ export type BusinessContextInput = Omit<ProtocolBusinessContext, 'kind' | 'version'>;
4
+ /**
5
+ * Everything `hypequery deploy` publishes to Cloud from a code project.
6
+ *
7
+ * The deployment contract stays the executable source of truth; the business
8
+ * context travels beside it in the same immutable release, so publishing,
9
+ * staging and rollback move both together.
10
+ */
11
+ export interface CloudPublication {
12
+ readonly kind: 'hypequery-cloud-publication';
13
+ readonly version: 1;
14
+ readonly deployment: ProtocolDeploymentContract;
15
+ readonly businessContext?: ProtocolBusinessContext;
16
+ }
17
+ export interface CloudPublicationOptions {
18
+ /** The result of `publishToCloud({ datasets, access })`. */
19
+ readonly deployment: ProtocolDeploymentContract;
20
+ /** Reviewed business context: summary, KPIs, glossary, conventions, caveats. */
21
+ readonly businessContext?: ProtocolBusinessContext | BusinessContextInput;
22
+ }
23
+ /**
24
+ * Declare reviewed business context for AI analysts in Cloud.
25
+ *
26
+ * Text is trimmed and empty lists are dropped. Throws a
27
+ * `ProtocolBusinessContextError` naming the offending path when the document
28
+ * is invalid, e.g. a glossary term defined twice.
29
+ */
30
+ export declare function defineBusinessContext(input: BusinessContextInput): ProtocolBusinessContext;
31
+ /**
32
+ * Bundle a deployment contract with its business context for Cloud.
33
+ * Export the result as `cloud` from the deployment entrypoint. A bare
34
+ * `publishToCloud(...)` export remains valid and publishes no context.
35
+ */
36
+ export declare function defineCloudPublication(options: CloudPublicationOptions): CloudPublication;
37
+ //# sourceMappingURL=cloud-publication.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloud-publication.d.ts","sourceRoot":"","sources":["../src/cloud-publication.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,uBAAuB,EAC5B,KAAK,0BAA0B,EAChC,MAAM,qBAAqB,CAAC;AAE7B,6EAA6E;AAC7E,MAAM,MAAM,oBAAoB,GAAG,IAAI,CAAC,uBAAuB,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;AAErF;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,IAAI,EAAE,6BAA6B,CAAC;IAC7C,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;IACpB,QAAQ,CAAC,UAAU,EAAE,0BAA0B,CAAC;IAChD,QAAQ,CAAC,eAAe,CAAC,EAAE,uBAAuB,CAAC;CACpD;AAED,MAAM,WAAW,uBAAuB;IACtC,4DAA4D;IAC5D,QAAQ,CAAC,UAAU,EAAE,0BAA0B,CAAC;IAChD,gFAAgF;IAChF,QAAQ,CAAC,eAAe,CAAC,EAAE,uBAAuB,GAAG,oBAAoB,CAAC;CAC3E;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,oBAAoB,GAAG,uBAAuB,CAS1F;AAMD;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,uBAAuB,GAAG,gBAAgB,CAqBzF"}
@@ -0,0 +1,46 @@
1
+ import { validateProtocolBusinessContext, } from '@hypequery/protocol';
2
+ /**
3
+ * Declare reviewed business context for AI analysts in Cloud.
4
+ *
5
+ * Text is trimmed and empty lists are dropped. Throws a
6
+ * `ProtocolBusinessContextError` naming the offending path when the document
7
+ * is invalid, e.g. a glossary term defined twice.
8
+ */
9
+ export function defineBusinessContext(input) {
10
+ if (typeof input !== 'object' || input === null || Array.isArray(input)) {
11
+ throw new TypeError('defineBusinessContext expects an object.');
12
+ }
13
+ return validateProtocolBusinessContext({
14
+ ...input,
15
+ kind: 'hypequery-business-context',
16
+ version: 1,
17
+ });
18
+ }
19
+ function isBusinessContextDocument(value) {
20
+ return 'kind' in value && value.kind === 'hypequery-business-context';
21
+ }
22
+ /**
23
+ * Bundle a deployment contract with its business context for Cloud.
24
+ * Export the result as `cloud` from the deployment entrypoint. A bare
25
+ * `publishToCloud(...)` export remains valid and publishes no context.
26
+ */
27
+ export function defineCloudPublication(options) {
28
+ const deployment = options?.deployment;
29
+ if (typeof deployment !== 'object' || deployment === null
30
+ || deployment.kind !== 'hypequery-deployment') {
31
+ throw new Error('defineCloudPublication requires `deployment: publishToCloud({ datasets, access })`.');
32
+ }
33
+ const input = options.businessContext;
34
+ let businessContext;
35
+ if (input !== undefined) {
36
+ businessContext = isBusinessContextDocument(input)
37
+ ? validateProtocolBusinessContext(input)
38
+ : defineBusinessContext(input);
39
+ }
40
+ return Object.freeze({
41
+ kind: 'hypequery-cloud-publication',
42
+ version: 1,
43
+ deployment: options.deployment,
44
+ ...(businessContext ? { businessContext } : {}),
45
+ });
46
+ }
@@ -1,4 +1,4 @@
1
- import { type ProtocolDeploymentContract } from '@hypequery/protocol';
1
+ import { type ProtocolDeploymentContract, type ProtocolEndpointPolicy } from '@hypequery/protocol';
2
2
  import type { AnyDatasetInstance } from './types.js';
3
3
  export interface CloudPublishingOptions {
4
4
  /** Datasets exposed to Cloud. Relationships are included as supporting datasets. */
@@ -13,6 +13,19 @@ export interface CloudPublishingOptions {
13
13
  readonly roles: readonly string[];
14
14
  readonly scopes: readonly string[];
15
15
  }>>;
16
+ /**
17
+ * The exact endpoint policy for a published dataset, by name. It replaces
18
+ * the policy derived from `access` (authenticated, tenant auto-injected from
19
+ * `tenantKey`, `maxLimit` from `limits.maxResultSize` or 1000), so it can say
20
+ * what that derivation can't: an optional tenant, a cache TTL, no row limit.
21
+ * Exported Cloud models use it to stay byte-identical (decision 0020).
22
+ */
23
+ readonly endpoints?: Readonly<Record<string, ProtocolEndpointPolicy>>;
24
+ /**
25
+ * Datasets published without an endpoint, beyond those reached through a
26
+ * relationship (which are always included). They can't be queried directly.
27
+ */
28
+ readonly supporting?: Readonly<Record<string, AnyDatasetInstance>>;
16
29
  }
17
30
  /**
18
31
  * Declare the dataset-only contract uploaded by `hypequery deploy`.
@@ -1 +1 @@
1
- {"version":3,"file":"cloud-publishing.d.ts","sourceRoot":"","sources":["../src/cloud-publishing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,0BAA0B,EAA+B,MAAM,qBAAqB,CAAC;AAEnG,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAGrD,MAAM,WAAW,sBAAsB;IACrC,oFAAoF;IACpF,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC,CAAC;IAChE,2EAA2E;IAC3E,QAAQ,CAAC,MAAM,EAAE;QACf,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;QAClC,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;KACpC,CAAC;IACF,uEAAuE;IACvE,QAAQ,CAAC,aAAa,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE;QAC/C,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;QAClC,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;KACpC,CAAC,CAAC,CAAC;CACL;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,0BAA0B,CAyD1F"}
1
+ {"version":3,"file":"cloud-publishing.d.ts","sourceRoot":"","sources":["../src/cloud-publishing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,0BAA0B,EAAE,KAAK,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAEnG,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAGrD,MAAM,WAAW,sBAAsB;IACrC,oFAAoF;IACpF,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC,CAAC;IAChE,2EAA2E;IAC3E,QAAQ,CAAC,MAAM,EAAE;QACf,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;QAClC,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;KACpC,CAAC;IACF,uEAAuE;IACvE,QAAQ,CAAC,aAAa,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE;QAC/C,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;QAClC,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;KACpC,CAAC,CAAC,CAAC;IACJ;;;;;;OAMG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,sBAAsB,CAAC,CAAC,CAAC;IACtE;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC,CAAC;CACpE;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,0BAA0B,CAyE1F"}
@@ -19,6 +19,17 @@ export function publishToCloud(options) {
19
19
  collectCloudDatasets(datasets, dataset);
20
20
  exposed.add(dataset.name);
21
21
  }
22
+ for (const [, dataset] of Object.entries(options.supporting ?? {})) {
23
+ if (exposed.has(dataset.name)) {
24
+ throw new Error(`Cloud dataset "${dataset.name}" can't be both published and supporting.`);
25
+ }
26
+ collectCloudDatasets(datasets, dataset);
27
+ }
28
+ for (const name of Object.keys(options.endpoints ?? {})) {
29
+ if (!exposed.has(name)) {
30
+ throw new Error(`Cloud endpoint policy names an unpublished dataset: "${name}".`);
31
+ }
32
+ }
22
33
  for (const dataset of datasets.values()) {
23
34
  const namedMetrics = dataset.metrics;
24
35
  if (namedMetrics && Object.keys(namedMetrics).length > 0) {
@@ -39,6 +50,11 @@ export function publishToCloud(options) {
39
50
  for (const dataset of datasets.values()) {
40
51
  if (!exposed.has(dataset.name))
41
52
  continue;
53
+ const explicit = options.endpoints?.[dataset.name];
54
+ if (explicit) {
55
+ endpoints[dataset.name] = explicit;
56
+ continue;
57
+ }
42
58
  const access = options.datasetAccess?.[dataset.name] ?? options.access;
43
59
  endpoints[dataset.name] = {
44
60
  access: {
@@ -0,0 +1,8 @@
1
+ import type { ProtocolDeploymentDataset } from '@hypequery/protocol';
2
+ export interface CloudSource {
3
+ readonly code: string;
4
+ /** Dataset constants `cloud.ts` imports from `datasets.ts`, besides `datasets`. */
5
+ readonly supporting: readonly string[];
6
+ }
7
+ export declare function cloudSource(datasets: readonly ProtocolDeploymentDataset[], constants: ReadonlyMap<string, string>, importSource: string): CloudSource;
8
+ //# sourceMappingURL=cloud-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloud-source.d.ts","sourceRoot":"","sources":["../../src/codegen/cloud-source.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAA0B,MAAM,qBAAqB,CAAC;AAyD7F,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,mFAAmF;IACnF,QAAQ,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;CACxC;AAED,wBAAgB,WAAW,CACzB,QAAQ,EAAE,SAAS,yBAAyB,EAAE,EAC9C,SAAS,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,EACtC,YAAY,EAAE,MAAM,GACnB,WAAW,CAsDb"}
@@ -0,0 +1,90 @@
1
+ import { stableStringify, uniqueSorted } from '../utils/canonical-json.js';
2
+ import { code, literal } from './utils/source-writer.js';
3
+ /** What `publishToCloud` derives for `dataset` under `access`. */
4
+ function derivedEndpoint(dataset, access) {
5
+ return {
6
+ access: { kind: 'authenticated', roles: uniqueSorted(access.roles), scopes: uniqueSorted(access.scopes) },
7
+ tenant: dataset.tenant.kind === 'required'
8
+ ? { kind: 'required', mode: 'auto-inject', column: dataset.tenant.field }
9
+ : { kind: 'not-required' },
10
+ maxLimit: dataset.limits?.maxResultSize ?? 1_000,
11
+ path: `/api/analytics/datasets/${String(dataset.name)}/query`,
12
+ };
13
+ }
14
+ /** The access policy that derives this endpoint exactly, if there is one. */
15
+ function derivingAccess(dataset) {
16
+ const endpoint = dataset.endpoint;
17
+ if (endpoint === undefined || endpoint.access.kind !== 'authenticated')
18
+ return undefined;
19
+ const access = { roles: [...endpoint.access.roles], scopes: [...endpoint.access.scopes] };
20
+ return stableStringify(derivedEndpoint(dataset, access)) === stableStringify(endpoint) ? access : undefined;
21
+ }
22
+ /** Names reachable from `start` through relationships, `start` included. */
23
+ function reachable(start, byName) {
24
+ const seen = new Set();
25
+ const queue = [...start];
26
+ while (queue.length > 0) {
27
+ const name = queue.pop();
28
+ if (seen.has(name))
29
+ continue;
30
+ seen.add(name);
31
+ for (const relationship of byName.get(name)?.relationships ?? [])
32
+ queue.push(String(relationship.target));
33
+ }
34
+ return seen;
35
+ }
36
+ export function cloudSource(datasets, constants, importSource) {
37
+ const exposed = datasets.filter(dataset => dataset.endpoint !== undefined);
38
+ const byName = new Map(datasets.map(dataset => [String(dataset.name), dataset]));
39
+ const reached = reachable(exposed.map(dataset => String(dataset.name)), byName);
40
+ const accessByDataset = new Map(exposed.map(dataset => [String(dataset.name), derivingAccess(dataset)]));
41
+ const counts = new Map();
42
+ for (const access of accessByDataset.values()) {
43
+ if (access === undefined)
44
+ continue;
45
+ const key = stableStringify(access);
46
+ const entry = counts.get(key) ?? { access, count: 0 };
47
+ entry.count += 1;
48
+ counts.set(key, entry);
49
+ }
50
+ // The most common policy; ties go to the first in sorted key order, so the
51
+ // choice doesn't depend on dataset order.
52
+ const defaultAccess = [...counts.entries()]
53
+ .sort(([leftKey, left], [rightKey, right]) => right.count - left.count || (leftKey < rightKey ? -1 : 1))[0]?.[1].access
54
+ ?? { roles: [], scopes: [] };
55
+ const defaultKey = stableStringify(defaultAccess);
56
+ const datasetAccess = {};
57
+ const endpoints = {};
58
+ for (const dataset of exposed) {
59
+ const name = String(dataset.name);
60
+ const access = accessByDataset.get(name);
61
+ if (access === undefined)
62
+ endpoints[name] = dataset.endpoint;
63
+ else if (stableStringify(access) !== defaultKey)
64
+ datasetAccess[name] = access;
65
+ }
66
+ const supporting = datasets
67
+ .filter(dataset => dataset.endpoint === undefined && !reached.has(String(dataset.name)))
68
+ .map(dataset => String(dataset.name));
69
+ const options = {
70
+ datasets: code('datasets'),
71
+ access: { roles: [...defaultAccess.roles], scopes: [...defaultAccess.scopes] },
72
+ datasetAccess: Object.keys(datasetAccess).length > 0 ? datasetAccess : undefined,
73
+ endpoints: Object.keys(endpoints).length > 0 ? endpoints : undefined,
74
+ supporting: supporting.length > 0
75
+ ? Object.fromEntries(supporting.map(name => [name, code(constants.get(name))]))
76
+ : undefined,
77
+ };
78
+ const supportingConstants = supporting.map(name => constants.get(name));
79
+ const fromDatasets = ['datasets', ...supportingConstants].join(', ');
80
+ return {
81
+ code: [
82
+ `import { publishToCloud } from ${literal(importSource)};`,
83
+ `import { ${fromDatasets} } from './datasets.js';`,
84
+ '',
85
+ `export const cloud = publishToCloud(${literal(options)});`,
86
+ '',
87
+ ].join('\n'),
88
+ supporting: supportingConstants,
89
+ };
90
+ }
@@ -0,0 +1,19 @@
1
+ import type { ProtocolDeploymentDataset } from '@hypequery/protocol';
2
+ /**
3
+ * One dataset of a deployment contract as a `dataset()` definition.
4
+ *
5
+ * This is `protocol-adapter.ts` run backwards, field by field, and it writes
6
+ * only what that adapter would not default: a column named like its
7
+ * dimension, `filterable: true`, or the filters every filterable dimension
8
+ * gets anyway are left out, as an author would leave them out. Anything the
9
+ * authoring API can't reproduce exactly is refused (`ContractExportError`).
10
+ */
11
+ export interface DatasetSource {
12
+ readonly code: string;
13
+ /** Names imported from `@hypequery/datasets`. */
14
+ readonly imports: ReadonlySet<string>;
15
+ }
16
+ export declare function datasetSource(dataset: ProtocolDeploymentDataset, constants: ReadonlyMap<string, string>,
17
+ /** Datasets declared above this one in the file. */
18
+ earlier: ReadonlySet<string>): DatasetSource;
19
+ //# sourceMappingURL=dataset-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dataset-source.d.ts","sourceRoot":"","sources":["../../src/codegen/dataset-source.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAKV,yBAAyB,EAK1B,MAAM,qBAAqB,CAAC;AAQ7B;;;;;;;;GAQG;AAEH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,iDAAiD;IACjD,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;CACvC;AAwCD,wBAAgB,aAAa,CAC3B,OAAO,EAAE,yBAAyB,EAClC,SAAS,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC;AACtC,oDAAoD;AACpD,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,GAC3B,aAAa,CA4Lf"}
@@ -0,0 +1,223 @@
1
+ import { SEMANTIC_FILTER_OPERATORS } from '../constants.js';
2
+ import { stableStringify } from '../utils/canonical-json.js';
3
+ import { ContractExportError } from './errors.js';
4
+ import { formulaSource } from './formula-source.js';
5
+ import { call, code, literal } from './utils/source-writer.js';
6
+ const METADATA_KEYS = ['examples', 'synonyms', 'format', 'unit', 'currency', 'sensitivity'];
7
+ /** The forward adapter's output schema for a SQL-backed field of this type. */
8
+ function fieldSchema(type) {
9
+ switch (type) {
10
+ case 'string':
11
+ case 'timestamp':
12
+ return { kind: 'string' };
13
+ case 'number':
14
+ return { kind: 'number' };
15
+ case 'boolean':
16
+ return { kind: 'boolean' };
17
+ default:
18
+ return { kind: 'any' };
19
+ }
20
+ }
21
+ function sameJson(left, right) {
22
+ return stableStringify(left) === stableStringify(right);
23
+ }
24
+ /** `options` when any of its values is set, else `undefined`: `dimension.string()` over `dimension.string({})`. */
25
+ function present(options) {
26
+ return Object.values(options).some(value => value !== undefined) ? options : undefined;
27
+ }
28
+ /** A filter value as authored: plain where the forward adapter tags it the same way. */
29
+ function filterValue(value) {
30
+ if (value === null || typeof value !== 'object')
31
+ return value;
32
+ const tagged = value.$hypequery;
33
+ if (tagged?.type === 'array' && Array.isArray(tagged.values)
34
+ && tagged.values.every(item => item === null || typeof item !== 'object')) {
35
+ return tagged.values;
36
+ }
37
+ // Any other tagged value is passed through unchanged by the adapter.
38
+ return value;
39
+ }
40
+ export function datasetSource(dataset, constants,
41
+ /** Datasets declared above this one in the file. */
42
+ earlier) {
43
+ const name = String(dataset.name);
44
+ const imports = new Set(['dataset']);
45
+ const refuse = (feature, detail) => new ContractExportError(name, feature, detail);
46
+ const dimensionTypes = new Map(dataset.dimensions.map(item => [String(item.name), item.type]));
47
+ const metadata = (item, subject) => {
48
+ if (item.timezone !== undefined) {
49
+ throw refuse(subject, 'semantic timezone metadata has no dataset() equivalent');
50
+ }
51
+ return Object.fromEntries(METADATA_KEYS.filter(key => item[key] !== undefined).map(key => [key, item[key]]));
52
+ };
53
+ const sql = (expression, expected, subject) => {
54
+ if (expression.dialect !== 'clickhouse' || !sameJson(expression.output, expected)) {
55
+ throw refuse(subject, 'its SQL expression has an output type or dialect code does not produce');
56
+ }
57
+ return { sql: expression.sql, dependencies: expression.dependencies.map(String) };
58
+ };
59
+ const dimension = (item) => {
60
+ imports.add('dimension');
61
+ const dimensionName = String(item.name);
62
+ const subject = `dimension "${dimensionName}"`;
63
+ const source = item.source.kind === 'column'
64
+ ? item.source.column === dimensionName ? {} : { column: item.source.column }
65
+ : sql(item.source, fieldSchema(item.type), subject);
66
+ const options = {
67
+ label: item.label,
68
+ description: item.description,
69
+ ...source,
70
+ ...(item.filterable ? {} : { filterable: false }),
71
+ ...(item.groupable ? {} : { groupable: false }),
72
+ ...metadata(item, subject),
73
+ };
74
+ return call(`dimension.${item.type}`, [present(options)], ' ');
75
+ };
76
+ const baseMeasure = (item) => {
77
+ imports.add('measure');
78
+ const measureName = String(item.name);
79
+ const subject = `measure "${measureName}"`;
80
+ const field = String(item.field);
81
+ const filters = item.filters.map((expression, index) => measureFilter(expression, subject, index));
82
+ const sqlOptions = item.sql === undefined
83
+ ? {}
84
+ : sql(item.sql, fieldSchema(dimensionTypes.get(field)), subject);
85
+ const options = {
86
+ label: item.label,
87
+ description: item.description,
88
+ ...sqlOptions,
89
+ ...(filters.length > 0 ? { filters } : {}),
90
+ ...metadata(item, subject),
91
+ };
92
+ const opts = present(options);
93
+ const noFiltersOrSql = (helper) => {
94
+ if (filters.length > 0 || item.sql !== undefined) {
95
+ throw refuse(subject, `measure.${helper} can't carry fixed filters or SQL`);
96
+ }
97
+ };
98
+ if (item.level !== undefined && item.aggregation !== 'percentile') {
99
+ throw refuse(subject, `a level on ${item.aggregation} has no dataset() equivalent`);
100
+ }
101
+ switch (item.aggregation) {
102
+ case 'merge':
103
+ noFiltersOrSql('merge');
104
+ if (item.stateFunction === undefined)
105
+ throw refuse(subject, 'a merge needs its state function');
106
+ return call('measure.merge', [item.stateFunction, field, opts], ' ');
107
+ case 'argMax':
108
+ case 'argMin':
109
+ if (filters.length > 0)
110
+ throw refuse(subject, `measure.${item.aggregation} can't carry fixed filters`);
111
+ if (item.argField === undefined)
112
+ throw refuse(subject, `${item.aggregation} needs its argument field`);
113
+ return call(`measure.${item.aggregation}`, [field, String(item.argField), opts], ' ');
114
+ case 'percentile':
115
+ if (item.level === undefined)
116
+ throw refuse(subject, 'a percentile needs its level');
117
+ return item.level === 0.5
118
+ ? call('measure.median', [field, opts], ' ')
119
+ : call('measure.percentile', [field, item.level, opts], ' ');
120
+ default:
121
+ if (item.argField !== undefined || item.stateFunction !== undefined) {
122
+ throw refuse(subject, `extra fields on ${item.aggregation} have no dataset() equivalent`);
123
+ }
124
+ return call(`measure.${item.aggregation}`, [field, opts], ' ');
125
+ }
126
+ };
127
+ const measureFilter = (expression, subject, index) => {
128
+ if (expression.kind !== 'comparison' || expression.left.kind !== 'reference') {
129
+ throw refuse(subject, `fixed filter ${index} is not a field/operator/value comparison`);
130
+ }
131
+ const field = String(expression.left.name);
132
+ if (!('right' in expression) || expression.right === undefined) {
133
+ return { field, operator: expression.operator };
134
+ }
135
+ if (expression.right.kind !== 'literal') {
136
+ throw refuse(subject, `fixed filter ${index} compares with something other than a value`);
137
+ }
138
+ return { field, operator: expression.operator, value: filterValue(expression.right.value) };
139
+ };
140
+ const derivedMeasure = (item) => {
141
+ imports.add('measure');
142
+ const subject = `measure "${String(item.name)}"`;
143
+ const aliases = item.uses.map(use => String(use.alias));
144
+ const formula = formulaSource(item.expression, aliases, reason => refuse(subject, reason));
145
+ for (const helper of formula.helpers)
146
+ imports.add(helper);
147
+ return call('measure.derived', [{
148
+ uses: Object.fromEntries(item.uses.map(use => [String(use.alias), String(use.measure)])),
149
+ formula: code(formula.code),
150
+ label: item.label,
151
+ description: item.description,
152
+ ...metadata(item, subject),
153
+ }], ' ');
154
+ };
155
+ const filters = () => {
156
+ const derived = dataset.dimensions
157
+ .filter(item => item.filterable)
158
+ .map(item => ({ name: String(item.name), field: String(item.name), operators: [...SEMANTIC_FILTER_OPERATORS] }));
159
+ const actual = dataset.filters.map(item => ({ ...item, name: String(item.name), field: String(item.field) }));
160
+ if (sameJson(actual, derived))
161
+ return undefined;
162
+ return Object.fromEntries(dataset.filters.map((item) => [String(item.name), {
163
+ __type: 'filter_definition',
164
+ field: String(item.field),
165
+ ...(sameJson(item.operators, SEMANTIC_FILTER_OPERATORS) ? {} : { operators: [...item.operators] }),
166
+ label: item.label,
167
+ description: item.description,
168
+ ...metadata(item, `filter "${String(item.name)}"`),
169
+ }]));
170
+ };
171
+ const relationships = () => {
172
+ if (dataset.relationships.length === 0)
173
+ return undefined;
174
+ return Object.fromEntries(dataset.relationships.map(item => {
175
+ const subject = `relationship "${String(item.name)}"`;
176
+ if (item.queryable !== (item.kind !== 'hasMany')) {
177
+ throw refuse(subject, `a ${item.queryable ? 'queryable' : 'non-queryable'} ${item.kind} has no dataset() equivalent`);
178
+ }
179
+ const target = constants.get(String(item.target));
180
+ if (target === undefined)
181
+ throw refuse(subject, `its target "${String(item.target)}" is not in the contract`);
182
+ imports.add(item.kind);
183
+ const join = item.keys !== undefined
184
+ ? { keys: item.keys.map(key => ({ from: String(key.from), to: String(key.to) })) }
185
+ : { from: String(item.from), to: String(item.to) };
186
+ // A target declared further down (a cycle, or this dataset itself) can't
187
+ // be inferred while this one is: TypeScript needs the arrow's type.
188
+ const ahead = !earlier.has(String(item.target));
189
+ if (ahead)
190
+ imports.add('type AnyDatasetInstance');
191
+ const arrow = ahead ? `(): AnyDatasetInstance => ${target}` : `() => ${target}`;
192
+ return [String(item.name), call(item.kind, [code(arrow), join], ' ')];
193
+ }));
194
+ };
195
+ const derivedMeasures = dataset.measures.filter((item) => 'kind' in item && item.kind === 'derived');
196
+ const baseMeasures = dataset.measures.filter((item) => !('kind' in item));
197
+ // Base measures, then derived ones: the order the forward adapter lists them in.
198
+ const measures = [
199
+ ...baseMeasures.map(item => [String(item.name), baseMeasure(item)]),
200
+ ...derivedMeasures.map(item => [String(item.name), derivedMeasure(item)]),
201
+ ];
202
+ const config = {
203
+ source: dataset.source,
204
+ description: dataset.description,
205
+ ...metadata(dataset, 'the dataset'),
206
+ rowResolution: dataset.rowResolution,
207
+ freshness: dataset.freshness,
208
+ owner: dataset.owner,
209
+ tenantKey: dataset.tenant.kind === 'required' ? dataset.tenant.field : undefined,
210
+ timeKey: dataset.timeField === undefined ? undefined : String(dataset.timeField),
211
+ defaults: dataset.defaults,
212
+ dimensions: Object.fromEntries(dataset.dimensions.map(item => [String(item.name), dimension(item)])),
213
+ measures: measures.length > 0 ? Object.fromEntries(measures) : undefined,
214
+ filters: filters(),
215
+ relationships: relationships(),
216
+ limits: dataset.limits,
217
+ };
218
+ const constant = constants.get(name);
219
+ return {
220
+ code: `export const ${constant} = dataset(${literal(name)}, ${literal(config)});\n`,
221
+ imports,
222
+ };
223
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * A contract holds something `dataset()` code can't express, so exporting it
3
+ * would change the model. Export refuses rather than writing an approximation
4
+ * (decision 0020 §3); each such feature needs authoring support first.
5
+ */
6
+ export declare class ContractExportError extends Error {
7
+ readonly dataset: string;
8
+ readonly feature: string;
9
+ constructor(dataset: string, feature: string, detail: string);
10
+ }
11
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/codegen/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;gBAEb,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAM7D"}