@hypequery/datasets 0.30.0 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client-contract/build-from-deployment.d.ts +8 -0
- package/dist/client-contract/build-from-deployment.d.ts.map +1 -1
- package/dist/client-contract/build-from-deployment.js +1 -1
- package/dist/client-contract/deployment-annotations.d.ts +8 -2
- package/dist/client-contract/deployment-annotations.d.ts.map +1 -1
- package/dist/client-contract/deployment-annotations.js +37 -7
- package/dist/cloud-publishing.d.ts +14 -1
- package/dist/cloud-publishing.d.ts.map +1 -1
- package/dist/cloud-publishing.js +16 -0
- package/dist/codegen/cloud-source.d.ts +8 -0
- package/dist/codegen/cloud-source.d.ts.map +1 -0
- package/dist/codegen/cloud-source.js +90 -0
- package/dist/codegen/dataset-source.d.ts +19 -0
- package/dist/codegen/dataset-source.d.ts.map +1 -0
- package/dist/codegen/dataset-source.js +223 -0
- package/dist/codegen/errors.d.ts +11 -0
- package/dist/codegen/errors.d.ts.map +1 -0
- package/dist/codegen/errors.js +15 -0
- package/dist/codegen/formula-source.d.ts +8 -0
- package/dist/codegen/formula-source.d.ts.map +1 -0
- package/dist/codegen/formula-source.js +83 -0
- package/dist/codegen/index.d.ts +28 -0
- package/dist/codegen/index.d.ts.map +1 -0
- package/dist/codegen/index.js +67 -0
- package/dist/codegen/utils/declaration-order.d.ts +9 -0
- package/dist/codegen/utils/declaration-order.d.ts.map +1 -0
- package/dist/codegen/utils/declaration-order.js +28 -0
- package/dist/codegen/utils/member-order.d.ts +17 -0
- package/dist/codegen/utils/member-order.d.ts.map +1 -0
- package/dist/codegen/utils/member-order.js +52 -0
- package/dist/codegen/utils/naming.d.ts +7 -0
- package/dist/codegen/utils/naming.d.ts.map +1 -0
- package/dist/codegen/utils/naming.js +22 -0
- package/dist/codegen/utils/source-writer.d.ts +35 -0
- package/dist/codegen/utils/source-writer.d.ts.map +1 -0
- package/dist/codegen/utils/source-writer.js +121 -0
- 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;
|
|
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
|
-
/**
|
|
5
|
-
export declare function
|
|
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,
|
|
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
|
-
|
|
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
|
|
12
|
-
|
|
13
|
-
|
|
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
|
-
/**
|
|
16
|
-
|
|
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);
|
|
@@ -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,
|
|
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"}
|
package/dist/cloud-publishing.js
CHANGED
|
@@ -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"}
|
|
@@ -0,0 +1,15 @@
|
|
|
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 class ContractExportError extends Error {
|
|
7
|
+
dataset;
|
|
8
|
+
feature;
|
|
9
|
+
constructor(dataset, feature, detail) {
|
|
10
|
+
super(`Cannot export ${feature} on dataset "${dataset}": ${detail}`);
|
|
11
|
+
this.name = 'ContractExportError';
|
|
12
|
+
this.dataset = dataset;
|
|
13
|
+
this.feature = feature;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ProtocolExpression } from '@hypequery/protocol';
|
|
2
|
+
export interface FormulaSource {
|
|
3
|
+
readonly code: string;
|
|
4
|
+
/** Helpers from `@hypequery/datasets` the formula calls. */
|
|
5
|
+
readonly helpers: ReadonlySet<string>;
|
|
6
|
+
}
|
|
7
|
+
export declare function formulaSource(expression: ProtocolExpression, aliases: readonly string[], unsupported: (reason: string) => Error): FormulaSource;
|
|
8
|
+
//# sourceMappingURL=formula-source.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"formula-source.d.ts","sourceRoot":"","sources":["../../src/codegen/formula-source.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAiB9D,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,4DAA4D;IAC5D,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;CACvC;AAED,wBAAgB,aAAa,CAC3B,UAAU,EAAE,kBAAkB,EAC9B,OAAO,EAAE,SAAS,MAAM,EAAE,EAC1B,WAAW,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,KAAK,GACrC,aAAa,CA0Ef"}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { isBindingName, literal } from './utils/source-writer.js';
|
|
2
|
+
/**
|
|
3
|
+
* A derived measure's formula as the arrow function an author writes:
|
|
4
|
+
* `({ revenue, orders }) => divide(revenue, nullIfZero(orders))`.
|
|
5
|
+
*
|
|
6
|
+
* It accepts exactly the grammar `protocol-rehydrate-derivation.ts` rebuilds
|
|
7
|
+
* through `formulas.ts`, so the code calls the same helpers that produced the
|
|
8
|
+
* contract and its SQL is byte-identical. Anything else is refused.
|
|
9
|
+
*/
|
|
10
|
+
const BINARY = new Set(['add', 'subtract', 'multiply', 'divide']);
|
|
11
|
+
/** Every helper a formula can call: an input destructured under one of these names would hide it. */
|
|
12
|
+
const HELPERS = new Set([...BINARY, 'nullIfZero', 'floor', 'ceil', 'round', 'coalesce']);
|
|
13
|
+
export function formulaSource(expression, aliases, unsupported) {
|
|
14
|
+
const helpers = new Set();
|
|
15
|
+
const known = new Set(aliases);
|
|
16
|
+
const referenced = new Set();
|
|
17
|
+
// `({ revenue, orders }) => …` where every input can be a binding that hides
|
|
18
|
+
// no helper; otherwise `(inputs) => divide(inputs.divide, …)`.
|
|
19
|
+
const destructure = aliases.every(alias => isBindingName(alias) && !HELPERS.has(alias));
|
|
20
|
+
const reference = (name) => {
|
|
21
|
+
if (!known.has(name))
|
|
22
|
+
return literal(name);
|
|
23
|
+
referenced.add(name);
|
|
24
|
+
return destructure ? name : `inputs[${literal(name)}]`;
|
|
25
|
+
};
|
|
26
|
+
const numeric = (value, what) => {
|
|
27
|
+
if (value.kind !== 'literal' || typeof value.value !== 'number') {
|
|
28
|
+
throw unsupported(`${what} must be a numeric literal`);
|
|
29
|
+
}
|
|
30
|
+
return literal(value.value);
|
|
31
|
+
};
|
|
32
|
+
const arity = (args, expected, name) => {
|
|
33
|
+
if (args.length !== expected) {
|
|
34
|
+
throw unsupported(`"${name}" takes ${expected} argument(s), received ${args.length}`);
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
const operand = (value) => {
|
|
38
|
+
switch (value.kind) {
|
|
39
|
+
case 'reference':
|
|
40
|
+
return reference(String(value.name));
|
|
41
|
+
case 'binary':
|
|
42
|
+
if (!BINARY.has(value.operator)) {
|
|
43
|
+
throw unsupported(`unsupported operator "${value.operator}"`);
|
|
44
|
+
}
|
|
45
|
+
helpers.add(value.operator);
|
|
46
|
+
return `${value.operator}(${operand(value.left)}, ${operand(value.right)})`;
|
|
47
|
+
case 'call': {
|
|
48
|
+
const name = String(value.function);
|
|
49
|
+
helpers.add(name);
|
|
50
|
+
switch (name) {
|
|
51
|
+
case 'nullIfZero':
|
|
52
|
+
case 'floor':
|
|
53
|
+
case 'ceil':
|
|
54
|
+
arity(value.args, 1, name);
|
|
55
|
+
return `${name}(${operand(value.args[0])})`;
|
|
56
|
+
case 'round':
|
|
57
|
+
arity(value.args, 2, name);
|
|
58
|
+
return `round(${operand(value.args[0])}, ${numeric(value.args[1], 'a "round" precision')})`;
|
|
59
|
+
case 'coalesce': {
|
|
60
|
+
arity(value.args, 2, name);
|
|
61
|
+
const fallback = value.args[1];
|
|
62
|
+
const second = fallback.kind === 'literal'
|
|
63
|
+
? numeric(fallback, 'a "coalesce" fallback literal')
|
|
64
|
+
: operand(fallback);
|
|
65
|
+
return `coalesce(${operand(value.args[0])}, ${second})`;
|
|
66
|
+
}
|
|
67
|
+
default:
|
|
68
|
+
throw unsupported(`unsupported function "${name}"`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
default:
|
|
72
|
+
throw unsupported(`a formula cannot contain a "${value.kind}" expression here`);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
if (expression.kind === 'reference') {
|
|
76
|
+
throw unsupported('a formula must combine its inputs rather than name one');
|
|
77
|
+
}
|
|
78
|
+
const body = operand(expression);
|
|
79
|
+
const parameter = destructure
|
|
80
|
+
? referenced.size === 0 ? '()' : `({ ${aliases.filter(alias => referenced.has(alias)).join(', ')} })`
|
|
81
|
+
: referenced.size === 0 ? '()' : '(inputs)';
|
|
82
|
+
return { code: `${parameter} => ${body}`, helpers };
|
|
83
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@hypequery/datasets/codegen`: a deployment contract as the TypeScript that
|
|
3
|
+
* builds it (decision 0020 §3).
|
|
4
|
+
*
|
|
5
|
+
* The output is idiomatic `dataset()` code, a `datasets.ts` and the
|
|
6
|
+
* `cloud.ts` entrypoint `hypequery deploy` reads, and `publishToCloud` over it
|
|
7
|
+
* builds the same contract as the input, with its members in name order (the
|
|
8
|
+
* only order code produces; see `canonicalMemberOrder`). That round trip is
|
|
9
|
+
* the guarantee: anything the authoring API can't reproduce exactly is
|
|
10
|
+
* refused with `ContractExportError` instead of being approximated.
|
|
11
|
+
*/
|
|
12
|
+
import { canonicalMemberOrder } from './utils/member-order.js';
|
|
13
|
+
import { ContractExportError } from './errors.js';
|
|
14
|
+
export { ContractExportError, canonicalMemberOrder };
|
|
15
|
+
export interface GenerateDatasetSourceOptions {
|
|
16
|
+
/** Comment lines at the top of each file, without `//`. */
|
|
17
|
+
readonly header?: readonly string[];
|
|
18
|
+
/** Module the code imports from; `@hypequery/datasets` unless a test points it elsewhere. */
|
|
19
|
+
readonly importSource?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface GeneratedDatasetSource {
|
|
22
|
+
/** File path relative to the output directory, and its contents. */
|
|
23
|
+
readonly files: Readonly<Record<'datasets.ts' | 'cloud.ts', string>>;
|
|
24
|
+
/** The file `hypequery deploy` takes. */
|
|
25
|
+
readonly entrypoint: 'cloud.ts';
|
|
26
|
+
}
|
|
27
|
+
export declare function generateDatasetSource(contract: unknown, options?: GenerateDatasetSourceOptions): GeneratedDatasetSource;
|
|
28
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/codegen/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAQH,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAE/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAGlD,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,CAAC;AAErD,MAAM,WAAW,4BAA4B;IAC3C,2DAA2D;IAC3D,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACpC,6FAA6F;IAC7F,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;CAChC;AAED,MAAM,WAAW,sBAAsB;IACrC,oEAAoE;IACpE,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,aAAa,GAAG,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;IACrE,yCAAyC;IACzC,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC;CACjC;AAOD,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,OAAO,EACjB,OAAO,GAAE,4BAAiC,GACzC,sBAAsB,CAgDxB"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@hypequery/datasets/codegen`: a deployment contract as the TypeScript that
|
|
3
|
+
* builds it (decision 0020 §3).
|
|
4
|
+
*
|
|
5
|
+
* The output is idiomatic `dataset()` code, a `datasets.ts` and the
|
|
6
|
+
* `cloud.ts` entrypoint `hypequery deploy` reads, and `publishToCloud` over it
|
|
7
|
+
* builds the same contract as the input, with its members in name order (the
|
|
8
|
+
* only order code produces; see `canonicalMemberOrder`). That round trip is
|
|
9
|
+
* the guarantee: anything the authoring API can't reproduce exactly is
|
|
10
|
+
* refused with `ContractExportError` instead of being approximated.
|
|
11
|
+
*/
|
|
12
|
+
import { validateProtocolDeploymentContract } from '@hypequery/protocol';
|
|
13
|
+
import { compareStrings } from '../utils/canonical-json.js';
|
|
14
|
+
import { cloudSource } from './cloud-source.js';
|
|
15
|
+
import { datasetSource } from './dataset-source.js';
|
|
16
|
+
import { declarationOrder } from './utils/declaration-order.js';
|
|
17
|
+
import { canonicalMemberOrder } from './utils/member-order.js';
|
|
18
|
+
import { datasetConstantNames } from './utils/naming.js';
|
|
19
|
+
import { ContractExportError } from './errors.js';
|
|
20
|
+
import { literal, propertyKey } from './utils/source-writer.js';
|
|
21
|
+
export { ContractExportError, canonicalMemberOrder };
|
|
22
|
+
const DEFAULT_HEADER = [
|
|
23
|
+
'Generated by hypequery from a deployment contract.',
|
|
24
|
+
'This code is now the source of the model: edit it here and deploy with `npx hypequery deploy`.',
|
|
25
|
+
];
|
|
26
|
+
export function generateDatasetSource(contract, options = {}) {
|
|
27
|
+
// Code can only produce members in name order (see `canonicalMemberOrder`).
|
|
28
|
+
const validated = canonicalMemberOrder(validateProtocolDeploymentContract(contract));
|
|
29
|
+
const importSource = options.importSource ?? '@hypequery/datasets';
|
|
30
|
+
// A line break in a header line would end its comment, so each piece gets its own `//`.
|
|
31
|
+
const header = (options.header ?? DEFAULT_HEADER)
|
|
32
|
+
.flatMap(line => line.split(/\r\n|[\n\r\u2028\u2029]/))
|
|
33
|
+
.map(line => `// ${line}`.trimEnd())
|
|
34
|
+
.join('\n');
|
|
35
|
+
const datasets = validated.datasets;
|
|
36
|
+
if (!datasets.some(dataset => dataset.endpoint !== undefined)) {
|
|
37
|
+
throw new ContractExportError(String(datasets[0]?.name ?? '(none)'), 'the deployment', 'publishToCloud needs at least one dataset with an endpoint');
|
|
38
|
+
}
|
|
39
|
+
const constants = datasetConstantNames(datasets.map(dataset => String(dataset.name)));
|
|
40
|
+
const order = declarationOrder(datasets);
|
|
41
|
+
const earlier = new Set();
|
|
42
|
+
const sources = order.map(dataset => {
|
|
43
|
+
const source = datasetSource(dataset, constants, new Set(earlier));
|
|
44
|
+
earlier.add(String(dataset.name));
|
|
45
|
+
return source;
|
|
46
|
+
});
|
|
47
|
+
const imports = [...new Set(sources.flatMap(source => [...source.imports]))]
|
|
48
|
+
.sort((left, right) => compareStrings(left.replace(/^type /, ''), right.replace(/^type /, '')));
|
|
49
|
+
const registry = datasets
|
|
50
|
+
.filter(dataset => dataset.endpoint !== undefined)
|
|
51
|
+
.map(dataset => ` ${propertyKey(String(dataset.name))}: ${constants.get(String(dataset.name))},`);
|
|
52
|
+
const datasetsFile = [
|
|
53
|
+
header,
|
|
54
|
+
'',
|
|
55
|
+
`import { ${imports.join(', ')} } from ${literal(importSource)};`,
|
|
56
|
+
'',
|
|
57
|
+
sources.map(source => source.code).join('\n'),
|
|
58
|
+
'/** The datasets published with an endpoint. */',
|
|
59
|
+
registry.length > 0 ? `export const datasets = {\n${registry.join('\n')}\n};` : 'export const datasets = {};',
|
|
60
|
+
'',
|
|
61
|
+
].join('\n');
|
|
62
|
+
const cloud = cloudSource(datasets, constants, importSource);
|
|
63
|
+
return {
|
|
64
|
+
files: { 'datasets.ts': datasetsFile, 'cloud.ts': `${header}\n\n${cloud.code}` },
|
|
65
|
+
entrypoint: 'cloud.ts',
|
|
66
|
+
};
|
|
67
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ProtocolDeploymentDataset } from '@hypequery/protocol';
|
|
2
|
+
/**
|
|
3
|
+
* The order datasets are declared in: each after the targets of its to-one
|
|
4
|
+
* relationships (`belongsTo`, `hasOne`), so TypeScript infers the target
|
|
5
|
+
* first, ties by name. Datasets in a to-one cycle follow by name; the edges
|
|
6
|
+
* that then point down the file are annotated where they're written.
|
|
7
|
+
*/
|
|
8
|
+
export declare function declarationOrder(datasets: readonly ProtocolDeploymentDataset[]): ProtocolDeploymentDataset[];
|
|
9
|
+
//# sourceMappingURL=declaration-order.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"declaration-order.d.ts","sourceRoot":"","sources":["../../../src/codegen/utils/declaration-order.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAIrE;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,SAAS,yBAAyB,EAAE,GAC7C,yBAAyB,EAAE,CAoB7B"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { byName } from '../../utils/by-name.js';
|
|
2
|
+
/**
|
|
3
|
+
* The order datasets are declared in: each after the targets of its to-one
|
|
4
|
+
* relationships (`belongsTo`, `hasOne`), so TypeScript infers the target
|
|
5
|
+
* first, ties by name. Datasets in a to-one cycle follow by name; the edges
|
|
6
|
+
* that then point down the file are annotated where they're written.
|
|
7
|
+
*/
|
|
8
|
+
export function declarationOrder(datasets) {
|
|
9
|
+
const sorted = [...datasets].sort((left, right) => byName({ name: String(left.name) }, { name: String(right.name) }));
|
|
10
|
+
const names = new Set(sorted.map(dataset => String(dataset.name)));
|
|
11
|
+
const needs = new Map(sorted.map(dataset => [
|
|
12
|
+
String(dataset.name),
|
|
13
|
+
new Set(dataset.relationships
|
|
14
|
+
.filter(item => item.kind !== 'hasMany' && String(item.target) !== String(dataset.name) && names.has(String(item.target)))
|
|
15
|
+
.map(item => String(item.target))),
|
|
16
|
+
]));
|
|
17
|
+
const placed = new Set();
|
|
18
|
+
const order = [];
|
|
19
|
+
while (order.length < sorted.length) {
|
|
20
|
+
const ready = sorted.find(dataset => !placed.has(String(dataset.name))
|
|
21
|
+
&& [...(needs.get(String(dataset.name)) ?? [])].every(target => placed.has(target)))
|
|
22
|
+
// Only a cycle is left: take the first by name, and its edges are annotated.
|
|
23
|
+
?? sorted.find(dataset => !placed.has(String(dataset.name)));
|
|
24
|
+
placed.add(String(ready.name));
|
|
25
|
+
order.push(ready);
|
|
26
|
+
}
|
|
27
|
+
return order;
|
|
28
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ProtocolDeploymentContract } from '@hypequery/protocol';
|
|
2
|
+
/**
|
|
3
|
+
* A contract with its named members in the order `dataset()` code produces
|
|
4
|
+
* them: datasets, dimensions, filters and relationships by name, and base
|
|
5
|
+
* measures by name followed by derived measures by name. The lists the
|
|
6
|
+
* adapter sorts inside a member are sorted too: `examples`, `synonyms` and SQL
|
|
7
|
+
* `dependencies` (all duplicate-free once validated).
|
|
8
|
+
*
|
|
9
|
+
* Code can't keep any other order, because `protocol-adapter.ts` sorts these
|
|
10
|
+
* lists, so nothing in a contract depends on it. Cloud's editor appends
|
|
11
|
+
* members as they're added, so exporting a Cloud model gives code whose
|
|
12
|
+
* contract equals this, not always the input byte for byte. Any other order
|
|
13
|
+
* inside a member (filter operators, relationship keys, `uses`, `defaults`)
|
|
14
|
+
* is kept.
|
|
15
|
+
*/
|
|
16
|
+
export declare function canonicalMemberOrder(contract: ProtocolDeploymentContract): ProtocolDeploymentContract;
|
|
17
|
+
//# sourceMappingURL=member-order.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"member-order.d.ts","sourceRoot":"","sources":["../../../src/codegen/utils/member-order.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,0BAA0B,EAK3B,MAAM,qBAAqB,CAAC;AAsB7B;;;;;;;;;;;;;GAaG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,0BAA0B,GAAG,0BAA0B,CAuBrG"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { byName } from '../../utils/by-name.js';
|
|
2
|
+
import { compareStrings } from '../../utils/canonical-json.js';
|
|
3
|
+
const sorted = (values) => [...values].sort((left, right) => compareStrings(String(left), String(right)));
|
|
4
|
+
/** `examples` and `synonyms` sorted, as `snapshotSemanticMetadata` writes them. */
|
|
5
|
+
function metadataOrder(item) {
|
|
6
|
+
return {
|
|
7
|
+
...item,
|
|
8
|
+
...(item.examples !== undefined ? { examples: sorted(item.examples) } : {}),
|
|
9
|
+
...(item.synonyms !== undefined ? { synonyms: sorted(item.synonyms) } : {}),
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
/** SQL `dependencies` sorted, as `protocol-adapter.ts` writes them. */
|
|
13
|
+
function sqlOrder(expression) {
|
|
14
|
+
return { ...expression, dependencies: sorted(expression.dependencies) };
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* A contract with its named members in the order `dataset()` code produces
|
|
18
|
+
* them: datasets, dimensions, filters and relationships by name, and base
|
|
19
|
+
* measures by name followed by derived measures by name. The lists the
|
|
20
|
+
* adapter sorts inside a member are sorted too: `examples`, `synonyms` and SQL
|
|
21
|
+
* `dependencies` (all duplicate-free once validated).
|
|
22
|
+
*
|
|
23
|
+
* Code can't keep any other order, because `protocol-adapter.ts` sorts these
|
|
24
|
+
* lists, so nothing in a contract depends on it. Cloud's editor appends
|
|
25
|
+
* members as they're added, so exporting a Cloud model gives code whose
|
|
26
|
+
* contract equals this, not always the input byte for byte. Any other order
|
|
27
|
+
* inside a member (filter operators, relationship keys, `uses`, `defaults`)
|
|
28
|
+
* is kept.
|
|
29
|
+
*/
|
|
30
|
+
export function canonicalMemberOrder(contract) {
|
|
31
|
+
const named = (items) => [...items].sort((left, right) => byName({ name: String(left.name) }, { name: String(right.name) }));
|
|
32
|
+
const isDerived = (measure) => 'kind' in measure && measure.kind === 'derived';
|
|
33
|
+
return {
|
|
34
|
+
...contract,
|
|
35
|
+
datasets: named(contract.datasets).map((dataset) => ({
|
|
36
|
+
...metadataOrder(dataset),
|
|
37
|
+
dimensions: named(dataset.dimensions).map(dimension => ({
|
|
38
|
+
...metadataOrder(dimension),
|
|
39
|
+
source: dimension.source.kind === 'sql-expression' ? sqlOrder(dimension.source) : dimension.source,
|
|
40
|
+
})),
|
|
41
|
+
measures: [
|
|
42
|
+
...named(dataset.measures.filter(measure => !isDerived(measure))).map(measure => {
|
|
43
|
+
const ordered = metadataOrder(measure);
|
|
44
|
+
return 'sql' in ordered && ordered.sql !== undefined ? { ...ordered, sql: sqlOrder(ordered.sql) } : ordered;
|
|
45
|
+
}),
|
|
46
|
+
...named(dataset.measures.filter(isDerived)).map(metadataOrder),
|
|
47
|
+
],
|
|
48
|
+
filters: named(dataset.filters).map(metadataOrder),
|
|
49
|
+
relationships: named(dataset.relationships),
|
|
50
|
+
})),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The exported constant for each dataset, as `generate:datasets` names them:
|
|
3
|
+
* `order_items` → `OrderItemsDataset`. Names that collide or can't be a
|
|
4
|
+
* binding get a numeric suffix, so every dataset has exactly one constant.
|
|
5
|
+
*/
|
|
6
|
+
export declare function datasetConstantNames(names: readonly string[]): ReadonlyMap<string, string>;
|
|
7
|
+
//# sourceMappingURL=naming.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"naming.d.ts","sourceRoot":"","sources":["../../../src/codegen/utils/naming.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAa1F"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { isBindingName } from './source-writer.js';
|
|
2
|
+
/**
|
|
3
|
+
* The exported constant for each dataset, as `generate:datasets` names them:
|
|
4
|
+
* `order_items` → `OrderItemsDataset`. Names that collide or can't be a
|
|
5
|
+
* binding get a numeric suffix, so every dataset has exactly one constant.
|
|
6
|
+
*/
|
|
7
|
+
export function datasetConstantNames(names) {
|
|
8
|
+
const used = new Set();
|
|
9
|
+
const result = new Map();
|
|
10
|
+
for (const name of [...names].sort()) {
|
|
11
|
+
const words = name.split(/[^A-Za-z0-9]+/).filter(Boolean);
|
|
12
|
+
let base = `${words.map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('')}Dataset`;
|
|
13
|
+
if (!isBindingName(base) || /^[0-9]/.test(base))
|
|
14
|
+
base = `Dataset${base}`;
|
|
15
|
+
let candidate = base;
|
|
16
|
+
for (let suffix = 2; used.has(candidate); suffix += 1)
|
|
17
|
+
candidate = `${base}${suffix}`;
|
|
18
|
+
used.add(candidate);
|
|
19
|
+
result.set(name, candidate);
|
|
20
|
+
}
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writes JavaScript values as TypeScript source, the way a person would type
|
|
3
|
+
* them: single-quoted strings, bare keys where they are identifiers, short
|
|
4
|
+
* collections on one line. Output is deterministic for the same input, which
|
|
5
|
+
* is what lets exported code be compared byte for byte.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Source text to place as-is, such as `dimension.string()` or a formula. A
|
|
9
|
+
* class rather than a tagged object, so no plain object (say, a dimensions
|
|
10
|
+
* map with a member named like the tag) can pass for one.
|
|
11
|
+
*/
|
|
12
|
+
export declare class Code {
|
|
13
|
+
readonly text: string;
|
|
14
|
+
constructor(text: string);
|
|
15
|
+
}
|
|
16
|
+
export declare function code(text: string): Code;
|
|
17
|
+
/** True when `name` can be a variable or destructured binding. */
|
|
18
|
+
export declare function isBindingName(name: string): boolean;
|
|
19
|
+
/** Single-quoted, or double-quoted when that avoids escaping an apostrophe (as Prettier does). */
|
|
20
|
+
export declare function stringLiteral(value: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* An object key: bare when it is an identifier. `__proto__` is computed
|
|
23
|
+
* (`['__proto__']`): bare or quoted, it would set the object's prototype
|
|
24
|
+
* instead of creating a property.
|
|
25
|
+
*/
|
|
26
|
+
export declare function propertyKey(key: string): string;
|
|
27
|
+
/**
|
|
28
|
+
* `value` as source at `indent` (the current line's indentation). Objects and
|
|
29
|
+
* arrays go on one line when that fits in `LINE` columns and holds no nested
|
|
30
|
+
* multi-line value; otherwise one entry per line.
|
|
31
|
+
*/
|
|
32
|
+
export declare function literal(value: unknown, indent?: string): string;
|
|
33
|
+
/** `name(arg, …)`, dropping trailing `undefined` arguments. */
|
|
34
|
+
export declare function call(name: string, args: readonly unknown[], indent?: string): Code;
|
|
35
|
+
//# sourceMappingURL=source-writer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"source-writer.d.ts","sourceRoot":"","sources":["../../../src/codegen/utils/source-writer.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;GAIG;AACH,qBAAa,IAAI;IACf,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;gBAEV,IAAI,EAAE,MAAM;CAGzB;AAED,wBAAgB,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAEvC;AAgBD,kEAAkE;AAClE,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEnD;AAED,kGAAkG;AAClG,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAenD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAG/C;AAID;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,SAAK,GAAG,MAAM,CAiC3D;AAED,+DAA+D;AAC/D,wBAAgB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,OAAO,EAAE,EAAE,MAAM,SAAK,GAAG,IAAI,CAI9E"}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writes JavaScript values as TypeScript source, the way a person would type
|
|
3
|
+
* them: single-quoted strings, bare keys where they are identifiers, short
|
|
4
|
+
* collections on one line. Output is deterministic for the same input, which
|
|
5
|
+
* is what lets exported code be compared byte for byte.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Source text to place as-is, such as `dimension.string()` or a formula. A
|
|
9
|
+
* class rather than a tagged object, so no plain object (say, a dimensions
|
|
10
|
+
* map with a member named like the tag) can pass for one.
|
|
11
|
+
*/
|
|
12
|
+
export class Code {
|
|
13
|
+
text;
|
|
14
|
+
constructor(text) {
|
|
15
|
+
this.text = text;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function code(text) {
|
|
19
|
+
return new Code(text);
|
|
20
|
+
}
|
|
21
|
+
function isCode(value) {
|
|
22
|
+
return value instanceof Code;
|
|
23
|
+
}
|
|
24
|
+
const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
25
|
+
const RESERVED = new Set([
|
|
26
|
+
'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do',
|
|
27
|
+
'else', 'enum', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'import', 'in',
|
|
28
|
+
'instanceof', 'new', 'null', 'return', 'super', 'switch', 'this', 'throw', 'true', 'try',
|
|
29
|
+
'typeof', 'var', 'void', 'while', 'with', 'yield', 'let', 'static', 'implements', 'interface',
|
|
30
|
+
'package', 'private', 'protected', 'public', 'await', 'arguments', 'eval',
|
|
31
|
+
]);
|
|
32
|
+
/** True when `name` can be a variable or destructured binding. */
|
|
33
|
+
export function isBindingName(name) {
|
|
34
|
+
return IDENTIFIER.test(name) && !RESERVED.has(name);
|
|
35
|
+
}
|
|
36
|
+
/** Single-quoted, or double-quoted when that avoids escaping an apostrophe (as Prettier does). */
|
|
37
|
+
export function stringLiteral(value) {
|
|
38
|
+
const quote = value.includes("'") && !value.includes('"') ? '"' : "'";
|
|
39
|
+
let out = quote;
|
|
40
|
+
for (const char of value) {
|
|
41
|
+
const point = char.codePointAt(0);
|
|
42
|
+
if (char === '\\')
|
|
43
|
+
out += '\\\\';
|
|
44
|
+
else if (char === quote)
|
|
45
|
+
out += `\\${quote}`;
|
|
46
|
+
else if (char === '\n')
|
|
47
|
+
out += '\\n';
|
|
48
|
+
else if (char === '\r')
|
|
49
|
+
out += '\\r';
|
|
50
|
+
else if (char === '\t')
|
|
51
|
+
out += '\\t';
|
|
52
|
+
else if (point < 0x20 || point === 0x7f || point === 0x2028 || point === 0x2029) {
|
|
53
|
+
out += `\\u${point.toString(16).padStart(4, '0')}`;
|
|
54
|
+
}
|
|
55
|
+
else
|
|
56
|
+
out += char;
|
|
57
|
+
}
|
|
58
|
+
return `${out}${quote}`;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* An object key: bare when it is an identifier. `__proto__` is computed
|
|
62
|
+
* (`['__proto__']`): bare or quoted, it would set the object's prototype
|
|
63
|
+
* instead of creating a property.
|
|
64
|
+
*/
|
|
65
|
+
export function propertyKey(key) {
|
|
66
|
+
if (key === '__proto__')
|
|
67
|
+
return `[${stringLiteral(key)}]`;
|
|
68
|
+
return IDENTIFIER.test(key) ? key : stringLiteral(key);
|
|
69
|
+
}
|
|
70
|
+
const LINE = 100;
|
|
71
|
+
/**
|
|
72
|
+
* `value` as source at `indent` (the current line's indentation). Objects and
|
|
73
|
+
* arrays go on one line when that fits in `LINE` columns and holds no nested
|
|
74
|
+
* multi-line value; otherwise one entry per line.
|
|
75
|
+
*/
|
|
76
|
+
export function literal(value, indent = '') {
|
|
77
|
+
if (isCode(value))
|
|
78
|
+
return value.text;
|
|
79
|
+
if (value === null)
|
|
80
|
+
return 'null';
|
|
81
|
+
if (typeof value === 'string')
|
|
82
|
+
return stringLiteral(value);
|
|
83
|
+
if (typeof value === 'boolean')
|
|
84
|
+
return String(value);
|
|
85
|
+
if (typeof value === 'number') {
|
|
86
|
+
if (!Number.isFinite(value))
|
|
87
|
+
throw new Error(`Cannot write ${value} as a literal.`);
|
|
88
|
+
return Object.is(value, -0) ? '-0' : String(value);
|
|
89
|
+
}
|
|
90
|
+
const inner = `${indent} `;
|
|
91
|
+
if (Array.isArray(value)) {
|
|
92
|
+
if (value.length === 0)
|
|
93
|
+
return '[]';
|
|
94
|
+
const items = value.map(item => literal(item, inner));
|
|
95
|
+
const flat = `[${items.join(', ')}]`;
|
|
96
|
+
if (!flat.includes('\n') && indent.length + flat.length <= LINE)
|
|
97
|
+
return flat;
|
|
98
|
+
return `[\n${items.map(item => `${inner}${item},`).join('\n')}\n${indent}]`;
|
|
99
|
+
}
|
|
100
|
+
if (typeof value === 'object') {
|
|
101
|
+
const entries = Object.entries(value).filter(([, item]) => item !== undefined);
|
|
102
|
+
if (entries.length === 0)
|
|
103
|
+
return '{}';
|
|
104
|
+
// `{ datasets }` rather than `{ datasets: datasets }`.
|
|
105
|
+
const items = entries.map(([key, item]) => (isCode(item) && item.text === key && IDENTIFIER.test(key) && key !== '__proto__'
|
|
106
|
+
? key
|
|
107
|
+
: `${propertyKey(key)}: ${literal(item, inner)}`));
|
|
108
|
+
const flat = `{ ${items.join(', ')} }`;
|
|
109
|
+
if (!flat.includes('\n') && indent.length + flat.length <= LINE)
|
|
110
|
+
return flat;
|
|
111
|
+
return `{\n${items.map(item => `${inner}${item},`).join('\n')}\n${indent}}`;
|
|
112
|
+
}
|
|
113
|
+
throw new Error(`Cannot write a ${typeof value} as a literal.`);
|
|
114
|
+
}
|
|
115
|
+
/** `name(arg, …)`, dropping trailing `undefined` arguments. */
|
|
116
|
+
export function call(name, args, indent = '') {
|
|
117
|
+
const kept = [...args];
|
|
118
|
+
while (kept.length > 0 && kept[kept.length - 1] === undefined)
|
|
119
|
+
kept.pop();
|
|
120
|
+
return code(`${name}(${kept.map(arg => literal(arg, indent)).join(', ')})`);
|
|
121
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hypequery/datasets",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.31.0",
|
|
4
4
|
"description": "Code-first TypeScript semantic layer for ClickHouse datasets, metrics, multi-tenancy, and AI agents",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"semantic-layer",
|
|
@@ -29,6 +29,11 @@
|
|
|
29
29
|
"import": "./dist/schemas.js",
|
|
30
30
|
"require": "./dist/schemas.js"
|
|
31
31
|
},
|
|
32
|
+
"./codegen": {
|
|
33
|
+
"types": "./dist/codegen/index.d.ts",
|
|
34
|
+
"import": "./dist/codegen/index.js",
|
|
35
|
+
"require": "./dist/codegen/index.js"
|
|
36
|
+
},
|
|
32
37
|
"./internal": {
|
|
33
38
|
"types": "./dist/internal.d.ts",
|
|
34
39
|
"import": "./dist/internal.js",
|
|
@@ -37,6 +42,9 @@
|
|
|
37
42
|
},
|
|
38
43
|
"typesVersions": {
|
|
39
44
|
"*": {
|
|
45
|
+
"codegen": [
|
|
46
|
+
"./dist/codegen/index.d.ts"
|
|
47
|
+
],
|
|
40
48
|
"internal": [
|
|
41
49
|
"./dist/internal.d.ts"
|
|
42
50
|
],
|
|
@@ -55,7 +63,7 @@
|
|
|
55
63
|
"!dist/**/type-tests/**"
|
|
56
64
|
],
|
|
57
65
|
"dependencies": {
|
|
58
|
-
"@hypequery/protocol": "^0.
|
|
66
|
+
"@hypequery/protocol": "^0.26.0",
|
|
59
67
|
"@noble/hashes": "^2.4.0",
|
|
60
68
|
"zod": "^4.6.6",
|
|
61
69
|
"zod-to-json-schema": "^3.25.2"
|
|
@@ -73,7 +81,7 @@
|
|
|
73
81
|
"typescript": "^6.0.3",
|
|
74
82
|
"@vitest/coverage-v8": "^5.1.0",
|
|
75
83
|
"vitest": "^5.1.0",
|
|
76
|
-
"@hypequery/protocol-conformance": "^0.17.
|
|
84
|
+
"@hypequery/protocol-conformance": "^0.17.2"
|
|
77
85
|
},
|
|
78
86
|
"repository": {
|
|
79
87
|
"type": "git",
|