@malloy-publisher/server 0.18.0 → 0.18.1
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/app/api-doc.yaml +37 -6
- package/dist/app/assets/{EnvironmentPage-BYi5H87v.js → EnvironmentPage-CsFUI8IX.js} +1 -1
- package/dist/app/assets/{HomePage-DB-CSs0p.js → HomePage-B_FVtnN-.js} +1 -1
- package/dist/app/assets/{MainPage-2j-MpcYJ.js → MainPage-wFF9nPEr.js} +1 -1
- package/dist/app/assets/{ModelPage-BQE-ZC6E.js → ModelPage-CxenqDcz.js} +2 -2
- package/dist/app/assets/PackagePage-dcF6vrvw.js +1 -0
- package/dist/app/assets/PackageSplatRoute-CASBZk0k.js +2 -0
- package/dist/app/assets/{RenderedResult-QdYnecnr.es-PKDmuES7.js → RenderedResult--fYcsY1h.es-DzOt5Lwv.js} +3 -3
- package/dist/app/assets/{RouteError-7Fw_wYUy.js → RouteError-CUIolYwb.js} +1 -1
- package/dist/app/assets/{ThemeEditorPage-DmiRg7rU.js → ThemeEditorPage-DgU2YYq6.js} +1 -1
- package/dist/app/assets/{ToggleButtonGroup-BXVbLuei.js → ToggleButtonGroup-Dmr-hVlD.js} +1 -1
- package/dist/app/assets/{documentRoutes-DWIPC8nU.js → documentRoutes-Drv-WDwO.js} +1 -1
- package/dist/app/assets/{editPageMounted-BaGHeFZ5.js → editPageMounted-C5yJiIVi.js} +2 -2
- package/dist/app/assets/{index-CHfKShi-.js → index-BIoSdsU9.js} +1 -1
- package/dist/app/assets/{index-OQqQyWrE.js → index-BSyL0zds.js} +97 -97
- package/dist/app/assets/{index-BRdik0lA.js → index-Dtw4eTxH.js} +1 -1
- package/dist/app/assets/{index-APmAmrTn.js → index-DxF3kMLJ.js} +1 -1
- package/dist/app/assets/{index.es-DLFu6xFm.js → index.es-CX9m4CBD.js} +10 -10
- package/dist/app/assets/usePackageLinkNavigate-qNjcXPcY.js +1 -0
- package/dist/app/assets/{usePackageRoute-pIAy965Q.js → usePackageRoute-wJGaZEiY.js} +1 -1
- package/dist/app/index.html +1 -1
- package/dist/instrumentation.mjs +16 -7
- package/dist/package_load_worker.mjs +144 -43
- package/dist/runtime/publisher.colorScheme.spec.ts +167 -0
- package/dist/runtime/publisher.js +173 -3
- package/dist/runtime/publisher_embed.spec.ts +108 -0
- package/dist/server.mjs +1554 -554
- package/package.json +1 -1
- package/dist/app/assets/PackagePage-BMv6ojk4.js +0 -1
- package/dist/app/assets/PackageSplatRoute-BOAFRQKR.js +0 -2
- package/dist/app/assets/usePackageLinkNavigate-DTlEYsed.js +0 -1
package/dist/server.mjs
CHANGED
|
@@ -541,7 +541,7 @@ var init_launch = __esm(() => {
|
|
|
541
541
|
default: false,
|
|
542
542
|
kind: "launch",
|
|
543
543
|
description: "Wipe persisted storage and re-sync it from the config.",
|
|
544
|
-
notes: "Set to `true` (or pass `--init`) to **wipe persisted storage** (`publisher_data/`) and re-sync it from the config on boot. A first boot with empty storage loads the config automatically, so you only need this to reset state or pick up config changes. Also exposed as the `start:init` / `start:dev:init` scripts.",
|
|
544
|
+
notes: "Set to `true` (or pass `--init`) to **wipe persisted storage** (`publisher_data/`) and re-sync it from the config on boot. A first boot with empty storage loads the config automatically, so you only need this to reset state or pick up config changes. The search index (stored value reads, embeddings and LLM output) is kept, since each entry is reused only while what it was built from is unchanged; the rows of a package the config no longer lists are deleted. Also exposed as the `start:init` / `start:dev:init` scripts.",
|
|
545
545
|
shortFlags: ["--init"],
|
|
546
546
|
aliases: {
|
|
547
547
|
env: ["INITIALIZE_STORAGE"],
|
|
@@ -811,7 +811,7 @@ var init_provider_names = __esm(() => {
|
|
|
811
811
|
var EGRESS_PRESETS, DEFAULT_LLM_TIMEOUT_MS = 30000, DEFAULT_LLM_CONCURRENCY = 4, DEFAULT_LLM_MAX_CALLS_PER_SYNC = 300, DEFAULT_LLM_MAX_CALLS_PER_REQUEST = 20, DIMENSION_VALUE_DEFAULTS;
|
|
812
812
|
var init_defaults = __esm(() => {
|
|
813
813
|
EGRESS_PRESETS = ["default", "full"];
|
|
814
|
-
DIMENSION_VALUE_DEFAULTS = { enabled: true };
|
|
814
|
+
DIMENSION_VALUE_DEFAULTS = { enabled: true, givens: {} };
|
|
815
815
|
});
|
|
816
816
|
|
|
817
817
|
// src/settings/registry/retrieval.ts
|
|
@@ -826,7 +826,7 @@ var init_retrieval = __esm(() => {
|
|
|
826
826
|
key: "retrieval",
|
|
827
827
|
type: structured(),
|
|
828
828
|
kind: "structured",
|
|
829
|
-
description: "Semantic retrieval: indexing limits, the LLM, the embedding provider and
|
|
829
|
+
description: "Semantic retrieval: indexing limits, the LLM, the embedding provider and value search.",
|
|
830
830
|
aliases: { file: ["retrieval"] }
|
|
831
831
|
}),
|
|
832
832
|
setting({
|
|
@@ -927,9 +927,9 @@ var init_retrieval = __esm(() => {
|
|
|
927
927
|
setting({
|
|
928
928
|
key: "retrieval.egress.preset",
|
|
929
929
|
type: oneOf(EGRESS_PRESETS),
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
930
|
+
description: "No longer read: #(index) alone decides whether a dimension's values reach the embedding provider and LLM. Setting it logs a startup warning.",
|
|
931
|
+
notes: "Retired. An earlier release sent `#(index)` values to the embedding provider and the LLM only under `full`. Now the `#(index)` tag decides, as it does on a hosted index. To keep values on the machine, leave `EMBEDDING_API_KEY` unset, set `retrieval.fcj.valueEmbeddings` to `false` in the package's `publisher.json`, or set `retrieval.dimensionValues.enabled` to `false`. Access predicates (`#(access_filter)`, `#(authorize)`) never leave.",
|
|
932
|
+
defaultText: "_ignored_",
|
|
933
933
|
aliases: { file: ["retrieval.egress.preset"] }
|
|
934
934
|
}),
|
|
935
935
|
setting({
|
|
@@ -942,6 +942,15 @@ var init_retrieval = __esm(() => {
|
|
|
942
942
|
today: { file: "json-boolean" }
|
|
943
943
|
}
|
|
944
944
|
}),
|
|
945
|
+
setting({
|
|
946
|
+
key: "retrieval.dimensionValues.givens",
|
|
947
|
+
type: structured(),
|
|
948
|
+
kind: "structured",
|
|
949
|
+
description: "Local development: per package, the givens the value index reads with, so a source gated by `column = $GIVEN` is indexed for the listed values only.",
|
|
950
|
+
notes: 'An object of packages, each an object of givens, each one value or a list: `{ "<package>": { "REPORT_ID": [123, 456] } }`. Each `#(index)` dimension is read once per combination of the listed values (at most 50), through its gate. A source gated by `column = $GIVEN` is skipped unless its given is listed here. Never published with a package, and not a way to limit what hosted Credible indexes. See "Dimension value search" below.',
|
|
951
|
+
defaultText: "_unset_ (gated sources skipped)",
|
|
952
|
+
aliases: { file: ["retrieval.dimensionValues.givens"] }
|
|
953
|
+
}),
|
|
945
954
|
setting({
|
|
946
955
|
key: "retrieval.embedding.apiKey",
|
|
947
956
|
type: string(),
|
|
@@ -13037,14 +13046,34 @@ function parseEmbedding(raw) {
|
|
|
13037
13046
|
documentPrefix: plainString(obj.documentPrefix, "retrieval.embedding.documentPrefix", `"documentPrefix": "search_document: "`) ?? ""
|
|
13038
13047
|
};
|
|
13039
13048
|
}
|
|
13040
|
-
function
|
|
13041
|
-
const
|
|
13042
|
-
|
|
13043
|
-
|
|
13044
|
-
|
|
13045
|
-
|
|
13049
|
+
function parseValueGivens(raw) {
|
|
13050
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
13051
|
+
const isValue = (v) => typeof v === "string" || typeof v === "boolean" || typeof v === "number" && Number.isFinite(v);
|
|
13052
|
+
if (!isObject(raw)) {
|
|
13053
|
+
throw new Error(`Invalid retrieval.dimensionValues.givens: expected an object of packages, got ${describe(raw)}. Fix: ${GIVENS_FIX}`);
|
|
13054
|
+
}
|
|
13055
|
+
const out = {};
|
|
13056
|
+
for (const [pkg, givens] of Object.entries(raw)) {
|
|
13057
|
+
const at = `retrieval.dimensionValues.givens.${pkg}`;
|
|
13058
|
+
if (!isObject(givens)) {
|
|
13059
|
+
throw new Error(`Invalid ${at}: expected an object of givens, got ${describe(givens)}. Fix: ${GIVENS_FIX}`);
|
|
13060
|
+
}
|
|
13061
|
+
const parsed = {};
|
|
13062
|
+
let combinations = 1;
|
|
13063
|
+
for (const [name, value] of Object.entries(givens)) {
|
|
13064
|
+
const list = Array.isArray(value) ? value : [value];
|
|
13065
|
+
if (list.length === 0 || !list.every(isValue)) {
|
|
13066
|
+
throw new Error(`Invalid ${at}.${name}: expected a string, number or boolean, or a non-empty list of them, got ${describe(value)}. Fix: ${GIVENS_FIX}`);
|
|
13067
|
+
}
|
|
13068
|
+
parsed[name] = [...new Set(list)];
|
|
13069
|
+
combinations *= parsed[name].length;
|
|
13070
|
+
}
|
|
13071
|
+
if (combinations > MAX_GIVEN_COMBINATIONS) {
|
|
13072
|
+
throw new Error(`Invalid ${at}: its lists make ${combinations} combinations, and each is one read per indexed dimension; at most ${MAX_GIVEN_COMBINATIONS}. Fix: list fewer values`);
|
|
13073
|
+
}
|
|
13074
|
+
out[pkg] = parsed;
|
|
13046
13075
|
}
|
|
13047
|
-
return
|
|
13076
|
+
return out;
|
|
13048
13077
|
}
|
|
13049
13078
|
function parseDimensionValues(raw) {
|
|
13050
13079
|
const fields = block(raw, "retrieval.dimensionValues", DIMENSION_VALUE_KEYS, `"dimensionValues": { "enabled": false }`);
|
|
@@ -13055,6 +13084,9 @@ function parseDimensionValues(raw) {
|
|
|
13055
13084
|
}
|
|
13056
13085
|
out.enabled = fields.enabled;
|
|
13057
13086
|
}
|
|
13087
|
+
if (fields.givens !== undefined && fields.givens !== null) {
|
|
13088
|
+
out.givens = parseValueGivens(fields.givens);
|
|
13089
|
+
}
|
|
13058
13090
|
return out;
|
|
13059
13091
|
}
|
|
13060
13092
|
function parseRetrievalConfig(raw) {
|
|
@@ -13081,17 +13113,16 @@ function parseRetrievalConfig(raw) {
|
|
|
13081
13113
|
if (embedding)
|
|
13082
13114
|
out.embedding = embedding;
|
|
13083
13115
|
}
|
|
13084
|
-
if (input.egress !== undefined
|
|
13085
|
-
|
|
13086
|
-
if (egress)
|
|
13087
|
-
out.egress = egress;
|
|
13088
|
-
}
|
|
13116
|
+
if (input.egress !== undefined)
|
|
13117
|
+
out.egressIgnored = true;
|
|
13089
13118
|
if (input.dimensionValues !== undefined && input.dimensionValues !== null) {
|
|
13090
13119
|
out.dimensionValues = parseDimensionValues(input.dimensionValues);
|
|
13091
13120
|
}
|
|
13092
13121
|
return out;
|
|
13093
13122
|
}
|
|
13094
13123
|
function setRetrievalConfig(config) {
|
|
13124
|
+
if (config?.egressIgnored)
|
|
13125
|
+
logger.warn(RETIRED_EGRESS_WARNING);
|
|
13095
13126
|
loaded = config;
|
|
13096
13127
|
}
|
|
13097
13128
|
function loadedRetrievalConfig() {
|
|
@@ -13100,14 +13131,12 @@ function loadedRetrievalConfig() {
|
|
|
13100
13131
|
function getDimensionValueSettings() {
|
|
13101
13132
|
return { ...DIMENSION_VALUE_DEFAULTS, ...loaded?.dimensionValues };
|
|
13102
13133
|
}
|
|
13103
|
-
|
|
13104
|
-
return loaded?.egress?.preset ?? "default";
|
|
13105
|
-
}
|
|
13106
|
-
var DIMENSION_VALUE_KEYS, loaded;
|
|
13134
|
+
var RETIRED_EGRESS_WARNING = "retrieval.egress is no longer read and is ignored. The values of #(index) dimensions are now sent to the configured embedding provider and LLM whenever one is configured. To keep them on this machine, set retrieval.dimensionValues.enabled to false in publisher.config.json. Leaving EMBEDDING_API_KEY unset, or setting retrieval.fcj.valueEmbeddings to false, only stops values being embedded: a configured LLM still sees them. Remove the egress block to silence this warning.", MAX_GIVEN_COMBINATIONS = 50, DIMENSION_VALUE_KEYS, GIVENS_FIX = `"givens": { "<package>": { "REPORT_ID": [123, 456] } }`, loaded;
|
|
13107
13135
|
var init_config = __esm(() => {
|
|
13136
|
+
init_logger();
|
|
13108
13137
|
init_types2();
|
|
13109
13138
|
init_defaults();
|
|
13110
|
-
DIMENSION_VALUE_KEYS = ["enabled"];
|
|
13139
|
+
DIMENSION_VALUE_KEYS = ["enabled", "givens"];
|
|
13111
13140
|
});
|
|
13112
13141
|
|
|
13113
13142
|
// src/config.ts
|
|
@@ -13336,7 +13365,7 @@ function assembleRetrieval(file) {
|
|
|
13336
13365
|
return { block: file, ignored };
|
|
13337
13366
|
}
|
|
13338
13367
|
const block = file ? structuredClone(file) : {};
|
|
13339
|
-
for (const leaf of REGISTRY.filter((entry) => entry.key.startsWith("retrieval.")
|
|
13368
|
+
for (const leaf of REGISTRY.filter((entry) => entry.key.startsWith("retrieval."))) {
|
|
13340
13369
|
const pathInBlock = leaf.key.split(".").slice(1);
|
|
13341
13370
|
const parent = nodeAt(block, pathInBlock.slice(0, -1));
|
|
13342
13371
|
const last = pathInBlock[pathInBlock.length - 1];
|
|
@@ -14713,13 +14742,15 @@ var init_errors2 = __esm(() => {
|
|
|
14713
14742
|
};
|
|
14714
14743
|
ManifestBindFailedError = class ManifestBindFailedError extends Error {
|
|
14715
14744
|
applied;
|
|
14745
|
+
problem;
|
|
14716
14746
|
get kind() {
|
|
14717
14747
|
return "manifest_bind_failed";
|
|
14718
14748
|
}
|
|
14719
|
-
constructor(manifestLocation, cause, applied) {
|
|
14749
|
+
constructor(manifestLocation, cause, applied, problem) {
|
|
14720
14750
|
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
14721
14751
|
super(`The build manifest ${manifestLocation} could not be bound ` + `(${detail}), so it was not applied: the package serves what ` + `it served before.`, { cause });
|
|
14722
14752
|
this.applied = applied;
|
|
14753
|
+
this.problem = problem;
|
|
14723
14754
|
this.name = "ManifestBindFailedError";
|
|
14724
14755
|
}
|
|
14725
14756
|
};
|
|
@@ -15182,8 +15213,8 @@ var init_errors2 = __esm(() => {
|
|
|
15182
15213
|
connection_save: { status: 500, mcp: { advice: "internal" } },
|
|
15183
15214
|
write_rolled_back: { status: 500, mcp: { advice: "internal" } },
|
|
15184
15215
|
manifest_bind_failed: {
|
|
15185
|
-
status: 500,
|
|
15186
|
-
reason: "MANIFEST_BIND_FAILED",
|
|
15216
|
+
status: (error) => error.problem === "not_found" ? 400 : error.problem === "invalid" ? 422 : 500,
|
|
15217
|
+
reason: (error) => error.problem === "not_found" ? "MANIFEST_NOT_FOUND" : error.problem === "invalid" ? "MANIFEST_INVALID" : "MANIFEST_BIND_FAILED",
|
|
15187
15218
|
mcp: { advice: "internal" }
|
|
15188
15219
|
},
|
|
15189
15220
|
service_unavailable: BACK_PRESSURE,
|
|
@@ -17993,17 +18024,20 @@ class VersionService {
|
|
|
17993
18024
|
});
|
|
17994
18025
|
let version = existing;
|
|
17995
18026
|
const newManifest = options.manifestLocation && options.manifestLocation !== existing.manifestPath ? options.manifestLocation : undefined;
|
|
17996
|
-
|
|
17997
|
-
|
|
17998
|
-
|
|
17999
|
-
|
|
18000
|
-
|
|
18027
|
+
const loaded = await this.sharingManifestFetches(async () => {
|
|
18028
|
+
if (newManifest) {
|
|
18029
|
+
version = await this.registry.setVersionManifestPath(this.environmentId, packageName, versionId, newManifest);
|
|
18030
|
+
const resident = this.cache.peek(packageName, versionId);
|
|
18031
|
+
if (resident !== undefined) {
|
|
18032
|
+
await host.bindVersionManifest(resident, newManifest);
|
|
18033
|
+
}
|
|
18001
18034
|
}
|
|
18002
|
-
|
|
18003
|
-
|
|
18004
|
-
|
|
18005
|
-
|
|
18006
|
-
|
|
18035
|
+
const loaded = await this.cache.get(packageName, versionId);
|
|
18036
|
+
if (newManifest && host.boundManifestOf && host.boundManifestOf(loaded) !== newManifest) {
|
|
18037
|
+
await host.bindVersionManifest(loaded, newManifest);
|
|
18038
|
+
}
|
|
18039
|
+
return loaded;
|
|
18040
|
+
});
|
|
18007
18041
|
if (options.description !== undefined) {
|
|
18008
18042
|
await host.ensurePackageRecord(packageName, options.description);
|
|
18009
18043
|
}
|
|
@@ -18193,31 +18227,37 @@ class VersionService {
|
|
|
18193
18227
|
}
|
|
18194
18228
|
async setManifest(packageName, rawVersion, manifestLocation) {
|
|
18195
18229
|
const versionId = requiredVersionId(rawVersion);
|
|
18196
|
-
|
|
18230
|
+
this.requireHost();
|
|
18197
18231
|
await this.getVersion(packageName, versionId);
|
|
18198
|
-
return this.withVersionWrite(packageName, versionId,
|
|
18199
|
-
|
|
18200
|
-
|
|
18201
|
-
|
|
18232
|
+
return this.withVersionWrite(packageName, versionId, () => this.sharingManifestFetches(() => this.setManifestLocked(packageName, versionId, manifestLocation)));
|
|
18233
|
+
}
|
|
18234
|
+
async setManifestLocked(packageName, versionId, manifestLocation) {
|
|
18235
|
+
const host = this.requireHost();
|
|
18236
|
+
const current = await this.getVersion(packageName, versionId);
|
|
18237
|
+
if (current.archiveStatus === "archive") {
|
|
18238
|
+
throw versionArchived(packageName, versionId);
|
|
18239
|
+
}
|
|
18240
|
+
await this.registry.setVersionManifestPath(this.environmentId, packageName, versionId, manifestLocation);
|
|
18241
|
+
const resident = this.cache.peek(packageName, versionId);
|
|
18242
|
+
let loaded = resident;
|
|
18243
|
+
try {
|
|
18244
|
+
loaded ??= await this.loadOrRefuse(packageName, versionId);
|
|
18245
|
+
if (resident !== undefined || !host.boundManifestOf || host.boundManifestOf(loaded) !== manifestLocation) {
|
|
18246
|
+
await host.bindVersionManifest(loaded, manifestLocation, {
|
|
18247
|
+
refuseOnFailure: true
|
|
18248
|
+
});
|
|
18202
18249
|
}
|
|
18203
|
-
|
|
18204
|
-
|
|
18205
|
-
|
|
18206
|
-
|
|
18207
|
-
|
|
18208
|
-
await host.bindVersionManifest(loaded, manifestLocation, {
|
|
18209
|
-
refuseOnFailure: true
|
|
18210
|
-
});
|
|
18211
|
-
}
|
|
18212
|
-
return loaded;
|
|
18213
|
-
} catch (error) {
|
|
18214
|
-
if (resident === undefined) {
|
|
18215
|
-
this.cache.evict(packageName, versionId);
|
|
18216
|
-
}
|
|
18217
|
-
await this.registry.setVersionManifestPath(this.environmentId, packageName, versionId, current.manifestPath).catch((restoreError) => logger.error("Could not restore a version's manifest after its bind failed", { packageName, versionId, error: restoreError }));
|
|
18218
|
-
throw error;
|
|
18250
|
+
return loaded;
|
|
18251
|
+
} catch (error) {
|
|
18252
|
+
await this.registry.setVersionManifestPath(this.environmentId, packageName, versionId, current.manifestPath).catch((restoreError) => logger.error("Could not restore a version's manifest after its bind failed", { packageName, versionId, error: restoreError }));
|
|
18253
|
+
if (resident === undefined && loaded !== undefined) {
|
|
18254
|
+
await host.bindVersionManifest(loaded, current.manifestPath).catch((rebindError) => logger.error("Could not rebind a version after its manifest was refused", { packageName, versionId, error: rebindError }));
|
|
18219
18255
|
}
|
|
18220
|
-
|
|
18256
|
+
throw error;
|
|
18257
|
+
}
|
|
18258
|
+
}
|
|
18259
|
+
sharingManifestFetches(fn) {
|
|
18260
|
+
return this.host?.shareManifestFetches ? this.host.shareManifestFetches(fn) : fn();
|
|
18221
18261
|
}
|
|
18222
18262
|
async loadOrRefuse(packageName, versionId) {
|
|
18223
18263
|
for (let attempt = 0;; attempt++) {
|
|
@@ -135440,7 +135480,9 @@ function columnCompare(args, isString, collation, name) {
|
|
|
135440
135480
|
}
|
|
135441
135481
|
if (args.stackedOn !== undefined)
|
|
135442
135482
|
return args.stackedOn;
|
|
135443
|
-
|
|
135483
|
+
return liveCompare(args.live?.get(name));
|
|
135484
|
+
}
|
|
135485
|
+
function liveCompare(live) {
|
|
135444
135486
|
return live === "binary" ? "exact" : live === "deterministic" ? "equality" : "none";
|
|
135445
135487
|
}
|
|
135446
135488
|
function weakestStringCompare(upstreams) {
|
|
@@ -136239,6 +136281,12 @@ var init_types3 = __esm(() => {
|
|
|
136239
136281
|
import { Storage } from "@google-cloud/storage";
|
|
136240
136282
|
import * as fs10 from "fs/promises";
|
|
136241
136283
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
136284
|
+
function isManifestNotFound(error) {
|
|
136285
|
+
if (typeof error !== "object" || error === null)
|
|
136286
|
+
return false;
|
|
136287
|
+
const e = error;
|
|
136288
|
+
return e.code === "ENOENT" || e.code === "ENOTDIR" || e.code === 404 || e.name === "NoSuchKey" || e.name === "NoSuchBucket" || e.$metadata?.httpStatusCode === 404;
|
|
136289
|
+
}
|
|
136242
136290
|
function parseBucketUri(uri, scheme) {
|
|
136243
136291
|
const rest = uri.slice(scheme.length);
|
|
136244
136292
|
const slash = rest.indexOf("/");
|
|
@@ -136269,14 +136317,32 @@ async function readManifestBytes(uri) {
|
|
|
136269
136317
|
return fs10.readFile(uri, "utf8");
|
|
136270
136318
|
}
|
|
136271
136319
|
async function fetchManifestEntries(uri) {
|
|
136272
|
-
|
|
136320
|
+
let raw;
|
|
136321
|
+
try {
|
|
136322
|
+
raw = await readManifestBytes(uri);
|
|
136323
|
+
} catch (err) {
|
|
136324
|
+
if (isManifestNotFound(err)) {
|
|
136325
|
+
throw new ManifestUnusableError("not_found", `No build manifest at ${uri}`, { cause: err });
|
|
136326
|
+
}
|
|
136327
|
+
if (err?.code === "EISDIR") {
|
|
136328
|
+
throw new ManifestUnusableError("invalid", `The build manifest location ${uri} is a directory, not a file`, { cause: err });
|
|
136329
|
+
}
|
|
136330
|
+
throw err;
|
|
136331
|
+
}
|
|
136273
136332
|
let parsed;
|
|
136274
136333
|
try {
|
|
136275
136334
|
parsed = JSON.parse(raw);
|
|
136276
136335
|
} catch (err) {
|
|
136277
|
-
throw new
|
|
136336
|
+
throw new ManifestUnusableError("invalid", `Failed to parse build manifest at ${uri}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
136337
|
+
}
|
|
136338
|
+
if (!isJsonObject(parsed)) {
|
|
136339
|
+
throw new ManifestUnusableError("invalid", `The build manifest at ${uri} is not a JSON object`);
|
|
136340
|
+
}
|
|
136341
|
+
const entries = parsed.entries;
|
|
136342
|
+
if (entries !== undefined && entries !== null && !isJsonObject(entries)) {
|
|
136343
|
+
throw new ManifestUnusableError("invalid", `The build manifest at ${uri} has an "entries" that is not an object`);
|
|
136278
136344
|
}
|
|
136279
|
-
return splitManifestEntries(
|
|
136345
|
+
return splitManifestEntries(entries ?? {}, uri);
|
|
136280
136346
|
}
|
|
136281
136347
|
function isUsableTableName2(name) {
|
|
136282
136348
|
return isUsableTableName(name);
|
|
@@ -136332,13 +136398,21 @@ function splitManifestEntries(entries, source, { quiet = false } = {}) {
|
|
|
136332
136398
|
}
|
|
136333
136399
|
return { tableNameManifest, storageEntries };
|
|
136334
136400
|
}
|
|
136335
|
-
var import_client_s32, gcsClient, s3Client;
|
|
136401
|
+
var import_client_s32, ManifestUnusableError, isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value), gcsClient, s3Client;
|
|
136336
136402
|
var init_manifest_loader = __esm(() => {
|
|
136337
136403
|
init_stored_column_types();
|
|
136338
136404
|
init_quoting();
|
|
136339
136405
|
init_logger();
|
|
136340
136406
|
init_types3();
|
|
136341
136407
|
import_client_s32 = __toESM(require_dist_cjs75());
|
|
136408
|
+
ManifestUnusableError = class ManifestUnusableError extends Error {
|
|
136409
|
+
problem;
|
|
136410
|
+
constructor(problem, message, options) {
|
|
136411
|
+
super(message, options);
|
|
136412
|
+
this.problem = problem;
|
|
136413
|
+
this.name = "ManifestUnusableError";
|
|
136414
|
+
}
|
|
136415
|
+
};
|
|
136342
136416
|
});
|
|
136343
136417
|
|
|
136344
136418
|
// src/service/malloy_lexer_core.ts
|
|
@@ -139047,6 +139121,136 @@ var init_source_capability = __esm(() => {
|
|
|
139047
139121
|
compiled = new WeakMap;
|
|
139048
139122
|
});
|
|
139049
139123
|
|
|
139124
|
+
// src/service/materialization/domain/string_reads.ts
|
|
139125
|
+
function unstoredReadRefusal(reads) {
|
|
139126
|
+
if (reads === undefined)
|
|
139127
|
+
return;
|
|
139128
|
+
if ("refused" in reads)
|
|
139129
|
+
return reads.unstored ? reads.refused : undefined;
|
|
139130
|
+
const unstored = reads.reads.find((r) => r.upstream === undefined);
|
|
139131
|
+
if (unstored === undefined)
|
|
139132
|
+
return;
|
|
139133
|
+
const name = unstored.names[unstored.names.length - 1] ?? "?";
|
|
139134
|
+
return `it reads '${name}' from a table no stored upstream holds (the source ` + `warehouse, through a join or a source nothing stores), which no ` + `stored table can stand in for`;
|
|
139135
|
+
}
|
|
139136
|
+
function stringReadsRefusal(reads, contracts) {
|
|
139137
|
+
if (reads === undefined)
|
|
139138
|
+
return "its string reads were not recorded";
|
|
139139
|
+
if ("refused" in reads)
|
|
139140
|
+
return reads.refused;
|
|
139141
|
+
if (reads.reads.length === 0)
|
|
139142
|
+
return;
|
|
139143
|
+
const unstored = unstoredReadRefusal(reads);
|
|
139144
|
+
if (unstored !== undefined)
|
|
139145
|
+
return unstored;
|
|
139146
|
+
if (contracts.size === 0 || [...contracts.values()].some((c) => !c)) {
|
|
139147
|
+
return "an upstream it reads has no column contract";
|
|
139148
|
+
}
|
|
139149
|
+
for (const read of reads.reads) {
|
|
139150
|
+
const name = read.names[read.names.length - 1] ?? "?";
|
|
139151
|
+
const contract = read.upstream === undefined ? undefined : contracts.get(read.upstream);
|
|
139152
|
+
if (contract === undefined) {
|
|
139153
|
+
return `it compares '${name}', which could not be followed to the ` + `stored table of an upstream it reads`;
|
|
139154
|
+
}
|
|
139155
|
+
const compare = recordedCompare(read.names, contract);
|
|
139156
|
+
if (!MEETS[read.need].has(compare)) {
|
|
139157
|
+
return `it ${read.need === "exact" ? "orders" : "groups or compares"} ` + `'${name}', which its upstream's table records as compared ` + `${compare === "none" ? "unlike live" : `by ${compare} only`}`;
|
|
139158
|
+
}
|
|
139159
|
+
}
|
|
139160
|
+
return;
|
|
139161
|
+
}
|
|
139162
|
+
function recordedCompare(names, contract) {
|
|
139163
|
+
for (const name of [...names].reverse()) {
|
|
139164
|
+
const column = contractColumn(contract, name);
|
|
139165
|
+
if ("nativeType" in column)
|
|
139166
|
+
return column.compare;
|
|
139167
|
+
}
|
|
139168
|
+
return "none";
|
|
139169
|
+
}
|
|
139170
|
+
function unboundStringReadsRefusal(reads, unbound) {
|
|
139171
|
+
if ("refused" in reads)
|
|
139172
|
+
return;
|
|
139173
|
+
for (const read of reads.reads) {
|
|
139174
|
+
const upstream = read.upstream === undefined ? undefined : unbound.get(read.upstream);
|
|
139175
|
+
if (upstream === undefined)
|
|
139176
|
+
continue;
|
|
139177
|
+
const name = read.names[read.names.length - 1] ?? "?";
|
|
139178
|
+
const verb = read.need === "exact" ? "orders" : "groups or compares";
|
|
139179
|
+
const { capability } = upstream;
|
|
139180
|
+
if (capability === "unread") {
|
|
139181
|
+
return `it ${verb} '${name}' from '${upstream.name}', whose table is not ` + `bound yet and whose source's string comparison has not been ` + `read yet`;
|
|
139182
|
+
}
|
|
139183
|
+
const live = [...read.names].reverse().map((n) => capability.fields.get(n)).find((c) => c !== undefined);
|
|
139184
|
+
const compare = liveCompare(live);
|
|
139185
|
+
if (!MEETS[read.need].has(compare)) {
|
|
139186
|
+
return `it ${verb} '${name}' from '${upstream.name}', whose table is not ` + `bound yet and whose source compares it ` + `${compare === "none" ? "unlike byte order" : `by ${compare} only`}`;
|
|
139187
|
+
}
|
|
139188
|
+
}
|
|
139189
|
+
return;
|
|
139190
|
+
}
|
|
139191
|
+
function capabilityFingerprint(judged) {
|
|
139192
|
+
if (typeof judged === "string")
|
|
139193
|
+
return judged;
|
|
139194
|
+
return JSON.stringify([...judged.fields].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
139195
|
+
}
|
|
139196
|
+
var MEETS;
|
|
139197
|
+
var init_string_reads = __esm(() => {
|
|
139198
|
+
init_column_contract();
|
|
139199
|
+
MEETS = {
|
|
139200
|
+
exact: new Set(["exact"]),
|
|
139201
|
+
equality: new Set(["exact", "equality"])
|
|
139202
|
+
};
|
|
139203
|
+
});
|
|
139204
|
+
|
|
139205
|
+
// src/service/materialization/domain/compiled_build_plan.ts
|
|
139206
|
+
function stringCapabilityKey(sourceID, destination) {
|
|
139207
|
+
return JSON.stringify([sourceID, destination]);
|
|
139208
|
+
}
|
|
139209
|
+
function stringCapabilityKeyParts(key) {
|
|
139210
|
+
const [sourceID, destination] = JSON.parse(key);
|
|
139211
|
+
return { sourceID, destination };
|
|
139212
|
+
}
|
|
139213
|
+
function* sourcesInBuildOrder(build, tables) {
|
|
139214
|
+
for (const sourceID of build.order) {
|
|
139215
|
+
const source = tables[sourceID]?.source;
|
|
139216
|
+
if (source)
|
|
139217
|
+
yield source;
|
|
139218
|
+
}
|
|
139219
|
+
}
|
|
139220
|
+
function sourcesInDependencyOrder(builds) {
|
|
139221
|
+
const items = builds.flatMap((build) => build.order.map((sourceID) => ({
|
|
139222
|
+
sourceID,
|
|
139223
|
+
connectionName: build.connectionName
|
|
139224
|
+
})));
|
|
139225
|
+
const named = new Set(items.map((i) => i.sourceID));
|
|
139226
|
+
const upstreams = new Map;
|
|
139227
|
+
for (const build of builds) {
|
|
139228
|
+
for (const [sourceID, reads] of Object.entries(build.dependsOn)) {
|
|
139229
|
+
const set = upstreams.get(sourceID) ?? new Set;
|
|
139230
|
+
for (const r of reads)
|
|
139231
|
+
if (r !== sourceID && named.has(r))
|
|
139232
|
+
set.add(r);
|
|
139233
|
+
upstreams.set(sourceID, set);
|
|
139234
|
+
}
|
|
139235
|
+
}
|
|
139236
|
+
const out = [];
|
|
139237
|
+
const placed = new Set;
|
|
139238
|
+
const pending = [...items];
|
|
139239
|
+
while (pending.length > 0) {
|
|
139240
|
+
let at = pending.findIndex((item) => [...upstreams.get(item.sourceID) ?? []].every((u) => placed.has(u)));
|
|
139241
|
+
if (at < 0)
|
|
139242
|
+
at = 0;
|
|
139243
|
+
const [item] = pending.splice(at, 1);
|
|
139244
|
+
out.push(item);
|
|
139245
|
+
placed.add(item.sourceID);
|
|
139246
|
+
}
|
|
139247
|
+
return out;
|
|
139248
|
+
}
|
|
139249
|
+
function materializePlansOf(tables) {
|
|
139250
|
+
return Object.fromEntries(Object.entries(tables).flatMap(([sourceID, table]) => table.materialize ? [[sourceID, table.materialize]] : []));
|
|
139251
|
+
}
|
|
139252
|
+
var EVERY_SOURCE = "*";
|
|
139253
|
+
|
|
139050
139254
|
// src/service/composite_row_filter.ts
|
|
139051
139255
|
function rowFilterOnComposite(struct, modelDef) {
|
|
139052
139256
|
const contents = modelDef?.contents;
|
|
@@ -149976,48 +150180,6 @@ var init_persist_dynamic_terms = __esm(() => {
|
|
|
149976
150180
|
FIELD_PATH_SKIPPED_KEYS2 = new Set(["at", "location", "annotations"]);
|
|
149977
150181
|
});
|
|
149978
150182
|
|
|
149979
|
-
// src/service/materialization/domain/compiled_build_plan.ts
|
|
149980
|
-
function* sourcesInBuildOrder(build, tables) {
|
|
149981
|
-
for (const sourceID of build.order) {
|
|
149982
|
-
const source = tables[sourceID]?.source;
|
|
149983
|
-
if (source)
|
|
149984
|
-
yield source;
|
|
149985
|
-
}
|
|
149986
|
-
}
|
|
149987
|
-
function sourcesInDependencyOrder(builds) {
|
|
149988
|
-
const items = builds.flatMap((build) => build.order.map((sourceID) => ({
|
|
149989
|
-
sourceID,
|
|
149990
|
-
connectionName: build.connectionName
|
|
149991
|
-
})));
|
|
149992
|
-
const named = new Set(items.map((i) => i.sourceID));
|
|
149993
|
-
const upstreams = new Map;
|
|
149994
|
-
for (const build of builds) {
|
|
149995
|
-
for (const [sourceID, reads] of Object.entries(build.dependsOn)) {
|
|
149996
|
-
const set = upstreams.get(sourceID) ?? new Set;
|
|
149997
|
-
for (const r of reads)
|
|
149998
|
-
if (r !== sourceID && named.has(r))
|
|
149999
|
-
set.add(r);
|
|
150000
|
-
upstreams.set(sourceID, set);
|
|
150001
|
-
}
|
|
150002
|
-
}
|
|
150003
|
-
const out = [];
|
|
150004
|
-
const placed = new Set;
|
|
150005
|
-
const pending = [...items];
|
|
150006
|
-
while (pending.length > 0) {
|
|
150007
|
-
let at = pending.findIndex((item) => [...upstreams.get(item.sourceID) ?? []].every((u) => placed.has(u)));
|
|
150008
|
-
if (at < 0)
|
|
150009
|
-
at = 0;
|
|
150010
|
-
const [item] = pending.splice(at, 1);
|
|
150011
|
-
out.push(item);
|
|
150012
|
-
placed.add(item.sourceID);
|
|
150013
|
-
}
|
|
150014
|
-
return out;
|
|
150015
|
-
}
|
|
150016
|
-
function materializePlansOf(tables) {
|
|
150017
|
-
return Object.fromEntries(Object.entries(tables).flatMap(([sourceID, table]) => table.materialize ? [[sourceID, table.materialize]] : []));
|
|
150018
|
-
}
|
|
150019
|
-
var EVERY_SOURCE = "*";
|
|
150020
|
-
|
|
150021
150183
|
// src/service/materialization/domain/key_check.ts
|
|
150022
150184
|
function requireUnique(verdict) {
|
|
150023
150185
|
return verdict === "unique";
|
|
@@ -153741,6 +153903,18 @@ function reachedUpstreams(root, modelDef, map) {
|
|
|
153741
153903
|
}
|
|
153742
153904
|
return out;
|
|
153743
153905
|
}
|
|
153906
|
+
function materializedUpstream(sourceID, map) {
|
|
153907
|
+
const node = map.node(sourceID);
|
|
153908
|
+
const def = node?.def;
|
|
153909
|
+
const notes = ownLevelNotes(def?.annotations);
|
|
153910
|
+
if (notesDeclarePersist(notes.filter((n) => routeOfNote(n.text) === "@"))) {
|
|
153911
|
+
return;
|
|
153912
|
+
}
|
|
153913
|
+
if (!notes.some((n) => routeOfNote(n.text) === "materialize")) {
|
|
153914
|
+
return;
|
|
153915
|
+
}
|
|
153916
|
+
return { name: node?.name ?? sourceID, dialect: def?.dialect };
|
|
153917
|
+
}
|
|
153744
153918
|
function storedElsewhereReason(upstreams) {
|
|
153745
153919
|
const stored = upstreams.find((u) => u.storage !== undefined);
|
|
153746
153920
|
return stored ? `its upstream '${stored.name}' is stored in the storage= destination ` + `'${stored.storage}', whose table a build in the warehouse cannot ` + `read, and a downstream is never built by recomputing its upstream ` + `from raw; it is ` + `answered live, over '${stored.name}''s table` : undefined;
|
|
@@ -157903,7 +158077,7 @@ var init_generated_files = __esm(() => {
|
|
|
157903
158077
|
});
|
|
157904
158078
|
|
|
157905
158079
|
// package.json
|
|
157906
|
-
var version = "0.18.
|
|
158080
|
+
var version = "0.18.1";
|
|
157907
158081
|
var init_package = () => {};
|
|
157908
158082
|
|
|
157909
158083
|
// src/version.ts
|
|
@@ -161030,61 +161204,6 @@ var init_over_stored_proof = __esm(() => {
|
|
|
161030
161204
|
init_addressing();
|
|
161031
161205
|
});
|
|
161032
161206
|
|
|
161033
|
-
// src/service/materialization/domain/string_reads.ts
|
|
161034
|
-
function unstoredReadRefusal(reads) {
|
|
161035
|
-
if (reads === undefined)
|
|
161036
|
-
return;
|
|
161037
|
-
if ("refused" in reads)
|
|
161038
|
-
return reads.unstored ? reads.refused : undefined;
|
|
161039
|
-
const unstored = reads.reads.find((r) => r.upstream === undefined);
|
|
161040
|
-
if (unstored === undefined)
|
|
161041
|
-
return;
|
|
161042
|
-
const name = unstored.names[unstored.names.length - 1] ?? "?";
|
|
161043
|
-
return `it reads '${name}' from a table no stored upstream holds (the source ` + `warehouse, through a join or a source nothing stores), which no ` + `stored table can stand in for`;
|
|
161044
|
-
}
|
|
161045
|
-
function stringReadsRefusal(reads, contracts) {
|
|
161046
|
-
if (reads === undefined)
|
|
161047
|
-
return "its string reads were not recorded";
|
|
161048
|
-
if ("refused" in reads)
|
|
161049
|
-
return reads.refused;
|
|
161050
|
-
if (reads.reads.length === 0)
|
|
161051
|
-
return;
|
|
161052
|
-
const unstored = unstoredReadRefusal(reads);
|
|
161053
|
-
if (unstored !== undefined)
|
|
161054
|
-
return unstored;
|
|
161055
|
-
if (contracts.size === 0 || [...contracts.values()].some((c) => !c)) {
|
|
161056
|
-
return "an upstream it reads has no column contract";
|
|
161057
|
-
}
|
|
161058
|
-
for (const read of reads.reads) {
|
|
161059
|
-
const name = read.names[read.names.length - 1] ?? "?";
|
|
161060
|
-
const contract = read.upstream === undefined ? undefined : contracts.get(read.upstream);
|
|
161061
|
-
if (contract === undefined) {
|
|
161062
|
-
return `it compares '${name}', which could not be followed to the ` + `stored table of an upstream it reads`;
|
|
161063
|
-
}
|
|
161064
|
-
const compare = recordedCompare(read.names, contract);
|
|
161065
|
-
if (!MEETS[read.need].has(compare)) {
|
|
161066
|
-
return `it ${read.need === "exact" ? "orders" : "groups or compares"} ` + `'${name}', which its upstream's table records as compared ` + `${compare === "none" ? "unlike live" : `by ${compare} only`}`;
|
|
161067
|
-
}
|
|
161068
|
-
}
|
|
161069
|
-
return;
|
|
161070
|
-
}
|
|
161071
|
-
function recordedCompare(names, contract) {
|
|
161072
|
-
for (const name of [...names].reverse()) {
|
|
161073
|
-
const column = contractColumn(contract, name);
|
|
161074
|
-
if ("nativeType" in column)
|
|
161075
|
-
return column.compare;
|
|
161076
|
-
}
|
|
161077
|
-
return "none";
|
|
161078
|
-
}
|
|
161079
|
-
var MEETS;
|
|
161080
|
-
var init_string_reads = __esm(() => {
|
|
161081
|
-
init_column_contract();
|
|
161082
|
-
MEETS = {
|
|
161083
|
-
exact: new Set(["exact"]),
|
|
161084
|
-
equality: new Set(["exact", "equality"])
|
|
161085
|
-
};
|
|
161086
|
-
});
|
|
161087
|
-
|
|
161088
161207
|
// src/service/materialization/text/author_model.ts
|
|
161089
161208
|
function authorModelLiftContext(modelDef, readFile) {
|
|
161090
161209
|
const cacheable = modelDef !== null && typeof modelDef === "object";
|
|
@@ -161922,7 +162041,8 @@ function emptyBuildPlanParts() {
|
|
|
161922
162041
|
modelGateLines: noModelGateLines(),
|
|
161923
162042
|
persistedViews: {},
|
|
161924
162043
|
omittedSources: [],
|
|
161925
|
-
accessReads: []
|
|
162044
|
+
accessReads: [],
|
|
162045
|
+
stringCapabilityReads: {}
|
|
161926
162046
|
};
|
|
161927
162047
|
}
|
|
161928
162048
|
function mergeBuildPlanParts(into, from) {
|
|
@@ -161940,6 +162060,7 @@ function mergeBuildPlanParts(into, from) {
|
|
|
161940
162060
|
into.accessReads = [
|
|
161941
162061
|
...new Set([...into.accessReads, ...from.accessReads])
|
|
161942
162062
|
].sort();
|
|
162063
|
+
Object.assign(into.stringCapabilityReads, from.stringCapabilityReads);
|
|
161943
162064
|
}
|
|
161944
162065
|
function addAnnotationFinding(parts, finding) {
|
|
161945
162066
|
const key = (f) => [f.code, f.model ?? "", f.subject ?? "", f.message].join("\x00");
|
|
@@ -162133,7 +162254,10 @@ async function collectGeneratedRollups(parts, args) {
|
|
|
162133
162254
|
measures: plan.measures.map((m) => m.name)
|
|
162134
162255
|
},
|
|
162135
162256
|
stored: [storedBase.baseSourceID]
|
|
162136
|
-
}, plan.storage
|
|
162257
|
+
}, plan.storage, {
|
|
162258
|
+
modelDef: args.modelDef,
|
|
162259
|
+
judged: parts.stringCapabilityReads
|
|
162260
|
+
}) : undefined;
|
|
162137
162261
|
const overStored = provenRollupOverStored(source, plan, generated.overStoredBases.get(source.sourceID), parts.tables);
|
|
162138
162262
|
const unusableUpstream = storedBase && plan.storage !== undefined ? storedBaseDecline(args, source, plan, storedBase, plan.storage) : !storedBase && !overStored.overStoredBase ? rollupOverDefinition(args, plan) : undefined;
|
|
162139
162263
|
parts.tables[source.sourceID] = {
|
|
@@ -162160,7 +162284,7 @@ function provenRollupOverStored(source, plan, variant, tables) {
|
|
|
162160
162284
|
return {};
|
|
162161
162285
|
return overStoredProven(source, variant, base.source) ? { overStoredBase: variant } : {};
|
|
162162
162286
|
}
|
|
162163
|
-
async function planStringReads(ports, materializer, request, destination) {
|
|
162287
|
+
async function planStringReads(ports, materializer, request, destination, upstreams) {
|
|
162164
162288
|
if (!ports) {
|
|
162165
162289
|
return { refused: "this package reads no string a build compares" };
|
|
162166
162290
|
}
|
|
@@ -162173,14 +162297,30 @@ async function planStringReads(ports, materializer, request, destination) {
|
|
|
162173
162297
|
const unstored = unstoredReadRefusal(reads);
|
|
162174
162298
|
if (unstored !== undefined)
|
|
162175
162299
|
return { refused: unstored, unstored: true };
|
|
162176
|
-
if ("refused" in reads
|
|
162177
|
-
return reads;
|
|
162178
|
-
const contracts = new Map(request.stored.map((id) => [id, ports.boundContract(id, destination)]));
|
|
162179
|
-
if ([...contracts.values()].some((c) => c === undefined))
|
|
162300
|
+
if ("refused" in reads)
|
|
162180
162301
|
return reads;
|
|
162181
|
-
const
|
|
162302
|
+
const contracts = new Map(request.stored.map((id) => [id, ports.boundContract?.(id, destination)]));
|
|
162303
|
+
const why = ports.boundContract && [...contracts.values()].every((c) => c !== undefined) ? stringReadsRefusal(reads, contracts) : unboundStringReadsRefusal(reads, await unboundCapabilities(ports, reads, request.stored.filter((id) => contracts.get(id) === undefined), destination, upstreams));
|
|
162182
162304
|
return why === undefined ? reads : { refused: why };
|
|
162183
162305
|
}
|
|
162306
|
+
async function unboundCapabilities(ports, reads, unbound, destination, upstreams) {
|
|
162307
|
+
const out = new Map;
|
|
162308
|
+
if ("refused" in reads)
|
|
162309
|
+
return out;
|
|
162310
|
+
const map = SourceMap.of(upstreams.modelDef);
|
|
162311
|
+
for (const id of unbound) {
|
|
162312
|
+
if (!reads.reads.some((r) => r.upstream === id))
|
|
162313
|
+
continue;
|
|
162314
|
+
const upstream = materializedUpstream(id, map);
|
|
162315
|
+
if (upstream === undefined || capabilitiesOf(upstream.dialect).stringCollation !== "column") {
|
|
162316
|
+
continue;
|
|
162317
|
+
}
|
|
162318
|
+
const capability = ports.capability ? await ports.capability(id).catch(() => "unread") : "unread";
|
|
162319
|
+
upstreams.judged[stringCapabilityKey(id, destination)] = capabilityFingerprint(capability);
|
|
162320
|
+
out.set(id, { name: upstream.name, capability });
|
|
162321
|
+
}
|
|
162322
|
+
return out;
|
|
162323
|
+
}
|
|
162184
162324
|
function viewUnusableUpstream(generated, sourceID, proven) {
|
|
162185
162325
|
const unusable = generated.overStoredUnusable.get(sourceID);
|
|
162186
162326
|
if (unusable !== undefined)
|
|
@@ -162241,11 +162381,11 @@ function storedBaseDecline(args, source, plan, storedBase, destination) {
|
|
|
162241
162381
|
return `its model does not declare ${base}`;
|
|
162242
162382
|
return "declined" in text ? `${base} cannot be re-rooted on that table: ${text.declined}` : undefined;
|
|
162243
162383
|
}
|
|
162244
|
-
function inDestinationStringReads(args, stored, planned) {
|
|
162384
|
+
function inDestinationStringReads(args, stored, planned, upstreams) {
|
|
162245
162385
|
const run = planned.kind === "query" ? `run: ${quotedIdentifier(planned.queryName)}` : `run: ${quotedIdentifier(planned.sourceName)} -> ${quotedIdentifier(planned.viewName)}`;
|
|
162246
|
-
return planStringReads(args.stringReads, args.materializer, { run, stored: stored.upstreams.map((u) => u.sourceID) }, planned.storage);
|
|
162386
|
+
return planStringReads(args.stringReads, args.materializer, { run, stored: stored.upstreams.map((u) => u.sourceID) }, planned.storage, upstreams);
|
|
162247
162387
|
}
|
|
162248
|
-
async function chainedStringReads(source, modelDef, materializer, ports) {
|
|
162388
|
+
async function chainedStringReads(source, modelDef, materializer, ports, judged) {
|
|
162249
162389
|
const destination = declaredStorage(source)?.trim();
|
|
162250
162390
|
if (!destination)
|
|
162251
162391
|
return;
|
|
@@ -162257,7 +162397,7 @@ async function chainedStringReads(source, modelDef, materializer, ports) {
|
|
|
162257
162397
|
const stored = reachedUpstreams(def, modelDef, map).filter((u) => u.storage === destination && u.sourceID !== source.sourceID).map((u) => u.sourceID);
|
|
162258
162398
|
if (stored.length === 0)
|
|
162259
162399
|
return;
|
|
162260
|
-
const reads = await planStringReads(ports, materializer, { downstream: source.name, stored }, destination);
|
|
162400
|
+
const reads = await planStringReads(ports, materializer, { downstream: source.name, stored }, destination, { modelDef, judged });
|
|
162261
162401
|
if (!("refused" in reads) || !reads.unstored)
|
|
162262
162402
|
return reads;
|
|
162263
162403
|
const persisted = new Set(reachedUpstreams(def, modelDef, map).map((u) => u.sourceID));
|
|
@@ -162340,7 +162480,7 @@ async function collectGeneratedPersistedViews(parts, args) {
|
|
|
162340
162480
|
continue;
|
|
162341
162481
|
}
|
|
162342
162482
|
kept++;
|
|
162343
|
-
const stringReads = inDestination && "stored" in inDestination ? await inDestinationStringReads(args, inDestination.stored, query ?? plan) : undefined;
|
|
162483
|
+
const stringReads = inDestination && "stored" in inDestination ? await inDestinationStringReads(args, inDestination.stored, query ?? plan, { modelDef: authorDef, judged: parts.stringCapabilityReads }) : undefined;
|
|
162344
162484
|
const unusableUpstream = viewUnusableUpstream(generated, source.sourceID, overStoredBase !== undefined);
|
|
162345
162485
|
parts.tables[source.sourceID] = {
|
|
162346
162486
|
kind: "view",
|
|
@@ -162641,7 +162781,7 @@ async function planV1PersistSources(parts, planned, args) {
|
|
|
162641
162781
|
modelDef: modelDefOf(malloyModel),
|
|
162642
162782
|
deps: gateDepsFor(malloyModel, modelPath)
|
|
162643
162783
|
};
|
|
162644
|
-
const stringReads = declaringModelPath(sourceIDFileURL(sourceID), packagePath, modelPath) === modelPath ? await chainedStringReads(source, classificationCtx.modelDef, materializer, args.stringReads) : parts.tables[sourceID]?.stringReads;
|
|
162784
|
+
const stringReads = declaringModelPath(sourceIDFileURL(sourceID), packagePath, modelPath) === modelPath ? await chainedStringReads(source, classificationCtx.modelDef, materializer, args.stringReads, parts.stringCapabilityReads) : parts.tables[sourceID]?.stringReads;
|
|
162645
162785
|
const destination = declaredStorage(source)?.trim();
|
|
162646
162786
|
const map = SourceMap.of(classificationCtx.modelDef);
|
|
162647
162787
|
const query = map.node(sourceID)?.def?.query;
|
|
@@ -163003,6 +163143,7 @@ function derivePackagePlan(compiled, materializationConfig, counts = {}) {
|
|
|
163003
163143
|
materializePlans: materializePlansOf(compiled.tables),
|
|
163004
163144
|
asOfBuild,
|
|
163005
163145
|
accessReads: [...compiled.accessReads ?? []],
|
|
163146
|
+
...compiled.stringCapabilityReads && Object.keys(compiled.stringCapabilityReads).length > 0 ? { stringCapabilityReads: { ...compiled.stringCapabilityReads } } : {},
|
|
163006
163147
|
eligibilityRefused: { ...counts }
|
|
163007
163148
|
};
|
|
163008
163149
|
}
|
|
@@ -163303,6 +163444,7 @@ var init_build_plan = __esm(() => {
|
|
|
163303
163444
|
init_over_stored_proof();
|
|
163304
163445
|
init_downstream_upstreams();
|
|
163305
163446
|
init_string_reads();
|
|
163447
|
+
init_dialect();
|
|
163306
163448
|
init_column_contract();
|
|
163307
163449
|
init_source_map();
|
|
163308
163450
|
init_author_model();
|
|
@@ -164563,7 +164705,8 @@ async function collectPackageParts(pkg, signal, keyChecks) {
|
|
|
164563
164705
|
...pkg.planChainStringReads ? {
|
|
164564
164706
|
stringReads: {
|
|
164565
164707
|
read: pkg.planChainStringReads,
|
|
164566
|
-
...pkg.boundStorageContract ? { boundContract: pkg.boundStorageContract } : {}
|
|
164708
|
+
...pkg.boundStorageContract ? { boundContract: pkg.boundStorageContract } : {},
|
|
164709
|
+
...pkg.upstreamStringCapability ? { capability: pkg.upstreamStringCapability } : {}
|
|
164567
164710
|
}
|
|
164568
164711
|
} : {}
|
|
164569
164712
|
});
|
|
@@ -180331,6 +180474,9 @@ class PlanLifecycle {
|
|
|
180331
180474
|
get upstreamSchemas() {
|
|
180332
180475
|
return this.serving().upstreamSchemas;
|
|
180333
180476
|
}
|
|
180477
|
+
get stringCapabilityReads() {
|
|
180478
|
+
return this.serving().stringCapabilityReads;
|
|
180479
|
+
}
|
|
180334
180480
|
get asOfBuild() {
|
|
180335
180481
|
return this.serving().asOfBuild;
|
|
180336
180482
|
}
|
|
@@ -180426,7 +180572,8 @@ class PlanLifecycle {
|
|
|
180426
180572
|
buildConnectionNames: new Set(outcome.buildConnectionNames),
|
|
180427
180573
|
asOfBuild: outcome.asOfBuild ?? {},
|
|
180428
180574
|
upstreamSchemas: outcome.upstreamSchemas ?? {},
|
|
180429
|
-
withdrawn: new Set
|
|
180575
|
+
withdrawn: new Set,
|
|
180576
|
+
stringCapabilityReads: outcome.stringCapabilityReads ?? {}
|
|
180430
180577
|
};
|
|
180431
180578
|
}
|
|
180432
180579
|
serving() {
|
|
@@ -180605,7 +180752,8 @@ var init_plan_lifecycle = __esm(() => {
|
|
|
180605
180752
|
buildConnectionNames: new Set,
|
|
180606
180753
|
asOfBuild: {},
|
|
180607
180754
|
upstreamSchemas: {},
|
|
180608
|
-
withdrawn: new Set
|
|
180755
|
+
withdrawn: new Set,
|
|
180756
|
+
stringCapabilityReads: {}
|
|
180609
180757
|
};
|
|
180610
180758
|
});
|
|
180611
180759
|
|
|
@@ -183146,6 +183294,8 @@ var init_incremental_upstream = __esm(() => {
|
|
|
183146
183294
|
});
|
|
183147
183295
|
|
|
183148
183296
|
// src/service/materialization/package_materialization.ts
|
|
183297
|
+
import * as path24 from "path";
|
|
183298
|
+
import { fileURLToPath as fileURLToPath10 } from "url";
|
|
183149
183299
|
function toTableNameManifest(entries) {
|
|
183150
183300
|
const out = {};
|
|
183151
183301
|
for (const [sourceEntityId, entry] of Object.entries(entries)) {
|
|
@@ -183184,6 +183334,7 @@ class PackageMaterialization {
|
|
|
183184
183334
|
buildFound = new Map;
|
|
183185
183335
|
rebinding;
|
|
183186
183336
|
commitChain = Promise.resolve();
|
|
183337
|
+
capabilityChecks = Promise.resolve();
|
|
183187
183338
|
committing;
|
|
183188
183339
|
lapseTimer;
|
|
183189
183340
|
storageRetry;
|
|
@@ -183240,8 +183391,13 @@ class PackageMaterialization {
|
|
|
183240
183391
|
isBuildPlanStale() {
|
|
183241
183392
|
return this.plan.isStale();
|
|
183242
183393
|
}
|
|
183243
|
-
refreshBuildPlan(derive, options = {}) {
|
|
183244
|
-
|
|
183394
|
+
async refreshBuildPlan(derive, options = {}) {
|
|
183395
|
+
const judged = this.plan.stringCapabilityReads;
|
|
183396
|
+
const derived = await this.plan.refresh(derive, options);
|
|
183397
|
+
if (derived && this.plan.stringCapabilityReads !== judged) {
|
|
183398
|
+
await this.capabilitiesRead();
|
|
183399
|
+
}
|
|
183400
|
+
return derived;
|
|
183245
183401
|
}
|
|
183246
183402
|
whenBuildPlanCurrent(timeoutMs) {
|
|
183247
183403
|
return this.plan.whenCurrent(timeoutMs);
|
|
@@ -183543,11 +183699,13 @@ class PackageMaterialization {
|
|
|
183543
183699
|
change();
|
|
183544
183700
|
const next = this.snapshot();
|
|
183545
183701
|
if (models || next.bindings.length > 0 || Object.keys(next.entries).length > 0) {
|
|
183702
|
+
const reads = [];
|
|
183546
183703
|
for (const model of this.owner.models().values()) {
|
|
183547
183704
|
model.setStringCapabilityReader(refreshStringCapabilities);
|
|
183548
183705
|
model.setScopeFactsRecorder(recordScopeFacts);
|
|
183549
|
-
model.refreshStringCapabilities();
|
|
183706
|
+
reads.push(model.refreshStringCapabilities());
|
|
183550
183707
|
}
|
|
183708
|
+
Promise.all(reads).then(() => this.capabilitiesRead());
|
|
183551
183709
|
}
|
|
183552
183710
|
if (next.bindings !== this.publishedBindings || models) {
|
|
183553
183711
|
this.publishedBindings = next.bindings;
|
|
@@ -184205,6 +184363,63 @@ class PackageMaterialization {
|
|
|
184205
184363
|
}
|
|
184206
184364
|
async recordStringCapabilitiesAtLoad() {
|
|
184207
184365
|
await Promise.all([...this.owner.models().values()].map((model) => model.refreshStringCapabilities()));
|
|
184366
|
+
await this.capabilitiesRead();
|
|
184367
|
+
}
|
|
184368
|
+
async upstreamStringCapability(sourceID) {
|
|
184369
|
+
const split = splitSourceID(sourceID);
|
|
184370
|
+
if (!split)
|
|
184371
|
+
return "unread";
|
|
184372
|
+
let declaring;
|
|
184373
|
+
try {
|
|
184374
|
+
declaring = path24.resolve(fileURLToPath10(split.url));
|
|
184375
|
+
} catch {
|
|
184376
|
+
return "unread";
|
|
184377
|
+
}
|
|
184378
|
+
const root = this.owner.packagePath();
|
|
184379
|
+
const model = [...this.owner.models()].find(([modelPath]) => path24.resolve(root, modelPath) === declaring)?.[1];
|
|
184380
|
+
if (!model)
|
|
184381
|
+
return "unread";
|
|
184382
|
+
const recorded = await stringCapabilitiesOf(model.stringCapabilityRuntime());
|
|
184383
|
+
const source = recorded?.sources.get(split.name);
|
|
184384
|
+
if (!source)
|
|
184385
|
+
return "unread";
|
|
184386
|
+
const fields = new Map;
|
|
184387
|
+
for (const [key, field] of source.fields) {
|
|
184388
|
+
if (!key.includes("\x00"))
|
|
184389
|
+
fields.set(key, field.collation);
|
|
184390
|
+
}
|
|
184391
|
+
return { fields };
|
|
184392
|
+
}
|
|
184393
|
+
capabilitiesRead() {
|
|
184394
|
+
const check = this.capabilityChecks.then(() => this.replanOnCapabilityChange());
|
|
184395
|
+
this.capabilityChecks = check.catch(() => {
|
|
184396
|
+
return;
|
|
184397
|
+
});
|
|
184398
|
+
return check.catch((err) => {
|
|
184399
|
+
logger.warn("Could not re-derive the build plan after reading how its sources compare strings", {
|
|
184400
|
+
packageName: this.owner.packageName(),
|
|
184401
|
+
code: errorCodeOf(err)
|
|
184402
|
+
});
|
|
184403
|
+
});
|
|
184404
|
+
}
|
|
184405
|
+
async replanOnCapabilityChange() {
|
|
184406
|
+
const judged = this.plan.stringCapabilityReads;
|
|
184407
|
+
for (const [key, before] of Object.entries(judged)) {
|
|
184408
|
+
if (this.disposed)
|
|
184409
|
+
return;
|
|
184410
|
+
const { sourceID, destination } = stringCapabilityKeyParts(key);
|
|
184411
|
+
const now = this.boundStorageContract(sourceID, destination) ? capabilityFingerprint("bound") : capabilityFingerprint(await this.upstreamStringCapability(sourceID));
|
|
184412
|
+
if (now === before)
|
|
184413
|
+
continue;
|
|
184414
|
+
if (this.disposed || this.plan.stringCapabilityReads !== judged) {
|
|
184415
|
+
return;
|
|
184416
|
+
}
|
|
184417
|
+
this.plan.markStale();
|
|
184418
|
+
await this.plan.refresh(async () => {
|
|
184419
|
+
return;
|
|
184420
|
+
});
|
|
184421
|
+
return;
|
|
184422
|
+
}
|
|
184208
184423
|
}
|
|
184209
184424
|
setServedCopyContextOn(model) {
|
|
184210
184425
|
model.setStringCapabilityReader(refreshStringCapabilities);
|
|
@@ -184439,6 +184654,7 @@ var init_package_materialization = __esm(() => {
|
|
|
184439
184654
|
init_manifest_loader();
|
|
184440
184655
|
init_read_text();
|
|
184441
184656
|
init_source_capability();
|
|
184657
|
+
init_string_reads();
|
|
184442
184658
|
init_freshness();
|
|
184443
184659
|
init_scope_facts();
|
|
184444
184660
|
init_config2();
|
|
@@ -184543,7 +184759,7 @@ function updateRowSql(table, id, values, rawAssignments = [], where) {
|
|
|
184543
184759
|
import {
|
|
184544
184760
|
DuckDBInstance as DuckDBInstance2
|
|
184545
184761
|
} from "@duckdb/node-api";
|
|
184546
|
-
import * as
|
|
184762
|
+
import * as path25 from "path";
|
|
184547
184763
|
function duckDBInstanceResourceOptions() {
|
|
184548
184764
|
const options = {};
|
|
184549
184765
|
const threads = getDuckDBThreads();
|
|
@@ -184570,7 +184786,7 @@ class DuckDBConnection6 {
|
|
|
184570
184786
|
dbPath;
|
|
184571
184787
|
mutex = new Mutex;
|
|
184572
184788
|
constructor(dbPath) {
|
|
184573
|
-
this.dbPath = dbPath ||
|
|
184789
|
+
this.dbPath = dbPath || path25.join(process.cwd(), "publisher.db");
|
|
184574
184790
|
}
|
|
184575
184791
|
async initialize() {
|
|
184576
184792
|
try {
|
|
@@ -185161,16 +185377,32 @@ function newestServingEntries(runs, reader, excludeId) {
|
|
|
185161
185377
|
function newestIncrementalEntries(runs, reader, excludeId) {
|
|
185162
185378
|
const committed = runs.filter((m) => m.id !== excludeId && readsRun(m, reader) && m.status === "MANIFEST_FILE_READY" && m.manifest?.entries).sort((a, b) => committedAt(b) - committedAt(a));
|
|
185163
185379
|
const out = {};
|
|
185380
|
+
const newer = new Set;
|
|
185164
185381
|
for (const m of committed) {
|
|
185382
|
+
const superseded = new Set(tableNamesIn(m.metadata, SUPERSEDED_TABLES_KEY).map(tableIdentity));
|
|
185383
|
+
const recorded = [];
|
|
185165
185384
|
for (const [address, entry] of Object.entries(m.manifest.entries)) {
|
|
185166
|
-
if (
|
|
185385
|
+
if (isLegacyFailedEntry(entry))
|
|
185386
|
+
continue;
|
|
185387
|
+
const table = recordedTable(entry);
|
|
185388
|
+
recorded.push(table);
|
|
185389
|
+
if (out[address] || !entry.ledger || superseded.has(tableIdentity(entry.physicalTableName)) || newer.has(table)) {
|
|
185167
185390
|
continue;
|
|
185168
185391
|
}
|
|
185169
185392
|
out[address] = entry;
|
|
185170
185393
|
}
|
|
185394
|
+
for (const table of recorded)
|
|
185395
|
+
newer.add(table);
|
|
185171
185396
|
}
|
|
185172
185397
|
return out;
|
|
185173
185398
|
}
|
|
185399
|
+
function recordedTable(entry) {
|
|
185400
|
+
return JSON.stringify([
|
|
185401
|
+
entry.connectionName ?? null,
|
|
185402
|
+
entry.storageDestinationName ?? null,
|
|
185403
|
+
tableIdentity(entry.physicalTableName)
|
|
185404
|
+
]);
|
|
185405
|
+
}
|
|
185174
185406
|
function tableIdentity(physicalTableName) {
|
|
185175
185407
|
return leafKey(physicalTableName);
|
|
185176
185408
|
}
|
|
@@ -185230,9 +185462,9 @@ var init_materialization_scope = __esm(() => {
|
|
|
185230
185462
|
|
|
185231
185463
|
// src/package_relative_text.ts
|
|
185232
185464
|
import * as fs12 from "fs";
|
|
185233
|
-
import * as
|
|
185465
|
+
import * as path26 from "path";
|
|
185234
185466
|
import { pathToFileURL as pathToFileURL13 } from "url";
|
|
185235
|
-
function packageRelativeText(text, packagePath, pathModule =
|
|
185467
|
+
function packageRelativeText(text, packagePath, pathModule = path26) {
|
|
185236
185468
|
if (!text || !packagePath)
|
|
185237
185469
|
return text;
|
|
185238
185470
|
const windows = pathModule.sep === "\\";
|
|
@@ -185244,7 +185476,7 @@ function packageRelativeText(text, packagePath, pathModule = path25) {
|
|
|
185244
185476
|
};
|
|
185245
185477
|
addRoot(packagePath);
|
|
185246
185478
|
addRoot(pathModule.resolve(packagePath));
|
|
185247
|
-
if (pathModule ===
|
|
185479
|
+
if (pathModule === path26) {
|
|
185248
185480
|
for (const real of [fs12.realpathSync, fs12.realpathSync.native]) {
|
|
185249
185481
|
try {
|
|
185250
185482
|
addRoot(real(packagePath));
|
|
@@ -185262,7 +185494,7 @@ function packageRelativeText(text, packagePath, pathModule = path25) {
|
|
|
185262
185494
|
if (/^\/[A-Za-z]:/.test(urlPath)) {
|
|
185263
185495
|
spellings.add(`file://${encodeURI(urlPath).replace(/^\/([A-Za-z]):/, "/$1%3A")}`);
|
|
185264
185496
|
}
|
|
185265
|
-
if (pathModule ===
|
|
185497
|
+
if (pathModule === path26 && pathModule.isAbsolute(root)) {
|
|
185266
185498
|
try {
|
|
185267
185499
|
spellings.add(pathToFileURL13(root).href);
|
|
185268
185500
|
} catch {}
|
|
@@ -185282,7 +185514,7 @@ function packageRelativeText(text, packagePath, pathModule = path25) {
|
|
|
185282
185514
|
function escapeRegExp(text) {
|
|
185283
185515
|
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
185284
185516
|
}
|
|
185285
|
-
function callerVisibleText(text, packagePath, pathModule =
|
|
185517
|
+
function callerVisibleText(text, packagePath, pathModule = path26) {
|
|
185286
185518
|
if (!text)
|
|
185287
185519
|
return text;
|
|
185288
185520
|
const relative = packagePath ? packageRelativeText(text, packagePath, pathModule) : text;
|
|
@@ -186323,7 +186555,8 @@ async function planSourceRefresh(params) {
|
|
|
186323
186555
|
};
|
|
186324
186556
|
}
|
|
186325
186557
|
}
|
|
186326
|
-
const
|
|
186558
|
+
const unheld = ledgerEntry !== null && !forceRefresh && !context.callerLedger && !heldForDelta(context, lineage);
|
|
186559
|
+
const postgresVersionNum = lineage.strategy === "merge" && capabilitiesOf(target.dialect).mergeGatedByServerVersion && ledgerEntry !== null && !unheld ? await probeServerVersion(target.runner, target.dialect) : undefined;
|
|
186327
186560
|
const upstream = coordinateWithParent({
|
|
186328
186561
|
lineage,
|
|
186329
186562
|
recorded: ledgerEntry,
|
|
@@ -186340,23 +186573,31 @@ async function planSourceRefresh(params) {
|
|
|
186340
186573
|
});
|
|
186341
186574
|
}
|
|
186342
186575
|
let step;
|
|
186343
|
-
|
|
186344
|
-
step =
|
|
186345
|
-
target,
|
|
186346
|
-
lineage,
|
|
186347
|
-
ledgerEntry,
|
|
186348
|
-
forceRefresh,
|
|
186349
|
-
now: context.now,
|
|
186350
|
-
columns: params.columns,
|
|
186351
|
-
postgresVersionNum,
|
|
186352
|
-
...upstream ? { upstream } : {}
|
|
186353
|
-
});
|
|
186354
|
-
} catch (err) {
|
|
186355
|
-
return {
|
|
186576
|
+
if (unheld) {
|
|
186577
|
+
step = {
|
|
186356
186578
|
mode: "seed",
|
|
186357
|
-
reasonCode: "
|
|
186358
|
-
reason:
|
|
186579
|
+
reasonCode: "ledger_unheld",
|
|
186580
|
+
reason: "the table its recorded boundary names was not held to its contract before the run"
|
|
186359
186581
|
};
|
|
186582
|
+
} else {
|
|
186583
|
+
try {
|
|
186584
|
+
step = await planIncrementalStep({
|
|
186585
|
+
target,
|
|
186586
|
+
lineage,
|
|
186587
|
+
ledgerEntry,
|
|
186588
|
+
forceRefresh,
|
|
186589
|
+
now: context.now,
|
|
186590
|
+
columns: params.columns,
|
|
186591
|
+
postgresVersionNum,
|
|
186592
|
+
...upstream ? { upstream } : {}
|
|
186593
|
+
});
|
|
186594
|
+
} catch (err) {
|
|
186595
|
+
return {
|
|
186596
|
+
mode: "seed",
|
|
186597
|
+
reasonCode: "plan_error",
|
|
186598
|
+
reason: `the delta could not be planned (${errMessage(err)})`
|
|
186599
|
+
};
|
|
186600
|
+
}
|
|
186360
186601
|
}
|
|
186361
186602
|
noteStep(context, lineage, ledgerEntry, step, params.sourceName);
|
|
186362
186603
|
if (context.callerLedger && step.mode === "seed" && (step.reasonCode === "lineage_changed" || step.reasonCode === "table_renamed")) {
|
|
@@ -186364,6 +186605,12 @@ async function planSourceRefresh(params) {
|
|
|
186364
186605
|
}
|
|
186365
186606
|
return step;
|
|
186366
186607
|
}
|
|
186608
|
+
function heldForDelta(context, lineage) {
|
|
186609
|
+
if (context.heldAdvanced === undefined)
|
|
186610
|
+
return true;
|
|
186611
|
+
const held = context.heldAdvanced.get(lineage.sourceEntityId);
|
|
186612
|
+
return held !== undefined && held.physicalTableName === lineage.physicalTableName && (held.storageDestinationName ?? undefined) === (lineage.storageDestinationName ?? undefined);
|
|
186613
|
+
}
|
|
186367
186614
|
function lastReadParent(context, lineage, recorded) {
|
|
186368
186615
|
const parent = lineage.parent;
|
|
186369
186616
|
if (!parent)
|
|
@@ -187489,7 +187736,7 @@ var init_database_build_strategy = __esm(() => {
|
|
|
187489
187736
|
|
|
187490
187737
|
// src/service/materialization/run/storage_admin.ts
|
|
187491
187738
|
import { existsSync as existsSync3, readdirSync as readdirSync3 } from "node:fs";
|
|
187492
|
-
import
|
|
187739
|
+
import path27 from "node:path";
|
|
187493
187740
|
function dropStorageTableSql(destinationName, physicalTableName, schema) {
|
|
187494
187741
|
return `DROP TABLE IF EXISTS ${quoteManifestTablePath(storageTablePath(destinationName, physicalTableName, schema), STORAGE_DIALECT)}`;
|
|
187495
187742
|
}
|
|
@@ -187532,7 +187779,7 @@ async function listStorageTables(params) {
|
|
|
187532
187779
|
} else {
|
|
187533
187780
|
const dbPath = storageDestinationFile(environmentPath, destinationName);
|
|
187534
187781
|
const destinationRoot = storageDestinationRoot(environmentPath);
|
|
187535
|
-
if (!existsSync3(destinationRoot) || !readdirSync3(destinationRoot).includes(
|
|
187782
|
+
if (!existsSync3(destinationRoot) || !readdirSync3(destinationRoot).includes(path27.basename(dbPath))) {
|
|
187536
187783
|
return [];
|
|
187537
187784
|
}
|
|
187538
187785
|
await session.runSQL(`ATTACH '${escapeSQL(dbPath)}' AS ${quoteIdentifier(destinationName, STORAGE_DIALECT)} (READ_ONLY)`);
|
|
@@ -189369,8 +189616,8 @@ var init_table_ownership = __esm(() => {
|
|
|
189369
189616
|
});
|
|
189370
189617
|
|
|
189371
189618
|
// src/service/materialization/run/run_instructions.ts
|
|
189372
|
-
import * as
|
|
189373
|
-
import { fileURLToPath as
|
|
189619
|
+
import * as path28 from "path";
|
|
189620
|
+
import { fileURLToPath as fileURLToPath11 } from "url";
|
|
189374
189621
|
function gateSources(compiled, include, pulledIn = new Set) {
|
|
189375
189622
|
const sources = [];
|
|
189376
189623
|
const refused = {};
|
|
@@ -189435,10 +189682,10 @@ function modelPathOf(compiled, persistSource, packagePath) {
|
|
|
189435
189682
|
const url = at >= 0 ? persistSource.sourceID.slice(at + 1) : "";
|
|
189436
189683
|
if (packagePath && url.startsWith("file:")) {
|
|
189437
189684
|
try {
|
|
189438
|
-
const file = authorModelPath(
|
|
189439
|
-
const relative =
|
|
189440
|
-
if (relative && !relative.startsWith("..") && !
|
|
189441
|
-
return relative.split(
|
|
189685
|
+
const file = authorModelPath(fileURLToPath11(url));
|
|
189686
|
+
const relative = path28.relative(packagePath, file);
|
|
189687
|
+
if (relative && !relative.startsWith("..") && !path28.isAbsolute(relative)) {
|
|
189688
|
+
return relative.split(path28.sep).join("/");
|
|
189442
189689
|
}
|
|
189443
189690
|
} catch {}
|
|
189444
189691
|
}
|
|
@@ -189745,7 +189992,7 @@ function deriveSelfInstructions(compiled, sourceNames, priorEntries, incremental
|
|
|
189745
189992
|
const superseded = naming && supersededTable(prior, persistSource, sourceEntityId, destination, logicalName);
|
|
189746
189993
|
if (superseded)
|
|
189747
189994
|
renamed.push(superseded);
|
|
189748
|
-
if (inPlace !== undefined && !mustRebuild && !incremental?.forceRefresh
|
|
189995
|
+
if (inPlace !== undefined && !mustRebuild && !incremental?.forceRefresh) {
|
|
189749
189996
|
advanced[sourceEntityId] = inPlace;
|
|
189750
189997
|
}
|
|
189751
189998
|
if (awaitsVerifyingRebuild(prior ?? inPlace, materialize)) {
|
|
@@ -194045,7 +194292,11 @@ Fix the files and reload the package, then run again.`);
|
|
|
194045
194292
|
}
|
|
194046
194293
|
let recheck;
|
|
194047
194294
|
let confirmExists;
|
|
194295
|
+
let advanced;
|
|
194048
194296
|
const freshness = declaredFreshnessIndex(pkg.getBuildPlan());
|
|
194297
|
+
const hold = pkg.holdCarriedToContracts ? (kept) => pkg.holdCarriedToContracts(kept, environment, {
|
|
194298
|
+
signal: run.signal
|
|
194299
|
+
}) : undefined;
|
|
194049
194300
|
({
|
|
194050
194301
|
instructions,
|
|
194051
194302
|
carried,
|
|
@@ -194054,7 +194305,8 @@ Fix the files and reload the package, then run again.`);
|
|
|
194054
194305
|
recheck = {},
|
|
194055
194306
|
confirmExists = {},
|
|
194056
194307
|
renamed = [],
|
|
194057
|
-
rebuiltToVerify
|
|
194308
|
+
rebuiltToVerify,
|
|
194309
|
+
advanced
|
|
194058
194310
|
} = await deriveHoldingCarried((incompatible) => this.collaborators.deriveSelfInstructions(compiled, opts.sourceNames, priorEntries, incremental, {
|
|
194059
194311
|
environmentName,
|
|
194060
194312
|
packageName,
|
|
@@ -194070,9 +194322,10 @@ Fix the files and reload the package, then run again.`);
|
|
|
194070
194322
|
},
|
|
194071
194323
|
incompatible,
|
|
194072
194324
|
incrementalPriors
|
|
194073
|
-
}), () => pkg.incompatibleTables?.(priorEntries) ?? new Set,
|
|
194074
|
-
|
|
194075
|
-
|
|
194325
|
+
}), () => pkg.incompatibleTables?.(priorEntries) ?? new Set, hold, packageName));
|
|
194326
|
+
if (incremental) {
|
|
194327
|
+
incremental.heldAdvanced = new Map(Object.entries(advanced ?? {}));
|
|
194328
|
+
}
|
|
194076
194329
|
const siteContext = () => tableSiteContext({
|
|
194077
194330
|
compiled,
|
|
194078
194331
|
environment,
|
|
@@ -195622,19 +195875,19 @@ var init_package_load_metrics = __esm(() => {
|
|
|
195622
195875
|
});
|
|
195623
195876
|
|
|
195624
195877
|
// src/controller/manifest_location.ts
|
|
195625
|
-
import * as
|
|
195626
|
-
import { fileURLToPath as
|
|
195878
|
+
import * as path29 from "path";
|
|
195879
|
+
import { fileURLToPath as fileURLToPath12 } from "url";
|
|
195627
195880
|
function isManifestLocation(value) {
|
|
195628
195881
|
if (/^(gs|s3):\/\/[^/]+\/./.test(value))
|
|
195629
195882
|
return true;
|
|
195630
195883
|
if (value.startsWith("file://")) {
|
|
195631
195884
|
try {
|
|
195632
|
-
return
|
|
195885
|
+
return path29.isAbsolute(fileURLToPath12(value));
|
|
195633
195886
|
} catch {
|
|
195634
195887
|
return false;
|
|
195635
195888
|
}
|
|
195636
195889
|
}
|
|
195637
|
-
return !value.includes("://") &&
|
|
195890
|
+
return !value.includes("://") && path29.isAbsolute(value);
|
|
195638
195891
|
}
|
|
195639
195892
|
function versionManifestLocation(value) {
|
|
195640
195893
|
if (value === undefined)
|
|
@@ -197532,7 +197785,7 @@ var init_report_controller = __esm(() => {
|
|
|
197532
197785
|
|
|
197533
197786
|
// src/service/skills/build_skills_bundle.ts
|
|
197534
197787
|
import * as fs13 from "fs";
|
|
197535
|
-
import * as
|
|
197788
|
+
import * as path30 from "path";
|
|
197536
197789
|
function unquote3(s) {
|
|
197537
197790
|
return s.trim().replace(/^["']|["']$/g, "");
|
|
197538
197791
|
}
|
|
@@ -197550,7 +197803,7 @@ function parseSkill(md, dirName) {
|
|
|
197550
197803
|
return { name, description, body };
|
|
197551
197804
|
}
|
|
197552
197805
|
function referenceName(skillName, file) {
|
|
197553
|
-
return `${skillName}/${
|
|
197806
|
+
return `${skillName}/${path30.basename(file, ".md")}`;
|
|
197554
197807
|
}
|
|
197555
197808
|
function parseReference(md, skillName, file) {
|
|
197556
197809
|
const body = stripLicenseHeader(md.replace(/\r\n/g, `
|
|
@@ -197563,7 +197816,7 @@ function parseReference(md, skillName, file) {
|
|
|
197563
197816
|
};
|
|
197564
197817
|
}
|
|
197565
197818
|
function referencePointer(skillName, files, channel = "bundled") {
|
|
197566
|
-
const stems = files.map((f) =>
|
|
197819
|
+
const stems = files.map((f) => path30.basename(f, ".md"));
|
|
197567
197820
|
const how = channel === "bundled" ? `served as separate prompts, one per file, fetched only when you ask for them. Where the text above says to read \`${REFERENCE_DIR}/<name>.md\`, get the prompt named \`${skillName}/<name>\` instead.` : `served as separate guides, one per file, fetched only when you ask for them. Where the text above says to read \`${REFERENCE_DIR}/<name>.md\`, call get_skill with skill_name \`${skillName}/<name>\` and the same \`scopes\` you used for this skill instead.`;
|
|
197568
197821
|
return [
|
|
197569
197822
|
`## Reference files over MCP`,
|
|
@@ -197575,7 +197828,7 @@ function referencePointer(skillName, files, channel = "bundled") {
|
|
|
197575
197828
|
`);
|
|
197576
197829
|
}
|
|
197577
197830
|
function referenceFiles(skillDir) {
|
|
197578
|
-
const dir =
|
|
197831
|
+
const dir = path30.join(skillDir, REFERENCE_DIR);
|
|
197579
197832
|
if (!fs13.existsSync(dir))
|
|
197580
197833
|
return [];
|
|
197581
197834
|
return fs13.readdirSync(dir).filter((f) => f.endsWith(".md")).sort();
|
|
@@ -205642,12 +205895,17 @@ Call \`search_malloy_docs\` BEFORE first use of any of these. Don't guess the sy
|
|
|
205642
205895
|
|
|
205643
205896
|
| The user wants | Use |
|
|
205644
205897
|
|---|---|
|
|
205645
|
-
| A
|
|
205898
|
+
| A dashboard, a notebook, a report or a data story | a Malloy report (\`<slug>.malloy\` at the package root, \`layout=grid\` for a dashboard, \`layout=linear\` for a story; the \`malloy-reports\` skill) |
|
|
205899
|
+
| An app or a page of its own: several pages a reader moves between, a page for each thing they open, its own design, HTML and JavaScript with no toolchain | this skill (an HTML data app) |
|
|
205646
205900
|
| A React app with managed components | the Publisher React SDK (out of scope here) |
|
|
205647
|
-
| An analyst notebook or dashboard with charts | a Malloy report (\`<slug>.malloy\` at the package root, \`layout=linear\` or \`layout=grid\`; the \`malloy-reports\` skill) |
|
|
205648
205901
|
| Point-and-click exploration, no code | the Publisher Explorer |
|
|
205649
205902
|
|
|
205650
|
-
|
|
205903
|
+
**A dashboard and a data app are different things in Publisher.** A dashboard is a report: Malloy and layout tags,
|
|
205904
|
+
no code, filters drawn from givens. A data app is a page you write in \`public/\`. When the user asks for a
|
|
205905
|
+
dashboard, build a report. Build a data app when they ask for an app or a page, or when what they want is beyond a
|
|
205906
|
+
report: pages that link to a page per entity, a chart form the renderer does not have, a design of its own. When you
|
|
205907
|
+
build a data app for a request that said "dashboard", say in one line that it is a data app and why.
|
|
205908
|
+
\`docs/choosing-a-surface.md\` has the full comparison.
|
|
205651
205909
|
|
|
205652
205910
|
## Package anatomy
|
|
205653
205911
|
|
|
@@ -205669,11 +205927,11 @@ Only \`public/\` is reachable over the web, at \`/environments/<env>/packages/<p
|
|
|
205669
205927
|
|
|
205670
205928
|
The agent orchestrates these. Each query and chart step hands off to a focused skill.
|
|
205671
205929
|
|
|
205672
|
-
1. DESIGN IT FIRST. Read \`reference/design.md\`: who opens it, the
|
|
205930
|
+
1. DESIGN IT FIRST. Read \`reference/data-app-design.md\`, then \`reference/design.md\`: who opens it, the subject that leads, the archetype, the entities a reader opens one at a time, the pages and the paths between them. Skipping this is what produces an app that enumerates the model - a KPI row and a chart grid, whatever the domain - instead of one that answers a question. Decide, do not stop to ask: write the plan at the top of \`app.js\` and in your hand-over, where the user can correct it in one reply.
|
|
205673
205931
|
2. READ THE MODEL. Get the model's real source and view names, through your environment's context tool if it has one, or by opening the \`.malloy\` file directly. Never guess field or view names.
|
|
205674
|
-
3. SCAFFOLD the package (
|
|
205932
|
+
3. SCAFFOLD the package from this skill's \`assets/data-app/\`: the data app kit (blocks for the subject, ranked lists, shares, lines over time, tables, grids, watchlists and entity pages, drawn to one design) and a worked example app. \`reference/app-frame.md\` says what to copy and how to write the config and pages. Only when \`assets/\` is not on disk because the skill reached you only as text, use the minimal scaffold below, to the same design.
|
|
205675
205933
|
4. WRITE THE QUERIES. Read \`reference/runtime.md\`. Validate each before pasting it into the page, using whatever query tool your environment provides or a running Publisher (see \`reference/runtime.md\`). Malloy syntax questions go to \`skill:malloy-queries\`.
|
|
205676
|
-
5. CHOOSE CHARTS with \`skill:malloy-charts\` when rendering through \`<malloy-render>\`; otherwise it is your own chart library drawing the returned rows. Vendor any chart library into \`public/\` and load it locally, not from a CDN. Two reasons: embedded author JavaScript runs with the viewing user's data authority, and a blocked CDN (agent sandboxes and many corporate networks block them) is easy to miss, because the script never runs and the charts come up empty. The \`storefront\` example ships its chart library in \`public/vendor/\` and loads it from \`public/index.html\` as \`./vendor/chart.umd.js\`. Copy its vendoring, not its loading (it uses a plain \`<script>\`, which the next sentences rule out), and resolve the path against the page's own directory: a page in a subdirectory (\`public/reports/index.html\`) needs \`../vendor/chart.umd.js\`. A wrong relative path 404s and leaves the charts blank, which is the failure you are trying to avoid. Load it off the critical path (\`<link rel="preload">\`, then injected on the first chart), not as a plain \`<script>\` ahead of the app: it is usually most of the page's weight and would hold every query until it has parsed (\`reference/performance.md\`).
|
|
205934
|
+
5. CHOOSE CHARTS with \`skill:malloy-charts\` when rendering through \`<malloy-render>\`; otherwise it is your own chart library drawing the returned rows. Vendor any chart library into \`public/\` and load it locally, not from a CDN. Two reasons: embedded author JavaScript runs with the viewing user's data authority, and a blocked CDN (agent sandboxes and many corporate networks block them) is easy to miss, because the script never runs and the charts come up empty. The \`storefront\` example ships its chart library in \`public/vendor/\` and loads it from \`public/index.html\` as \`./vendor/chart.umd.js\`. Copy its vendoring, not its loading (it uses a plain \`<script>\`, which the next sentences rule out), and resolve the path against the page's own directory: a page in a subdirectory (\`public/reports/index.html\`) needs \`../vendor/chart.umd.js\`. A wrong relative path 404s and leaves the charts blank, which is the failure you are trying to avoid. Load it off the critical path (\`<link rel="preload">\`, then injected on the first chart), not as a plain \`<script>\` ahead of the app: it is usually most of the page's weight and would hold every query until it has parsed (\`reference/performance.md\`). With the kit from step 3, the chart library is d3 inside the kit, which it loads beside its first queries; the kit's blocks draw the common forms and \`charts.js\` the rest (\`reference/charts.md\`, maps in \`reference/maps.md\`).
|
|
205677
205935
|
6. EMBED (optional). Read \`reference/embedding.md\`.
|
|
205678
205936
|
7. PREVIEW with the local authoring loop (below).
|
|
205679
205937
|
8. VERIFY before you call it done (see "What 'done' means" below). This step is not optional.
|
|
@@ -205691,12 +205949,16 @@ A data app you can defend has all of these. Build to this list, not to the scaff
|
|
|
205691
205949
|
- **Every tile handles loading, empty, and error on its own.** One failing query must not blank the page. (\`reference/runtime.md\`.)
|
|
205692
205950
|
- **Defensible numbers.** Missing ≠ zero (omit the point, don't plot a fake 0); show the latest non-null value for "current"; guard division with \`nullif\`; convert units explicitly. (\`reference/runtime.md\`.)
|
|
205693
205951
|
- **Visible assumptions.** When you assume something (two sources joined by month, an in-month proxy that differs from a certified definition) or a metric is incomplete, say so *in the app*: a caption, a footnote, a placeholder card with the reason. The non-technical user cannot see your reasoning; bury a caveat and you have misled them. Don't silently drop a metric you couldn't model. Show a placeholder that names what's missing and why.
|
|
205952
|
+
- **Several pages, with paths between them.** Never one long page. A first page that answers the first question, a page per area the reader works in, and a page per entity, reached by clicking it anywhere it appears, at least two levels deep for the main entity (\`reference/data-app-design.md\`).
|
|
205953
|
+
- **Every chart does something when clicked, and every section explains itself.** A click opens an entity's page, filters the app, or zooms the period; "How it's made" says what the section shows, what it covers, what each number means and the query. The kit's blocks do both; a block of your own must too.
|
|
205694
205954
|
- **Built to the design brief, not to the model's shape.** The app matches the archetype, forms, and depth plan from step 1 (\`reference/design.md\`), carries a real token contract (surfaces, text ramp, semantic colors, a categorical chart palette) that the chart code reads at runtime rather than hardcoding, and puts visible weight on the two or three numbers that lead. A uniform grid of same-size cards, or a tile per view, means the brief was skipped.
|
|
205955
|
+
- **No sentence is typed.** A finding, a verdict, a count or a superlative on the page comes from the rows, and a claim the rows do not support is left out. No number goes in a static caption, sub-line or legend, where the next refresh would leave it wrong. Each finding is also a sentence, for readers who cannot see the chart. A change is coloured by what it means to the reader (a falling price is good for a buyer), not by its direction.
|
|
205956
|
+
- **Colours from the kit.** The kit's paper, ink, accent and good and bad colours are checked for contrast in both modes. Choose the accent from the subject; never put a hex in a chart. A colour an app adds (a party's colour) must hold 4.5:1 as text and 3:1 as a mark, in light and dark.
|
|
205695
205957
|
- **Vendored libraries.** Chart and helper libraries live in \`public/\`, loaded locally (step 5). When a package agent builds apps, every file it copies into one (a vendored library for \`public/vendor/\`, its own components, a template) lives in its skill's \`assets/\` and is copied from there, never pasted into the skill's Markdown (\`skill:malloy-define-agent\`).
|
|
205696
|
-
- **Light, and nothing waits on the chart library.** Pages that draw charts preload the library and load it on first use; a page that draws none never loads it. Trim
|
|
205697
|
-
- **Holds still while it loads.** Script-filled blocks reserve their final size in the HTML, skeletons are sized from what is coming, settled tile heights are remembered for the next visit, and a tile re-running for a new filter keeps its last answer dimmed instead of collapsing. Target: layout shift under 0.1 on a first visit and 0 on a repeat, embedded as well as standalone. (\`reference/performance.md\`.)
|
|
205698
|
-
- **Works embedded.** Inside an auto-sized frame there is no viewport: the frame never scrolls, nothing extends past the content, and anything that floats (a drawer, a tray) is placed over the slice of the page the reader can see, keeps its scroll to itself, and returns the reader exactly where they were. A drawer built the standalone way opens at the top of the document and drags the host page up to meet it. (\`reference/embedding.md\`, \`reference/overlays.md\`.)
|
|
205699
|
-
- **Lazy-load below the fold, once the page has more than about eight query-backed tiles.** ("Many" is not decidable; that is the threshold.) Tiles sitting below the fold is *why* the technique works, not a second trigger for it - almost every real data app scrolls, so reading it as one makes the rule "always" and contradicts the count. Under that threshold, firing every tile at once is cheaper than the machinery. Don't fire every tile's query on load. \`reference/lazy-load.md\` is the recipe: \`IntersectionObserver\` (rootMargin ~240px) + a small concurrency cap + reserve each tile's height so lazy tiles don't reflow. Includes the verification trap - on a short/tall-default viewport all tiles intersect at once and you get a false "everything deferred" pass, so test on a deliberately small viewport.
|
|
205958
|
+
- **Light, and nothing waits on the chart library.** Pages that draw charts preload the library and load it on first use; a page that draws none never loads it. The kit loads d3 once, beside its first queries, on every page. Trim a library of your own to the series types the app draws once it is big enough to matter (not the kit, which is copied whole so a fix can be copied over it), and verify a trimmed build by reading pixels, because a missing type draws an empty box without an error. One query text per resource, so any cache or prefetch actually hits. (\`reference/performance.md\`, which also has two opt-in recipes, answering from the last visit and starting a drawer's queries on intent, each with the conditions it needs.)
|
|
205959
|
+
- **Holds still while it loads.** Script-filled blocks reserve their final size in the HTML, skeletons are sized from what is coming, settled tile heights are remembered for the next visit (the kit reserves each block's drawn height instead), and a tile re-running for a new filter keeps its last answer dimmed instead of collapsing. Target: layout shift under 0.1 on a first visit and 0 on a repeat, embedded as well as standalone. (\`reference/performance.md\`.)
|
|
205960
|
+
- **Works embedded.** Inside an auto-sized frame there is no viewport: the frame never scrolls, nothing extends past the content, and anything that floats (a drawer, a tray) is placed over the slice of the page the reader can see, keeps its scroll to itself, and returns the reader exactly where they were. A drawer built the standalone way opens at the top of the document and drags the host page up to meet it. (\`reference/embedding.md\`, \`reference/overlays.md\`.) The kit avoids the problem: each page and entity is a page at its own address, with nothing that floats but its menus.
|
|
205961
|
+
- **Lazy-load below the fold, once the page has more than about eight query-backed tiles.** ("Many" is not decidable; that is the threshold.) Tiles sitting below the fold is *why* the technique works, not a second trigger for it - almost every real data app scrolls, so reading it as one makes the rule "always" and contradicts the count. Under that threshold, firing every tile at once is cheaper than the machinery. Don't fire every tile's query on load. The kit's blocks already do this. \`reference/lazy-load.md\` is the recipe: \`IntersectionObserver\` (rootMargin ~240px) + a small concurrency cap + reserve each tile's height so lazy tiles don't reflow. Includes the verification trap - on a short/tall-default viewport all tiles intersect at once and you get a false "everything deferred" pass, so test on a deliberately small viewport.
|
|
205700
205962
|
|
|
205701
205963
|
### Verify before you call it done
|
|
205702
205964
|
|
|
@@ -205809,7 +206071,12 @@ Publishing an app is publishing its package: get the package into publishable sh
|
|
|
205809
206071
|
|
|
205810
206072
|
This skill's \`reference/\` files are served as separate prompts, one per file, fetched only when you ask for them. Where the text above says to read \`reference/<name>.md\`, get the prompt named \`malloy-html-data-apps/<name>\` instead.
|
|
205811
206073
|
|
|
205812
|
-
Available: archetypes, depth-patterns, design, embedding, lazy-load, overlays, performance, runtime, token-contract, verification-harness, visual-craft.`
|
|
206074
|
+
Available: app-frame, archetypes, charts, data-app-design, depth-patterns, design, embedding, lazy-load, maps, overlays, performance, runtime, token-contract, verification-harness, visual-craft.`
|
|
206075
|
+
},
|
|
206076
|
+
{
|
|
206077
|
+
name: "malloy-html-data-apps/app-frame",
|
|
206078
|
+
description: "The data app kit. Reference detail for the malloy-html-data-apps skill.",
|
|
206079
|
+
body: "# The data app kit\n\n> Every data app starts from this skill's `assets/data-app/`: a kit of blocks (a subject with its figures, ranked\n> lists, shares, lines over time, tables, grids, watchlists, entity pages) and a worked example app. You write one\n> config and the pages; the kit draws them to one design (`reference/data-app-design.md`), keeps the state\n> in the address, makes every chart clickable and every section explain itself.\n\n## What is in `assets/data-app/`\n\n| File | What it is | Copy into `public/` |\n|---|---|---|\n| `kit/` | The kit: `kit.js` (import everything from it), its modules, `kit.css`, `themes.css` (nine themes, light and dark), `charts.js`/`charts.css` (more chart forms), `fonts.css` (Geist, inlined) and `fonts/` (each theme's display face, loaded only by its theme), `vendor/` (d3, topojson-client, the font licences) | Whole; never edit, copy again to take a fix |\n| `index.html` | The page: links the kit's styles, loads `/sdk/publisher.js` and `app.js` | Once, then it is the app's own |\n| `app.js` | A worked data app over an online store's orders: three pages and three entity pages | Once, then rewrite it for your data |\n\n`kit/themes.css` and the fonts are written by this skill's `scripts/themes.py`, which pins each font by its\naddress and checksum. A theme is added or changed there, in the skill, never in an app's copy.\n\nRun the copy from the package's own directory, the one holding `publisher.json`. `SKILL_DIR` is the directory you\nread this skill's `SKILL.md` from, wherever your host installed it:\n\n```sh\n: \"${SKILL_DIR:?set SKILL_DIR to the directory holding this skill's SKILL.md}\"\nT=\"$SKILL_DIR/assets/data-app\"\ntest -f publisher.json || { echo \"run this from the package directory, the one with publisher.json\"; exit 1; }\ntest -d \"$T/kit\" || { echo \"assets/data-app is not on disk: build from the minimal scaffold in SKILL.md\"; exit 1; }\nmkdir -p public && rm -rf public/kit && cp -R \"$T/kit\" public/kit\nfor f in index.html app.js; do [ -e \"public/$f\" ] || cp \"$T/$f\" public/; done\nchmod -R u+w public\n```\n\nAn app built earlier carries its kit's version as `KIT_VERSION`, exported from `public/kit/kit.js`, and on the\nrunning page (`<meta name=\"data-app-kit\">`). Copying a newer kit over it is meant to be safe within one major\nversion; across one, compare the app's config with the new kit's worked `app.js` before copying. An app with no\n`KIT_VERSION` was built on a kit before 1.0.0: before copying, drop each name `app.js` imports from the kit that\nthe new `kit.js` does not export, and write `credit: true` as `credit: { name }`, or the page will not load or will\nshow no credit.\n\nWhen the skill reached you only as text, `assets/` is not on disk: say so, and build from the minimal scaffold in\n`SKILL.md` to the same design.\n\n## The model the kit needs\n\nRead the model first and query it. The kit asks for:\n\n- **One source at record grain** (one row per order line, flight, claim, pull request), with its joins. Every query\n starts from it. Name it in `source`.\n- **A measure for every number on the page.** Use the model's; when you need one it lacks (net of returns, a rate),\n define it in `extend` (`measure: net_sales is total_sales { where: status != 'Cancelled' }`) and give it a `doc`\n in `metrics`. Ratios must be measures (`a / nullif(b, 0)`) so the kit can filter them to a period. Check a measure\n against the raw values before it leads a page (`reference/design.md`, the inventory).\n- **The date** every period filters on (`date: { field, label }`), a date or timestamp dimension. Data with no time\n dimension sets `date: null`: the period controls go, the subject stands alone, and `subject({ by })` ranks it.\n- **The entities**, each a dimension whose values a reader wants to open one at a time.\n\nA package with an `index.malloy` at its root answers queries only from the sources that file exports. Put the app's\nsource in its own file, export it from `index.malloy`, and point the config's `model` at `index.malloy`.\n\nQuery the model once for each measure and dimension you plan to use, and look at the rows.\n\n## Make it fast: store the source, roll up what it adds\n\nA data app over a warehouse table, or a file over about 100,000 rows, is materialized: its source stored as a table\nand the figures it adds up kept as rollups, so blocks answer from them. Read `skill:malloy-materialization` first:\nit says which spelling the server reads (`#(materialize)` and `#(rollup)`, or `#@ persist` and `#@ preaggregate`\nwhere the server's materialization switch is off and the newer tags would be ignored), and that a source with a row\ngate (`#(authorize)`, `#(access_filter)`) is built past its gate and must not be stored where every caller reads it.\nA small file in the package needs neither. What the kit adds to that skill:\n\n```malloy\nimport \"ecommerce.malloy\"\n\n#(doc) Order lines for the sales app, with the dimensions it filters by stored beside each line.\n#(materialize)\nsource: sales is order_items extend {\n dimension:\n order_date is created_at.day // the app's date: a day, so a rollup can filter on it\n category is inventory_items.product_category // what it filters and ranks by, as the source's own fields\n channel is users.traffic_source\n measure:\n #(rollup) grain=[\"order_date\", \"category\", \"channel\", \"status\"]\n net_sales is total_sales { where: status != 'Cancelled' and status != 'Returned' }\n #(rollup) grain=[\"order_date\", \"category\", \"channel\", \"status\"]\n items is count()\n #(rollup) grain=[\"order_date\", \"category\", \"channel\", \"status\"]\n returned is count() { where: status = 'Returned' }\n #(rollup) grain=[\"order_date\", \"category\", \"channel\", \"status\"]\n return_rate is returned / nullif(items, 0) // a ratio of rolled-up sums rolls up when it says so too\n aov is net_sales / nullif(order_count, 0) // a distinct count does not roll up: from the stored source\n}\n```\n\n- **The app's source lives in the model**, not in the config's `extend`, which a rollup cannot read, and the config\n names it (`source: 'sales'`).\n- **The dimensions the app filters, ranks and splits by are the source's own**, and the config names them\n (`field: 'category'`, not `inventory_items.product_category`); the date is a day dimension\n (`date: { field: 'order_date' }`).\n- **The rollup's grain is the date and the four to seven dimensions the app filters by most**; leave out one with\n thousands of values (a brand, a customer), which makes the rollup nearly as big as the source.\n- **The kit asks for a period and its comparison as two queries**, each with its dates in its own `where`, because a\n rollup answers those and never a measure that carries its own filter; a block of your own does the same\n (`S.kpiQueries`, `S.breakdownCompareQuery` with `S.withCompare`).\n- **Check it** on a ranked list's info mark: it names the summary that answered, its grain, and how fresh its rows\n are (their data-as-of when the table declares a freshness window, else when it was last built). \"Worked out from the raw data just now\" means the source was not stored or the query missed the rollup.\n\n## The config\n\n```js\nimport { dataApp, subject, rank, share, trend, table, heat, watch, entityHead, pageHead, aboutPage, blocks, block, S, F, C } from './kit/kit.js'\n\ndataApp({\n title: 'Sales performance', sub: 'Online store', // the masthead; keep `sub` to a few words\n model: 'sales.malloy', source: 'sales', // a materialized source (above)\n extend: '', // measures the model lacks; a rollup cannot read these\n date: { field: 'order_date', label: 'Order date' }, // a day dimension, or null\n recordNoun: 'order lines', // what a row is, for counts in menus\n theme: 'bloom', // from the subject: reference/data-app-design.md\n metrics: {\n net_sales: { label: 'Net revenue', format: 'usd', good: 'up', doc: 'What customers paid, less cancellations.' },\n return_rate: { label: 'Return rate', format: 'percent', good: 'down' },\n on_time_rate: { label: 'On-time rate', format: 'percent', good: 'up', thresholds: { watch: 0.8, breach: 0.7 } },\n flight_count: { label: 'Flights', format: 'number', good: null },\n },\n filters: [{ key: 'channel', field: 'channel', label: 'Channel', plural: 'channels' }],\n entities: {\n category: { field: 'category', label: 'Category', plural: 'categories' },\n customer: { field: 'user_id', label: 'Customer', plural: 'customers', nameField: 'users.full_name' },\n },\n defaults: { period: 'last_91', compare: 'previous' },\n sources: { // where the data comes from; on every block's back\n store: { name: 'Store orders', by: \"The shop's order system\", what: 'Every order line since the store opened.' },\n },\n glossary: [{ term: 'Net revenue', match: ['net'], plain: 'What customers paid, less cancellations and returns.' }],\n search: 'customer', // find an entity by name from the masthead\n pages: [\n { id: 'overview', title: 'Overview', render: overview },\n { id: 'products', title: 'Products', lists: 'category', render: products },\n { id: 'about', title: 'About the data', period: false, filters: false, render: () => aboutPage({ lede: '…' }) },\n { id: 'category', title: 'Category', entity: 'category', render: category },\n ],\n footer: 'Where the data comes from, in one line.',\n})\n```\n\n- **`metrics`**: every measure a block shows. `format`: `usd` (or any currency code in lower case), `number`,\n `percent` (a fraction), `decimal`, or `{ unit: 'min' }`; copy it from the model's tag (`# currency=usd` is `usd`,\n `# percent` is `percent`). `good`: `'up'`, `'down'` or `null`, which colours every change. `thresholds` give a\n monitor its statuses. `doc` is what \"How it's made\" says the number means, when the model has no `#(doc)` for it.\n- **`filters`**: the fields a reader can filter by, offered in the Filter menu with their values and counts: the\n 500 most common, or `limit` of them (`{ key, field, label, limit: 2000 }`) when a reader needs the rare ones.\n- **`entities`**: things with a page. An entity is also a filter, so its values are known. For an entity keyed by an\n id (a hospital's provider number), `nameField` names the dimension holding what to call it: the kit loads the\n names with the ids and uses them in every list, chip and title. `name: (id) => text` formats an id that needs no\n lookup.\n- **`pages`**: each `render(state)` returns its blocks. A page with `entity` is that entity's page, reached at\n `#/<page id>/<value>` and not listed in the navigation; every query on it is scoped to the entity. `lists: 'category'`\n marks the page that lists an entity, which its pages' breadcrumbs return to. `period: false` and `filters: false`\n hide those controls on a page they do not apply to, such as the About page.\n- **`defaults.filters`**: values a reader starts filtered to, when one slice is the whole story by default (regular\n gasoline in the US as a whole, `{ grade: ['Regular'], area: ['United States'] }`). A reader can clear them, and a shared\n link keeps what they chose. Copy each value from a query's rows: a value the data does not have is dropped, and\n `?check=1` fails on it.\n- **`sources`**: where the data comes from (`name`, `by`, `what`, `license`, `url`). Every block's info mark lists\n them, or the ones it names in its own `sources: ['eia']`; the footer credits them; `aboutPage()` lists them with\n their licences. An app on public data has `sources` and an About page.\n- **`search`**: an entity a reader looks up by name more often than they browse to it (a customer, a hospital, a\n ZIP code). The masthead gets a search box over its names; picking one opens its page.\n- **`articles`** (`{ title, outlet, date, url }`): the stories an app made from the news responds to. `news()` lists\n them as a section, and `aboutPage()` lists them too. Never quote their text.\n- **`credit`** (`{ name, logo }`): \"Made by\" and who made the app in the masthead, their logo when the app ships one\n as an image (`logo: './logo.svg'`), else their name.\n- **`glossary`**: the words a newcomer may not know (`term`, the words that mean it in `match`, `plain`). An info\n mark explains the ones its own text uses.\n- **Periods** (`defaults.period`): `last_7`, `last_28`, `last_91`, `last_364` (days counted back from the data's\n latest day, so weeks are whole and line up with the comparison), `mtd`, `qtd`, `ytd`, `last_month`,\n `last_quarter`, `last_year`, `all`. **Compare**: `previous`, `year`, `none`. Pick the default from how often the\n reader opens it: weekly readers `last_91`, daily ones `last_28`.\n\nTwo things come from the page that frames the app, not the config:\n\n- **Light and dark.** A host tells the page the reader's mode (`publisher:color-scheme`, through `/sdk/publisher.js`);\n the kit follows it and answers that it drew it. Publisher's own viewer sends it, and so may any host.\n- **Asking the host.** `setHost({ name, ask(prompt, context) })` registers a host that takes a reader's question;\n every block's info mark then offers \"Ask <name> about this\", with what the block covers and its queries in\n `context`. Register it only where the app knows it runs inside that host; the kit knows no host of its own.\n `prompt` is one sentence naming the app, the block and its finding. `context` is\n `{ scope: { package, model }, view: { type: 'block', id, title }, entities: [{ kind: 'source', name }],\n items: [{ label, value }], givens: { [filter key]: [values] } }`: `items` holds what the block covers and up to\n three of its queries, each value at most 900 characters. The whole stays under 7,800 characters as JSON: the\n queries go first, from the last, then each filter's values are cut to 20, then the filters, then the covers text.\n\n## The blocks\n\nShares of a total, in the kit's headlines, `share` and entity pages, are said only for metrics that add up (sums and\ncounts) with no part below zero; the kit checks, so an average or a rate never reads as \"180% of the total\", and\n`share` lists such a metric's parts without shares.\n\nEvery block takes `kicker` (what is measured; the kit writes one when you leave it out), `headline` (a function of\nits rows returning a sentence or `prose()` parts; the kit writes a standard one; `null` for none), and `span` (12,\nthe full width, or 6, half). Every block loads as it nears the screen, holds its height while loading, says when\nnothing matches, and has an info mark that turns it over to \"How it's made\".\n\n| Block | What it draws | A click |\n|---|---|---|\n| `subject({ metrics, by, layout })` | The first metric (or the one the reader picked) large, its change, a sentence, and its line over the period with the comparison; the rest in a ledger under it. `layout`: `split` (default), `band` (on a dark plane, for a monitor) or `board` (every figure large in a row, for a scorecard). With no date, `by` ranks it beside the figure | A ledger figure becomes the subject; a point zooms the period to it; a drag zooms to a range |\n| `rank({ field \\| entity, metric, top, extra, order })` | A ranked list: name, a thin bar over a pale one for the comparison, value, change. `extra` adds metric columns. `order` sorts by another expression (`'on_time_rate asc'`) | Opens the entity's page, or filters to the value |\n| `share({ field \\| entity, metric, top })` | One whole split into parts: a segmented bar, then each part's share, value and change | As rank |\n| `trend({ metric, by, top })` | The metric over time; with `by`, one line per top value, the leader in the accent | A point zooms; with `by`, a line opens or filters |\n| `table({ kicker, query, columns, open, sort })` | Dense rows, sortable, searchable, 25 a page, CSV of all. `columns`: `{ key, label, metric \\| format, bar, status }`. `open: { entity, key }` makes rows open that entity's page | Opens the row's entity |\n| `heat({ rows, cols, metric, volume, min, period })` | A metric across two dimensions (weekday by hour). `rows`/`cols`: `{ expr, label, name, count }`. `period: false` spans the whole data (year by week of year) | Filters to the row's value when it is a filter |\n| `watch({ field \\| entity, metric, volume, min, extra, limit })` | A monitor's list: each value's status against the metric's thresholds, the worst first, values under `min` of `volume` counted and left out | As rank |\n| `entityHead({ metric })` | An entity page's top: breadcrumb, name, and its rank among its peers by the metric, its share and its change | (Breadcrumb back) |\n| `pageHead(title, lede)` | A page's title and a sentence under it | |\n| `aboutPage({ title, lede, notes })` | Where the data comes from, each source with its licence, then `notes` (`{ title, text }`: what was reshaped, what is left out), then how fresh it is | |\n| `news()` | The config's `articles`, each linked with its outlet and date | Opens the article |\n| `blocks(...)` | Lays blocks out: span-12 ones take the row, span-6 ones pair | |\n\n`rank`, `share`, `trend`, `watch` and `heat` take `where`, a Malloy condition that narrows that block alone\n(`where: \"area_type = 'State'\"` ranks the states and leaves out the regions beside them).\n\n`S.run(view, state, opts)` writes a query over the source with the state's period and filters: `view` is a view the\nmodel names or a block in braces. `S.breakdownQuery`, `S.kpiQuery` and `S.seriesQuery` are what the blocks use.\n\n### Page plans, as examples of a shape\n\nThese are shapes that have worked, not templates. Choose sections from what the data shows and the reader needs,\ngive every data app at least one block of your own with the form native to its field, and do not copy a plan\nsection for section (`reference/data-app-design.md`, \"Make it about this subject\").\n\n- **Overview (performance)**: `subject` with 4 to 6 metrics; `rank` of the main entity and `share` of how it splits,\n side by side; `rank` of a second entity and of a place, side by side; `trend` of the subject by the main entity.\n- **Monitor**: `subject` with `layout: 'band'` and the status metrics (they carry thresholds); `watch` for each entity that can breach,\n side by side; `heat` of when it happens; `trend` of the status metric by the entity.\n- **An area's page** (`lists: '<entity>'`): `pageHead`; a full-width `rank` of every entity with `extra` columns;\n two `rank`s by the other metrics that matter, side by side; a `table` of the rows below.\n- **An entity's page**: `entityHead`; `subject` scoped to it; `rank`s of the entities inside it (a category's brands)\n and a `share` of how it splits; a `table` of its rows that opens the next level down.\n\n## A block of your own\n\nWhen a question needs a form the blocks do not have (a dumbbell, a slope, a bump chart, a map), use `block()` with\na chart from `charts.js` (`reference/charts.md` lists them, `reference/maps.md` the maps). It must say what it shows\nand it must do something when clicked:\n\n```js\nblock({\n kicker: 'Margin against volume by category', span: 12, reserve: 340, metrics: ['margin_pct', 'net_sales'],\n what: 'Each category placed by its sales and its margin, so the big low-margin ones stand out.',\n queries: (s) => [S.breakdownQuery('inventory_items.product_category', ['net_sales', 'margin_pct'], s, { top: 30 })],\n draw: ([rows], body) => C.scatterChange(body.appendChild(document.createElement('div')), rows.map((r) => ({ id: r.product_category, label: r.product_category, x: r.net_sales, y: r.margin_pct })), {\n onPick: (id) => store.open('category', id), // every chart does something when clicked\n }),\n headline: ([rows]) => [/* a sentence from the rows */],\n})\n```\n\n`block()` takes `kicker`, `what`, `metrics`, `queries(state)`, `draw(results, body, state)`, `headline(results,\nstate)`, `of(results)` (a few words after the kicker), `span`, `reserve` (its height while loading), `ignore`\n(filter keys its queries leave out), `compare: true` when it shows the comparison period (so \"How it's made\" says\nwhat it is compared with) and `period: false` when its queries ignore the period. Import `store` from the kit for `store.open(page, id)`,\n`store.toggleFilter(key, value)` and `store.setPeriod(...)`.\n\n## Before you call it done\n\nServe it and look at every page, at 1280 and 390 wide, light and dark (`?mode=dark`):\n\n- Open each page from its address alone, and an entity page for a real value and for a value that does not exist.\n- Click through every path in the plan: a row to its page, that page's row to the next, the breadcrumb back. Pick a\n filter, change the period, make another figure the subject: every block redraws and the address keeps it.\n- Open \"How it's made\" on a block of each kind: the definitions are filled and the query runs.\n- `?check=1` puts a banner on the page saying whether any block failed or shows `undefined`, `NaN` or `null`.\n- `body[data-ready=\"true\"]` is set once every block on the page has drawn. Blocks below the fold load only as they\n near the screen, so on a short window it waits for a scroll: scroll to the bottom first, then wait on it. In a host\n frame as tall as its content, the host page is what scrolls.\n- No console errors, no horizontal scroll at 390, layout shift under 0.1 (`reference/performance.md`). Measure layout\n shift on a cold load left still, before any scroll: a scroll while blocks load counts their arrival as shift.\n Then scroll to the bottom to load the rest and check those blocks drew."
|
|
205813
206080
|
},
|
|
205814
206081
|
{
|
|
205815
206082
|
name: "malloy-html-data-apps/archetypes",
|
|
@@ -205855,6 +206122,8 @@ Anything below that says "drawer", "drill", or "cross-filter" has its mechanics
|
|
|
205855
206122
|
[ comparison tray: collected entities, side by side ]
|
|
205856
206123
|
\`\`\`
|
|
205857
206124
|
|
|
206125
|
+
In a frame as tall as its content, the drawer and tray float over a page that never scrolls (\`reference/overlays.md\`). The data app kit (\`reference/app-frame.md\`) builds the same Explorer without them: the entity is a page at its own address, reached from every list that names it.
|
|
206126
|
+
|
|
205858
206127
|
**Leads with:** the ranked population, not a total. A total is the one number an explorer's user already knows.
|
|
205859
206128
|
|
|
205860
206129
|
**Depth:** deep, and this is where it is the point. Drill-down, entity detail, comparison, cross-filtering, all backed by parameterised detail sources so every panel inherits one definition.
|
|
@@ -205909,6 +206178,199 @@ Anything below that says "drawer", "drill", or "cross-filter" has its mechanics
|
|
|
205909
206178
|
| Anything vs briefing | Will this be read once, or repeatedly? | Once -> briefing. Repeatedly -> the other one. |
|
|
205910
206179
|
|
|
205911
206180
|
When two genuinely apply to different audiences, that is two apps, not one app with a mode switch. The compromise app serves neither, and it is the most common way a good brief still produces a generic result.`
|
|
206181
|
+
},
|
|
206182
|
+
{
|
|
206183
|
+
name: "malloy-html-data-apps/charts",
|
|
206184
|
+
description: "The d3 Chart Module. Reference detail for the malloy-html-data-apps skill.",
|
|
206185
|
+
body: "# The d3 Chart Module\n\nEvery chart is drawn with d3 into SVG by one chart module, which you copy whole into the app and never read: bars,\nlines, areas, scatters, heatmaps, maps, the ranked table, and the forms a specialist reaches for (slope, bump,\nbeeswarm, flow, treemap, waterfall and the rest). Each sizes itself to its box, redraws when the box changes width,\ntakes a click (`onPick`; not `sparkline`, `waterfall`, `multiples` or `connectedScatter`, and `rankTable` opens a row\nwith `onOpen`), shows a tooltip on hover and on keyboard focus, and writes under itself what it could not\ndraw. It ships inside the data app kit, `assets/data-app/kit/charts.js` (`reference/app-frame.md`), and the kit's own\nblocks cover the common forms (the subject's line, ranked lists, shares, lines by a field, tables, grids, watchlists).\nReach for this module for the rest, inside a `block()` of your own.\n\nIt is the exception to `SKILL.md`'s \"trim the chart library\" rule: it is part of the kit, copied whole and never\nedited, so a fixed version can be copied over it. The kit loads d3 beside its first queries (`reference/performance.md`).\n\n## Using it from the kit\n\nThe kit's copy step copies it with d3 and the styles it reads; `index.html` already links `kit/charts.css`, and\n`kit.css` maps the module's colour names onto the kit's palette. Import it from the kit, `import { C } from\n'./kit/kit.js'`. To learn a function's arguments, read only its comment and signature, never the code:\n`awk -v f=bump '/^\\/\\*\\*/{b=\"\";c=1} c{b=b $0 \"\\n\"; if (/\\*\\//) c=0; next} $0 ~ \"^export (function|const) \" f \"[ (=]\" {i=index($0, \"){\"); printf \"%s%s\\n\", b, substr($0, 1, i && i < 200 ? i + 1 : 200); exit} {b=\"\"}' public/kit/charts.js`.\nIts helpers are `C.fmt`, `C.pct`, `C.token`, `C.loadTopo` (boundary files) and `C.tercile`; `C.ABBR` maps state\nnames to postal codes. Its `rankTable` is superseded by the kit's `rank()` block; use that.\n\n## Choose the form by the question\n\n| The question | The form | In the module |\n|---|---|---|\n| How has it changed over time? | A line, the selected period shaded; drag to choose a period | `C.lines` with `band` and `onBrush` |\n| How do a few groups compare over time? | A line per group, named at its end | `C.lines` |\n| How did this year's season run against earlier ones? | Periods overlaid on one axis (Jan to Dec, one line per era) | `C.lines`, labels are months, a series per era |\n| What is it made of, over time? | Stacked areas, each named inside its band | `C.area` |\n| Which share of each group is which part? | Stacked bars to 100% | `C.stackedShare` |\n| Who has the most? | A ranked list with bars and the change | The kit's `rank()` block |\n| Which items, by one measure? | Bars with their values at the end, no value axis | `C.bars` with `direct` |\n| How big was each period, and which stand out? | Columns, a reference line where a number means something | `C.bars` with `refs` |\n| Which places lead, and by how much? | Not a map: sorted bars, a dumbbell, a slope, or a ranked list | `C.bars`, `C.dumbbell`, `C.slope`, the kit's `rank()` |\n| Where, when the pattern in space is the finding (neighbours, a gradient, a cluster)? | A choropleth of the places | `C.choropleth` (`reference/maps.md`) |\n| Where, for points with coordinates and no boundaries? | Hexagons binned from the points, the unfiltered points grey underneath | `C.hexMap` |\n| Where, when every state should read equally? | A tile-grid map of US states, each tile with its trend | `C.tileMap` |\n| Where, as an amount rather than a rate? | Circles on the map, area to the amount | `C.circleMap` |\n| Where, by two measures at once? | A bivariate map, three classes each | `C.bivariateMap` |\n| What moved, then against now? | A scatter of then (x) against now (y), with the line where nothing changed | `C.scatterChange` |\n| How does it differ with and without something? | A dot for each, joined, the difference written beside it | `C.dumbbell` |\n| When in the week, or the year, does it happen? | A heatmap, or a clock of rings (days) by hours | `C.heatmap`, `C.clock` |\n| What happens next: from one grouping to the next? | A flow, bands as wide as their count | `C.flow` |\n| How did each item move between two dates? | A slope: a line per item from then to now | `C.slope` |\n| Who led, year by year? | A bump chart of ranks | `C.bump` |\n| How are many items spread along one measure? | A beeswarm, a dot per item | `C.beeswarm` |\n| Which parts drove each period's change? | Contribution columns: gains above zero, losses below, the net marked | `C.contrib` |\n| How did a total get from one value to another? | A waterfall of the contributors | `C.waterfall` |\n| Who gained and who lost? | Diverging bars either side of zero | `C.divergingBars` |\n| What is one whole made of? | A waffle of a hundred squares (few parts) or a treemap (many, or many in groups) | `C.waffle`, `C.treemap` |\n| What is each group made of, and how big is each group? | A marimekko: widths are the groups, bands the parts | `C.marimekko` |\n| How did a few items change, in the same unit? | Arrows from the old value to the new | `C.arrows` |\n| How do many series compare in shape? | Small multiples, each on its own scale | `C.multiples` |\n| How did two measures move together over time? | A connected scatter, one point per period | `C.connectedScatter` |\n\nPick the form a specialist in the field would draw, not the first one the columns suggest and not the one the\ntemplate already holds. This table is where you start, not the whole choice: when a finding deserves a form it lacks,\ndraw it in a `block()` of your own (`reference/app-frame.md`, \"A block of your own\"). Never the same form for two questions next to each other.\n\n## The ranked list\n\nMost apps have one list readers come for: the categories, the carriers, the hospitals, ranked. Draw it with the\nkit's `rank()` block: each row carries its value as a thin bar over a pale one for the comparison, its number and\nits change, and opens the entity's page (or filters) on a click. Use `extra` for a second metric column.\n\n## Everything clicks\n\n- **A click does what the kit's blocks do.** A mark that stands for an entity opens its page (`store.open`); any\n other filters the app to it (`store.toggleFilter`); a period zooms to it. Pass `onPick`, and `selected` where the chart takes it, to\n every chart that stands for something in the scope: a bar, a period, a place, a part, a district. The selected\n mark keeps its colour; the rest fade. Time charts take `onBrush(from, to)` to set the scope's period, and show it,\n and a picked period, with `band`.\n- **The tooltip is built in**: the value, its share, the total it is part of, and what a click does. Hover and\n keyboard focus both show it.\n- **Marks move.** A chart drawn again into the same box moves each mark from where it was, and a first chart rises in;\n `C.MOTION` is false when the reader asks for less motion or the address has `?motion=0`, and `C.DUR` (380 ms) is\n the time a mark takes to move between two answers. That is longer than a UI transition (`reference/visual-craft.md`)\n on purpose: the reader is following a mark, not waiting for a control. `C.countTo`\n (node, from, to) counts a number in text to its new value. Hovering a mark lights the marks and ranked rows that stand for\n the same thing in every chart, by the key `onPick` gets (a map's `linkOf` names its shapes the same way).\n- **Marks are named buttons** a keyboard reaches, and focus comes back after a pick. Large sets (counties, hexagons,\n clock cells, a beeswarm of more than 60 dots) are clicked rather than tabbed to: put a ranked table beside them.\n\n## Using the module\n\n- Draw into a box you append to the block's body, `body.appendChild(document.createElement('div'))`: no fixed height, the chart fills it at its own height. Give the block a `reserve` close to that height.\n- Colours are token names (`'--accent'`, `'--c2'`), so a part keeps one colour on every chart. The bivariate map's\n nine colours mix `--accent` and `--c2`, so the app's accent reaches them.\n- Changes are neutral unless `good` ('rise' or 'fall', or 'up' or 'down') says which way is good news.\n- The maps need topojson-client and a boundary file from `reference/maps.md`; `C.hexMap` and `C.tileMap` need neither.\n- With nothing to draw, a chart says so in the card; what it cannot draw (a row with no value, zero on a log scale, a\n place with no shape, steps that miss their total) it says under the drawing, never drops in silence.\n- A chart prints only numbers it is given. It places marks by arithmetic (a band's height, where a waterfall step\n starts), but a share, a net or a total it prints comes from the model: pass contrib its `nets` and the marimekko\n each part's `share`, or they draw the marks and print no number.\n\nEach form needs its numbers ready from the model, in the shape the last column gives.\n\n| Form | Not for | The model gives |\n|---|---|---|\n| `hexMap` | Places with boundaries (use a choropleth), or a rate: a hexagon sums what falls in it | One row per location, `group_by: lat, lon`, with a count and a `limit` above the number of locations; the same with no filters as `base` |\n| `clock` | Fewer than three rings, or a cycle that is not a clock (use a heatmap) | One row per ring and slot, such as day of week and hour of day, with a count |\n| `flow` | More than about twelve names in a stage, or stages that do not follow from each other | One row per combination of the stages' fields, with a count |\n| `tileMap` | Places other than US states, or a map where area is the point | One value per state, and a nested trend if the tiles carry one |\n| `circleMap` | Rates and shares: a circle's area reads as an amount | One amount per place, matched to the boundary file's names |\n| `bivariateMap` | A single measure, or two that move together | Two measures per place; the classes are thirds of the places shown |\n| `slope` | More than about twelve items, or more than two dates | A first-date and a last-date measure per item (filtered measures such as `m_first`, `m_latest`) and the change |\n| `bump` | Fewer than three periods, items that leave the top for long, or ranks that hardly change: flat lines say only that, and a ranked table says it better | `calculate: m_rank is rank() { partition_by: period; order_by: m desc }`, one row per item and period; a tie draws on one spot |\n| `beeswarm` | A count that takes only a few values, which stacks into towers; under 30 or over about 400 items | One continuous value per item; `log: true` for values spread over decades |\n| `contrib` | Fewer than three periods, or parts that do not add up to the total | `calculate: change is m - lag(m) { partition_by: part }`, one row per part and period, and the net per period, `change` with no part |\n| `waterfall` | A total that is not the sum of its contributors | Each contributor's change, the two totals, and the change for \"All others\" so the steps add up |\n| `divergingBars` | Values that are all on one side of zero, or more than about 30 items (it draws the first 40) | A signed change per item, computed in the model |\n| `waffle` | More than six parts, or parts of different wholes | Each part's value and its share, `m / nullif(all(m), 0)`; a top few that are not the whole leave the rest as \"Everything else\" |\n| `marimekko` | More than about ten groups, or parts that overlap | One row per group and part, with the part's share of its group, `m / nullif(all(m, group), 0)`; the group's total; and what of the total no part holds (withheld) |\n| `arrows` | Items in different units, or more than about eight | A first and a last value per item, and the change |\n| `multiples` | Series meant to be compared by height: each panel has its own scale | One row per series and period |\n| `connectedScatter` | Fewer than about ten periods, or two measures that bounce from year to year (a crop and its price): the path tangles, and two lines read better | Two measures per period, in time order |\n| `treemap` | Comparing items that are close in size | One row per item with its value; its `group`, `share` (`m / nullif(all(m), 0)`) or `change` when the tiles show them |\n\n## Rules\n\n- **Label directly.** A line is named at its end, an area inside its band, a bar by its value at its end, a\n notable point beside it. A key is only for marks that cannot carry a name: a map's or heatmap's ramp, and parts too\n thin to name inside them.\n- **Show the scope on the chart.** When the app's scope selects a period, every time chart shades it (`band`).\n Where a number has a meaning (a target, the national rate, last year's level), draw it as a labelled reference\n line (`refs`).\n- **Colours come from the kit's tokens** (`reference/data-app-design.md`, \"Colour\"), each with one meaning across the app.\n Neutral bars use `--c-bar`; the accent is for the lead number and the selection.\n- **Every chart's finding is also a sentence**: the block's headline, written from its rows, for readers who cannot\n see the chart.\n- **Every block says what it shows**, in its `what`, so its info mark reads as a definition, then the query and its\n rows.\n- **Verification reads SVG, not pixels.** The module draws SVG, so a check counts marks (`svg path`, `svg rect`,\n `svg circle`) and reads their labels, where a canvas library's check reads pixels\n (`reference/verification-harness.md`)."
|
|
206186
|
+
},
|
|
206187
|
+
{
|
|
206188
|
+
name: "malloy-html-data-apps/data-app-design",
|
|
206189
|
+
description: "How a data app built on the kit looks and works, and why. Reference detail for the malloy-html-data-apps skill.",
|
|
206190
|
+
body: `# How a data app built on the kit looks and works, and why
|
|
206191
|
+
|
|
206192
|
+
> Read this before building any data app. The kit in \`assets/data-app/\` draws every element described here, so
|
|
206193
|
+
> most of it is already true of what you build. Your job is what the kit cannot do: decide who it is for and what
|
|
206194
|
+
> leads, plan the pages and the paths between them, write the findings, and leave things out.
|
|
206195
|
+
>
|
|
206196
|
+
> A data app is not a dashboard. In Publisher a dashboard is a report: a \`.malloy\` file with an \`## artifact\` tag
|
|
206197
|
+
> and \`layout=grid\`, built with the \`malloy-reports\` skill (\`docs/choosing-a-surface.md\`). \`SKILL.md\`, "When this is
|
|
206198
|
+
> the right tool", says which to build.
|
|
206199
|
+
|
|
206200
|
+
## The idea
|
|
206201
|
+
|
|
206202
|
+
A data app built on the kit reads like the pages a well-run business prints for itself, not like a control panel. It
|
|
206203
|
+
is printed on warm paper in ink. Each page has one subject, stated as a number and a sentence at the
|
|
206204
|
+
top; every other element is evidence for it or a way deeper into it. Sections are separated by space and hairline
|
|
206205
|
+
rules, never boxed. Headings say what the data shows, not what the chart is. Colour is spent on meaning.
|
|
206206
|
+
|
|
206207
|
+
A reader who opens it knows in two seconds what it is about and whether things are going well. From there every
|
|
206208
|
+
chart takes them somewhere: a click filters the data app, opens the page of the thing they clicked, or zooms the
|
|
206209
|
+
period. And on every section they can ask how it is made, and get the period, the filters, what each number means in
|
|
206210
|
+
the model's own words, how fresh it is, and the query.
|
|
206211
|
+
|
|
206212
|
+
## Decide, then build
|
|
206213
|
+
|
|
206214
|
+
Do not stop to ask what the data app should show. Read the model (its sources, measures, dimensions and docs) and
|
|
206215
|
+
the request, and decide:
|
|
206216
|
+
|
|
206217
|
+
- **Who opens it and how often.** An owner checking weekly, an operator watching daily, an analyst digging.
|
|
206218
|
+
- **The subject.** The number that reader asks for first: revenue for a sales team, the on-time rate for operations,
|
|
206219
|
+
active users or conversion for a product. It leads the first page.
|
|
206220
|
+
- **The archetype** (\`reference/archetypes.md\`): an overview of performance, a monitor of what is breaking, an
|
|
206221
|
+
explorer of a population. It sets what the first page leads with.
|
|
206222
|
+
- **The entities.** The things a reader wants to look at one at a time: a category, a brand, a customer, a carrier, an
|
|
206223
|
+
airport, a hospital, a repository. Each gets its own page, reached by clicking it anywhere it appears.
|
|
206224
|
+
- **The pages and the paths.** Usually three to five pages in the navigation and a page per entity. Write the plan
|
|
206225
|
+
down before building (below).
|
|
206226
|
+
|
|
206227
|
+
Write what you decided at the top of \`app.js\` and in your hand-over, in a few lines, so the reader can correct it in
|
|
206228
|
+
one reply. An app built on a stated guess is useful; an app waiting for an answer is not.
|
|
206229
|
+
|
|
206230
|
+
## Make it about this subject
|
|
206231
|
+
|
|
206232
|
+
Two data apps built with this kit share a grammar, not a page. What makes one about bike share and the other about
|
|
206233
|
+
hospital bills:
|
|
206234
|
+
|
|
206235
|
+
- **One form native to the field**, drawn as a block of your own (\`reference/app-frame.md\`): net arrivals per
|
|
206236
|
+
station for a bike share, a price index against the national price for hospital charges, a cohort grid for
|
|
206237
|
+
subscriptions, an hour-by-weekday grid for operations. Every data app has at least one.
|
|
206238
|
+
- **Its own sections**, chosen from what the data shows, in the order the reader needs them. The page plans in the
|
|
206239
|
+
kit reference are examples of a shape; never copy one section for section.
|
|
206240
|
+
- **Its own words.** Kickers and headlines in the reader's vocabulary ("trips", "stays", "pull requests"), headlines
|
|
206241
|
+
written for what matters in the domain rather than the kit's standard ones where you can.
|
|
206242
|
+
|
|
206243
|
+
## Pages, and the paths between them
|
|
206244
|
+
|
|
206245
|
+
A data app is never one long page. Plan it as pages a reader moves between:
|
|
206246
|
+
|
|
206247
|
+
- **The first page** answers the reader's first question. It leads with the subject and the supporting figures,
|
|
206248
|
+
then four to six sections of evidence: where the number comes from, what is moving it, what needs attention.
|
|
206249
|
+
- **One page per area the reader works in**, named for it: Products, Customers, Carriers, Airports. Each opens with a
|
|
206250
|
+
title and a sentence, then a full list of that area's entities (every category, not the top ten), then the
|
|
206251
|
+
sections that compare them, then the rows.
|
|
206252
|
+
- **One page per entity.** It says what the entity is and where it stands among its peers ("3rd of 26 categories by
|
|
206253
|
+
net revenue, 16% of the total, up 19%"), then the same subject and figures for the entity alone, then the entity's
|
|
206254
|
+
own parts (a category's brands, a carrier's airports), then its rows. Every query on the page is scoped to it
|
|
206255
|
+
automatically.
|
|
206256
|
+
- **Paths go down and across.** Overview → a category → one of its brands → one of that brand's customers. A ranked
|
|
206257
|
+
list on any page opens its entities' pages; an entity's page lists the entities inside it. Plan at least two levels
|
|
206258
|
+
of depth for the main entity.
|
|
206259
|
+
|
|
206260
|
+
Write the plan as a short list before building: each page, what leads it, its sections in order, and for each list
|
|
206261
|
+
which page a click opens. If a page has nothing a reader would click into, it is a dead end: give it a path or cut it.
|
|
206262
|
+
|
|
206263
|
+
## Every chart does something when clicked
|
|
206264
|
+
|
|
206265
|
+
This is not optional. A chart that only shows is half a chart.
|
|
206266
|
+
|
|
206267
|
+
- A row of a ranked list, a part of a share bar, a line of a multi-line chart: opens that value's page when it is an
|
|
206268
|
+
entity, filters the whole data app to it otherwise.
|
|
206269
|
+
- A point on a line over time: zooms the period to that week or month. Dragging across several zooms to those.
|
|
206270
|
+
- A cell of a grid: filters to its row's value.
|
|
206271
|
+
- A figure in the ledger: makes it the subject.
|
|
206272
|
+
- A table row: opens its entity's page when it names one.
|
|
206273
|
+
|
|
206274
|
+
The kit does all of these. A custom chart you draw yourself (\`reference/app-frame.md\`, "A block of your own") must
|
|
206275
|
+
do one of them too, and say so in its tooltip.
|
|
206276
|
+
|
|
206277
|
+
## Every section explains itself
|
|
206278
|
+
|
|
206279
|
+
Each block has an info mark (ⓘ) in its corner: an icon, never a text button such as "How it's made" or "Show the
|
|
206280
|
+
working", and a block of your own gets the same one from \`block()\`. It turns the section over to "How it's made", which says: what it
|
|
206281
|
+
shows (one sentence you write for a reader who does not know the data); what it covers (the period, the comparison
|
|
206282
|
+
and the filters, in words, written by the kit); what each number means (from the model's \`#(doc)\`, or the metric's
|
|
206283
|
+
\`doc\` when the app defines it) and the words a newcomer may not know (the config's \`glossary\`); where the data comes
|
|
206284
|
+
from (the config's \`sources\`); where the answer came from (a summary built ahead of time, with the grain it is kept at and
|
|
206285
|
+
how fresh its rows are, or when it was last built; a stored copy; or the raw data just now) and how fast, from Publisher's own answer; and the
|
|
206286
|
+
query and its rows with a CSV. Where the app has registered a host that takes questions (\`setHost\`), it also offers
|
|
206287
|
+
"Ask <host> about this", with the section's queries attached. Write \`what\` for every block you add, and a \`doc\` for every
|
|
206288
|
+
metric the app defines itself.
|
|
206289
|
+
|
|
206290
|
+
## What makes a data app look generated, so you can avoid it
|
|
206291
|
+
|
|
206292
|
+
- A row of equal boxes, each with one number. It says the page has no subject.
|
|
206293
|
+
- Every chart in its own bordered card with a shadow, an info icon and a title like "Revenue by category".
|
|
206294
|
+
- Pills: green and red badges on every change, status chips in every row.
|
|
206295
|
+
- The system font, the default blue, rainbow categories, library chart defaults.
|
|
206296
|
+
- A row of dropdowns reading "Category: All", "Brand: All".
|
|
206297
|
+
- One long page with everything on it, and charts that do nothing when clicked.
|
|
206298
|
+
|
|
206299
|
+
None of these are in the kit. Do not add them back.
|
|
206300
|
+
|
|
206301
|
+
## The page, top to bottom
|
|
206302
|
+
|
|
206303
|
+
1. **The masthead.** The data app's name, a few words on what it covers, its pages, and how fresh the data is.
|
|
206304
|
+
2. **The controls**, read as a sentence: *Last 13 weeks compared with the 13 weeks before · by week*. Filters are
|
|
206305
|
+
added with Filter (a field, then its values) and shown as tokens. Copy link copies this exact view.
|
|
206306
|
+
3. **The subject.** One large number, its change in words and colour, the period it is compared with, a sentence
|
|
206307
|
+
written from the data, and beside it the same number over the period with the comparison in grey.
|
|
206308
|
+
4. **The ledger.** Three to five other figures in one ruled row, smaller on purpose. Clicking one makes it the
|
|
206309
|
+
subject.
|
|
206310
|
+
5. **Sections.** A kicker (what is measured, small), a headline (what it shows, a sentence from the data), the
|
|
206311
|
+
evidence. Two may sit side by side.
|
|
206312
|
+
6. **Rows.** Tables at the bottom or on their own page: dense, ruled, sortable, searchable.
|
|
206313
|
+
|
|
206314
|
+
## Each element
|
|
206315
|
+
|
|
206316
|
+
**A look of its own.** Every data app follows the same rules and none should look like the last one. Its theme,
|
|
206317
|
+
chosen from the subject, sets the paper, the inks, the accent, the chart colours, the masthead, the weight of the
|
|
206318
|
+
rules between sections and the face of the large numbers:
|
|
206319
|
+
|
|
206320
|
+
| Theme | For | Its look |
|
|
206321
|
+
|---|---|---|
|
|
206322
|
+
| \`ledger\` | Finance, revenue, pricing, costs, investment | Cream paper, navy, a serif, a heavy ink rule under the masthead |
|
|
206323
|
+
| \`clinic\` | Health, medicine, care, safety, science | Cool mist, deep teal, a teal bar over the masthead |
|
|
206324
|
+
| \`transit\` | Operations, transport, logistics, energy | Grey, signal blue, a condensed face, a dark masthead |
|
|
206325
|
+
| \`terminal\` | Software, engineering, AI, infrastructure | White, violet, mono figures, a dark masthead |
|
|
206326
|
+
| \`harvest\` | Food, agriculture, environment, climate | Sand, pine green, a soft serif |
|
|
206327
|
+
| \`civic\` | Government, public data, elections, education, cities | Cool white, navy, a serif, a navy masthead |
|
|
206328
|
+
| \`bloom\` | Consumers, retail, media, travel, people | Blush, plum, a soft serif, the largest figures |
|
|
206329
|
+
| \`paper\` | Any business subject, the default | Warm paper, steel blue |
|
|
206330
|
+
| \`stone\` | Internal tools, anything that should recede | Grey, graphite |
|
|
206331
|
+
|
|
206332
|
+
Pick the theme whose row names the subject; when two fit, the one nearer to who reads it (a hospital's finance team
|
|
206333
|
+
reads \`ledger\`, its clinicians \`clinic\`). Every theme is checked for contrast in light and dark, so never override
|
|
206334
|
+
its colours; a colour an app adds for meaning (a party, a brand) must hold 4.5:1 as text and 3:1 as a mark.
|
|
206335
|
+
|
|
206336
|
+
**The lead's layout**, chosen by archetype (\`subject({ layout })\`):
|
|
206337
|
+
|
|
206338
|
+
- \`split\`, the figure beside its line and the rest in a ledger under them: an overview of performance.
|
|
206339
|
+
- \`band\`, the same on a dark plane: a monitor, whose lead is a status read at a glance.
|
|
206340
|
+
- \`board\`, three or four figures equally large in a row, the chosen one's line across the page under them: a
|
|
206341
|
+
scorecard whose figures matter equally, or a page whose subject is a mix.
|
|
206342
|
+
|
|
206343
|
+
**Type.** Geist for the interface, Geist Mono for axes and queries; the theme's face for the large numbers and, in
|
|
206344
|
+
the serif themes, the headlines. Weight 400 to read, 500 for labels and names. Large numbers use proportional
|
|
206345
|
+
figures; columns use tabular ones. Currency symbols and units sit a step smaller than their number.
|
|
206346
|
+
|
|
206347
|
+
**Colour.** Paper, ink and four ink tones carry nearly everything. The theme's accent marks the subject, the
|
|
206348
|
+
selection and focus. Good and bad appear only on changes and status. The comparison is always grey.
|
|
206349
|
+
|
|
206350
|
+
**Changes.** Text, not badges: "+16.2%", "−0.4 pts", "no change", coloured by what the change means for the metric
|
|
206351
|
+
(\`good: 'down'\` makes a fall green). Percentages change in points.
|
|
206352
|
+
|
|
206353
|
+
**Headlines.** Written by code from the rows. The kit writes a standard one for each block ("Jeans leads; Fashion
|
|
206354
|
+
Hoodies grew fastest, +29.1%"). Write your own when you know what matters in the domain: a monitor's "Two carriers
|
|
206355
|
+
are past the line", a cost explorer's "Three hospitals charge more than twice the median". Never type a number.
|
|
206356
|
+
|
|
206357
|
+
**Status (monitors).** A coloured dot and a word. Counts lead: "2 breaching, 8 to watch, 3 on track". Thresholds
|
|
206358
|
+
belong to the metric, so every list and figure of it uses the same lines.
|
|
206359
|
+
|
|
206360
|
+
**Motion.** Only for a change the reader caused. The old chart stays dimmed until the new one is ready.
|
|
206361
|
+
|
|
206362
|
+
## Fast, and saying why
|
|
206363
|
+
|
|
206364
|
+
A data app over a warehouse or a large file is answered from tables Publisher builds ahead of time: a stored copy of
|
|
206365
|
+
the app's source, and rollups of the figures it adds up (\`reference/app-frame.md\`, "Make it fast"). Readers never see
|
|
206366
|
+
a spinner for long, and the info mark says which table answered and how it was made, in words: one row for each day,
|
|
206367
|
+
category and channel, with revenue already added up, its rows as of a date. Design the model for it: the app's
|
|
206368
|
+
measures and filters live on one source, as its own fields.
|
|
206369
|
+
|
|
206370
|
+
## Leave things out
|
|
206371
|
+
|
|
206372
|
+
Four well-chosen sections beat eight. A section whose headline the kit cannot write anything interesting for (every
|
|
206373
|
+
value the same, one value only, a split no one acts on) is cut, not padded. A filter nobody would use is cut.`
|
|
205912
206374
|
},
|
|
205913
206375
|
{
|
|
205914
206376
|
name: "malloy-html-data-apps/depth-patterns",
|
|
@@ -206100,7 +206562,7 @@ The apps that hold up against Looker or Sigma are not better-decorated versions
|
|
|
206100
206562
|
|
|
206101
206563
|
## 1. Establish the job
|
|
206102
206564
|
|
|
206103
|
-
Answer these four before choosing anything.
|
|
206565
|
+
Answer these four before choosing anything. Answer them yourself from the model and the request, and build: state what you decided at the top of \`app.js\` and in the hand-over, so the user corrects it in one reply rather than answering questions before seeing anything.
|
|
206104
206566
|
|
|
206105
206567
|
| Question | Why it changes the app |
|
|
206106
206568
|
|---|---|
|
|
@@ -206192,6 +206654,8 @@ Two traps worth naming, because they produce charts that are *readable and wrong
|
|
|
206192
206654
|
- **Diverging bars on disjoint vocabularies.** If the positive and negative sides are drawn from different taxonomies (an NLP model whose praise labels and complaint labels do not overlap), a diverging chart keyed on a shared label renders nearly every row one-sided and implies a balance the data does not contain. Use two ranked lists side by side.
|
|
206193
206655
|
- **A shared axis across different scales.** Mixing a 0-7 rating with a 0-10 rating on one radar, or two measures with different units on one y-axis, silently lets the larger scale dominate. Normalize, use a second axis explicitly labeled, or split the chart.
|
|
206194
206656
|
|
|
206657
|
+
Three more rules from apps built this way. Each finding gets its own form: never the same form for two questions next to each other. Pick the form a specialist in the field would draw, and give the app one form native to its field (an hour-by-weekday grid for calls, an epidemic curve, a calendar heatmap for seasons). A map earns its place only when the pattern in space is the finding. With the kit, \`reference/charts.md\` has a longer catalogue, each form with what the model must give it.
|
|
206658
|
+
|
|
206195
206659
|
Pie and donut are absent from that table on purpose. They answer "what is the composition" worse than a ranked bar or a waffle at almost every n. Use one only when parts-of-whole is the entire message and there are two or three parts.
|
|
206196
206660
|
|
|
206197
206661
|
## 4. Plan the depth
|
|
@@ -206215,7 +206679,7 @@ Also decide what the app does **not** do. An explorer that cannot export, or a m
|
|
|
206215
206679
|
|
|
206216
206680
|
## 5. Design for consistency without a shared kit
|
|
206217
206681
|
|
|
206218
|
-
|
|
206682
|
+
With the data app kit (\`reference/app-frame.md\`) the tokens below are already defined and checked; this section is for an app built without it. Consistency comes from a **token contract**: define the tokens in CSS, and have every chart read them at runtime rather than hardcoding color. That is what lets one app carry a client's identity while still looking like it was built on purpose.
|
|
206219
206683
|
|
|
206220
206684
|
Three rules do the load-bearing work here:
|
|
206221
206685
|
|
|
@@ -206238,7 +206702,7 @@ Before building, you should be able to state, in a few lines:
|
|
|
206238
206702
|
- the depth plan: what drills into what, what shares scope, what goes in the URL
|
|
206239
206703
|
- the token contract the app will use
|
|
206240
206704
|
|
|
206241
|
-
|
|
206705
|
+
Write that brief at the top of \`app.js\` and in the hand-over. It is short, and the user can correct it in one message.`
|
|
206242
206706
|
},
|
|
206243
206707
|
{
|
|
206244
206708
|
name: "malloy-html-data-apps/embedding",
|
|
@@ -206262,7 +206726,7 @@ Hand that brief over before scaffolding. It is short, the user can correct it in
|
|
|
206262
206726
|
</script>
|
|
206263
206727
|
\`\`\`
|
|
206264
206728
|
|
|
206265
|
-
\`embed(selector, options)\` returns \`{ iframe, destroy() }\`. Options: \`src\` (required), \`token\` (a signed token for cross-origin auth, appended as \`embed_token\`), \`height\` (omit to auto-size; a number is treated as pixels),
|
|
206729
|
+
\`embed(selector, options)\` returns \`{ iframe, destroy() }\`. Options: \`src\` (required), \`token\` (a signed token for cross-origin auth, appended as \`embed_token\`), \`height\` (omit to auto-size; a number is treated as pixels), \`allow\` (the iframe permissions policy; \`clipboard-write; fullscreen\` when omitted, \`""\` for none) and \`sandbox\` (the iframe sandbox tokens, replacing the default below).
|
|
206266
206730
|
|
|
206267
206731
|
## Sizing and the resize contract
|
|
206268
206732
|
|
|
@@ -206277,6 +206741,26 @@ The host scrolls; the frame does not. Inside an auto-sized frame \`window.innerH
|
|
|
206277
206741
|
- **An auto-sized frame must never become scrollable.** Anything whose box reaches past the content's bottom edge (a sentinel, an absolutely positioned helper, an overlay) is scrollable overflow: the document grows past the height the host sized, and the reader's first wheel turns scroll the app inside its frame before the host moves. Keep every added element within the content, and check it with the harness rather than hiding overflow: a fixed-height frame (\`height\` above, or \`publisher:fit\`) needs the app to scroll inside it.
|
|
206278
206742
|
- **Anything that floats over the page needs placing.** A drawer, a compare tray, a toast: built with \`position: fixed\` it opens at the top of the document, far above the reader, and focusing it scrolls the host page up to meet it. \`reference/overlays.md\` is the recipe: track the slice of the page the reader can see, place one clipped layer over it, contain its scroll, and focus without scrolling.
|
|
206279
206743
|
|
|
206744
|
+
A frame as tall as its content changes more than these two. Each is invisible standalone:
|
|
206745
|
+
|
|
206746
|
+
- **\`100vh\` is the whole frame.** Size nothing to the viewport; a block sized to \`100vh\` grows to the host's height cap.
|
|
206747
|
+
- **Sticky never sticks**, because the frame never scrolls. A sticky header or scope bar is fine as long as nothing
|
|
206748
|
+
depends on it staying in view.
|
|
206749
|
+
- **\`scrollTo\`, \`scrollBy\` and \`scrollY\` do nothing**, while \`scrollIntoView\` scrolls the host. To land a reader at
|
|
206750
|
+
the top of a new view, call \`scrollIntoView({ block: 'start' })\` on its header, as the kit does.
|
|
206751
|
+
- **\`IntersectionObserver\` ignores \`rootMargin\` in a cross-origin frame**, so a lazy tile starts loading as it
|
|
206752
|
+
enters the screen rather than before (\`reference/lazy-load.md\`).
|
|
206753
|
+
- **The runtime measures the bottoms of \`body\`'s children**, so a margin on the last child sits outside the
|
|
206754
|
+
measurement and gives the frame an inner scrollbar. Put the space inside, as padding.
|
|
206755
|
+
- **The host may cap the frame's height**, for example at 20,000 px. A view runs taller at phone width than at
|
|
206756
|
+
desktop, by half again or more, so keep each view under about 5,000 px at desktop width; split a long view into two
|
|
206757
|
+
views rather than growing one.
|
|
206758
|
+
- **What the frame refuses fails silently.** Publisher's frame sandbox allows scripts, same-origin requests and
|
|
206759
|
+
forms, so a download (a CSV button), a new tab and an \`alert\` do nothing inside it, though each works standalone.
|
|
206760
|
+
A clipboard write and full screen work in the same-origin Console, and are refused in a frame on another origin
|
|
206761
|
+
unless the host delegates them. A host may allow more. Check the kit's "Download CSV" and "Copy link"
|
|
206762
|
+
in the frame your app will live in.
|
|
206763
|
+
|
|
206280
206764
|
Test embedded, not just standalone: the Publisher console renders a package's app at \`/<env>/<package>/data-apps/<path>\`, which exercises the same resize contract a host does (\`reference/verification-harness.md\`).
|
|
206281
206765
|
|
|
206282
206766
|
## Auth
|
|
@@ -206286,7 +206770,7 @@ Test embedded, not just standalone: the Publisher console renders a package's ap
|
|
|
206286
206770
|
|
|
206287
206771
|
## Guardrails (v1)
|
|
206288
206772
|
|
|
206289
|
-
-
|
|
206773
|
+
- By default the iframe is sandboxed (\`allow-scripts allow-same-origin allow-forms allow-downloads allow-popups\`), with \`clipboard-write\` and \`fullscreen\` allowed. A download, a link in a new tab, a copy and full screen work; the opened tab keeps the sandbox, so its own dialogs do nothing and Chromium won't show a PDF in it: link a PDF with \`download\`. Top-level navigation and \`alert\`, \`confirm\`, \`prompt\` and \`print\` do not: drive dialogs in-page. A host's own \`sandbox\` replaces these tokens.
|
|
206290
206774
|
- Embedded author JavaScript runs with the viewing user's data authority, so treat everything under \`public/\` as strictly first-party code: do not load untrusted third-party scripts, and do not move query results off to other hosts. Tighter per-embed isolation is planned.`
|
|
206291
206775
|
},
|
|
206292
206776
|
{
|
|
@@ -206298,7 +206782,7 @@ Test embedded, not just standalone: the Publisher console renders a package's ap
|
|
|
206298
206782
|
|
|
206299
206783
|
Three parts, all required: drop any one and you get a subtle bug rather than an obvious one:
|
|
206300
206784
|
|
|
206301
|
-
1. **\`IntersectionObserver\`** with a \`rootMargin\` (~240px) so a tile starts loading just *before* it scrolls into view, not the instant it appears.
|
|
206785
|
+
1. **\`IntersectionObserver\`** with a \`rootMargin\` (~240px) so a tile starts loading just *before* it scrolls into view, not the instant it appears. In a cross-origin frame, or inside a scrolling container, the browser ignores the margin and the tile starts as it enters the screen: reserve its height so that still reads as loading, not as a jump. The kit uses 480px and four in flight.
|
|
206302
206786
|
2. **A small concurrency cap** so a fast scroll to the bottom doesn't fire twenty queries at once.
|
|
206303
206787
|
3. **Reserve each tile's height** while its skeleton shows, so lazy-loaded tiles don't reflow the page and retrigger the observer.
|
|
206304
206788
|
|
|
@@ -206345,6 +206829,17 @@ function reserveHeight(el) {
|
|
|
206345
206829
|
}
|
|
206346
206830
|
\`\`\`
|
|
206347
206831
|
|
|
206832
|
+
**In a frame, the margin rarely reaches.** The observer's implicit root is the top-level window, and every scrolling box between it and a tile clips the margin away: a host page's own scroll container, or the frame itself when it scrolls. Across origins the browser also ignores \`rootMargin\` outright. So in most embeds a tile starts loading only once it is on screen, which is when reserved heights matter most.
|
|
206833
|
+
|
|
206834
|
+
- **A page that scrolls itself inside its frame** (one that declares \`<meta name="publisher:fit" content="viewport">\`, in a host that honors it, such as the Publisher console): observe with \`root: document\`. It measures against the frame's own viewport, so the margin works again.
|
|
206835
|
+
- **A frame sized to the whole page** (the default in the console, and every \`Publisher.embed\` frame): keep the implicit root. With \`root: document\` the whole page counts as visible and every tile loads at once.
|
|
206836
|
+
|
|
206837
|
+
\`\`\`js
|
|
206838
|
+
// Pass ROOT to the observer in lazyLoad above: { root: ROOT, rootMargin: MARGIN }.
|
|
206839
|
+
const FITS_VIEWPORT = !!document.querySelector('meta[name="publisher:fit"][content="viewport"]');
|
|
206840
|
+
const ROOT = window.self !== window.top && FITS_VIEWPORT ? document : null;
|
|
206841
|
+
\`\`\`
|
|
206842
|
+
|
|
206348
206843
|
## Verification gotcha: test on a *small* viewport
|
|
206349
206844
|
|
|
206350
206845
|
On a short page (or a tall default headless viewport like 1280×720+), every tile intersects the \`rootMargin\` box at once, so *nothing* actually defers, and your test reports a false "everything lazy-loaded correctly" pass while the feature does nothing. **Verify with a deliberately small viewport** so tiles genuinely start off-screen:
|
|
@@ -206377,6 +206872,11 @@ for (let y = 0; y <= pageH; y += vh) {
|
|
|
206377
206872
|
await page.waitForFunction((n) => document.querySelectorAll(".tile .value").length >= n, total);
|
|
206378
206873
|
\`\`\``
|
|
206379
206874
|
},
|
|
206875
|
+
{
|
|
206876
|
+
name: "malloy-html-data-apps/maps",
|
|
206877
|
+
description: "Maps With the d3 Chart Module. Reference detail for the malloy-html-data-apps skill.",
|
|
206878
|
+
body: '# Maps With the d3 Chart Module\n\nWhen the pattern in space is the finding, draw a map. A choropleth of states, counties or countries answers "where" at\na glance, and a click on a place filters the app or opens its page. Boundaries ship as TopoJSON, which is text, and are drawn by the\nchart module\'s `choropleth` with d3 and topojson-client. Every file is pinned and checked, like d3. Data with\ncoordinates and no boundaries (a complaint\'s latitude and longitude) is drawn with `hexMap`, below.\n\n## Which boundaries\n\n| Places in the data | File | Object | Key on each shape | Size |\n|---|---|---|---|---|\n| US states | `us-atlas@3.0.1/states-albers-10m.json` | `states` | `id`: 2-digit FIPS (`"36"`); `properties.name` (`"New York"`) | 82 KB |\n| US counties | `us-atlas@3.0.1/counties-albers-10m.json` | `counties` (borders: `states`) | `id`: 5-digit FIPS (`"36061"`) | 795 KB |\n| Countries | `world-atlas@2.0.2/countries-110m.json` | `countries` | `id`: ISO 3166-1 numeric (`"840"`); `properties.name` | 108 KB |\n\nThe US files are already projected (Albers USA, Alaska and Hawaii inset) to a 975 by 610 box; the world file is in\nlongitude and latitude and is projected with Equal Earth. Match on FIPS or ISO codes when the data has them; names\ndiffer between sources ("Côte d\'Ivoire", "Ivory Coast"), so when you join on names, list every name that found no\nshape, and fix them in the model, not in the app. Counties are large: use them only when the data is by county, and put a ranked table beside the map, since county\nshapes take no keyboard focus.\nCanadian provinces and other regions have no packaged open file here; draw those as a ranked table instead.\n\n## Vendor\n\nd3 and topojson-client are already in the kit (`public/kit/vendor/`). Fetch the one boundary file the app needs, from\nthe package directory:\n\n```sh\nmkdir -p public/vendor/maps\ncd public/vendor\nbase=https://cdn.jsdelivr.net/npm\ncurl -sSL --fail --max-time 60 -o maps/states-albers-10m.json $base/us-atlas@3.0.1/states-albers-10m.json\ncurl -sSL --fail --max-time 60 -o maps/LICENSE-atlas.txt $base/us-atlas@3.0.1/LICENSE\nsha256sum -c - <<\'SUMS\'\n6e7bb086a3c791490361968a3094f377f7726c5d0c4900fec03cc42db2305a3d maps/states-albers-10m.json\n8048290dfdb6e83fbed17e8985c8cfc4ce9da9b842642f3d3e497280790cfa31 maps/LICENSE-atlas.txt\nSUMS\n[ $? -eq 0 ] || { rm -f maps/states-albers-10m.json maps/LICENSE-atlas.txt; echo "sum differs: draw a ranked table instead"; exit 1; }\ncd ../..\n```\n\nOn a Mac without `sha256sum`, use `shasum -a 256 -c -` in its place.\n\nThe other two boundary files, with their sums:\n\n```\na674dfa31b625e92635f32684a61ae135b05a91507f17f2d5164833237fecf46 maps/counties-albers-10m.json (us-atlas@3.0.1)\n2516c915867c7baf18ddec727aec46c315541a07cfb3d79a6559b05d5e94eee8 maps/countries-110m.json (world-atlas@2.0.2)\n```\n\nNever keep a file whose sum differs. If the fetch fails or the sum differs, draw the places as a ranked table instead and say so. topojson-client carries its licence in `kit/vendor/`. Add to\n`public/vendor/README.md` the boundary file, ISC license, from us-atlas (US Census Bureau cartographic boundaries, public domain) or\nworld-atlas (Natural Earth, public domain). Credit the boundaries in About the data. Load topojson-client with a\nplain script before `app.js` in `index.html`: `<script src="./kit/vendor/topojson-client.min.js"></script>`.\nIt is 7 KB, and the module calls it only once d3 is in.\n\n## Drawing a map\n\nA `block()` of your own draws a choropleth like this; the SVG keeps its proportions as the width changes, and a\nclick filters or opens the place:\n\n```js\ndraw: ([rows], body) => C.loadTopo(\'./vendor/maps/states-albers-10m.json\').then((topo) =>\n C.choropleth(body.appendChild(document.createElement(\'div\')), topo, new Map(rows.map((r) => [r.state, r.production])), {\n object: \'states\', legendTitle: \'Million lb\', onPick: (s) => store.toggleFilter(\'state\', s),\n })),\n```\n\nThe legend\'s classes are quintiles of the values shown; say so in the tile\'s method note.\n\nPoints with coordinates go on `hexMap`: one row per location with its count, `group_by: lat, lon` with a `limit` above\nthe number of locations (a query without one stops at the server\'s default row cap), and the same query with no\nfilters as `opts.base`, drawn grey underneath so the place keeps its shape. It needs no boundary file. Its hexagons are\nclicked, not tabbed to: put a ranked table beside it.\n\nA map earns its place only when the pattern in space is the finding: neighbours that move together, a gradient\nacross a region, a cluster along a border. Being about places is not a reason for a map. A map is not a ranking either: where the shapes take no\nkeyboard focus (counties, hexagons), the ranked table beside it is how a keyboard reader reaches each place; a\nranked table beside a states map that says the same thing is a repeat.'
|
|
206879
|
+
},
|
|
206380
206880
|
{
|
|
206381
206881
|
name: "malloy-html-data-apps/overlays",
|
|
206382
206882
|
description: "Drawers, trays and toasts in an embedded app. Reference detail for the malloy-html-data-apps skill.",
|
|
@@ -206449,6 +206949,8 @@ export function mount(host, buildOption) {
|
|
|
206449
206949
|
|
|
206450
206950
|
### Trim the library to what the app draws
|
|
206451
206951
|
|
|
206952
|
+
Not the kit's d3 module (\`reference/charts.md\`): it is copied whole, so a fixed version can be copied over it, and it draws SVG, which a check counts by marks rather than pixels.
|
|
206953
|
+
|
|
206452
206954
|
Most chart libraries publish a modular build. A bundle of only the series types and components the app actually uses is typically a third smaller (one build: 1,122 KB to 713 KB, 369 KB to 243 KB gzipped). Inventory what the code passes the library (every series \`type:\`, and components such as legend, tooltip, visualMap, markLine), bundle exactly those once with a bundler outside the package, and commit the bundle together with its entry file and the command that rebuilt it.
|
|
206453
206955
|
|
|
206454
206956
|
**A trimmed build fails silently.** A series type left out of the bundle still mounts its canvas, throws nothing and logs nothing, and draws an empty box. A canvas count proves nothing. Verify by reading pixels: open every page and every kind of drawer, and require each chart canvas to have drawn pixels, against the full build first and then the trimmed one. Write the list of included types next to the bundle, so the next person to add a chart type knows to rebuild.
|
|
@@ -206631,7 +207133,7 @@ Compression and cache headers belong to whatever serves \`public/\`. Check them
|
|
|
206631
207133
|
{
|
|
206632
207134
|
name: "malloy-html-data-apps/runtime",
|
|
206633
207135
|
description: "HTML Data App Runtime. Reference detail for the malloy-html-data-apps skill.",
|
|
206634
|
-
body: '# HTML Data App Runtime\n\n> `Publisher.query(modelPath, malloy)` returns an array of plain row objects. Build the Malloy string, let the model do the work, and render the rows with whatever front-end code you like.\n\nThe runtime loads from the root-relative `<script src="/sdk/publisher.js">` and adds one global, `window.Publisher`.\n\n## The query contract\n\n| Call | Returns | Use for |\n| ----------------------------------------------- | ------------------------ | ---------------------------------- |\n| `Publisher.query(modelPath, malloy, opts?)` | `Promise<Array>` of rows | driving your own charts and tables |\n| `Publisher.queryFull(modelPath, malloy, opts?)` | `Promise<MalloyResult>` | handing to `<malloy-render>` |\n\n- `modelPath` is the model FILE path within the package, with `/` separators (`"subscriptions.malloy"`, `"models/events.malloy"`). It is not the source name.\n- `malloy` is any query string, written in standard Malloy. This skill covers only the JavaScript glue, not Malloy syntax.\n- `opts` (all optional): `sourceName`, `queryName` (`queryName` runs a saved query, with `sourceName` qualifying the source a view hangs off; `sourceName` on its own is a 400), `givens` (a `{ name: value }` map bound to the model\'s Malloy `given:` runtime parameters for this query; safe parameterization, values are bound by Publisher server-side, not string-interpolated), `filterParams` (values for the model\'s legacy `#(filter)` source filters), `bypassFilters`, and `environment` / `package` (only if the page is served from outside `/environments/<env>/packages/<pkg>/`). `givens` and `filterParams` compose (both apply). With package versioning on, `versionId` queries one published version instead of the package\'s `latest`; a page opened with `?versionId=` in its URL already pins every query to its own package to that version, once a read of the package confirms it has it (otherwise the page queries `latest`; a query that names another `package` gets that package\'s `latest`), but its own relative files (`./app.js`, stylesheets) are served from `latest` unless their URLs carry `?versionId=` too.\n\n## Structure the app as modules, not one inline script\n\nPast a single tile, an inline `<script>` becomes unmaintainable and untestable. Split the work, and load it without a build step: the runtime first as a plain global, then one ES-module entry point that `import`s your own files.\n\n```html\n<head>\n <!-- Start the chart library\'s download now, without making anything wait for it.\n Only on pages that draw a chart. -->\n <link rel="preload" as="script" href="./vendor/chart.umd.js" />\n</head>\n...\n<script src="/sdk/publisher.js"></script>\n<!-- One module entry; it imports the rest. ES modules resolve with no bundler. -->\n<script type="module" src="./app.js"></script>\n```\n\n**Do not load the chart library with a plain `<script>` ahead of your code.** It is usually most of the page\'s weight, and loaded that way it holds every query until it has downloaded and parsed. `charts.js` injects it the first time it draws, so the queries start at once. `reference/performance.md` has the loader, and the stand-in that lets callers wire chart clicks before the library has arrived.\n\nA separation that keeps each piece testable and changeable on its own:\n\n- **`format.js`**. Pure functions only: number/date formatting, a series-align-by-month helper, status thresholds. No DOM, no globals. This is the file `node --test` can cover directly.\n- **`charts.js`**. Turns a prepared data object into a drawn chart; the only file that touches the chart library, and the one that loads it.\n- **`tiles.js`**. Your tiles as _data_: for each, its model/source/view (and target source, if any), plus a pure `build(rows)` that shapes query rows for the chart. This is the single source of truth for what each tile queries.\n- **`app.js`**. The thin entry point: reads `tiles.js`, runs the queries, wires results to the DOM. Adding a tile means adding a `tiles.js` entry, not editing `app.js`.\n\nDeclare each tile\'s source and view names once, in `tiles.js`, and have everything else (render code, any agent prompt, tests) read from there. A second copy of those names in another file is the classic drift bug, and a _derived_ name (`okr_4_4_2_targets` invented from a tile code) is simply wrong: a target source may have an irregular name or not exist at all. Read the model; don\'t compute names.\n\n## Patterns that work\n\nThese assume a `subscriptions.malloy` model whose `subscriptions` source defines the views `plan_mix`, `mrr_by_industry`, and `kpis`. The names are illustrative; swap in your own model and view names.\n\nRun a named view:\n\n```js\nconst rows = await Publisher.query(\n "subscriptions.malloy",\n "run: subscriptions -> plan_mix",\n);\n```\n\nRefine a view from UI state by appending a `where:`. Restrict the values to ones you control (for example a dropdown populated from the model\'s own distinct values) and escape each interpolated value with a backslash before quotes and backslashes (Malloy rejects the SQL-style `\'\'` doubling). An unescaped apostrophe in a value breaks out of the literal:\n\n```js\nfunction whereClause(state) {\n const q = (s) => s.replace(/\\\\/g, "\\\\\\\\").replace(/\'/g, "\\\\\'"); // backslash-escape for Malloy\n const parts = [];\n if (state.plan) parts.push(`plan = \'${q(state.plan)}\'`);\n if (state.industry) parts.push(`industry = \'${q(state.industry)}\'`);\n return parts.length ? `where: ${parts.join(", ")}` : "";\n}\nconst rows = await Publisher.query(\n "subscriptions.malloy",\n `run: subscriptions -> plan_mix + { ${whereClause(state)} }`,\n);\n```\n\nDo not interpolate free-text or otherwise untrusted input into the query string. Route parameterized input through `opts.givens` (or the legacy `opts.filterParams`) instead: Publisher binds those values server-side as typed parameters, so they are never concatenated into query text and can\'t inject query syntax. (One nuance: a `filter<T>`-typed given takes Malloy filter syntax as its value, so validate it against a known set like any other input; scalar givens carry no syntax at all.) `opts.givens` is safe _parameterization_, not an authorization boundary on its own: a plain given is whatever the request carries. A given the model declares `#(secure)` is the host\'s to set: the trusted tier in front of Publisher resolves it from the viewer\'s verified identity and replaces anything the page sent, which is what makes a gate on it a real boundary (`docs/authorize.md`). A page should never try to set a secure given itself in a deployed app; on a bare local server with no trusted tier in front, whatever the page sends is used, so say so in the app if it lets the viewer pick one. Where you must build query text from input, constrain it to a known set and escape it, or keep the filtering in model-defined views.\n\nKPI or single-row view. Destructure element zero:\n\n```js\nconst [kpis] = await Publisher.query(\n "subscriptions.malloy",\n "run: subscriptions -> kpis",\n);\nel.textContent = kpis.active_mrr; // the result is an array; kpis.active_mrr, not rows.active_mrr\n```\n\nRefresh a dashboard. Fire the tiles together:\n\n```js\nconst [planMix, byIndustry, kpisRows] = await Promise.all([\n Publisher.query("subscriptions.malloy", "run: subscriptions -> plan_mix"),\n Publisher.query(\n "subscriptions.malloy",\n "run: subscriptions -> mrr_by_industry",\n ),\n Publisher.query("subscriptions.malloy", "run: subscriptions -> kpis"),\n]);\n```\n\nPrefer defining the views in the model (one per tile, pre-aggregated and sorted) over building long query strings in JS.\n\n**Same question, same query text.** `Publisher.query` caches nothing, but a cache the app keeps, a shared in-flight request, and any prefetch are all keyed on the exact string. Two pages reading the same view with different text (one adds an `order_by`) pay for two round trips for one answer, and a prefetch that warms different text from what the destination page sends warms nothing. Build each tile\'s query in one place and reuse that string wherever the same rows are needed.\n\n**Set ARIA and data attributes as attributes.** A small element helper that does `Object.assign(document.createElement(tag), props)` silently drops `aria-modal`, `aria-label`, `aria-busy` and `data-*`: they are not properties, so assigning them does nothing and no error says so. Route any `aria-*`, `data-*` and `role` key through `setAttribute`. And a clickable row is a control: give it `tabIndex = 0` and Enter/Space handling, or keyboard users cannot open what a mouse user can.\n\nGet the numbers right. The fastest way to ship a wrong-but-convincing dashboard is to paper over missing data:\n\n- **Missing is not zero.** When you join two series (actuals to a separately-keyed target) and a key is absent, leave it `null` so the chart skips it. Do not `|| 0`, which plots a real-looking zero and reads as "we hit nothing that month." Align on a normalized key (`"YYYY-MM"`), and let the renderer omit null points:\n\n ```js\n // monthKey/monthLabel are your own format.js helpers: monthKey normalizes a\n // date to a "YYYY-MM" string; monthLabel formats it for display.\n // target may not cover every actual month; an absent month stays null, never 0.\n const target = new Map(\n planRows.map((r) => [monthKey(r.plan_month), Number(r.target_revenue)]),\n );\n const data = actualRows.map((r) => ({\n label: monthLabel(r.order_month),\n actual: Number(r.revenue),\n target: target.has(monthKey(r.order_month))\n ? target.get(monthKey(r.order_month))\n : null,\n }));\n ```\n\n- **"Current" means latest non-null.** For a KPI scorecard, scan back to the last month that actually has data rather than reading the final row, which may be an incomplete current month.\n- **Guard division in Malloy, not after.** `avg(paid / nullif(active, 0))`. A `nullif` in the query beats catching `Infinity`/`NaN` in JS.\n- **Convert units explicitly.** If the model stores a 0 to 1 fraction and you show a percent, multiply once in `build()` and comment it. Mismatched units are a silent off-by-100.\n\nLoading, empty, and error states. Handle all three; a bare `.then()` that assumes rows leaves the page blank when the query is slow or fails:\n\n```js\nconst el = document.getElementById("out");\nel.textContent = "Loading...";\nPublisher.query("subscriptions.malloy", "run: subscriptions -> plan_mix")\n .then((rows) => {\n if (!rows.length) {\n el.textContent = "No data.";\n return;\n }\n render(rows);\n })\n .catch((err) => {\n el.textContent = `Query failed (${err.status ?? ""}): ${err.response?.message ?? err.message}`;\n });\n```\n\nRender through `<malloy-render>`. `queryFull` returns the full Malloy result envelope (the JSON form of the server\'s result, not a live result object) to hand to the component:\n\n```js\nconst el = document.querySelector("malloy-render");\nel.result = await Publisher.queryFull(\n "subscriptions.malloy",\n "run: subscriptions -> plan_mix",\n);\n```\n\nPublisher does not serve or bundle `<malloy-render>`; you must obtain a built component bundle matched to your model\'s Malloy version and vendor it into `public/` yourself, then confirm it accepts the envelope as-is. The `storefront` example draws with Chart.js and has no `<malloy-render>` element in its pages, so the component itself is not exercised there. A view tagged in the model (for example `# bar_chart`) drives how it draws.\n\nValidate every query before wiring it into render code, using whatever query tool your environment provides, or by POSTing the query to a running Publisher at `/api/v0/environments/<env>/packages/<pkg>/models/<modelPath>/query` with body `{"compactJson":true,"query":"..."}`, or by running `Publisher.query` once and logging the rows. Malloy names result columns after the `group_by` / `aggregate` field names (`group_by: plan` gives a `plan` column; `aggregate: account_count` gives an `account_count` column), so confirm those names against real output before you read them.\n\nIf you validate the rendered page in a headless browser (Playwright or Puppeteer), do not wait for network idle: `publisher.js` holds the live-reload SSE stream open, so the page never reaches it. Wait on `domcontentloaded` or `load` plus a content selector instead.\n\n## Context, auth, live reload (all automatic)\n\n- Context. A page served under `/environments/<env>/packages/<pkg>/...` infers its environment and package, so `query` needs no env or package args. Serving from elsewhere? Pass `opts.environment` and `opts.package`.\n- Auth. By default the runtime sends cookies (`credentials: include`), so a signed-in user is authenticated with no code. For a bearer token, call `Publisher.setToken(token)` first; `Publisher.setToken(null)` reverts to cookies.\n- Live reload. Under `--watch-env`, the page reloads on package changes by itself. Nothing to wire.\n\n## When the app fails\n\n| Symptom | Likely cause and fix |\n| ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 404 or "model not found" | `modelPath` wrong. It is the file path (`"subscriptions.malloy"`), with `/` separators, not the source name. |\n| "source/view not defined" | View or source name guessed. Read the model (your environment\'s context tool, or open the `.malloy` file) and use the real names. |\n| Promise rejects, message starts `Publisher.query:` | Read `error.status` and `error.response` for the server\'s reason (compile error, missing required parameter, permission). |\n| Empty array when you expect rows | Filter value mismatch (case, spelling, type, or a non-ASCII character like `≤` or an en-dash in the literal). Copy the literal verbatim from the model, do not retype the user\'s paraphrase, and confirm it with a distinct-values query (`run: src -> { group_by: the_dimension }`). Quote strings, use `@` for dates. |\n| 400 on a given (ungated source) | An unknown given name (check spelling; names are case-sensitive), a required given left unset, or a value that doesn\'t fit the declared type. Malloy rejects it when preparing the query; supply declared givens via `opts.givens` with the right shape (see the givens type table). |\n| 403 on a query that should be allowed, when passing givens to a gated source | On a gated source, a bad given (unknown name or wrong-typed value) fails closed, so it looks like access denied rather than validation. A `#(authorize)` lock also answers 403 for a caller it simply does not admit. Check the given names and values against the model. |\n| KPI shows `undefined` | The result is an array. Read `rows[0].field` (or destructure `const [k] = ...`), not `rows.field`. |\n| A NEW file under `public/` 404s while the rest of the app serves | The server loaded the package **before** `public/` existed, and it is not watching. Without `--watch-env` the package is published at load as an immutable version under `publisher_data/<env>/<pkg>/<version>/` and static files are served from it, so a file you add afterwards is never seen. Restart with `--watch-env <env>`, or bump `version` in `publisher.json` and publish again; never write into `publisher_data/`. Verified by writing a probe file into the real package and getting a 404 while the served package answered fine - and note the existing row below sends you looking under `public/`, which is exactly the wrong place for this one. |\n| Page loads in dev but is not listed or not served | The file is not under the package\'s `public/` directory. Publisher serves only `public/`; a page written anywhere else (for example `/tmp`) is never reachable at `/environments/<env>/packages/<pkg>/<file>`. |\n| Queries fail only when embedded cross-origin | Cookies are not sent cross-site. Serve same-origin, or pass a bearer token. |\n| No live reload | Watch mode is off. Start with `--watch-env <env>`; without it the events stream reports `mode: disabled` and never reloads. |'
|
|
207136
|
+
body: '# HTML Data App Runtime\n\n> `Publisher.query(modelPath, malloy)` returns an array of plain row objects. Build the Malloy string, let the model do the work, and render the rows with whatever front-end code you like.\n\nThe runtime loads from the root-relative `<script src="/sdk/publisher.js">` and adds one global, `window.Publisher`.\n\n## The query contract\n\n| Call | Returns | Use for |\n| ----------------------------------------------- | ------------------------ | ---------------------------------- |\n| `Publisher.query(modelPath, malloy, opts?)` | `Promise<Array>` of rows | driving your own charts and tables |\n| `Publisher.queryFull(modelPath, malloy, opts?)` | `Promise<MalloyResult>` | handing to `<malloy-render>` |\n| `Publisher.model(modelPath, opts?)` | `Promise<Model>` | the model\'s sources and their docs |\n| `Publisher.packageResource(name, opts?)` | `Promise<JSON>` | `"build-plan"` or `"materializations"`: what Publisher builds for the package, and its runs, newest first (`opts.limit` reads only the newest) |\n\n- `modelPath` is the model FILE path within the package, with `/` separators (`"subscriptions.malloy"`, `"models/events.malloy"`). It is not the source name.\n- `malloy` is any query string, written in standard Malloy. This skill covers only the JavaScript glue, not Malloy syntax.\n- `opts` (all optional): `sourceName`, `queryName` (`queryName` runs a saved query, with `sourceName` qualifying the source a view hangs off; `sourceName` on its own is a 400), `givens` (a `{ name: value }` map bound to the model\'s Malloy `given:` runtime parameters for this query; safe parameterization, values are bound by Publisher server-side, not string-interpolated), `filterParams` (values for the model\'s legacy `#(filter)` source filters), `bypassFilters`, and `environment` / `package` (only if the page is served from outside `/environments/<env>/packages/<pkg>/`). `givens` and `filterParams` compose (both apply). `meta`, an object you pass, is filled with `{ servedFrom, path, executionTimeMs, versionId }`: the first three from the response, where `path` names the table that served the answer and the ones considered; `versionId` is the version the query was pinned to, or `null`. With package versioning on, `versionId` queries one published version instead of the package\'s `latest`; a page opened with `?versionId=` in its URL already pins every query to its own package to that version, once a read of the package confirms it has it (otherwise the page queries `latest`; a query that names another `package` gets that package\'s `latest`), but its own relative files (`./app.js`, stylesheets) are served from `latest` unless their URLs carry `?versionId=` too. `model` and `packageResource` read the same pinned version as the page\'s queries.\n\n### Light and dark, from the host\n\nA page in a frame learns the reader\'s mode from the host. `Publisher.colorScheme` is `\'light\'`, `\'dark\'` or `null` before the host says; `Publisher.onColorScheme(fn)` calls `fn` with each mode, at once if one is known, and returns a function that stops it. Once the page has drawn a mode, call `Publisher.colorSchemeApplied(mode)` so the host can let the frame show it. The messages are `publisher:color-scheme` (host to page), `publisher:color-scheme-request` and `publisher:color-scheme-applied` (page to host); `DataAppViewer` in the SDK sends the console\'s mode.\n\n## Structure the app as modules, not one inline script\n\nPast a single tile, an inline `<script>` becomes unmaintainable and untestable. Split the work, and load it without a build step: the runtime first as a plain global, then one ES-module entry point that `import`s your own files.\n\n```html\n<head>\n <!-- Start the chart library\'s download now, without making anything wait for it.\n Only on pages that draw a chart. -->\n <link rel="preload" as="script" href="./vendor/chart.umd.js" />\n</head>\n...\n<script src="/sdk/publisher.js"></script>\n<!-- One module entry; it imports the rest. ES modules resolve with no bundler. -->\n<script type="module" src="./app.js"></script>\n```\n\n**Do not load the chart library with a plain `<script>` ahead of your code.** It is usually most of the page\'s weight, and loaded that way it holds every query until it has downloaded and parsed. `charts.js` injects it the first time it draws, so the queries start at once. `reference/performance.md` has the loader, and the stand-in that lets callers wire chart clicks before the library has arrived.\n\nA separation that keeps each piece testable and changeable on its own:\n\n- **`format.js`**. Pure functions only: number/date formatting, a series-align-by-month helper, status thresholds. No DOM, no globals. This is the file `node --test` can cover directly.\n- **`charts.js`**. Turns a prepared data object into a drawn chart; the only file that touches the chart library, and the one that loads it.\n- **`tiles.js`**. Your tiles as _data_: for each, its model/source/view (and target source, if any), plus a pure `build(rows)` that shapes query rows for the chart. This is the single source of truth for what each tile queries.\n- **`app.js`**. The thin entry point: reads `tiles.js`, runs the queries, wires results to the DOM. Adding a tile means adding a `tiles.js` entry, not editing `app.js`.\n\nDeclare each tile\'s source and view names once, in `tiles.js`, and have everything else (render code, any agent prompt, tests) read from there. A second copy of those names in another file is the classic drift bug, and a _derived_ name (`okr_4_4_2_targets` invented from a tile code) is simply wrong: a target source may have an irregular name or not exist at all. Read the model; don\'t compute names.\n\n## Patterns that work\n\nThese assume a `subscriptions.malloy` model whose `subscriptions` source defines the views `plan_mix`, `mrr_by_industry`, and `kpis`. The names are illustrative; swap in your own model and view names.\n\nRun a named view:\n\n```js\nconst rows = await Publisher.query(\n "subscriptions.malloy",\n "run: subscriptions -> plan_mix",\n);\n```\n\nRefine a view from UI state by appending a `where:`. Restrict the values to ones you control (for example a dropdown populated from the model\'s own distinct values) and escape each interpolated value with a backslash before quotes and backslashes (Malloy rejects the SQL-style `\'\'` doubling). An unescaped apostrophe in a value breaks out of the literal:\n\n```js\nfunction whereClause(state) {\n const q = (s) => s.replace(/\\\\/g, "\\\\\\\\").replace(/\'/g, "\\\\\'"); // backslash-escape for Malloy\n const parts = [];\n if (state.plan) parts.push(`plan = \'${q(state.plan)}\'`);\n if (state.industry) parts.push(`industry = \'${q(state.industry)}\'`);\n return parts.length ? `where: ${parts.join(", ")}` : "";\n}\nconst rows = await Publisher.query(\n "subscriptions.malloy",\n `run: subscriptions -> plan_mix + { ${whereClause(state)} }`,\n);\n```\n\nDo not interpolate free-text or otherwise untrusted input into the query string. Route parameterized input through `opts.givens` (or the legacy `opts.filterParams`) instead: Publisher binds those values server-side as typed parameters, so they are never concatenated into query text and can\'t inject query syntax. (One nuance: a `filter<T>`-typed given takes Malloy filter syntax as its value, so validate it against a known set like any other input; scalar givens carry no syntax at all.) `opts.givens` is safe _parameterization_, not an authorization boundary on its own: a plain given is whatever the request carries. A given the model declares `#(secure)` is the host\'s to set: the trusted tier in front of Publisher resolves it from the viewer\'s verified identity and replaces anything the page sent, which is what makes a gate on it a real boundary (`docs/authorize.md`). A page should never try to set a secure given itself in a deployed app; on a bare local server with no trusted tier in front, whatever the page sends is used, so say so in the app if it lets the viewer pick one. Where you must build query text from input, constrain it to a known set and escape it, or keep the filtering in model-defined views. The kit does this: a filter value comes from the values a query returned, its search box and an entity\'s id in the address are the free text it takes, and every value goes through `S.lit`, which escapes quotes, backslashes and control characters. It writes literals rather than givens because a given must be declared in the model, and the kit works over a model that declares none.\n\nKPI or single-row view. Destructure element zero:\n\n```js\nconst [kpis] = await Publisher.query(\n "subscriptions.malloy",\n "run: subscriptions -> kpis",\n);\nel.textContent = kpis.active_mrr; // the result is an array; kpis.active_mrr, not rows.active_mrr\n```\n\nRefresh a dashboard. Fire the tiles together:\n\n```js\nconst [planMix, byIndustry, kpisRows] = await Promise.all([\n Publisher.query("subscriptions.malloy", "run: subscriptions -> plan_mix"),\n Publisher.query(\n "subscriptions.malloy",\n "run: subscriptions -> mrr_by_industry",\n ),\n Publisher.query("subscriptions.malloy", "run: subscriptions -> kpis"),\n]);\n```\n\nPrefer defining the views in the model (one per tile, pre-aggregated and sorted) over building long query strings in JS.\n\n**Same question, same query text.** `Publisher.query` caches nothing, but a cache the app keeps, a shared in-flight request, and any prefetch are all keyed on the exact string. Two pages reading the same view with different text (one adds an `order_by`) pay for two round trips for one answer, and a prefetch that warms different text from what the destination page sends warms nothing. Build each tile\'s query in one place and reuse that string wherever the same rows are needed.\n\n**Set ARIA and data attributes as attributes.** A small element helper that does `Object.assign(document.createElement(tag), props)` silently drops `aria-modal`, `aria-label`, `aria-busy` and `data-*`: they are not properties, so assigning them does nothing and no error says so. Route any `aria-*`, `data-*` and `role` key through `setAttribute`. And a clickable row is a control: give it `tabIndex = 0` and Enter/Space handling, or keyboard users cannot open what a mouse user can.\n\nGet the numbers right. The fastest way to ship a wrong-but-convincing dashboard is to paper over missing data:\n\n- **Missing is not zero.** When you join two series (actuals to a separately-keyed target) and a key is absent, leave it `null` so the chart skips it. Do not `|| 0`, which plots a real-looking zero and reads as "we hit nothing that month." Align on a normalized key (`"YYYY-MM"`), and let the renderer omit null points:\n\n ```js\n // monthKey/monthLabel are your own format.js helpers: monthKey normalizes a\n // date to a "YYYY-MM" string; monthLabel formats it for display.\n // target may not cover every actual month; an absent month stays null, never 0.\n const target = new Map(\n planRows.map((r) => [monthKey(r.plan_month), Number(r.target_revenue)]),\n );\n const data = actualRows.map((r) => ({\n label: monthLabel(r.order_month),\n actual: Number(r.revenue),\n target: target.has(monthKey(r.order_month))\n ? target.get(monthKey(r.order_month))\n : null,\n }));\n ```\n\n- **"Current" means latest non-null.** For a KPI scorecard, scan back to the last month that actually has data rather than reading the final row, which may be an incomplete current month.\n- **Guard division in Malloy, not after.** `avg(paid / nullif(active, 0))`. A `nullif` in the query beats catching `Infinity`/`NaN` in JS.\n- **Convert units explicitly.** If the model stores a 0 to 1 fraction and you show a percent, multiply once in `build()` and comment it. Mismatched units are a silent off-by-100.\n\nLoading, empty, and error states. Handle all three; a bare `.then()` that assumes rows leaves the page blank when the query is slow or fails:\n\n```js\nconst el = document.getElementById("out");\nel.textContent = "Loading...";\nPublisher.query("subscriptions.malloy", "run: subscriptions -> plan_mix")\n .then((rows) => {\n if (!rows.length) {\n el.textContent = "No data.";\n return;\n }\n render(rows);\n })\n .catch((err) => {\n el.textContent = `Query failed (${err.status ?? ""}): ${err.response?.message ?? err.message}`;\n });\n```\n\nRender through `<malloy-render>`. `queryFull` returns the full Malloy result envelope (the JSON form of the server\'s result, not a live result object) to hand to the component:\n\n```js\nconst el = document.querySelector("malloy-render");\nel.result = await Publisher.queryFull(\n "subscriptions.malloy",\n "run: subscriptions -> plan_mix",\n);\n```\n\nPublisher does not serve or bundle `<malloy-render>`; you must obtain a built component bundle matched to your model\'s Malloy version and vendor it into `public/` yourself, then confirm it accepts the envelope as-is. The `storefront` example draws with Chart.js and has no `<malloy-render>` element in its pages, so the component itself is not exercised there. A view tagged in the model (for example `# bar_chart`) drives how it draws.\n\nValidate every query before wiring it into render code, using whatever query tool your environment provides, or by POSTing the query to a running Publisher at `/api/v0/environments/<env>/packages/<pkg>/models/<modelPath>/query` with body `{"compactJson":true,"query":"..."}`, or by running `Publisher.query` once and logging the rows. Malloy names result columns after the `group_by` / `aggregate` field names (`group_by: plan` gives a `plan` column; `aggregate: account_count` gives an `account_count` column), so confirm those names against real output before you read them.\n\nFour more that each cost a real build a debugging cycle:\n\n- **Drop nulls from a distinct-value list.** A null becomes a blank option that matches "nothing selected".\n- **Codes are strings.** A ZIP or FIPS code that is a number loses its leading zero and never matches the address,\n which holds strings. Make it a string dimension in the model.\n- **Give every list query a `limit`.** A query without one stops at the server\'s default row cap, which looks like\n data that ends early. A refinement that adds `limit` to a view should repeat the view\'s `order_by` beside it.\n- **Quote a CSV cell that starts with `=`, `+`, `-` or `@`.** A spreadsheet runs it as a formula.\n\nIf you validate the rendered page in a headless browser (Playwright or Puppeteer), do not wait for network idle: `publisher.js` holds the live-reload SSE stream open, so the page never reaches it. Wait on `domcontentloaded` or `load` plus a content selector instead.\n\n## Context, auth, live reload (all automatic)\n\n- Context. A page served under `/environments/<env>/packages/<pkg>/...` infers its environment and package, so `query` needs no env or package args. Serving from elsewhere? Pass `opts.environment` and `opts.package`.\n- Auth. By default the runtime sends cookies (`credentials: include`), so a signed-in user is authenticated with no code. For a bearer token, call `Publisher.setToken(token)` first; `Publisher.setToken(null)` reverts to cookies.\n- Live reload. Under `--watch-env`, the page reloads on package changes by itself. Nothing to wire.\n\n## When the app fails\n\n| Symptom | Likely cause and fix |\n| ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| 404 or "model not found" | `modelPath` wrong. It is the file path (`"subscriptions.malloy"`), with `/` separators, not the source name. |\n| "source/view not defined" | View or source name guessed. Read the model (your environment\'s context tool, or open the `.malloy` file) and use the real names. |\n| Promise rejects, message starts `Publisher.query:` | Read `error.status` and `error.response` for the server\'s reason (compile error, missing required parameter, permission). |\n| Empty array when you expect rows | Filter value mismatch (case, spelling, type, or a non-ASCII character like `≤` or an en-dash in the literal). Copy the literal verbatim from the model, do not retype the user\'s paraphrase, and confirm it with a distinct-values query (`run: src -> { group_by: the_dimension }`). Quote strings, use `@` for dates. |\n| 400 on a given (ungated source) | An unknown given name (check spelling; names are case-sensitive), a required given left unset, or a value that doesn\'t fit the declared type. Malloy rejects it when preparing the query; supply declared givens via `opts.givens` with the right shape (see the givens type table). |\n| 403 on a query that should be allowed, when passing givens to a gated source | On a gated source, a bad given (unknown name or wrong-typed value) fails closed, so it looks like access denied rather than validation. A `#(authorize)` lock also answers 403 for a caller it simply does not admit. Check the given names and values against the model. |\n| KPI shows `undefined` | The result is an array. Read `rows[0].field` (or destructure `const [k] = ...`), not `rows.field`. |\n| A NEW file under `public/` 404s while the rest of the app serves | The server loaded the package **before** `public/` existed, and it is not watching. Without `--watch-env` the package is published at load as an immutable version under `publisher_data/<env>/<pkg>/<version>/` and static files are served from it, so a file you add afterwards is never seen. Restart with `--watch-env <env>`, or bump `version` in `publisher.json` and publish again; never write into `publisher_data/`. Verified by writing a probe file into the real package and getting a 404 while the served package answered fine - and note the existing row below sends you looking under `public/`, which is exactly the wrong place for this one. |\n| Page loads in dev but is not listed or not served | The file is not under the package\'s `public/` directory. Publisher serves only `public/`; a page written anywhere else (for example `/tmp`) is never reachable at `/environments/<env>/packages/<pkg>/<file>`. |\n| Queries fail only when embedded cross-origin | Cookies are not sent cross-site. Serve same-origin, or pass a bearer token. |\n| No live reload | Watch mode is off. Start with `--watch-env <env>`; without it the events stream reports `mode: disabled` and never reloads. |'
|
|
206635
207137
|
},
|
|
206636
207138
|
{
|
|
206637
207139
|
name: "malloy-html-data-apps/token-contract",
|
|
@@ -206640,7 +207142,7 @@ Compression and cache headers belong to whatever serves \`public/\`. Check them
|
|
|
206640
207142
|
|
|
206641
207143
|
Read when setting up an app's stylesheet, or when reskinning one for a client.
|
|
206642
207144
|
|
|
206643
|
-
|
|
207145
|
+
Outside the data app kit (\`reference/app-frame.md\`), which defines and checks these tokens itself, there is no shipped component library, so visual consistency across apps comes from every app defining the same *kinds* of token and every chart reading them at runtime. The values are free - that is what carries a client's identity. The contract is the shape. The template's stylesheet defines its own tokens (\`--up\` is bad news and \`--down\` good news, by what a change means to the reader, not its direction), and its chart module reads them at runtime; the module's own few fixed label sizes are the module's, not the app's.
|
|
206644
207146
|
|
|
206645
207147
|
## What to define on \`:root\`
|
|
206646
207148
|
|
|
@@ -206649,7 +207151,7 @@ There is no shipped component library, so visual consistency across apps comes f
|
|
|
206649
207151
|
| Surfaces | page background, card surface, a raised and a sunken variant, border, strong border |
|
|
206650
207152
|
| Text | strong, default, muted, soft - a real ramp, not one color at three opacities |
|
|
206651
207153
|
| Semantic | positive, negative, warning, each with a soft background variant for fills and badges |
|
|
206652
|
-
| Chart palette | a categorical ramp
|
|
207154
|
+
| Chart palette | a categorical ramp, ordered so the first is the brand accent, plus grid and axis-tick colors. Six is the most a reader tells apart; the data app kit ships six, checked in both modes |
|
|
206653
207155
|
| **Type** | a **closed** size scale of exactly 8 steps, plus the weights, line-heights and letter-spacings you actually use |
|
|
206654
207156
|
| **Spacing** | a scale (4 / 8 / 12 / 16 / 24 / 32 / 48), not a single step that gets multiplied and divided in place |
|
|
206655
207157
|
| Structure | a radius scale (small, default, large), a shadow for cards and a deeper one for popovers |
|
|
@@ -206765,6 +207267,15 @@ const palette = () => ["--c1","--c2","--c3","--c4","--c5","--c6","--c7","--c8"].
|
|
|
206765
207267
|
|
|
206766
207268
|
The mock below is for when there is no live server, or when you need a specific shape on demand - an empty result, a failing query, a tile whose data does not exist yet. The app talks to the world through exactly one seam: \`window.Publisher.query(modelPath, malloy)\`. Mock that seam and you can load the real page in a real browser with canned data, then assert on what actually rendered.
|
|
206767
207269
|
|
|
207270
|
+
|
|
207271
|
+
> **With the data app kit** (\`reference/app-frame.md\`), most of this file is done for you: the kit has no
|
|
207272
|
+
> \`.tile\`, \`.value\` or canvas. Its blocks are \`.block\`, a drawn one has \`data-loaded\`, a failed one holds
|
|
207273
|
+
> \`.state--error\`, and \`body[data-ready="true"]\` is set once every block on the page has drawn. Open each page with
|
|
207274
|
+
> \`?check=1\` for the kit's own banner (no failed block, no \`undefined\`, \`NaN\` or \`null\` on the page). In Playwright:
|
|
207275
|
+
> load, wait for \`.block[data-loaded]\`, read layout shift with the page left still, then scroll to the bottom in
|
|
207276
|
+
> steps and wait for \`body[data-ready="true"]\` before the full-page shot. The sections below are for an app built
|
|
207277
|
+
> without the kit.
|
|
207278
|
+
|
|
206768
207279
|
## 1. Mock \`sdk/publisher.js\` (when there is no live server)
|
|
206769
207280
|
|
|
206770
207281
|
Serve a stand-in at the same root-relative path the page loads (\`/sdk/publisher.js\`). It returns canned rows keyed by \`(modelPath, query)\`, and (this is the part that bites) it reproduces the **async delay** of the real runtime, so your assertions exercise the loading→loaded transition instead of racing a synchronous stub.
|
|
@@ -207003,7 +207514,7 @@ Sections 2 and 3 prove the tiles render. They do not prove the app is polished,
|
|
|
207003
207514
|
|
|
207004
207515
|
**Load it embedded, not only standalone.** Two hosts, in order of effort:
|
|
207005
207516
|
|
|
207006
|
-
- **The Publisher console**, at \`http://localhost:4000/<env>/<package>/data-apps/<path>\` (for example \`.../data-apps/index.html\`). Same origin, no setup, and it sizes the frame through the same resize contract a host does.
|
|
207517
|
+
- **The Publisher console**, at \`http://localhost:4000/<env>/<package>/data-apps/<path>\` (for example \`.../data-apps/index.html\`). Same origin, no setup, and it sizes the frame through the same resize contract a host does. Like most hosts it scrolls a container, so on a lazy page tiles start loading only once they are on screen, unlike the page standalone (\`reference/lazy-load.md\`).
|
|
207007
207518
|
- **A test host page** that calls \`Publisher.embed\` inside a fixed header and a *scrolling container*, which is how real hosts lay out. Serve it from another origin (\`python3 -m http.server 4100 --bind 127.0.0.1\`) and start Publisher with \`PUBLISHER_FRAME_ANCESTORS="'self' http://127.0.0.1:4100"\`, or the browser refuses to frame the app.
|
|
207008
207519
|
|
|
207009
207520
|
Then, per page, embedded and standalone:
|
|
@@ -207055,7 +207566,11 @@ Compare screen coordinates against the host's *visible* area, not against the wi
|
|
|
207055
207566
|
- **Wait out the mock's async delay before asserting.** Asserting immediately after \`load\` reads the skeleton, not the resolved tile, and reports a false "stuck skeleton." Wait until every tile shows its own resolved content (the per-tile \`waitForFunction\` above), never on \`networkidle\`, because \`publisher.js\` keeps the live-reload SSE stream open, so the page never reaches network idle.
|
|
207056
207567
|
- **A missing fixture is a test bug, not empty data.** Reject on an unknown \`(model, query)\` key so a drifted query string fails loudly, instead of returning \`[]\` and masquerading as a real empty state.
|
|
207057
207568
|
- **Assert on the rendered DOM, not on \`Publisher.query\` return values.** The bugs live in the render path (NaN formatting, wrong column read, \`|| 0\` faking a zero). Reading the query result back proves nothing the model didn't already prove.
|
|
207058
|
-
- Match the selectors (\`.tile .value\`, \`.is-error\`, \`.kit-skeleton\`, \`canvas\`) to whatever your app actually emits
|
|
207569
|
+
- Match the selectors (\`.tile .value\`, \`.is-error\`, \`.kit-skeleton\`, \`canvas\`) to whatever your app actually emits.
|
|
207570
|
+
- **Shoot a lazy page with a viewport taller than the view** (1280x6000, 390x12000) and wait for a marker the page sets once every tile has drawn (the kit sets \`body[data-ready="true"]\`; a per-card marker such as its \`data-loaded\` matches as soon as the first card draws). A normal viewport shoots the tiles below the fold as skeletons. This is the opposite of the lazy-load check, which wants a small viewport; do both.
|
|
207571
|
+
- **\`document.fonts.check\` is true when the face is missing.** To prove a font loaded, look for it in \`[...document.fonts]\` with \`status === 'loaded'\`.
|
|
207572
|
+
- **Check a module as a module.** \`node --check app.js\` on a \`.js\` file misses a name declared twice in an ES module, which leaves the page blank; \`node --input-type=module --check < app.js\` catches it.
|
|
207573
|
+
- **An SVG chart has no pixels to read.** For the kit's d3 module, count the marks (\`svg path\`, \`svg rect\`, \`svg circle\`) and read their labels instead of sampling a canvas.`
|
|
207059
207574
|
},
|
|
207060
207575
|
{
|
|
207061
207576
|
name: "malloy-html-data-apps/visual-craft",
|
|
@@ -207144,9 +207659,9 @@ Tables are where density pays. A stat table with generous row height wastes the
|
|
|
207144
207659
|
Every state change the user causes should be acknowledged, and nothing else should move.
|
|
207145
207660
|
|
|
207146
207661
|
- **Hover states on everything interactive**, and they must be visible: a surface shift, not a 2% opacity change nobody perceives. A row that opens a drawer on click must look clickable before the click.
|
|
207147
|
-
- **Transitions belong on state, not on load.** Animating *content* in on first paint delays the thing the reader came for. Animating a drawer open, a filter chip appearing, a sort re-ordering: those are feedback, and they are still right when the state came from the URL on first load.
|
|
207662
|
+
- **Transitions belong on state, not on load.** Animating *content* in on first paint delays the thing the reader came for. Animating a drawer open, a filter chip appearing, a sort re-ordering: those are feedback, and they are still right when the state came from the URL on first load. The kit's chart module eases a chart in on its first draw, briefly, and not at all under reduced motion or \`?motion=0\`.
|
|
207148
207663
|
- **Focus states are not optional and not the browser default.** A keyboard user needs a visible ring drawn from the accent.
|
|
207149
|
-
- Keep it fast. Anything over ~250ms on a UI transition feels sluggish; the contract's \`--dur-fast\` / \`--dur-base\` pair exists so these stay consistent.
|
|
207664
|
+
- Keep it fast. Anything over ~250ms on a UI transition feels sluggish (a mark moving between two answers is not a UI transition: the d3 module takes 380 ms so the eye can follow it, \`reference/charts.md\`); the contract's \`--dur-fast\` / \`--dur-base\` pair exists so these stay consistent.
|
|
207150
207665
|
|
|
207151
207666
|
## 6. Type carries personality
|
|
207152
207667
|
|
|
@@ -207167,7 +207682,7 @@ A data app is a wide layout full of the two things that refuse to shrink: tables
|
|
|
207167
207682
|
|
|
207168
207683
|
The obvious next idea is to compare bounding rects instead, and **that lies too, in exactly the case the fix below creates**. Once you cap a table's container and let it scroll inside itself, the table's own rect is legitimately wider than its container while being visually clipped - so a naive rect comparison reports a collision on every scrollable table on the page. Measured on a real build: false positives at four widths, all of them fine. If you automate this at all, walk the ancestors and ignore overflow inside a **scrollable** box (\`overflow-x: auto | scroll\`), where the content is reachable. Do not extend that to a clipping box (\`hidden\`, \`contain\`): content lost inside one of those is a real bug, and suppressing it is how you stop seeing the thing you were looking for.
|
|
207169
207684
|
|
|
207170
|
-
**The only check that does not lie is rendering at several widths and looking at the screenshots.** Automate the capture, not the judgement.
|
|
207685
|
+
**The only check that does not lie is rendering at several widths and looking at the screenshots.** Automate the capture, not the judgement. Include a phone: one column under 640 px, readable at 390.
|
|
207171
207686
|
|
|
207172
207687
|
Three rules carry most of it:
|
|
207173
207688
|
|
|
@@ -207756,7 +208271,7 @@ The \`publisher_storage_chained_build_total{outcome}\` counter reports the path
|
|
|
207756
208271
|
{
|
|
207757
208272
|
name: "malloy-materialization/refresh",
|
|
207758
208273
|
description: "Keeping a table current: freshness, schedule, incremental refresh. Reference detail for the malloy-materialization skill.",
|
|
207759
|
-
body: '# Keeping a table current: freshness, schedule, incremental refresh\n\nA persisted table is a snapshot. Three declarations govern when it is rebuilt and what a reader gets in the meantime; which of them does anything depends on who drives the builds.\n\n## `freshness`: the objective tier\n\n```malloy\n#@ persist name="daily_orders" freshness.window="24h" freshness.fallback="live"\n```\n\nor package-wide in `publisher.json` under `materialization.freshness`, or per model file with `## materialization.freshness.window="24h"`. The three layers resolve **per field** - source, then model file, then package - so a source that declares only `window` takes its `fallback` from the package. That is how a package-level `stale_ok` silently defeats a window set on one source.\n\n- `window` is how old a table may be before it is stale. `fallback` says what a query over a stale table does: `live` and `fail` both skip the table and compute live (`fail` is reserved to error later; today it behaves as `live`); `stale_ok` keeps serving the stale table.\n- A **hosted control plane** enforces the objective: it refreshes the table to stay within the window and stamps each manifest entry with `dataAsOf` and the window, and the serve path re-checks freshness **per query**, so a table that ages past its window drops out of the serving set whether or not a rebuild ever lands.\n- A **standalone** run stamps the same fields itself: each table it builds carries the declared window and fallback and a `dataAsOf` of the run\'s start (or of an older stored table it was built from), so the serve path ages it exactly as it ages a hosted table. Its next run rebuilds a table past its window instead of carrying it forward; nothing rebuilds it the moment the window passes, so trigger runs yourself (the package `schedule` excludes `freshness`). A window is a positive whole number and a unit (`90s`, `30m`, `24h`, `7d`, `2w`) and a fallback is `live`, `stale_ok` or `fail`; anything else fails the load on every mechanism. A table is never fresher than what it read: a rebuilt windowed table rebuilds a carried upstream of unknown age, and takes an older upstream\'s `dataAsOf`.\n- A **rollup** takes the same keys on `#(rollup)` or `#@ preaggregate`, and otherwise its base\'s own declaration, then the model file\'s and the package\'s, so it goes stale with its base. Measures of one rollup share one freshness; two that disagree, an unknown key in the group, or a window that does not read as above fail the load.\n- Two sources whose bodies compile to the same SQL, with the same `name=` or none, share one table, and a host that folds their policies keeps the tightest window and the bounding fallback for both. If two sources need different windows, give them different SQL or different `name=`s.\n\n## `schedule`: the power tier\n\n```jsonc\n{\n "name": "orders",\n "materialization": { "scope": "version", "schedule": "0 6 * * *" },\n}\n```\n\n- A 5-field UTC cron; `L`, `W`, `#`, `?` are rejected at publish. It **requires `scope: "version"`** and is **mutually exclusive with `freshness`** - including a per-source `freshness.*`.\n- It fires only on a standalone Publisher whose scheduler is enabled with `PUBLISHER_LOCAL_MATERIALIZATION_SCHEDULER`; without that, a schedule is inert. The scheduler sweeps loaded packages, skips one whose policy is invalid or that a control plane manages (`manifestLocation` set), fires at most a bounded number per tick, fires once to catch up after downtime, and skips a fire while a run is already active.\n- **Every scheduled fire is a forced run** (`forceRefresh: true`): every source is rebuilt whether or not its content address changed. A scheduled run therefore never reports reused sources, and a cron that is too frequent shows as build time, not as reuse.\n- `malloy-pub schedule set "<cron>"` writes the schedule and sets `scope: version` in one PATCH; it **replaces the whole `materialization` block**, dropping an existing `freshness` policy (it says so). `schedule clear` removes the cron and leaves `scope: version` in place; moving back to `package` scope is an edit to `publisher.json`. A published version (by default, any package outside a watched environment) refuses both with 409 `PACKAGE_IS_VERSIONED`: set the schedule in its `publisher.json` and publish a new version.\n\n## `refresh="incremental"`: bounded deltas\n\n```malloy\n#@ persist name="daily_orders" refresh="incremental" watermark="order_date"\nsource: daily_orders is orders -> { group_by: order_date; aggregate: revenue is amount.sum() }\n```\n\n- `watermark=` names one of the source\'s own output columns - real, orderable, non-aggregate. Publisher records how far each refresh reached (`covered_through`) and the next recomputes only `[start, frontier)`, half-open, so the frontier value itself is left for the next run. A `date`/`timestamp` watermark takes the run\'s start time as the frontier and **starts at the newest watermark the stored table holds** (one `max()` over the table), so a row stamped after the newest stored row is read however late it loads; it never starts at the previous run\'s start time, which would skip such a row for good. The start is inclusive: a merge or a range replace re-reads the newest stored instant without writing it twice. A numeric or string watermark reads `max(watermark)` from the source as its frontier, and the next range starts there; two refreshes of one with no new rows skip - correct, and it looks like nothing happened.\n- **Without `merge_key=`, a refresh replaces the whole range it re-reads**, from the newest stored row (on a `date` watermark, the whole newest stored day): a stored row the source no longer holds there is removed. A source that drops or trims recent rows (a staging table keeping only the latest day) notices; declare `merge_key=` for append-only behaviour, since a merge never deletes.\n- **Late rows: `lookback="2 days"`.** There is no lookback unless declared. A row stamped _below_ the newest stored row, loaded after it, is below every later delta. `lookback=` starts each delta that much further back (`[newest stored − lookback, frontier)`), and the merge key matches the rows read again. A positive whole number and one unit, `seconds`/`minutes`/`hours`/`days`/`weeks` spelled out or as `s`/`m`/`h`/`d`/`w` (`"36h"`), at most 365 days; no month or year. It needs a `date` or `timestamp` watermark **and** `merge_key=`; anything else fails the load (`persist-invalid` on `#@ persist`, `materialize-invalid` on `#(materialize)`). Size it to how late rows really arrive: each day of lookback is re-read every refresh.\n- **Missed rows are reported.** After each delta, one check counts the source\'s rows in the window just below where the delta started (as wide as the delta\'s own range, capped at 7 days or the lookback, whichever is longer) that the table lacks. Any found are on the manifest entry as `lateRows` (`count`, `from`, `to`) and on the package as a `persist-incremental-late-rows` warning: the served table undercounts. Both are carried, with later findings added, until the source is rebuilt in full. Recover with one `reseed`, then add or widen `lookback=`. The count is a lower bound (a slice is checked once, so a row landing in an already-checked slice is not counted), and the report stays until a full rebuild even after a widened lookback has written the rows. A row older than the window is not seen; pair tables, string watermarks and `storage=` sources on BigQuery are not checked; the check gives up after 60 seconds and never fails the run.\n- **A zoned timestamp watermark (`timestamptz`) in a session time zone other than UTC** (set by the connection\'s setupSQL) reads back with that zone\'s offset, so the source rebuilds in full each refresh, logged at `warn`. A plain `timestamp` or `date` watermark is not affected.\n- **An invalid declaration fails the package load**, not just the publish: `watermark=` without `refresh="incremental"`, `merge_key=` without a watermark, a watermark that names no materialized column or an aggregate, or a `lookback=` that is not a duration, is over 365 days, lacks `merge_key=`, or sits on a number or string watermark (`persist-invalid`; `materialize-invalid` on `#(materialize)`). (A `calculate:` field or an unsupported dialect is valid but refuses the source alone.) Postgres, BigQuery and Snowflake sources only (the dialect that has to express the range); a DuckDB source has to say `refresh="full"`.\n- **`forceRefresh` never re-seeds**; it only defeats skip-if-unchanged, and an incremental source is exempt from that anyway. Ask for a full rebuild with `reseed` (`malloy-pub materialize --reseed`, or per source on the build instruction). Keeping them apart is what lets a schedule drive deltas at all, since every scheduled fire is forced.\n- Each manifest entry reports what the run **did**: `refresh: delta | full | none`, with `ledger.coveredThrough` as the boundary now in force. Every fallback - no recorded boundary, a boundary measured on a different table or watermark, drifted columns, `MERGE` on a Postgres older than 15 - rebuilds in full and succeeds, so a source quietly rebuilding on every run looks exactly like one advancing unless you read `refresh`. The reason codes (`forced`, `no_boundary`, `lineage_changed`, `table_renamed`, `merge_unsupported`, `table_unreadable`, `table_emptied`, `shape_mismatch`, `ledger_unreadable`, `chained_storage`, `merge_key_not_unique`, `upstream_generation_skipped`, `upstream_watermark_differs`, `frontier_unreadable`, `not_advanced`) say why.\n- **An upstream column widened after the build** (INTEGER to BIGINT, REAL to DOUBLE PRECISION) is invisible to Malloy\'s types, so before each delta the delta\'s column types are compared with the stored ones; a stored column that cannot hold the delta\'s values exactly rebuilds the source in full (`shape_mismatch`). Read for a Postgres, DuckDB or MotherDuck database table and a `storage=` table with a Postgres source; BigQuery cannot widen (one integer type, one float type); Snowflake is not checked.\n- **`merge_key=` must be unique in the source.** A merge cannot store two rows under one key, so a delta that reads a key twice is rolled back and the source rebuilt in full (`merge_key_not_unique`; on Snowflake, found by a probe after the delta, which makes the next refresh rebuild), and a rebuilt table that holds a key twice records no boundary, so it is rebuilt in full on every refresh until the key is unique. Both raise a `persist-incremental-merge-key-not-unique` warning naming the source; fix the key (or drop `merge_key=`) and the next rebuild clears it. The warning is held in memory: after a restart it reappears on the next refresh. A key repeated *across* refreshes is not caught: a later delta\'s row replaces the stored one, as a restatement, so a source whose key is not a row\'s identity over time (a log of versions) keeps one row per key where live has several.\n- Two sources that compile to identical SQL, with the same `name=` or none, share one table **and one boundary**; if their incremental declarations differ, neither ever advances. Publisher warns and names both.\n- `storage=` is supported: the warehouse computes the bounded range and the DML lands in the destination. A **chained** stored source always rebuilds in full (`chained_storage`): see `reference/chaining.md`.\n- The boundary lives in the publisher\'s own per-process store. A host that spreads a package\'s refreshes over several workers holds the ledger itself: it stores each entry\'s `ledger` object and sends them back as `buildInstructions.ledger` on the next run. Standalone, the store is the publisher\'s, always.\n\n## Which refresh a gated source needs\n\nA `#(access_filter)`-gated source that is persisted freezes the column its gate filters on, so its "refresh" is also the bound on how long a revoked row keeps being served. Only a freshness window with `fallback: live` on a hosted deployment bounds that; a cron alone does not, and an incremental delta never re-reads a row whose watermark did not move. See `reference/access-filter.md`.'
|
|
208274
|
+
body: '# Keeping a table current: freshness, schedule, incremental refresh\n\nA persisted table is a snapshot. Three declarations govern when it is rebuilt and what a reader gets in the meantime; which of them does anything depends on who drives the builds.\n\n## `freshness`: the objective tier\n\n```malloy\n#@ persist name="daily_orders" freshness.window="24h" freshness.fallback="live"\n```\n\nor package-wide in `publisher.json` under `materialization.freshness`, or per model file with `## materialization.freshness.window="24h"`. The three layers resolve **per field** - source, then model file, then package - so a source that declares only `window` takes its `fallback` from the package. That is how a package-level `stale_ok` silently defeats a window set on one source.\n\n- `window` is how old a table may be before it is stale. `fallback` says what a query over a stale table does: `live` and `fail` both skip the table and compute live (`fail` is reserved to error later; today it behaves as `live`); `stale_ok` keeps serving the stale table.\n- A **hosted control plane** enforces the objective: it refreshes the table to stay within the window and stamps each manifest entry with `dataAsOf` and the window, and the serve path re-checks freshness **per query**, so a table that ages past its window drops out of the serving set whether or not a rebuild ever lands.\n- A **standalone** run stamps the same fields itself: each table it builds carries the declared window and fallback and a `dataAsOf` of the run\'s start (or of an older stored table it was built from), so the serve path ages it exactly as it ages a hosted table. Its next run rebuilds a table past its window instead of carrying it forward; nothing rebuilds it the moment the window passes, so trigger runs yourself (the package `schedule` excludes `freshness`). A window is a positive whole number and a unit (`90s`, `30m`, `24h`, `7d`, `2w`) and a fallback is `live`, `stale_ok` or `fail`; anything else fails the load on every mechanism. A table is never fresher than what it read: a rebuilt windowed table rebuilds a carried upstream of unknown age, and takes an older upstream\'s `dataAsOf`.\n- A **rollup** takes the same keys on `#(rollup)` or `#@ preaggregate`, and otherwise its base\'s own declaration, then the model file\'s and the package\'s, so it goes stale with its base. Measures of one rollup share one freshness; two that disagree, an unknown key in the group, or a window that does not read as above fail the load.\n- Two sources whose bodies compile to the same SQL, with the same `name=` or none, share one table, and a host that folds their policies keeps the tightest window and the bounding fallback for both. If two sources need different windows, give them different SQL or different `name=`s.\n\n## `schedule`: the power tier\n\n```jsonc\n{\n "name": "orders",\n "materialization": { "scope": "version", "schedule": "0 6 * * *" },\n}\n```\n\n- A 5-field UTC cron; `L`, `W`, `#`, `?` are rejected at publish. It **requires `scope: "version"`** and is **mutually exclusive with `freshness`** - including a per-source `freshness.*`.\n- It fires only on a standalone Publisher whose scheduler is enabled with `PUBLISHER_LOCAL_MATERIALIZATION_SCHEDULER`; without that, a schedule is inert. The scheduler sweeps loaded packages, skips one whose policy is invalid or that a control plane manages (`manifestLocation` set), fires at most a bounded number per tick, fires once to catch up after downtime, and skips a fire while a run is already active.\n- **Every scheduled fire is a forced run** (`forceRefresh: true`): every source is rebuilt whether or not its content address changed. A scheduled run therefore never reports reused sources, and a cron that is too frequent shows as build time, not as reuse.\n- `malloy-pub schedule set "<cron>"` writes the schedule and sets `scope: version` in one PATCH; it **replaces the whole `materialization` block**, dropping an existing `freshness` policy (it says so). `schedule clear` removes the cron and leaves `scope: version` in place; moving back to `package` scope is an edit to `publisher.json`. A published version (by default, any package outside a watched environment) refuses both with 409 `PACKAGE_IS_VERSIONED`: set the schedule in its `publisher.json` and publish a new version.\n\n## `refresh="incremental"`: bounded deltas\n\n```malloy\n#@ persist name="daily_orders" refresh="incremental" watermark="order_date"\nsource: daily_orders is orders -> { group_by: order_date; aggregate: revenue is amount.sum() }\n```\n\n- `watermark=` names one of the source\'s own output columns - real, orderable, non-aggregate. Publisher records how far each refresh reached (`covered_through`) and the next recomputes only `[start, frontier)`, half-open, so the frontier value itself is left for the next run. A `date`/`timestamp` watermark takes the run\'s start time as the frontier and **starts at the newest watermark the stored table holds** (one `max()` over the table), so a row stamped after the newest stored row is read however late it loads; it never starts at the previous run\'s start time, which would skip such a row for good. The start is inclusive: a merge or a range replace re-reads the newest stored instant without writing it twice. A numeric or string watermark reads `max(watermark)` from the source as its frontier, and the next range starts there; two refreshes of one with no new rows skip - correct, and it looks like nothing happened.\n- **Without `merge_key=`, a refresh replaces the whole range it re-reads**, from the newest stored row (on a `date` watermark, the whole newest stored day): a stored row the source no longer holds there is removed. A source that drops or trims recent rows (a staging table keeping only the latest day) notices; declare `merge_key=` for append-only behaviour, since a merge never deletes.\n- **Late rows: `lookback="2 days"`.** There is no lookback unless declared. A row stamped _below_ the newest stored row, loaded after it, is below every later delta. `lookback=` starts each delta that much further back (`[newest stored − lookback, frontier)`), and the merge key matches the rows read again. A positive whole number and one unit, `seconds`/`minutes`/`hours`/`days`/`weeks` spelled out or as `s`/`m`/`h`/`d`/`w` (`"36h"`), at most 365 days; no month or year. It needs a `date` or `timestamp` watermark **and** `merge_key=`; anything else fails the load (`persist-invalid` on `#@ persist`, `materialize-invalid` on `#(materialize)`). Size it to how late rows really arrive: each day of lookback is re-read every refresh.\n- **Missed rows are reported.** After each delta, one check counts the source\'s rows in the window just below where the delta started (as wide as the delta\'s own range, capped at 7 days or the lookback, whichever is longer) that the table lacks. Any found are on the manifest entry as `lateRows` (`count`, `from`, `to`) and on the package as a `persist-incremental-late-rows` warning: the served table undercounts. Both are carried, with later findings added, until the source is rebuilt in full. Recover with one `reseed`, then add or widen `lookback=`. The count is a lower bound (a slice is checked once, so a row landing in an already-checked slice is not counted), and the report stays until a full rebuild even after a widened lookback has written the rows. A row older than the window is not seen; pair tables, string watermarks and `storage=` sources on BigQuery are not checked; the check gives up after 60 seconds and never fails the run.\n- **A zoned timestamp watermark (`timestamptz`) in a session time zone other than UTC** (set by the connection\'s setupSQL) reads back with that zone\'s offset, so the source rebuilds in full each refresh, logged at `warn`. A plain `timestamp` or `date` watermark is not affected.\n- **An invalid declaration fails the package load**, not just the publish: `watermark=` without `refresh="incremental"`, `merge_key=` without a watermark, a watermark that names no materialized column or an aggregate, or a `lookback=` that is not a duration, is over 365 days, lacks `merge_key=`, or sits on a number or string watermark (`persist-invalid`; `materialize-invalid` on `#(materialize)`). (A `calculate:` field or an unsupported dialect is valid but refuses the source alone.) Postgres, BigQuery and Snowflake sources only (the dialect that has to express the range); a DuckDB source has to say `refresh="full"`.\n- **`forceRefresh` never re-seeds**; it only defeats skip-if-unchanged, and an incremental source is exempt from that anyway. Ask for a full rebuild with `reseed` (`malloy-pub materialize --reseed`, or per source on the build instruction). Keeping them apart is what lets a schedule drive deltas at all, since every scheduled fire is forced.\n- Each manifest entry reports what the run **did**: `refresh: delta | full | none`, with `ledger.coveredThrough` as the boundary now in force. Every fallback - no recorded boundary, a boundary measured on a different table or watermark, drifted columns, `MERGE` on a Postgres older than 15 - rebuilds in full and succeeds, so a source quietly rebuilding on every run looks exactly like one advancing unless you read `refresh`. The reason codes (`forced`, `no_boundary`, `lineage_changed`, `table_renamed`, `merge_unsupported`, `table_unreadable`, `table_emptied`, `shape_mismatch`, `ledger_unreadable`, `ledger_unheld`, `chained_storage`, `merge_key_not_unique`, `upstream_generation_skipped`, `upstream_watermark_differs`, `frontier_unreadable`, `not_advanced`) say why.\n- **An upstream column widened after the build** (INTEGER to BIGINT, REAL to DOUBLE PRECISION) is invisible to Malloy\'s types, so before each delta the delta\'s column types are compared with the stored ones; a stored column that cannot hold the delta\'s values exactly rebuilds the source in full (`shape_mismatch`). Read for a Postgres, DuckDB or MotherDuck database table and a `storage=` table with a Postgres source; BigQuery cannot widen (one integer type, one float type); Snowflake is not checked.\n- **`merge_key=` must be unique in the source.** A merge cannot store two rows under one key, so a delta that reads a key twice is rolled back and the source rebuilt in full (`merge_key_not_unique`; on Snowflake, found by a probe after the delta, which makes the next refresh rebuild), and a rebuilt table that holds a key twice records no boundary, so it is rebuilt in full on every refresh until the key is unique. Both raise a `persist-incremental-merge-key-not-unique` warning naming the source; fix the key (or drop `merge_key=`) and the next rebuild clears it. The warning is held in memory: after a restart it reappears on the next refresh. A key repeated *across* refreshes is not caught: a later delta\'s row replaces the stored one, as a restatement, so a source whose key is not a row\'s identity over time (a log of versions) keeps one row per key where live has several.\n- Two sources that compile to identical SQL, with the same `name=` or none, share one table **and one boundary**; if their incremental declarations differ, neither ever advances. Publisher warns and names both.\n- `storage=` is supported: the warehouse computes the bounded range and the DML lands in the destination. A **chained** stored source always rebuilds in full (`chained_storage`): see `reference/chaining.md`.\n- The boundary lives in the publisher\'s own per-process store. A host that spreads a package\'s refreshes over several workers holds the ledger itself: it stores each entry\'s `ledger` object and sends them back as `buildInstructions.ledger` on the next run. Standalone, the store is the publisher\'s, always.\n\n## Which refresh a gated source needs\n\nA `#(access_filter)`-gated source that is persisted freezes the column its gate filters on, so its "refresh" is also the bound on how long a revoked row keeps being served. Only a freshness window with `fallback: live` on a hosted deployment bounds that; a cron alone does not, and an incremental delta never re-reads a row whose watermark did not move. See `reference/access-filter.md`.'
|
|
207760
208275
|
},
|
|
207761
208276
|
{
|
|
207762
208277
|
name: "malloy-materialization/storage",
|
|
@@ -212007,7 +212522,7 @@ function compareText(a, b) {
|
|
|
212007
212522
|
// src/service/package_revision.ts
|
|
212008
212523
|
import { createHash as createHash13, randomUUID as randomUUID4 } from "crypto";
|
|
212009
212524
|
import fs14 from "fs";
|
|
212010
|
-
import
|
|
212525
|
+
import path31 from "path";
|
|
212011
212526
|
import { pathToFileURL as pathToFileURL14 } from "url";
|
|
212012
212527
|
function computeSourceContentSha(packagePath, contentPaths, extra, contentShas) {
|
|
212013
212528
|
const hash = createHash13("sha256");
|
|
@@ -212018,7 +212533,7 @@ function computeSourceContentSha(packagePath, contentPaths, extra, contentShas)
|
|
|
212018
212533
|
if (precomputed !== undefined) {
|
|
212019
212534
|
hash.update(`\x00sha256\x00${precomputed}`);
|
|
212020
212535
|
} else {
|
|
212021
|
-
const absolute =
|
|
212536
|
+
const absolute = path31.join(packagePath, relativePath);
|
|
212022
212537
|
try {
|
|
212023
212538
|
hash.update(fs14.readFileSync(confinedPackagePathSync(packagePath, pathToFileURL14(absolute))));
|
|
212024
212539
|
} catch {
|
|
@@ -212058,7 +212573,7 @@ var init_package_revision = __esm(() => {
|
|
|
212058
212573
|
// src/service/skills/package_skills.ts
|
|
212059
212574
|
import { createHash as createHash14 } from "crypto";
|
|
212060
212575
|
import * as fs15 from "fs";
|
|
212061
|
-
import * as
|
|
212576
|
+
import * as path32 from "path";
|
|
212062
212577
|
import { pathToFileURL as pathToFileURL15 } from "url";
|
|
212063
212578
|
function insidePackage(packageRoot, p) {
|
|
212064
212579
|
try {
|
|
@@ -212127,7 +212642,7 @@ function readFileInside(packageRoot, file, maxBytes, asset = false) {
|
|
|
212127
212642
|
}
|
|
212128
212643
|
function referenceFilesInside(packageRoot, skillDir, rel, warnings) {
|
|
212129
212644
|
try {
|
|
212130
|
-
if (insidePackage(packageRoot,
|
|
212645
|
+
if (insidePackage(packageRoot, path32.join(skillDir, "reference")) === undefined) {
|
|
212131
212646
|
warnings.push(`Package skill reference directory '${rel}/reference' resolves outside the package through a link, so it is not served. Fix: copy the files into the package.`);
|
|
212132
212647
|
return [];
|
|
212133
212648
|
}
|
|
@@ -212140,7 +212655,7 @@ function referenceFilesInside(packageRoot, skillDir, rel, warnings) {
|
|
|
212140
212655
|
}
|
|
212141
212656
|
}
|
|
212142
212657
|
function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
212143
|
-
const root =
|
|
212658
|
+
const root = path32.join(packagePath, dirRel);
|
|
212144
212659
|
const skills = [];
|
|
212145
212660
|
const files = [];
|
|
212146
212661
|
const warnings = [];
|
|
@@ -212154,7 +212669,7 @@ function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
|
212154
212669
|
let escapes;
|
|
212155
212670
|
try {
|
|
212156
212671
|
fs15.realpathSync(packagePath);
|
|
212157
|
-
packageRoot =
|
|
212672
|
+
packageRoot = path32.resolve(packagePath);
|
|
212158
212673
|
const inside = insidePackage(packageRoot, root);
|
|
212159
212674
|
escapes = inside === undefined;
|
|
212160
212675
|
if (inside !== undefined) {
|
|
@@ -212175,7 +212690,7 @@ function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
|
212175
212690
|
for (const entry of [...entries].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
|
|
212176
212691
|
if (entry.name.startsWith("."))
|
|
212177
212692
|
continue;
|
|
212178
|
-
const skillDir =
|
|
212693
|
+
const skillDir = path32.join(root, entry.name);
|
|
212179
212694
|
const skillInside = insidePackage(packageRoot, skillDir);
|
|
212180
212695
|
if (skillInside !== undefined) {
|
|
212181
212696
|
try {
|
|
@@ -212186,7 +212701,7 @@ function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
|
212186
212701
|
}
|
|
212187
212702
|
}
|
|
212188
212703
|
const rel = `${dirRel}/${entry.name}`;
|
|
212189
|
-
const read = readFileInside(packageRoot,
|
|
212704
|
+
const read = readFileInside(packageRoot, path32.join(skillDir, "SKILL.md"), PACKAGE_SKILL_FILE_MAX_BYTES);
|
|
212190
212705
|
if ("problem" in read) {
|
|
212191
212706
|
unserved(`Package skill '${rel}/SKILL.md' ${read.problem}, so it is not served. Fix: add a readable SKILL.md inside the package, or remove the directory.`);
|
|
212192
212707
|
continue;
|
|
@@ -212204,7 +212719,7 @@ function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
|
212204
212719
|
const served = [];
|
|
212205
212720
|
for (const file of referenceFilesInside(packageRoot, skillDir, rel, warnings)) {
|
|
212206
212721
|
const relative = `${rel}/reference/${file}`;
|
|
212207
|
-
const ref = readFileInside(packageRoot,
|
|
212722
|
+
const ref = readFileInside(packageRoot, path32.join(skillDir, "reference", file), PACKAGE_SKILL_FILE_MAX_BYTES);
|
|
212208
212723
|
if ("problem" in ref) {
|
|
212209
212724
|
warnings.push(`Package skill reference '${relative}' ${ref.problem}, so it is not served.`);
|
|
212210
212725
|
continue;
|
|
@@ -212227,13 +212742,13 @@ function agentPath(value, what) {
|
|
|
212227
212742
|
if (typeof value !== "string" || value === "" || value.includes("\x00")) {
|
|
212228
212743
|
throw new AgentProblem(`${what} must be a non-empty package-relative path`);
|
|
212229
212744
|
}
|
|
212230
|
-
if (
|
|
212745
|
+
if (path32.posix.isAbsolute(value) || path32.win32.isAbsolute(value)) {
|
|
212231
212746
|
throw new AgentProblem(`${what} '${value}' is an absolute path`);
|
|
212232
212747
|
}
|
|
212233
212748
|
if (value.includes("\\")) {
|
|
212234
212749
|
throw new AgentProblem(`${what} '${value}' contains a backslash; write it with forward slashes`);
|
|
212235
212750
|
}
|
|
212236
|
-
const normalized =
|
|
212751
|
+
const normalized = path32.posix.normalize(value).replace(/\/+$/, "");
|
|
212237
212752
|
if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
|
|
212238
212753
|
throw new AgentProblem(`${what} '${value}' is outside the package`);
|
|
212239
212754
|
}
|
|
@@ -212256,7 +212771,7 @@ function servedTreeHoldsManifest(packageRoot, root) {
|
|
|
212256
212771
|
const inside = insidePackage(packageRoot, root);
|
|
212257
212772
|
if (inside === undefined)
|
|
212258
212773
|
return false;
|
|
212259
|
-
return fs15.readdirSync(inside, { withFileTypes: true }).some((e) => (e.isDirectory() || e.isSymbolicLink()) && (holdsManifest(packageRoot,
|
|
212774
|
+
return fs15.readdirSync(inside, { withFileTypes: true }).some((e) => (e.isDirectory() || e.isSymbolicLink()) && (holdsManifest(packageRoot, path32.join(root, e.name)) || holdsManifest(packageRoot, path32.join(root, e.name, "reference"))));
|
|
212260
212775
|
} catch {
|
|
212261
212776
|
return false;
|
|
212262
212777
|
}
|
|
@@ -212266,12 +212781,12 @@ function readAgentText(packagePath, packageRoot, value, what) {
|
|
|
212266
212781
|
if (!rel.toLowerCase().endsWith(".md")) {
|
|
212267
212782
|
throw new AgentProblem(`${what} '${rel}' is not a .md file`);
|
|
212268
212783
|
}
|
|
212269
|
-
for (let dir =
|
|
212270
|
-
if (holdsManifest(packageRoot,
|
|
212784
|
+
for (let dir = path32.posix.dirname(rel);dir !== "."; dir = path32.posix.dirname(dir)) {
|
|
212785
|
+
if (holdsManifest(packageRoot, path32.join(packagePath, dir))) {
|
|
212271
212786
|
throw new AgentProblem(`${what} '${rel}' sits under a nested publisher.json at '${dir}'`);
|
|
212272
212787
|
}
|
|
212273
212788
|
}
|
|
212274
|
-
const read = readFileInside(packageRoot,
|
|
212789
|
+
const read = readFileInside(packageRoot, path32.join(packagePath, rel), PACKAGE_AGENT_TEXT_MAX_BYTES);
|
|
212275
212790
|
if ("problem" in read) {
|
|
212276
212791
|
throw new AgentProblem(`${what} '${rel}' ${read.problem}`);
|
|
212277
212792
|
}
|
|
@@ -212330,7 +212845,7 @@ function readAgentBudget(raw) {
|
|
|
212330
212845
|
return Object.keys(budget).length > 0 ? budget : undefined;
|
|
212331
212846
|
}
|
|
212332
212847
|
function realAssetsDir(packageRoot, skillDir, skillRel) {
|
|
212333
|
-
const assetsDir =
|
|
212848
|
+
const assetsDir = path32.join(skillDir, "assets");
|
|
212334
212849
|
const realSkillDir = insidePackage(packageRoot, skillDir);
|
|
212335
212850
|
if (realSkillDir === undefined) {
|
|
212336
212851
|
throw new AgentProblem(`'${skillRel}' resolves outside the package`);
|
|
@@ -212339,13 +212854,13 @@ function realAssetsDir(packageRoot, skillDir, skillRel) {
|
|
|
212339
212854
|
throw new AgentProblem(`'${skillRel}/assets' is a link; replace it with a real directory`);
|
|
212340
212855
|
}
|
|
212341
212856
|
const real = fs15.realpathSync(assetsDir);
|
|
212342
|
-
if (real !==
|
|
212857
|
+
if (real !== path32.join(realSkillDir, "assets")) {
|
|
212343
212858
|
throw new AgentProblem(`'${skillRel}/assets' resolves outside the skill's own directory`);
|
|
212344
212859
|
}
|
|
212345
212860
|
return assetsDir;
|
|
212346
212861
|
}
|
|
212347
212862
|
function assetFilesInside(packageRoot, skillDir, skillRel, skill, budget, walk) {
|
|
212348
|
-
const assetsDir =
|
|
212863
|
+
const assetsDir = path32.join(skillDir, "assets");
|
|
212349
212864
|
let link;
|
|
212350
212865
|
try {
|
|
212351
212866
|
link = fs15.lstatSync(assetsDir);
|
|
@@ -212409,7 +212924,7 @@ function assetFilesInside(packageRoot, skillDir, skillRel, skill, budget, walk)
|
|
|
212409
212924
|
skip(shown, `its path is over ${ASSET_PATH_MAX_CHARS} characters`);
|
|
212410
212925
|
continue;
|
|
212411
212926
|
}
|
|
212412
|
-
const absolute =
|
|
212927
|
+
const absolute = path32.join(dir, entry.name);
|
|
212413
212928
|
if (entry.isDirectory()) {
|
|
212414
212929
|
if (depth >= ASSET_MAX_DEPTH) {
|
|
212415
212930
|
skip(shown, `it is nested deeper than ${ASSET_MAX_DEPTH} levels`);
|
|
@@ -212481,8 +212996,8 @@ function readAgentAsset(packagePath, agent, relativeFilepath) {
|
|
|
212481
212996
|
if (skillRel === undefined || !listing)
|
|
212482
212997
|
return;
|
|
212483
212998
|
try {
|
|
212484
|
-
const skillDir =
|
|
212485
|
-
const read = readFileInside(realAssetsDir(packagePath, skillDir, skillRel),
|
|
212999
|
+
const skillDir = path32.join(packagePath, skillRel);
|
|
213000
|
+
const read = readFileInside(realAssetsDir(packagePath, skillDir, skillRel), path32.join(skillDir, relativeFilepath.slice(skill.length)), PACKAGE_ASSET_FILE_MAX_BYTES - 1, true);
|
|
212486
213001
|
if (!("text" in read))
|
|
212487
213002
|
return;
|
|
212488
213003
|
return createHash14("sha256").update(read.text).digest("hex") === listing.sha256 ? read.text : undefined;
|
|
@@ -212511,7 +213026,7 @@ function readAgentSkills(packagePath, packageRoot, raw, paths, warnings, assetBu
|
|
|
212511
213026
|
};
|
|
212512
213027
|
let bytes = 0;
|
|
212513
213028
|
for (const root of roots) {
|
|
212514
|
-
const rootInside = insidePackage(packageRoot,
|
|
213029
|
+
const rootInside = insidePackage(packageRoot, path32.join(packagePath, root));
|
|
212515
213030
|
if (rootInside === undefined) {
|
|
212516
213031
|
throw new AgentProblem(`skills directory '${root}' resolves outside the package`);
|
|
212517
213032
|
}
|
|
@@ -212522,8 +213037,8 @@ function readAgentSkills(packagePath, packageRoot, raw, paths, warnings, assetBu
|
|
|
212522
213037
|
} catch {
|
|
212523
213038
|
throw new AgentProblem(`skills directory '${root}' does not exist`);
|
|
212524
213039
|
}
|
|
212525
|
-
for (let dir = root;dir !== "."; dir =
|
|
212526
|
-
const holds = dir === root ? servedTreeHoldsManifest(packageRoot,
|
|
213040
|
+
for (let dir = root;dir !== "."; dir = path32.posix.dirname(dir)) {
|
|
213041
|
+
const holds = dir === root ? servedTreeHoldsManifest(packageRoot, path32.join(packagePath, dir)) : holdsManifest(packageRoot, path32.join(packagePath, dir));
|
|
212527
213042
|
if (holds) {
|
|
212528
213043
|
throw new AgentProblem(`skills directory '${root}' contains a nested publisher.json`);
|
|
212529
213044
|
}
|
|
@@ -212562,7 +213077,7 @@ function readAgentSkills(packagePath, packageRoot, raw, paths, warnings, assetBu
|
|
|
212562
213077
|
}
|
|
212563
213078
|
for (const skill of skillNames) {
|
|
212564
213079
|
const skillRel = `${root}/${skill}`;
|
|
212565
|
-
const listed = assetFilesInside(packageRoot,
|
|
213080
|
+
const listed = assetFilesInside(packageRoot, path32.join(packagePath, skillRel), skillRel, skill, assetBudget, walk);
|
|
212566
213081
|
for (const asset of listed) {
|
|
212567
213082
|
assets.set(asset.relative_filepath, asset);
|
|
212568
213083
|
assetRoots.set(skill, skillRel);
|
|
@@ -212676,7 +213191,7 @@ function readPackageAgents(packagePath, raw) {
|
|
|
212676
213191
|
let packageRoot;
|
|
212677
213192
|
try {
|
|
212678
213193
|
fs15.realpathSync(packagePath);
|
|
212679
|
-
packageRoot =
|
|
213194
|
+
packageRoot = path32.resolve(packagePath);
|
|
212680
213195
|
} catch {
|
|
212681
213196
|
return result;
|
|
212682
213197
|
}
|
|
@@ -214628,7 +215143,7 @@ var init_esm2 = __esm(() => {
|
|
|
214628
215143
|
// src/service/configured_publish_retry.ts
|
|
214629
215144
|
import { createHash as createHash15 } from "crypto";
|
|
214630
215145
|
import * as fs16 from "fs";
|
|
214631
|
-
import * as
|
|
215146
|
+
import * as path33 from "path";
|
|
214632
215147
|
function backoffAfter(failures) {
|
|
214633
215148
|
if (failures <= 0)
|
|
214634
215149
|
return 0;
|
|
@@ -214639,13 +215154,13 @@ async function localPackageFingerprint(root) {
|
|
|
214639
215154
|
const walk = async (dir) => {
|
|
214640
215155
|
const entries = await fs16.promises.readdir(dir, { withFileTypes: true });
|
|
214641
215156
|
for (const entry of entries) {
|
|
214642
|
-
const full =
|
|
215157
|
+
const full = path33.join(dir, entry.name);
|
|
214643
215158
|
if (entry.isDirectory()) {
|
|
214644
215159
|
if (!SKIPPED_DIRS.has(entry.name))
|
|
214645
215160
|
await walk(full);
|
|
214646
215161
|
} else if (entry.isFile() && FINGERPRINTED.test(entry.name)) {
|
|
214647
215162
|
const stat = await fs16.promises.stat(full);
|
|
214648
|
-
lines.push(`${
|
|
215163
|
+
lines.push(`${path33.relative(root, full)}\x00${stat.size}\x00${stat.mtimeMs}`);
|
|
214649
215164
|
}
|
|
214650
215165
|
}
|
|
214651
215166
|
};
|
|
@@ -367211,7 +367726,7 @@ var init_internal_types = () => {};
|
|
|
367211
367726
|
// src/service/entities/model_text.ts
|
|
367212
367727
|
import fs18 from "fs";
|
|
367213
367728
|
import { AsyncLocalStorage as AsyncLocalStorage7 } from "node:async_hooks";
|
|
367214
|
-
import { fileURLToPath as
|
|
367729
|
+
import { fileURLToPath as fileURLToPath13, pathToFileURL as pathToFileURL16 } from "url";
|
|
367215
367730
|
function withModelTextCache(fn, texts = new Map, packageRoot) {
|
|
367216
367731
|
const lines = new Map;
|
|
367217
367732
|
for (const [filePath, text] of texts)
|
|
@@ -367234,7 +367749,7 @@ function modelCode(url) {
|
|
|
367234
367749
|
let filePath;
|
|
367235
367750
|
let lines;
|
|
367236
367751
|
try {
|
|
367237
|
-
filePath =
|
|
367752
|
+
filePath = fileURLToPath13(url);
|
|
367238
367753
|
lines = readModelLines(filePath);
|
|
367239
367754
|
} catch {
|
|
367240
367755
|
return;
|
|
@@ -367292,7 +367807,7 @@ function extractCodeFromEntity(entity, docString) {
|
|
|
367292
367807
|
let lines;
|
|
367293
367808
|
const locationUrl = entity.location?.url;
|
|
367294
367809
|
if (locationUrl && !locationUrl.endsWith("internal.malloy")) {
|
|
367295
|
-
const filePath =
|
|
367810
|
+
const filePath = fileURLToPath13(locationUrl);
|
|
367296
367811
|
try {
|
|
367297
367812
|
lines = readModelLines(filePath);
|
|
367298
367813
|
} catch (error) {
|
|
@@ -368105,8 +368620,8 @@ var init_dim_index_entity_id = __esm(() => {
|
|
|
368105
368620
|
});
|
|
368106
368621
|
|
|
368107
368622
|
// src/service/entities/source_extraction.ts
|
|
368108
|
-
import
|
|
368109
|
-
import { fileURLToPath as
|
|
368623
|
+
import path34 from "path";
|
|
368624
|
+
import { fileURLToPath as fileURLToPath14 } from "url";
|
|
368110
368625
|
function buildSourceToModelPathMap(explores, relpath, packageRoot) {
|
|
368111
368626
|
const sourceToModelPath = new Map;
|
|
368112
368627
|
for (const explore of explores) {
|
|
@@ -368116,11 +368631,11 @@ function buildSourceToModelPathMap(explores, relpath, packageRoot) {
|
|
|
368116
368631
|
if (url.endsWith("internal.malloy")) {
|
|
368117
368632
|
modelPath = relpath;
|
|
368118
368633
|
} else if (url.startsWith("file://")) {
|
|
368119
|
-
const fullPath =
|
|
368634
|
+
const fullPath = fileURLToPath14(url);
|
|
368120
368635
|
if (fullPath.startsWith(packageRoot)) {
|
|
368121
368636
|
modelPath = fullPath.slice(packageRoot.length).replace(/^[/\\]/, "");
|
|
368122
368637
|
} else {
|
|
368123
|
-
modelPath =
|
|
368638
|
+
modelPath = path34.basename(fullPath);
|
|
368124
368639
|
}
|
|
368125
368640
|
} else {
|
|
368126
368641
|
modelPath = url;
|
|
@@ -369373,7 +369888,7 @@ var init_error_wire = __esm(() => {
|
|
|
369373
369888
|
// src/package_load/package_load_pool.ts
|
|
369374
369889
|
import { Worker } from "node:worker_threads";
|
|
369375
369890
|
import { dirname as dirname11, join as join17 } from "path";
|
|
369376
|
-
import { fileURLToPath as
|
|
369891
|
+
import { fileURLToPath as fileURLToPath15, pathToFileURL as pathToFileURL17 } from "url";
|
|
369377
369892
|
import { sqlKey } from "@malloydata/malloy";
|
|
369378
369893
|
function getPackageLoadWorkerCount() {
|
|
369379
369894
|
return settings.get("packageLoad.workers");
|
|
@@ -369391,7 +369906,7 @@ function nextQueuedJobIndex(queue, now = Date.now(), maxBackgroundWaitMs = BACKG
|
|
|
369391
369906
|
return foreground >= 0 ? foreground : 0;
|
|
369392
369907
|
}
|
|
369393
369908
|
function resolveWorkerScript() {
|
|
369394
|
-
const thisFile =
|
|
369909
|
+
const thisFile = fileURLToPath15(import.meta.url);
|
|
369395
369910
|
const thisDir = dirname11(thisFile);
|
|
369396
369911
|
const distCandidate = join17(thisDir, "package_load_worker.mjs");
|
|
369397
369912
|
if (thisFile.endsWith(".mjs") || thisFile.endsWith(".js")) {
|
|
@@ -370086,7 +370601,7 @@ var init_package_load_pool = __esm(() => {
|
|
|
370086
370601
|
// src/service/package_retrieval_settings.ts
|
|
370087
370602
|
import { createHash as createHash17 } from "crypto";
|
|
370088
370603
|
import * as fs19 from "fs";
|
|
370089
|
-
import * as
|
|
370604
|
+
import * as path35 from "path";
|
|
370090
370605
|
import { pathToFileURL as pathToFileURL18 } from "url";
|
|
370091
370606
|
function alsoLikelyOn(settings) {
|
|
370092
370607
|
return settings.alsoLikely === "auto" ? settings.connect === "list" : settings.alsoLikely;
|
|
@@ -370106,12 +370621,12 @@ function describe3(value) {
|
|
|
370106
370621
|
function resolvePromptPath(packageRoot, rel, promptKey = "judge") {
|
|
370107
370622
|
const key = `retrieval.prompts.${promptKey}`;
|
|
370108
370623
|
const fix = `Fix: use a path inside the package, e.g. "prompts/${promptKey}.md".`;
|
|
370109
|
-
if (rel.includes("\x00") ||
|
|
370624
|
+
if (rel.includes("\x00") || path35.isAbsolute(rel) || /^[A-Za-z]:[\\/]/.test(rel) || rel.startsWith("\\")) {
|
|
370110
370625
|
fail(`Invalid publisher.json ${key}: ${describe3(rel)} is an absolute path. ${fix}`);
|
|
370111
370626
|
}
|
|
370112
|
-
const root =
|
|
370113
|
-
const resolved =
|
|
370114
|
-
const within =
|
|
370627
|
+
const root = path35.resolve(packageRoot);
|
|
370628
|
+
const resolved = path35.resolve(root, rel);
|
|
370629
|
+
const within = path35.relative(root, resolved);
|
|
370115
370630
|
if (within === "" || stepsOutside(within)) {
|
|
370116
370631
|
fail(`Invalid publisher.json ${key}: ${describe3(rel)} resolves outside the package directory. ${fix}`);
|
|
370117
370632
|
}
|
|
@@ -370392,7 +370907,7 @@ var init_package_retrieval_settings = __esm(() => {
|
|
|
370392
370907
|
questions: "auto",
|
|
370393
370908
|
docParts: "auto",
|
|
370394
370909
|
values: true,
|
|
370395
|
-
valueCap:
|
|
370910
|
+
valueCap: 5000,
|
|
370396
370911
|
valueEmbeddings: true,
|
|
370397
370912
|
judge: "auto",
|
|
370398
370913
|
contenderShare: 0,
|
|
@@ -371526,11 +372041,11 @@ class VariantCompileCache {
|
|
|
371526
372041
|
var DEFAULT_LIMIT = 500;
|
|
371527
372042
|
|
|
371528
372043
|
// src/service/materialization/serve/author_imports.ts
|
|
371529
|
-
import * as
|
|
371530
|
-
import { fileURLToPath as
|
|
372044
|
+
import * as path36 from "path";
|
|
372045
|
+
import { fileURLToPath as fileURLToPath16 } from "url";
|
|
371531
372046
|
function relativeImport(from, url) {
|
|
371532
372047
|
try {
|
|
371533
|
-
return
|
|
372048
|
+
return path36.relative(path36.dirname(fileURLToPath16(from)), fileURLToPath16(url)).split(path36.sep).join("/");
|
|
371534
372049
|
} catch {
|
|
371535
372050
|
return;
|
|
371536
372051
|
}
|
|
@@ -371583,15 +372098,15 @@ var init_author_imports = __esm(() => {
|
|
|
371583
372098
|
});
|
|
371584
372099
|
|
|
371585
372100
|
// src/service/materialization/serve/declaring_file_variant.ts
|
|
371586
|
-
import * as
|
|
371587
|
-
import { fileURLToPath as
|
|
372101
|
+
import * as path37 from "path";
|
|
372102
|
+
import { fileURLToPath as fileURLToPath17, pathToFileURL as pathToFileURL19 } from "url";
|
|
371588
372103
|
async function compileDeclaringFileVariant(args) {
|
|
371589
372104
|
const { packagePath, modelPath, packageConfig, modelDef } = args;
|
|
371590
372105
|
const declared = args.sourceID !== undefined ? declaringFileOf2(args.sourceID, args.copySuffix) : args.declaringURL !== undefined ? declaringFileAt("", args.declaringURL, args.copySuffix) : { error: "no declaring file" };
|
|
371591
372106
|
if ("error" in declared)
|
|
371592
372107
|
return declared;
|
|
371593
372108
|
const { declaringURL, copyURL, copyName } = declared;
|
|
371594
|
-
const modelFile =
|
|
372109
|
+
const modelFile = path37.join(packagePath, modelPath);
|
|
371595
372110
|
const authorFiles = packageFiles(packagePath, modelPath, args.basis ? args.config : packageConfig);
|
|
371596
372111
|
const blanked = args.basis ? new Map(args.basis.files) : await authorFiles.blanked(modelDef);
|
|
371597
372112
|
if (!blanked)
|
|
@@ -371686,13 +372201,13 @@ function declaringFileOf2(sourceID, copySuffix) {
|
|
|
371686
372201
|
function declaringFileAt(name, url, copySuffix) {
|
|
371687
372202
|
let declaringFile;
|
|
371688
372203
|
try {
|
|
371689
|
-
declaringFile =
|
|
372204
|
+
declaringFile = fileURLToPath17(url);
|
|
371690
372205
|
} catch {
|
|
371691
372206
|
return { error: "not a local file" };
|
|
371692
372207
|
}
|
|
371693
372208
|
const declaringURL = pathToFileURL19(declaringFile);
|
|
371694
372209
|
const copyURL = pathToFileURL19(`${declaringFile}${copySuffix}`);
|
|
371695
|
-
const copyName =
|
|
372210
|
+
const copyName = path37.basename(fileURLToPath17(copyURL));
|
|
371696
372211
|
return { name, declaringURL, copyURL, copyName };
|
|
371697
372212
|
}
|
|
371698
372213
|
async function namesDeclaredIn(files, overlay, url) {
|
|
@@ -371822,8 +372337,8 @@ var init_stored_typed_source = __esm(() => {
|
|
|
371822
372337
|
});
|
|
371823
372338
|
|
|
371824
372339
|
// src/service/materialization/serve/view_variants.ts
|
|
371825
|
-
import * as
|
|
371826
|
-
import { fileURLToPath as
|
|
372340
|
+
import * as path38 from "path";
|
|
372341
|
+
import { fileURLToPath as fileURLToPath18, pathToFileURL as pathToFileURL20 } from "url";
|
|
371827
372342
|
|
|
371828
372343
|
class PersistedViewServe {
|
|
371829
372344
|
host;
|
|
@@ -372106,7 +372621,7 @@ async function compilePersistedResultVariant(args) {
|
|
|
372106
372621
|
return { refusal: read.refusal };
|
|
372107
372622
|
const sourceTimezone = shape.sourceTimezone ? `
|
|
372108
372623
|
timezone: ${stringLiteral(shape.sourceTimezone)}` : "";
|
|
372109
|
-
const modelFile =
|
|
372624
|
+
const modelFile = path38.join(packagePath, args.modelPath);
|
|
372110
372625
|
const config = table.binding && !isDatabase(table.binding) && args.destinations ? servedCopyConfig(packageConfig, args.destinations(), new Set([table.binding.destinationName])) : packageConfig;
|
|
372111
372626
|
return compileDeclaringFileVariant({
|
|
372112
372627
|
packagePath,
|
|
@@ -372149,7 +372664,7 @@ async function compilePersistedResultVariant(args) {
|
|
|
372149
372664
|
sourceTimezone,
|
|
372150
372665
|
stored: {
|
|
372151
372666
|
name,
|
|
372152
|
-
importLine: `import { ${identifier(name)} is ${identifier(plan.buildSourceName)} } from ${doubleQuotedString(
|
|
372667
|
+
importLine: `import { ${identifier(name)} is ${identifier(plan.buildSourceName)} } from ${doubleQuotedString(path38.basename(fileURLToPath18(companion)))}`
|
|
372153
372668
|
}
|
|
372154
372669
|
});
|
|
372155
372670
|
}
|
|
@@ -374092,7 +374607,7 @@ function outputName(f) {
|
|
|
374092
374607
|
function findField(s, name) {
|
|
374093
374608
|
return fieldsOf4(s).find((f) => outputName(f) === name);
|
|
374094
374609
|
}
|
|
374095
|
-
function
|
|
374610
|
+
function resolve18(scope, path) {
|
|
374096
374611
|
if (path.length === 0 || typeof path[0] !== "string")
|
|
374097
374612
|
return;
|
|
374098
374613
|
let owner = scope.extend && findField(scope.extend, path[0]) ? scope.extend : scope.struct;
|
|
@@ -374134,7 +374649,7 @@ function isFloat4Expr(e, scope, ctx, depth) {
|
|
|
374134
374649
|
return true;
|
|
374135
374650
|
}
|
|
374136
374651
|
}
|
|
374137
|
-
const hit =
|
|
374652
|
+
const hit = resolve18(scope, node.path);
|
|
374138
374653
|
if (!hit)
|
|
374139
374654
|
return false;
|
|
374140
374655
|
if (isFloat4Column(hit.field, hit.owner, ctx.float4))
|
|
@@ -376248,7 +376763,7 @@ function admits(node, ctx, depth) {
|
|
|
376248
376763
|
ctx.unresolvable = true;
|
|
376249
376764
|
return false;
|
|
376250
376765
|
}
|
|
376251
|
-
const value =
|
|
376766
|
+
const value = resolve19(pair.given, ctx);
|
|
376252
376767
|
if (typeof value !== "string") {
|
|
376253
376768
|
ctx.unresolvable = true;
|
|
376254
376769
|
return false;
|
|
@@ -376264,7 +376779,7 @@ function admits(node, ctx, depth) {
|
|
|
376264
376779
|
ctx.unresolvable = true;
|
|
376265
376780
|
return false;
|
|
376266
376781
|
}
|
|
376267
|
-
const value =
|
|
376782
|
+
const value = resolve19(given, ctx);
|
|
376268
376783
|
if (!Array.isArray(value)) {
|
|
376269
376784
|
ctx.unresolvable = true;
|
|
376270
376785
|
return false;
|
|
@@ -376297,7 +376812,7 @@ function asStringLiteral(node) {
|
|
|
376297
376812
|
return;
|
|
376298
376813
|
return typeof n.literal === "string" ? n.literal : undefined;
|
|
376299
376814
|
}
|
|
376300
|
-
function
|
|
376815
|
+
function resolve19(given, ctx) {
|
|
376301
376816
|
if (typeof given.id !== "string") {
|
|
376302
376817
|
ctx.unresolvable = true;
|
|
376303
376818
|
return;
|
|
@@ -378059,8 +378574,8 @@ var init_join_rollup = __esm(() => {
|
|
|
378059
378574
|
});
|
|
378060
378575
|
|
|
378061
378576
|
// src/service/materialization/serve/rollup_variants.ts
|
|
378062
|
-
import * as
|
|
378063
|
-
import { fileURLToPath as
|
|
378577
|
+
import * as path39 from "path";
|
|
378578
|
+
import { fileURLToPath as fileURLToPath19, pathToFileURL as pathToFileURL21 } from "url";
|
|
378064
378579
|
import { EMPTY_BUILD_MANIFEST as EMPTY_BUILD_MANIFEST4 } from "@malloydata/malloy";
|
|
378065
378580
|
|
|
378066
378581
|
class RollupVariantServe {
|
|
@@ -378864,7 +379379,7 @@ class RollupVariantServe {
|
|
|
378864
379379
|
if (!packagePath || !packageConfig)
|
|
378865
379380
|
return { error: "no context" };
|
|
378866
379381
|
const modelPath = this.host.modelPath();
|
|
378867
|
-
const modelFile =
|
|
379382
|
+
const modelFile = path39.join(packagePath, modelPath);
|
|
378868
379383
|
const queryModelURL = pathToFileURL21(`${modelFile}.rollup.malloy`);
|
|
378869
379384
|
const reads = table.binding ? storedRollupReads(plan, table.binding, this.host.modelDef(), declaredRollupColumns(this.host.catalog(), table.binding)) : undefined;
|
|
378870
379385
|
const destinations = this.host.serveDestinationConfig();
|
|
@@ -378908,11 +379423,11 @@ class RollupVariantServe {
|
|
|
378908
379423
|
const companion = declared ? rollupCompanionURLOf(declared.url) : undefined;
|
|
378909
379424
|
let declaringFile;
|
|
378910
379425
|
try {
|
|
378911
|
-
declaringFile = declared ?
|
|
379426
|
+
declaringFile = declared ? fileURLToPath19(declared.url) : undefined;
|
|
378912
379427
|
} catch {
|
|
378913
379428
|
declaringFile = undefined;
|
|
378914
379429
|
}
|
|
378915
|
-
const text = companion && declaringFile ? generateRollupBuildFile([plan],
|
|
379430
|
+
const text = companion && declaringFile ? generateRollupBuildFile([plan], path39.basename(declaringFile)) : undefined;
|
|
378916
379431
|
if (!companion || !text || !declaringFile) {
|
|
378917
379432
|
return { error: "no companion" };
|
|
378918
379433
|
}
|
|
@@ -378927,7 +379442,7 @@ class RollupVariantServe {
|
|
|
378927
379442
|
const made = rollupBuildCopyText(blanked.get(overlayKey(baseURL)) ?? await authorFiles.readIfAny(baseURL.href) ?? "", plan, (plan.privateGrain ?? []).length > 0);
|
|
378928
379443
|
if (!("copy" in made))
|
|
378929
379444
|
return { error: made.reason };
|
|
378930
|
-
overlay.set(pathToFileURL21(
|
|
379445
|
+
overlay.set(pathToFileURL21(path39.join(path39.dirname(declaringFile), rollupBuildCopyName(path39.basename(declaringFile), plan.baseDeclaredName))).href, made.copy);
|
|
378931
379446
|
}
|
|
378932
379447
|
const read = withoutLeftOut(plan, this.host.modelDef(), table.leftOut);
|
|
378933
379448
|
const declaration = `${databaseRollupSource(read.plan, this.host.modelDef(), servedName, relativeImport(queryModelURL, companion.href), read.dropped)}
|
|
@@ -379047,14 +379562,14 @@ ${gates}${over}`;
|
|
|
379047
379562
|
}
|
|
379048
379563
|
let baseFile;
|
|
379049
379564
|
try {
|
|
379050
|
-
baseFile = base ?
|
|
379565
|
+
baseFile = base ? fileURLToPath19(base.url) : undefined;
|
|
379051
379566
|
} catch {
|
|
379052
379567
|
baseFile = undefined;
|
|
379053
379568
|
}
|
|
379054
379569
|
if (!companion || !baseFile)
|
|
379055
379570
|
return { error: "no companion" };
|
|
379056
379571
|
const overlaid = overlayKey(pathToFileURL21(baseFile)) === overlayKey(declaringURL);
|
|
379057
|
-
const importPath = overlaid ? copyName :
|
|
379572
|
+
const importPath = overlaid ? copyName : path39.basename(baseFile);
|
|
379058
379573
|
const text = generateRollupBuildFile([plan], importPath);
|
|
379059
379574
|
if (!text)
|
|
379060
379575
|
return { error: "no companion" };
|
|
@@ -379063,7 +379578,7 @@ ${gates}${over}`;
|
|
|
379063
379578
|
const made = rollupBuildCopyText(await authorText(pathToFileURL21(baseFile)) ?? "", plan, (plan.privateGrain ?? []).length > 0);
|
|
379064
379579
|
if (!("copy" in made))
|
|
379065
379580
|
return { error: made.reason };
|
|
379066
|
-
addFile(pathToFileURL21(
|
|
379581
|
+
addFile(pathToFileURL21(path39.join(path39.dirname(baseFile), rollupBuildCopyName(importPath, plan.baseDeclaredName))), made.copy);
|
|
379067
379582
|
}
|
|
379068
379583
|
return `${databaseRollupSource(read.plan, modelDef, servedName, relativeImport(declaringURL, companion.href), read.dropped)}
|
|
379069
379584
|
${gates}${over}`;
|
|
@@ -379095,14 +379610,14 @@ async function databaseRollupInOverlay(plan, read, modelDef, ctx) {
|
|
|
379095
379610
|
const companion = base ? rollupCompanionURLOf(base.url) : undefined;
|
|
379096
379611
|
let baseFile;
|
|
379097
379612
|
try {
|
|
379098
|
-
baseFile = base ?
|
|
379613
|
+
baseFile = base ? fileURLToPath19(base.url) : undefined;
|
|
379099
379614
|
} catch {
|
|
379100
379615
|
baseFile = undefined;
|
|
379101
379616
|
}
|
|
379102
379617
|
if (!companion || !baseFile)
|
|
379103
379618
|
return { error: "no companion" };
|
|
379104
379619
|
const overlaid = overlayKey(pathToFileURL21(baseFile)) === overlayKey(declaringURL);
|
|
379105
|
-
const importPath = overlaid ? copyName :
|
|
379620
|
+
const importPath = overlaid ? copyName : path39.basename(baseFile);
|
|
379106
379621
|
const text = generateRollupBuildFile([plan], importPath);
|
|
379107
379622
|
if (!text)
|
|
379108
379623
|
return { error: "no companion" };
|
|
@@ -379111,7 +379626,7 @@ async function databaseRollupInOverlay(plan, read, modelDef, ctx) {
|
|
|
379111
379626
|
const made = rollupBuildCopyText(await authorText(pathToFileURL21(baseFile)) ?? "", plan, (plan.privateGrain ?? []).length > 0);
|
|
379112
379627
|
if (!("copy" in made))
|
|
379113
379628
|
return { error: made.reason };
|
|
379114
|
-
addFile(pathToFileURL21(
|
|
379629
|
+
addFile(pathToFileURL21(path39.join(path39.dirname(baseFile), rollupBuildCopyName(importPath, plan.baseDeclaredName))), made.copy);
|
|
379115
379630
|
}
|
|
379116
379631
|
return databaseRollupSource(read.plan, modelDef, ctx.servedName, relativeImport(declaringURL, companion.href), read.dropped);
|
|
379117
379632
|
}
|
|
@@ -379876,8 +380391,8 @@ import {
|
|
|
379876
380391
|
Annotations as Annotations11
|
|
379877
380392
|
} from "@malloydata/malloy";
|
|
379878
380393
|
import { createRequire as createRequire4 } from "module";
|
|
379879
|
-
import * as
|
|
379880
|
-
import { fileURLToPath as
|
|
380394
|
+
import * as path40 from "path";
|
|
380395
|
+
import { fileURLToPath as fileURLToPath20, pathToFileURL as pathToFileURL22 } from "url";
|
|
379881
380396
|
function placeholderGivens(givens) {
|
|
379882
380397
|
const out = {};
|
|
379883
380398
|
for (const given of givens ?? []) {
|
|
@@ -380118,7 +380633,7 @@ var init_model = __esm(() => {
|
|
|
380118
380633
|
if (this.modelFile === undefined)
|
|
380119
380634
|
return false;
|
|
380120
380635
|
try {
|
|
380121
|
-
return
|
|
380636
|
+
return path40.resolve(fileURLToPath20(url)) === this.modelFile;
|
|
380122
380637
|
} catch {
|
|
380123
380638
|
return false;
|
|
380124
380639
|
}
|
|
@@ -380227,7 +380742,7 @@ var init_model = __esm(() => {
|
|
|
380227
380742
|
modelType,
|
|
380228
380743
|
modelMaterializer,
|
|
380229
380744
|
modelDef,
|
|
380230
|
-
modelFile:
|
|
380745
|
+
modelFile: path40.resolve(packagePath, modelPath),
|
|
380231
380746
|
sources,
|
|
380232
380747
|
queries,
|
|
380233
380748
|
sourceInfos,
|
|
@@ -380308,7 +380823,7 @@ var init_model = __esm(() => {
|
|
|
380308
380823
|
modelType: data.modelType,
|
|
380309
380824
|
modelMaterializer,
|
|
380310
380825
|
modelDef,
|
|
380311
|
-
modelFile:
|
|
380826
|
+
modelFile: path40.resolve(packagePath, data.modelPath),
|
|
380312
380827
|
sources,
|
|
380313
380828
|
queries,
|
|
380314
380829
|
sourceInfos,
|
|
@@ -381279,12 +381794,15 @@ var init_model = __esm(() => {
|
|
|
381279
381794
|
await this.prepareServedCopyOver(snapshot);
|
|
381280
381795
|
this.recordScopeFactsOver(snapshot);
|
|
381281
381796
|
}
|
|
381797
|
+
stringCapabilityRuntime() {
|
|
381798
|
+
return this.modelMaterializer?.runtime;
|
|
381799
|
+
}
|
|
381282
381800
|
async refreshStringCapabilities() {
|
|
381283
381801
|
const refresh = this.stringCapabilityReader;
|
|
381284
381802
|
const materializer = this.modelMaterializer;
|
|
381285
381803
|
const load = this.modelType === "model" && !this.isNotebook() && materializer ? (query) => materializer.loadQuery(query) : undefined;
|
|
381286
381804
|
const modelDef = this.modelDef;
|
|
381287
|
-
const runtime = this.
|
|
381805
|
+
const runtime = this.stringCapabilityRuntime();
|
|
381288
381806
|
if (!refresh || !load || !modelDef || !runtime)
|
|
381289
381807
|
return;
|
|
381290
381808
|
try {
|
|
@@ -381826,7 +382344,7 @@ var init_model = __esm(() => {
|
|
|
381826
382344
|
return createModelMaterializer(...args);
|
|
381827
382345
|
}
|
|
381828
382346
|
async getFileText(packagePath) {
|
|
381829
|
-
const fullPath =
|
|
382347
|
+
const fullPath = path40.join(packagePath, this.modelPath);
|
|
381830
382348
|
try {
|
|
381831
382349
|
return await readPackageURL(packagePath, pathToFileURL22(fullPath));
|
|
381832
382350
|
} catch {
|
|
@@ -381957,7 +382475,7 @@ var init_package_load_gates = __esm(() => {
|
|
|
381957
382475
|
|
|
381958
382476
|
// src/service/package.ts
|
|
381959
382477
|
import * as fs20 from "fs/promises";
|
|
381960
|
-
import * as
|
|
382478
|
+
import * as path41 from "path";
|
|
381961
382479
|
import { pathToFileURL as pathToFileURL23 } from "url";
|
|
381962
382480
|
import"@malloydata/db-duckdb/native";
|
|
381963
382481
|
import { DuckDBConnection as DuckDBConnection8 } from "@malloydata/db-duckdb";
|
|
@@ -382330,7 +382848,7 @@ var init_package2 = __esm(() => {
|
|
|
382330
382848
|
applySiblingModelResolverToModels() {
|
|
382331
382849
|
const byUrl = new Map;
|
|
382332
382850
|
for (const [modelPath, model] of this.models) {
|
|
382333
|
-
byUrl.set(pathToFileURL23(
|
|
382851
|
+
byUrl.set(pathToFileURL23(path41.join(this.packagePath, modelPath)).toString(), model);
|
|
382334
382852
|
}
|
|
382335
382853
|
this.modelPolicy.setSiblingModelDefResolver((url) => byUrl.get(url)?.getModelDef());
|
|
382336
382854
|
}
|
|
@@ -382631,7 +383149,7 @@ var init_package2 = __esm(() => {
|
|
|
382631
383149
|
buildManifest
|
|
382632
383150
|
}, "throw", async (sm) => {
|
|
382633
383151
|
if (sm.modelPath.endsWith(MODEL_FILE_SUFFIX)) {
|
|
382634
|
-
const modelSource = await readPackageURL(packagePath, pathToFileURL23(
|
|
383152
|
+
const modelSource = await readPackageURL(packagePath, pathToFileURL23(path41.join(packagePath, sm.modelPath)));
|
|
382635
383153
|
nameProblems.push(...persistNameProblems(modelSource, sm.modelPath));
|
|
382636
383154
|
}
|
|
382637
383155
|
}));
|
|
@@ -382928,7 +383446,7 @@ var init_package2 = __esm(() => {
|
|
|
382928
383446
|
for (const [modelPath, model] of this.models) {
|
|
382929
383447
|
if (!modelPath.endsWith(MODEL_FILE_SUFFIX))
|
|
382930
383448
|
continue;
|
|
382931
|
-
const absolutePath =
|
|
383449
|
+
const absolutePath = path41.join(this.packagePath, modelPath);
|
|
382932
383450
|
const modelDef = model.getModelDef();
|
|
382933
383451
|
const compilationError = model.getCompilationError();
|
|
382934
383452
|
if (compilationError !== undefined || modelDef === undefined) {
|
|
@@ -383435,6 +383953,7 @@ var init_package2 = __esm(() => {
|
|
|
383435
383953
|
}
|
|
383436
383954
|
boundStorageColumns = (sourceID, destination) => this.mz.boundStorageColumns(sourceID, destination);
|
|
383437
383955
|
boundStorageContract = (sourceID, destination) => this.mz.boundStorageContract(sourceID, destination);
|
|
383956
|
+
upstreamStringCapability = (sourceID) => this.mz.upstreamStringCapability(sourceID);
|
|
383438
383957
|
boundTableContract = (sourceID, storage) => this.mz.boundTableContract(sourceID, storage);
|
|
383439
383958
|
planChainStringReads = chainBuildStringReads;
|
|
383440
383959
|
planChainBuildText = (request, model) => planChainBuildText(this.getPackagePath(), this.getMalloyConfig())(request, model);
|
|
@@ -383623,7 +384142,7 @@ var init_package2 = __esm(() => {
|
|
|
383623
384142
|
modelPathsByImportUrl() {
|
|
383624
384143
|
const byUrl = new Map;
|
|
383625
384144
|
for (const modelPath of this.models.keys()) {
|
|
383626
|
-
byUrl.set(pathToFileURL23(
|
|
384145
|
+
byUrl.set(pathToFileURL23(path41.join(this.packagePath, modelPath)).toString(), modelPath);
|
|
383627
384146
|
}
|
|
383628
384147
|
return byUrl;
|
|
383629
384148
|
}
|
|
@@ -384269,9 +384788,9 @@ var init_package2 = __esm(() => {
|
|
|
384269
384788
|
static async getDatabasePaths(packagePath) {
|
|
384270
384789
|
const files = await listPackageTree(packagePath);
|
|
384271
384790
|
const candidates = files.map((fullPath) => {
|
|
384272
|
-
return
|
|
384791
|
+
return path41.relative(packagePath, fullPath).replace(/\\/g, "/");
|
|
384273
384792
|
}).filter((modelPath) => {
|
|
384274
|
-
if (
|
|
384793
|
+
if (path41.basename(modelPath).startsWith("~$")) {
|
|
384275
384794
|
return false;
|
|
384276
384795
|
}
|
|
384277
384796
|
return modelPath.endsWith(".parquet") || modelPath.endsWith(".csv") || modelPath.endsWith(".xlsx");
|
|
@@ -384279,7 +384798,7 @@ var init_package2 = __esm(() => {
|
|
|
384279
384798
|
const probed = [];
|
|
384280
384799
|
for (const relativePath of candidates) {
|
|
384281
384800
|
try {
|
|
384282
|
-
const real = await confinedPackagePath(packagePath, pathToFileURL23(
|
|
384801
|
+
const real = await confinedPackagePath(packagePath, pathToFileURL23(path41.join(packagePath, relativePath)));
|
|
384283
384802
|
if ((await fs20.stat(real)).isFile())
|
|
384284
384803
|
probed.push(relativePath);
|
|
384285
384804
|
} catch {}
|
|
@@ -384287,7 +384806,7 @@ var init_package2 = __esm(() => {
|
|
|
384287
384806
|
return probed;
|
|
384288
384807
|
}
|
|
384289
384808
|
static async getDatabaseInfo(packagePath, databasePath, conn) {
|
|
384290
|
-
const fullPath =
|
|
384809
|
+
const fullPath = path41.join(packagePath, databasePath);
|
|
384291
384810
|
const runtime = new ConnectionRuntime({
|
|
384292
384811
|
urlReader: new EmptyURLReader,
|
|
384293
384812
|
connections: [conn]
|
|
@@ -384887,9 +385406,9 @@ var init_compile_document = __esm(() => {
|
|
|
384887
385406
|
// src/service/compile_source.ts
|
|
384888
385407
|
import { MalloyError as MalloyError18, Runtime as Runtime3 } from "@malloydata/malloy";
|
|
384889
385408
|
import * as fs21 from "fs";
|
|
384890
|
-
import * as
|
|
384891
|
-
import { fileURLToPath as
|
|
384892
|
-
function packageRelativeModelPath(packagePath, filePath, pathModule =
|
|
385409
|
+
import * as path42 from "path";
|
|
385410
|
+
import { fileURLToPath as fileURLToPath21, pathToFileURL as pathToFileURL24 } from "url";
|
|
385411
|
+
function packageRelativeModelPath(packagePath, filePath, pathModule = path42) {
|
|
384893
385412
|
const rel = pathModule.relative(packagePath, filePath);
|
|
384894
385413
|
if (rel === "" || rel.startsWith("..") || pathModule.isAbsolute(rel)) {
|
|
384895
385414
|
return;
|
|
@@ -385004,8 +385523,8 @@ async function openCompileContext(host, request, versioned) {
|
|
|
385004
385523
|
const source = request.source ?? (scope === "file" ? overlaidText(overlay, modelName) : undefined);
|
|
385005
385524
|
const packagePath = versioned ? versioned.getPackagePath() : safeJoinUnderRoot(host.environmentPath, packageName);
|
|
385006
385525
|
const modelPath = safeJoinUnderRoot(packagePath, modelName);
|
|
385007
|
-
const modelDir =
|
|
385008
|
-
const virtualUrl = scope === "append" ? pathToFileURL24(
|
|
385526
|
+
const modelDir = path42.dirname(modelPath);
|
|
385527
|
+
const virtualUrl = scope === "append" ? pathToFileURL24(path42.join(modelDir, "__compile_check.malloy")) : pathToFileURL24(modelPath);
|
|
385009
385528
|
const virtualUri = virtualUrl.toString();
|
|
385010
385529
|
const { fullSource, callerRegion } = scope === "append" ? await appendToSavedModel(packagePath, modelPath, source, virtualUri) : { fullSource: source ?? "", callerRegion: undefined };
|
|
385011
385530
|
const substitute = scope !== "package" || source !== undefined;
|
|
@@ -385045,7 +385564,7 @@ async function openCompileContext(host, request, versioned) {
|
|
|
385045
385564
|
let model;
|
|
385046
385565
|
if (url && url.startsWith("file:")) {
|
|
385047
385566
|
try {
|
|
385048
|
-
model = packageRelativeModelPath(packagePath,
|
|
385567
|
+
model = packageRelativeModelPath(packagePath, fileURLToPath21(url));
|
|
385049
385568
|
} catch {}
|
|
385050
385569
|
}
|
|
385051
385570
|
if (scope === "append" && url === virtualUri) {
|
|
@@ -385394,7 +385913,7 @@ async function compilePackageDryRun(ctx) {
|
|
|
385394
385913
|
if (compiled.problems) {
|
|
385395
385914
|
collect(compiled.problems, compiled.modelPath);
|
|
385396
385915
|
}
|
|
385397
|
-
const readerProblem = compiled.modelDef && compiled.modelSourceText !== undefined ? notebookReaderProblem(compiled.modelPath, compiled.modelSourceText, compiled.modelDef, pathToFileURL24(
|
|
385916
|
+
const readerProblem = compiled.modelDef && compiled.modelSourceText !== undefined ? notebookReaderProblem(compiled.modelPath, compiled.modelSourceText, compiled.modelDef, pathToFileURL24(path42.join(packagePath, compiled.modelPath)).toString()) : undefined;
|
|
385398
385917
|
if (readerProblem)
|
|
385399
385918
|
collect([readerProblem], compiled.modelPath);
|
|
385400
385919
|
if (compiled.compilationError) {
|
|
@@ -385410,11 +385929,11 @@ async function compilePackageDryRun(ctx) {
|
|
|
385410
385929
|
], compiled.modelPath);
|
|
385411
385930
|
}
|
|
385412
385931
|
}
|
|
385413
|
-
const lintText = !(compiled.modelPath.endsWith(".malloy") && isReportEligiblePath(compiled.modelPath)) ? undefined : compiled.modelSourceText ?? (compiled.modelPath === modelName && source !== undefined ? source : overlaidText(ctx.overlay, compiled.modelPath) ?? await readPackageURL(packagePath, pathToFileURL24(
|
|
385932
|
+
const lintText = !(compiled.modelPath.endsWith(".malloy") && isReportEligiblePath(compiled.modelPath)) ? undefined : compiled.modelSourceText ?? (compiled.modelPath === modelName && source !== undefined ? source : overlaidText(ctx.overlay, compiled.modelPath) ?? await readPackageURL(packagePath, pathToFileURL24(path42.join(packagePath, compiled.modelPath))).catch(() => {
|
|
385414
385933
|
return;
|
|
385415
385934
|
}));
|
|
385416
385935
|
if (lintText !== undefined) {
|
|
385417
|
-
collect(notebookLintProblems(compiled.modelPath, lintText, pathToFileURL24(
|
|
385936
|
+
collect(notebookLintProblems(compiled.modelPath, lintText, pathToFileURL24(path42.join(packagePath, compiled.modelPath)).toString()).filter((problem) => !reportedByDashboardLint(problem, compiled.modelPath, reportWarnings)), compiled.modelPath);
|
|
385418
385937
|
}
|
|
385419
385938
|
}
|
|
385420
385939
|
for (const warning of renderTagWarnings) {
|
|
@@ -385684,7 +386203,7 @@ var init_status_snapshot = __esm(() => {
|
|
|
385684
386203
|
// src/service/versions/package_content_hash.ts
|
|
385685
386204
|
import * as crypto4 from "crypto";
|
|
385686
386205
|
import * as fs22 from "fs";
|
|
385687
|
-
import * as
|
|
386206
|
+
import * as path43 from "path";
|
|
385688
386207
|
async function hashPackageTree(root) {
|
|
385689
386208
|
const hash = crypto4.createHash("sha256");
|
|
385690
386209
|
const entries = await listEntries(root, "");
|
|
@@ -385726,7 +386245,7 @@ async function hashPackageTree(root) {
|
|
|
385726
386245
|
return hash.digest("hex");
|
|
385727
386246
|
}
|
|
385728
386247
|
async function readEntry(root, entry) {
|
|
385729
|
-
const absolute =
|
|
386248
|
+
const absolute = path43.join(root, ...entry.relative.split("/"));
|
|
385730
386249
|
if (entry.kind === "dir")
|
|
385731
386250
|
return { kind: "dir" };
|
|
385732
386251
|
if (entry.kind === "link") {
|
|
@@ -385739,7 +386258,7 @@ async function readEntry(root, entry) {
|
|
|
385739
386258
|
return { kind: "file", absolute, size: bytes.length, bytes };
|
|
385740
386259
|
}
|
|
385741
386260
|
async function listEntries(root, prefix) {
|
|
385742
|
-
const directory = prefix === "" ? root :
|
|
386261
|
+
const directory = prefix === "" ? root : path43.join(root, ...prefix.split("/"));
|
|
385743
386262
|
const dirents = await fs22.promises.readdir(directory, {
|
|
385744
386263
|
withFileTypes: true
|
|
385745
386264
|
});
|
|
@@ -385768,7 +386287,7 @@ var init_package_content_hash = __esm(() => {
|
|
|
385768
386287
|
// src/service/versions/version_store.ts
|
|
385769
386288
|
import * as crypto5 from "crypto";
|
|
385770
386289
|
import * as fs23 from "fs";
|
|
385771
|
-
import * as
|
|
386290
|
+
import * as path44 from "path";
|
|
385772
386291
|
import { pathToFileURL as pathToFileURL25 } from "url";
|
|
385773
386292
|
|
|
385774
386293
|
class VersionStore {
|
|
@@ -385785,7 +386304,7 @@ class VersionStore {
|
|
|
385785
386304
|
async stage(packageName, downloader) {
|
|
385786
386305
|
assertSafePackageName(packageName);
|
|
385787
386306
|
const stagingPath = safeJoinUnderRoot(this.environmentPath, STAGING_DIR_NAME, `${packageName}-${crypto5.randomUUID()}`);
|
|
385788
|
-
await fs23.promises.mkdir(
|
|
386307
|
+
await fs23.promises.mkdir(path44.dirname(stagingPath), { recursive: true });
|
|
385789
386308
|
try {
|
|
385790
386309
|
await downloader(stagingPath);
|
|
385791
386310
|
const manifest = await readManifestVersion(stagingPath);
|
|
@@ -385807,8 +386326,8 @@ class VersionStore {
|
|
|
385807
386326
|
}
|
|
385808
386327
|
within(area, candidate) {
|
|
385809
386328
|
const root = safeJoinUnderRoot(this.environmentPath, area);
|
|
385810
|
-
const resolved =
|
|
385811
|
-
if (!resolved.startsWith(root +
|
|
386329
|
+
const resolved = path44.resolve(candidate);
|
|
386330
|
+
if (!resolved.startsWith(root + path44.sep)) {
|
|
385812
386331
|
throw new Error(`Not a path under ${area}: ${JSON.stringify(candidate)}`);
|
|
385813
386332
|
}
|
|
385814
386333
|
return resolved;
|
|
@@ -385819,7 +386338,7 @@ class VersionStore {
|
|
|
385819
386338
|
await this.discard(staged);
|
|
385820
386339
|
return false;
|
|
385821
386340
|
}
|
|
385822
|
-
await fs23.promises.mkdir(
|
|
386341
|
+
await fs23.promises.mkdir(path44.dirname(target), { recursive: true });
|
|
385823
386342
|
await fs23.promises.rename(this.within(STAGING_DIR_NAME, staged.stagingPath), target);
|
|
385824
386343
|
return true;
|
|
385825
386344
|
}
|
|
@@ -385865,7 +386384,7 @@ class VersionStore {
|
|
|
385865
386384
|
if (!await exists(packagePath))
|
|
385866
386385
|
return null;
|
|
385867
386386
|
const heldPath = safeJoinUnderRoot(this.environmentPath, LEGACY_DIR_NAME, `${packageName}-${crypto5.randomUUID()}`);
|
|
385868
|
-
await fs23.promises.mkdir(
|
|
386387
|
+
await fs23.promises.mkdir(path44.dirname(heldPath), { recursive: true });
|
|
385869
386388
|
await fs23.promises.rename(packagePath, heldPath);
|
|
385870
386389
|
return { packageName, heldPath };
|
|
385871
386390
|
}
|
|
@@ -385876,7 +386395,7 @@ class VersionStore {
|
|
|
385876
386395
|
let leftover = null;
|
|
385877
386396
|
if (await exists(packagePath)) {
|
|
385878
386397
|
leftover = safeJoinUnderRoot(this.environmentPath, STAGING_DIR_NAME, `${held.packageName}-${crypto5.randomUUID()}`);
|
|
385879
|
-
await fs23.promises.mkdir(
|
|
386398
|
+
await fs23.promises.mkdir(path44.dirname(leftover), { recursive: true });
|
|
385880
386399
|
await fs23.promises.rename(packagePath, leftover);
|
|
385881
386400
|
}
|
|
385882
386401
|
try {
|
|
@@ -385969,7 +386488,7 @@ class VersionStore {
|
|
|
385969
386488
|
}
|
|
385970
386489
|
}
|
|
385971
386490
|
async function readManifestVersion(packagePath) {
|
|
385972
|
-
const manifestPath =
|
|
386491
|
+
const manifestPath = path44.join(packagePath, PACKAGE_MANIFEST_NAME);
|
|
385973
386492
|
let text;
|
|
385974
386493
|
try {
|
|
385975
386494
|
text = await readPackageURL(packagePath, pathToFileURL25(manifestPath));
|
|
@@ -386019,9 +386538,10 @@ var init_version_store = __esm(() => {
|
|
|
386019
386538
|
});
|
|
386020
386539
|
|
|
386021
386540
|
// src/service/environment.ts
|
|
386541
|
+
import { AsyncLocalStorage as AsyncLocalStorage8 } from "async_hooks";
|
|
386022
386542
|
import crypto6 from "crypto";
|
|
386023
386543
|
import * as fs24 from "fs";
|
|
386024
|
-
import * as
|
|
386544
|
+
import * as path45 from "path";
|
|
386025
386545
|
import { isDeepStrictEqual } from "util";
|
|
386026
386546
|
import { pathToFileURL as pathToFileURL26 } from "url";
|
|
386027
386547
|
function mergePackageManifest(existingManifest, metadata) {
|
|
@@ -386225,7 +386745,7 @@ var init_environment = __esm(() => {
|
|
|
386225
386745
|
async writeEnvironmentReadme(readme) {
|
|
386226
386746
|
if (readme === undefined)
|
|
386227
386747
|
return;
|
|
386228
|
-
const readmePath =
|
|
386748
|
+
const readmePath = path45.join(this.environmentPath, "README.md");
|
|
386229
386749
|
try {
|
|
386230
386750
|
await fs24.promises.writeFile(readmePath, readme, "utf-8");
|
|
386231
386751
|
logger.info(`Updated README.md for environment ${this.environmentName}`);
|
|
@@ -386840,7 +387360,7 @@ var init_environment = __esm(() => {
|
|
|
386840
387360
|
throw error;
|
|
386841
387361
|
}
|
|
386842
387362
|
const missing = [];
|
|
386843
|
-
let dir =
|
|
387363
|
+
let dir = path45.dirname(target);
|
|
386844
387364
|
while (dir.startsWith(packageRoot)) {
|
|
386845
387365
|
const stat = await fs24.promises.stat(dir).catch((error) => {
|
|
386846
387366
|
const code = error.code;
|
|
@@ -386852,11 +387372,11 @@ var init_environment = __esm(() => {
|
|
|
386852
387372
|
if (await isLink(dir))
|
|
386853
387373
|
throw outside();
|
|
386854
387374
|
missing.push(dir);
|
|
386855
|
-
dir =
|
|
387375
|
+
dir = path45.dirname(dir);
|
|
386856
387376
|
continue;
|
|
386857
387377
|
}
|
|
386858
387378
|
if (!stat.isDirectory())
|
|
386859
|
-
throw new InvalidModelPathError(`Invalid model path: \`${
|
|
387379
|
+
throw new InvalidModelPathError(`Invalid model path: \`${path45.relative(packageRoot, dir).split(path45.sep).join("/")}\` ` + `is a file in the package, not a directory.`);
|
|
386860
387380
|
break;
|
|
386861
387381
|
}
|
|
386862
387382
|
const [realRoot, realExisting, realTarget] = await Promise.all([
|
|
@@ -386871,10 +387391,10 @@ var init_environment = __esm(() => {
|
|
|
386871
387391
|
for (const real of [realExisting, realTarget]) {
|
|
386872
387392
|
if (real === undefined)
|
|
386873
387393
|
continue;
|
|
386874
|
-
if (real !== realRoot && !real.startsWith(`${realRoot}${
|
|
387394
|
+
if (real !== realRoot && !real.startsWith(`${realRoot}${path45.sep}`)) {
|
|
386875
387395
|
throw new InvalidModelPathError(`Invalid model path: it resolves outside the package.`);
|
|
386876
387396
|
}
|
|
386877
|
-
if (isUnderPublicDir(
|
|
387397
|
+
if (isUnderPublicDir(path45.relative(realRoot, real).split(path45.sep).join("/"))) {
|
|
386878
387398
|
throw new InvalidModelPathError(`Invalid model path: it resolves into \`public/\`, which is served ` + `as raw static files.`);
|
|
386879
387399
|
}
|
|
386880
387400
|
}
|
|
@@ -386984,7 +387504,7 @@ var init_environment = __esm(() => {
|
|
|
386984
387504
|
const dir = safeJoinUnderRoot(environmentPath, dirName);
|
|
386985
387505
|
if (dir.indexOf("..") !== -1)
|
|
386986
387506
|
continue;
|
|
386987
|
-
if (
|
|
387507
|
+
if (path45.basename(dir) !== dirName)
|
|
386988
387508
|
continue;
|
|
386989
387509
|
try {
|
|
386990
387510
|
await fs24.promises.rm(dir, { recursive: true, force: true });
|
|
@@ -387551,6 +388071,7 @@ var init_environment = __esm(() => {
|
|
|
387551
388071
|
ensurePackageRecord: hooks.ensurePackageRecord,
|
|
387552
388072
|
removePackageRecord: hooks.removePackageRecord,
|
|
387553
388073
|
boundManifestOf: (loaded) => loaded.materialization().bindingState().manifestBindingStatus === "bind_failed" ? null : loaded.getManifestLocation() ?? null,
|
|
388074
|
+
shareManifestFetches: (fn) => this.shareManifestFetches(fn),
|
|
387554
388075
|
hostMarked: (loaded) => loaded.materialization().isHostOwned(),
|
|
387555
388076
|
isVersionBuilding: (packageName, versionId) => this.versionBuilds.has(`${packageName}@${versionId}`),
|
|
387556
388077
|
onVersionArchived: (packageName, versionId) => this.versionArchivedHook?.(packageName, versionId),
|
|
@@ -387992,7 +388513,7 @@ var init_environment = __esm(() => {
|
|
|
387992
388513
|
}
|
|
387993
388514
|
async stageDownload(packageName, downloader) {
|
|
387994
388515
|
const stagingPath = this.allocateStagingPath(packageName);
|
|
387995
|
-
await fs24.promises.mkdir(
|
|
388516
|
+
await fs24.promises.mkdir(path45.dirname(stagingPath), { recursive: true });
|
|
387996
388517
|
logger.debug("install.phase1.download.started", {
|
|
387997
388518
|
environmentName: this.environmentName,
|
|
387998
388519
|
packageName,
|
|
@@ -388060,7 +388581,7 @@ var init_environment = __esm(() => {
|
|
|
388060
388581
|
const oldExistsOnDisk = await fs24.promises.access(canonicalPath).then(() => true).catch(() => false);
|
|
388061
388582
|
if (oldExistsOnDisk) {
|
|
388062
388583
|
retiredPath = this.allocateRetiredPath(packageName);
|
|
388063
|
-
await fs24.promises.mkdir(
|
|
388584
|
+
await fs24.promises.mkdir(path45.dirname(retiredPath), {
|
|
388064
388585
|
recursive: true
|
|
388065
388586
|
});
|
|
388066
388587
|
await fs24.promises.rename(canonicalPath, retiredPath);
|
|
@@ -388357,12 +388878,38 @@ var init_environment = __esm(() => {
|
|
|
388357
388878
|
error: err instanceof Error ? err.message : String(err)
|
|
388358
388879
|
});
|
|
388359
388880
|
if (onFailure === "refuse") {
|
|
388360
|
-
throw new ManifestBindFailedError(manifestLocation, err, applying);
|
|
388881
|
+
throw new ManifestBindFailedError(manifestLocation, err, applying, !applying && err instanceof ManifestUnusableError ? err.problem : undefined);
|
|
388361
388882
|
}
|
|
388362
388883
|
pkg.materialization().markManifestBindFailed();
|
|
388363
388884
|
}
|
|
388364
388885
|
}
|
|
388365
|
-
|
|
388886
|
+
sharedManifestFetches = new AsyncLocalStorage8;
|
|
388887
|
+
async shareManifestFetches(fn) {
|
|
388888
|
+
if (this.sharedManifestFetches.getStore()?.open)
|
|
388889
|
+
return fn();
|
|
388890
|
+
const scope = {
|
|
388891
|
+
fetches: new Map,
|
|
388892
|
+
open: true
|
|
388893
|
+
};
|
|
388894
|
+
try {
|
|
388895
|
+
return await this.sharedManifestFetches.run(scope, fn);
|
|
388896
|
+
} finally {
|
|
388897
|
+
scope.open = false;
|
|
388898
|
+
scope.fetches.clear();
|
|
388899
|
+
}
|
|
388900
|
+
}
|
|
388901
|
+
fetchManifestEntriesWithTimeout(manifestLocation) {
|
|
388902
|
+
const scope = this.sharedManifestFetches.getStore();
|
|
388903
|
+
if (!scope?.open)
|
|
388904
|
+
return this.fetchManifestOnce(manifestLocation);
|
|
388905
|
+
let fetching = scope.fetches.get(manifestLocation);
|
|
388906
|
+
if (!fetching) {
|
|
388907
|
+
fetching = this.fetchManifestOnce(manifestLocation);
|
|
388908
|
+
scope.fetches.set(manifestLocation, fetching);
|
|
388909
|
+
}
|
|
388910
|
+
return fetching;
|
|
388911
|
+
}
|
|
388912
|
+
async fetchManifestOnce(manifestLocation) {
|
|
388366
388913
|
let timer;
|
|
388367
388914
|
const timeout = new Promise((_, reject) => {
|
|
388368
388915
|
timer = setTimeout(() => reject(new Error(`Timed out after ${MANIFEST_FETCH_TIMEOUT_MS}ms fetching manifest ${manifestLocation}`)), MANIFEST_FETCH_TIMEOUT_MS);
|
|
@@ -388411,7 +388958,7 @@ var init_environment = __esm(() => {
|
|
|
388411
388958
|
const updatedManifest = mergePackageManifest(existingManifest, metadata);
|
|
388412
388959
|
if (metadata.location !== undefined && metadata.location !== "") {
|
|
388413
388960
|
const recordPath = this.installRecordPath(packageName);
|
|
388414
|
-
await fs24.promises.mkdir(
|
|
388961
|
+
await fs24.promises.mkdir(path45.dirname(recordPath), {
|
|
388415
388962
|
recursive: true
|
|
388416
388963
|
});
|
|
388417
388964
|
await fs24.promises.writeFile(recordPath, JSON.stringify({ location: metadata.location }, null, 2), "utf-8");
|
|
@@ -388421,7 +388968,7 @@ var init_environment = __esm(() => {
|
|
|
388421
388968
|
if (error.code !== "ENOENT")
|
|
388422
388969
|
throw error;
|
|
388423
388970
|
});
|
|
388424
|
-
const temporary =
|
|
388971
|
+
const temporary = path45.join(packagePath, `.publisher.json.${crypto6.randomUUID()}.tmp`);
|
|
388425
388972
|
try {
|
|
388426
388973
|
await fs24.promises.writeFile(temporary, JSON.stringify(updatedManifest, null, 2), { encoding: "utf-8", flag: "wx" });
|
|
388427
388974
|
await fs24.promises.rename(temporary, manifestPath);
|
|
@@ -388449,7 +388996,7 @@ var init_environment = __esm(() => {
|
|
|
388449
388996
|
async restorePackageManifestFile(packageName, text) {
|
|
388450
388997
|
const packagePath = safeJoinUnderRoot(this.environmentPath, packageName);
|
|
388451
388998
|
const manifestPath = safeJoinUnderRoot(packagePath, "publisher.json");
|
|
388452
|
-
const temporary =
|
|
388999
|
+
const temporary = path45.join(packagePath, `.publisher.json.${crypto6.randomUUID()}.tmp`);
|
|
388453
389000
|
try {
|
|
388454
389001
|
if (text === null) {
|
|
388455
389002
|
await fs24.promises.rm(manifestPath, { force: true });
|
|
@@ -388753,7 +389300,7 @@ var init_environment = __esm(() => {
|
|
|
388753
389300
|
const canonicalPath = safeJoinUnderRoot(this.environmentPath, packageName);
|
|
388754
389301
|
const retiredPath = this.allocateRetiredPath(packageName);
|
|
388755
389302
|
try {
|
|
388756
|
-
await fs24.promises.mkdir(
|
|
389303
|
+
await fs24.promises.mkdir(path45.dirname(retiredPath), {
|
|
388757
389304
|
recursive: true
|
|
388758
389305
|
});
|
|
388759
389306
|
await fs24.promises.rename(canonicalPath, retiredPath);
|
|
@@ -388884,7 +389431,7 @@ var init_environment = __esm(() => {
|
|
|
388884
389431
|
};
|
|
388885
389432
|
}
|
|
388886
389433
|
async deleteDuckDBConnection(connectionName) {
|
|
388887
|
-
const duckdbPath =
|
|
389434
|
+
const duckdbPath = path45.join(this.environmentPath, `${connectionName}.duckdb`);
|
|
388888
389435
|
try {
|
|
388889
389436
|
await fs24.promises.rm(duckdbPath, { force: true });
|
|
388890
389437
|
logger.info(`Removed DuckDB connection file ${connectionName} from environment ${this.environmentName}`);
|
|
@@ -389708,7 +390255,7 @@ var init_DuckDBRepository = __esm(() => {
|
|
|
389708
390255
|
async function initializeSchema(db, force = false) {
|
|
389709
390256
|
const initialized = await db.isInitialized();
|
|
389710
390257
|
if (force) {
|
|
389711
|
-
logger.info("Reinitializing database schema dropping and recreating
|
|
390258
|
+
logger.info("Reinitializing database schema: dropping and recreating every table but the retrieval caches");
|
|
389712
390259
|
await dropAllTables(db);
|
|
389713
390260
|
} else if (!initialized) {
|
|
389714
390261
|
await dropLegacyProjectSchema(db);
|
|
@@ -390198,6 +390745,19 @@ async function createCatalogTables(db) {
|
|
|
390198
390745
|
PRIMARY KEY (environment_name, package_name, node_key, facet)
|
|
390199
390746
|
)
|
|
390200
390747
|
`);
|
|
390748
|
+
await db.run(`
|
|
390749
|
+
CREATE TABLE IF NOT EXISTS dimension_value_reads (
|
|
390750
|
+
environment_name VARCHAR NOT NULL,
|
|
390751
|
+
package_name VARCHAR NOT NULL,
|
|
390752
|
+
dimension_key VARCHAR NOT NULL,
|
|
390753
|
+
givens VARCHAR NOT NULL,
|
|
390754
|
+
read_key VARCHAR NOT NULL,
|
|
390755
|
+
truncated BOOLEAN NOT NULL,
|
|
390756
|
+
read_values VARCHAR NOT NULL,
|
|
390757
|
+
read_at TIMESTAMP NOT NULL,
|
|
390758
|
+
PRIMARY KEY (environment_name, package_name, dimension_key, givens)
|
|
390759
|
+
)
|
|
390760
|
+
`);
|
|
390201
390761
|
}
|
|
390202
390762
|
async function dropLegacyProjectSchema(db) {
|
|
390203
390763
|
const legacy = await db.all("SELECT name FROM sqlite_master WHERE type='table' AND name='projects'");
|
|
@@ -390213,6 +390773,18 @@ async function dropLegacyProjectSchema(db) {
|
|
|
390213
390773
|
}
|
|
390214
390774
|
}
|
|
390215
390775
|
}
|
|
390776
|
+
async function deleteUnconfiguredRetrievalRows(db, configured) {
|
|
390777
|
+
const pairs = configured.flatMap((e) => e.packages.map((p) => [e.environment, p]));
|
|
390778
|
+
const keep = pairs.length === 0 ? "FALSE" : `(environment_name, package_name) IN (${pairs.map(() => "(?, ?)").join(", ")})`;
|
|
390779
|
+
for (const table of RETRIEVAL_CACHE_TABLES) {
|
|
390780
|
+
try {
|
|
390781
|
+
await db.run(`DELETE FROM ${table} WHERE NOT ${keep}`, pairs.flat());
|
|
390782
|
+
} catch (err) {
|
|
390783
|
+
logger.warn(`Could not delete the rows of unconfigured packages from ${table}; emptying it`, err);
|
|
390784
|
+
await db.run(`DELETE FROM ${table}`);
|
|
390785
|
+
}
|
|
390786
|
+
}
|
|
390787
|
+
}
|
|
390216
390788
|
async function dropAllTables(db) {
|
|
390217
390789
|
const tables = [
|
|
390218
390790
|
"build_manifests",
|
|
@@ -390226,15 +390798,7 @@ async function dropAllTables(db) {
|
|
|
390226
390798
|
"themes",
|
|
390227
390799
|
"workload_log",
|
|
390228
390800
|
"entity_embeddings",
|
|
390229
|
-
"entity_keyphrases"
|
|
390230
|
-
"source_summaries",
|
|
390231
|
-
"catalog_nodes",
|
|
390232
|
-
"catalog_edges",
|
|
390233
|
-
"doc_parts",
|
|
390234
|
-
"node_questions",
|
|
390235
|
-
"catalog_embeddings",
|
|
390236
|
-
"dimension_values",
|
|
390237
|
-
"value_embeddings"
|
|
390801
|
+
"entity_keyphrases"
|
|
390238
390802
|
];
|
|
390239
390803
|
logger.info("Dropping tables:", tables.join(", "));
|
|
390240
390804
|
for (const table of tables) {
|
|
@@ -390254,7 +390818,7 @@ var COLUMN_SHAPE_QUERY = `
|
|
|
390254
390818
|
SELECT table_name, constraint_type, constraint_column_names
|
|
390255
390819
|
FROM duckdb_constraints()
|
|
390256
390820
|
WHERE schema_name = 'main' AND database_name = current_database()
|
|
390257
|
-
`, LEGACY_TABLES_DROP_ORDER;
|
|
390821
|
+
`, LEGACY_TABLES_DROP_ORDER, RETRIEVAL_CACHE_TABLES;
|
|
390258
390822
|
var init_schema = __esm(() => {
|
|
390259
390823
|
init_logger();
|
|
390260
390824
|
init_DuckDBConnection();
|
|
@@ -390265,6 +390829,17 @@ var init_schema = __esm(() => {
|
|
|
390265
390829
|
"connections",
|
|
390266
390830
|
"projects"
|
|
390267
390831
|
];
|
|
390832
|
+
RETRIEVAL_CACHE_TABLES = [
|
|
390833
|
+
"catalog_nodes",
|
|
390834
|
+
"catalog_edges",
|
|
390835
|
+
"doc_parts",
|
|
390836
|
+
"node_questions",
|
|
390837
|
+
"catalog_embeddings",
|
|
390838
|
+
"dimension_values",
|
|
390839
|
+
"value_embeddings",
|
|
390840
|
+
"dimension_value_reads",
|
|
390841
|
+
"source_summaries"
|
|
390842
|
+
];
|
|
390268
390843
|
});
|
|
390269
390844
|
|
|
390270
390845
|
// src/storage/StorageManager.ts
|
|
@@ -395056,12 +395631,12 @@ var require_extract_zip = __commonJS(function(exports, module) {
|
|
|
395056
395631
|
|
|
395057
395632
|
// src/service/package_sources/zip.ts
|
|
395058
395633
|
import * as fs26 from "fs";
|
|
395059
|
-
import * as
|
|
395634
|
+
import * as path46 from "path";
|
|
395060
395635
|
async function unzipEnvironment(absoluteEnvironmentPath) {
|
|
395061
395636
|
assertSafeEnvironmentPath(absoluteEnvironmentPath);
|
|
395062
|
-
const archiveDir =
|
|
395063
|
-
const unzippedEnvironmentPath =
|
|
395064
|
-
if (!unzippedEnvironmentPath.startsWith(archiveDir +
|
|
395637
|
+
const archiveDir = path46.resolve(path46.dirname(absoluteEnvironmentPath));
|
|
395638
|
+
const unzippedEnvironmentPath = path46.resolve(archiveDir, path46.basename(absoluteEnvironmentPath, ".zip"));
|
|
395639
|
+
if (!unzippedEnvironmentPath.startsWith(archiveDir + path46.sep)) {
|
|
395065
395640
|
throw new BadRequestError(`Refusing to unzip "${absoluteEnvironmentPath}": target escapes its directory`);
|
|
395066
395641
|
}
|
|
395067
395642
|
await extractZipInto(absoluteEnvironmentPath, unzippedEnvironmentPath);
|
|
@@ -395079,7 +395654,7 @@ async function extractZipInto(archivePath, targetDir) {
|
|
|
395079
395654
|
let totalUncompressedBytes = 0;
|
|
395080
395655
|
try {
|
|
395081
395656
|
await import_extract_zip.default(archivePath, {
|
|
395082
|
-
dir:
|
|
395657
|
+
dir: path46.resolve(targetDir),
|
|
395083
395658
|
onEntry: (entry) => {
|
|
395084
395659
|
if ((entry.externalFileAttributes >>> 16 & 61440) === 40960) {
|
|
395085
395660
|
throw new BadRequestError(`Refusing to unzip "${archivePath}": entry "${entry.fileName}" is a symbolic link`);
|
|
@@ -395108,7 +395683,7 @@ var init_zip = __esm(() => {
|
|
|
395108
395683
|
|
|
395109
395684
|
// src/service/package_sources/gcs_source.ts
|
|
395110
395685
|
import * as fs27 from "fs";
|
|
395111
|
-
import * as
|
|
395686
|
+
import * as path47 from "path";
|
|
395112
395687
|
function isGCSURL(location) {
|
|
395113
395688
|
return location.startsWith("gs://");
|
|
395114
395689
|
}
|
|
@@ -395146,7 +395721,7 @@ class GcsPackageSource {
|
|
|
395146
395721
|
if (file.name.endsWith("/")) {
|
|
395147
395722
|
return;
|
|
395148
395723
|
}
|
|
395149
|
-
await fs27.promises.mkdir(
|
|
395724
|
+
await fs27.promises.mkdir(path47.dirname(absoluteFilePath), {
|
|
395150
395725
|
recursive: true
|
|
395151
395726
|
});
|
|
395152
395727
|
return fs27.promises.writeFile(absoluteFilePath, await file.download());
|
|
@@ -395390,9 +395965,9 @@ var init_git_source = __esm(() => {
|
|
|
395390
395965
|
// src/service/package_sources/local_source.ts
|
|
395391
395966
|
import * as fs29 from "fs";
|
|
395392
395967
|
import * as os8 from "os";
|
|
395393
|
-
import * as
|
|
395968
|
+
import * as path48 from "path";
|
|
395394
395969
|
function isLocalPath(location) {
|
|
395395
|
-
return location.startsWith("./") || location.startsWith("../") || location.startsWith("~/") || location.startsWith("/") ||
|
|
395970
|
+
return location.startsWith("./") || location.startsWith("../") || location.startsWith("~/") || location.startsWith("/") || path48.isAbsolute(location);
|
|
395396
395971
|
}
|
|
395397
395972
|
function resolvePackageLocation(location, anchorDir, homeDir) {
|
|
395398
395973
|
let expanded = location;
|
|
@@ -395401,9 +395976,9 @@ function resolvePackageLocation(location, anchorDir, homeDir) {
|
|
|
395401
395976
|
if (!home) {
|
|
395402
395977
|
throw new Error(`Cannot expand "~" in location "${location}": home directory is not set`);
|
|
395403
395978
|
}
|
|
395404
|
-
expanded =
|
|
395979
|
+
expanded = path48.join(home, location.slice(2));
|
|
395405
395980
|
}
|
|
395406
|
-
return
|
|
395981
|
+
return path48.isAbsolute(expanded) ? expanded : path48.join(anchorDir, expanded);
|
|
395407
395982
|
}
|
|
395408
395983
|
|
|
395409
395984
|
class LocalPackageSource {
|
|
@@ -395441,7 +396016,7 @@ var init_local_source = __esm(() => {
|
|
|
395441
396016
|
|
|
395442
396017
|
// src/service/package_sources/s3_source.ts
|
|
395443
396018
|
import * as fs30 from "fs";
|
|
395444
|
-
import * as
|
|
396019
|
+
import * as path49 from "path";
|
|
395445
396020
|
import { Writable } from "stream";
|
|
395446
396021
|
function isS3URL(location) {
|
|
395447
396022
|
return location.startsWith("s3://");
|
|
@@ -395465,7 +396040,7 @@ class S3PackageSource {
|
|
|
395465
396040
|
const s3Client = this.client();
|
|
395466
396041
|
if (isCompressedFile) {
|
|
395467
396042
|
const zipFilePath = `${absoluteDirPath}.zip`;
|
|
395468
|
-
await fs30.promises.mkdir(
|
|
396043
|
+
await fs30.promises.mkdir(path49.dirname(zipFilePath), {
|
|
395469
396044
|
recursive: true
|
|
395470
396045
|
});
|
|
395471
396046
|
const command = new import_client_s33.GetObjectCommand({
|
|
@@ -395500,7 +396075,7 @@ class S3PackageSource {
|
|
|
395500
396075
|
return;
|
|
395501
396076
|
}
|
|
395502
396077
|
const absoluteFilePath = safeJoinUnderRoot(absoluteDirPath, relativeFilePath);
|
|
395503
|
-
await fs30.promises.mkdir(
|
|
396078
|
+
await fs30.promises.mkdir(path49.dirname(absoluteFilePath), {
|
|
395504
396079
|
recursive: true
|
|
395505
396080
|
});
|
|
395506
396081
|
const command = new import_client_s33.GetObjectCommand({
|
|
@@ -395527,7 +396102,7 @@ var init_s3_source = __esm(() => {
|
|
|
395527
396102
|
|
|
395528
396103
|
// src/service/package_sources/index.ts
|
|
395529
396104
|
import { Storage as Storage2 } from "@google-cloud/storage";
|
|
395530
|
-
import * as
|
|
396105
|
+
import * as path50 from "path";
|
|
395531
396106
|
|
|
395532
396107
|
class PackageSources {
|
|
395533
396108
|
resolveLocalPath;
|
|
@@ -395594,7 +396169,7 @@ class PackageSources {
|
|
|
395594
396169
|
} else if (packageLocation.startsWith("s3://")) {
|
|
395595
396170
|
await this.s3.fetch(packageLocation, targetPath, opts);
|
|
395596
396171
|
}
|
|
395597
|
-
if (packageLocation.startsWith("/") ||
|
|
396172
|
+
if (packageLocation.startsWith("/") || path50.isAbsolute(packageLocation)) {
|
|
395598
396173
|
await this.local.fetch(packageLocation, targetPath, opts);
|
|
395599
396174
|
}
|
|
395600
396175
|
}
|
|
@@ -395618,7 +396193,7 @@ var init_package_sources = __esm(() => {
|
|
|
395618
396193
|
// src/service/environment_store.ts
|
|
395619
396194
|
import crypto7 from "crypto";
|
|
395620
396195
|
import * as fs31 from "fs";
|
|
395621
|
-
import * as
|
|
396196
|
+
import * as path51 from "path";
|
|
395622
396197
|
function codesField(message) {
|
|
395623
396198
|
const codes = codesOfLines(message);
|
|
395624
396199
|
return codes.length > 0 ? { codes } : {};
|
|
@@ -395725,7 +396300,7 @@ class EnvironmentStore {
|
|
|
395725
396300
|
const storageConfig = {
|
|
395726
396301
|
type: "duckdb",
|
|
395727
396302
|
duckdb: {
|
|
395728
|
-
path:
|
|
396303
|
+
path: path51.join(serverRootPath, "publisher.db")
|
|
395729
396304
|
}
|
|
395730
396305
|
};
|
|
395731
396306
|
this.storageManager = deps.storageManager ?? new StorageManager(storageConfig);
|
|
@@ -395952,6 +396527,12 @@ class EnvironmentStore {
|
|
|
395952
396527
|
this.publisherConfigIsFrozen = isPublisherConfigFrozen();
|
|
395953
396528
|
const environmentManifest = await EnvironmentStore.reloadEnvironmentManifest(this.serverRootPath);
|
|
395954
396529
|
await this.cleanupAndCreatePublisherPath();
|
|
396530
|
+
if (reInit) {
|
|
396531
|
+
await deleteUnconfiguredRetrievalRows(this.storageManager.getDuckDbConnection(), environmentManifest.environments.map((e) => ({
|
|
396532
|
+
environment: e.name,
|
|
396533
|
+
packages: e.packages.map((p) => p.name)
|
|
396534
|
+
})));
|
|
396535
|
+
}
|
|
395955
396536
|
const repository = this.storageManager.getRepository();
|
|
395956
396537
|
let declaredEnvironments = environmentManifest.environments.length;
|
|
395957
396538
|
let existingEnvironments = [];
|
|
@@ -396401,7 +396982,7 @@ class EnvironmentStore {
|
|
|
396401
396982
|
const reInit = settings.get("initializeStorage");
|
|
396402
396983
|
await fs31.promises.mkdir(this.serverRootPath, { recursive: true });
|
|
396403
396984
|
if (reInit) {
|
|
396404
|
-
const uploadDocsPath =
|
|
396985
|
+
const uploadDocsPath = path51.join(this.serverRootPath, PUBLISHER_DATA_DIR);
|
|
396405
396986
|
logger.info(`Reinitialization mode: Cleaning up upload documents path ${uploadDocsPath}`);
|
|
396406
396987
|
try {
|
|
396407
396988
|
await fs31.promises.rm(uploadDocsPath, {
|
|
@@ -396418,7 +396999,7 @@ class EnvironmentStore {
|
|
|
396418
396999
|
} else {
|
|
396419
397000
|
logger.info(`Using existing publisher path`);
|
|
396420
397001
|
}
|
|
396421
|
-
const uploadDocsPath =
|
|
397002
|
+
const uploadDocsPath = path51.join(this.serverRootPath, PUBLISHER_DATA_DIR);
|
|
396422
397003
|
await fs31.promises.mkdir(uploadDocsPath, { recursive: true });
|
|
396423
397004
|
}
|
|
396424
397005
|
async listEnvironments(skipInitializationCheck = false, options = {}) {
|
|
@@ -396842,7 +397423,7 @@ class EnvironmentStore {
|
|
|
396842
397423
|
const isInPlace = this.inPlaceEnvs.has(environmentName) && isLocalPath(_package.location) && !isLocalArchive;
|
|
396843
397424
|
if (isInPlace) {
|
|
396844
397425
|
await clearMountTarget(absolutePackagePath);
|
|
396845
|
-
const absoluteSourcePath =
|
|
397426
|
+
const absoluteSourcePath = path51.resolve(sourcePath);
|
|
396846
397427
|
const linkType = process.platform === "win32" ? "junction" : "dir";
|
|
396847
397428
|
try {
|
|
396848
397429
|
await fs31.promises.symlink(absoluteSourcePath, absolutePackagePath, linkType);
|
|
@@ -396944,6 +397525,7 @@ var init_environment_store = __esm(() => {
|
|
|
396944
397525
|
init_path_safety();
|
|
396945
397526
|
init_StorageManager();
|
|
396946
397527
|
init_connection_config();
|
|
397528
|
+
init_schema();
|
|
396947
397529
|
init_db_utils();
|
|
396948
397530
|
init_environment();
|
|
396949
397531
|
init_api_resource();
|
|
@@ -396971,7 +397553,7 @@ var init_environment_store = __esm(() => {
|
|
|
396971
397553
|
|
|
396972
397554
|
// src/controller/watch-mode.controller.ts
|
|
396973
397555
|
import { EventEmitter as EventEmitter3 } from "events";
|
|
396974
|
-
import
|
|
397556
|
+
import path52 from "path";
|
|
396975
397557
|
|
|
396976
397558
|
class WatchModeController {
|
|
396977
397559
|
environmentStore;
|
|
@@ -397015,7 +397597,7 @@ class WatchModeController {
|
|
|
397015
397597
|
ignored: (filePath, stats) => {
|
|
397016
397598
|
if (!stats?.isFile())
|
|
397017
397599
|
return false;
|
|
397018
|
-
const ext =
|
|
397600
|
+
const ext = path52.extname(filePath).toLowerCase();
|
|
397019
397601
|
return !MODEL_EXTS.has(ext) && !ASSET_EXTS.has(ext);
|
|
397020
397602
|
},
|
|
397021
397603
|
ignoreInitial: true
|
|
@@ -397035,12 +397617,12 @@ class WatchModeController {
|
|
|
397035
397617
|
};
|
|
397036
397618
|
const onEvent = (kind) => async (filePath) => {
|
|
397037
397619
|
logger.info(`Watch ${kind}: ${filePath}; environment=${watchName}`);
|
|
397038
|
-
const rel =
|
|
397039
|
-
const segments = rel.split(
|
|
397620
|
+
const rel = path52.relative(this.watchingPath ?? "", filePath);
|
|
397621
|
+
const segments = rel.split(path52.sep);
|
|
397040
397622
|
const pkgName = segments.length > 1 && segments[0] && !segments[0].startsWith("..") ? segments[0] : null;
|
|
397041
397623
|
if (!pkgName)
|
|
397042
397624
|
return;
|
|
397043
|
-
const ext =
|
|
397625
|
+
const ext = path52.extname(filePath).toLowerCase();
|
|
397044
397626
|
if (MODEL_EXTS.has(ext)) {
|
|
397045
397627
|
const recompiled = await reloadPackage(pkgName);
|
|
397046
397628
|
if (!recompiled)
|
|
@@ -397113,7 +397695,7 @@ var init_watch_mode_controller = __esm(() => {
|
|
|
397113
397695
|
// src/mcp_config.ts
|
|
397114
397696
|
import * as fs32 from "fs";
|
|
397115
397697
|
import * as os9 from "os";
|
|
397116
|
-
import * as
|
|
397698
|
+
import * as path53 from "path";
|
|
397117
397699
|
function malloyServer(endpoint) {
|
|
397118
397700
|
return { type: "http", url: endpoint };
|
|
397119
397701
|
}
|
|
@@ -397136,11 +397718,11 @@ function mcpEndpoint(host, port) {
|
|
|
397136
397718
|
return `http://${host}:${port}/mcp`;
|
|
397137
397719
|
}
|
|
397138
397720
|
function findGitWorkTreeRoot(dir) {
|
|
397139
|
-
let current =
|
|
397721
|
+
let current = path53.resolve(dir);
|
|
397140
397722
|
for (;; ) {
|
|
397141
|
-
if (fs32.existsSync(
|
|
397723
|
+
if (fs32.existsSync(path53.join(current, ".git")))
|
|
397142
397724
|
return current;
|
|
397143
|
-
const parent =
|
|
397725
|
+
const parent = path53.dirname(current);
|
|
397144
397726
|
if (parent === current)
|
|
397145
397727
|
return;
|
|
397146
397728
|
current = parent;
|
|
@@ -397163,7 +397745,7 @@ function mcpConfigEnabled() {
|
|
|
397163
397745
|
}
|
|
397164
397746
|
function ensureMcpConfig(options) {
|
|
397165
397747
|
const { dir, endpoint, requestedPort, boundPort, homeDir } = options;
|
|
397166
|
-
const file =
|
|
397748
|
+
const file = path53.join(dir, MCP_CONFIG_FILENAME);
|
|
397167
397749
|
try {
|
|
397168
397750
|
const existing = (() => {
|
|
397169
397751
|
try {
|
|
@@ -397190,18 +397772,18 @@ function ensureMcpConfig(options) {
|
|
|
397190
397772
|
try {
|
|
397191
397773
|
return fs32.realpathSync(p);
|
|
397192
397774
|
} catch {
|
|
397193
|
-
return
|
|
397775
|
+
return path53.resolve(p);
|
|
397194
397776
|
}
|
|
397195
397777
|
};
|
|
397196
397778
|
if (realish(dir) === realish(homeDir ?? os9.homedir())) {
|
|
397197
397779
|
return { action: "skipped-home", dir, endpoint, staleConfig };
|
|
397198
397780
|
}
|
|
397199
|
-
if (
|
|
397781
|
+
if (path53.resolve(dir) === path53.parse(path53.resolve(dir)).root) {
|
|
397200
397782
|
return { action: "skipped-root", dir, endpoint, staleConfig };
|
|
397201
397783
|
}
|
|
397202
397784
|
const gitRoot = findGitWorkTreeRoot(dir);
|
|
397203
397785
|
if (gitRoot !== undefined) {
|
|
397204
|
-
const rootCandidate =
|
|
397786
|
+
const rootCandidate = path53.join(gitRoot, MCP_CONFIG_FILENAME);
|
|
397205
397787
|
return {
|
|
397206
397788
|
action: "skipped-git",
|
|
397207
397789
|
dir,
|
|
@@ -400075,8 +400657,8 @@ var init_registry3 = __esm(() => {
|
|
|
400075
400657
|
});
|
|
400076
400658
|
|
|
400077
400659
|
// src/retrieval/model/package_entities.ts
|
|
400078
|
-
import
|
|
400079
|
-
import { fileURLToPath as
|
|
400660
|
+
import path54 from "path";
|
|
400661
|
+
import { fileURLToPath as fileURLToPath22 } from "url";
|
|
400080
400662
|
import { parseAnnotation as parseAnnotation3 } from "@malloydata/malloy-tag";
|
|
400081
400663
|
function truncateDoc(doc, max) {
|
|
400082
400664
|
if (doc.length <= max)
|
|
@@ -400175,7 +400757,7 @@ function makeSourceTextReader(pkg) {
|
|
|
400175
400757
|
let text;
|
|
400176
400758
|
try {
|
|
400177
400759
|
if (url.startsWith("file:") && packagePath) {
|
|
400178
|
-
const relative =
|
|
400760
|
+
const relative = path54.relative(packagePath, fileURLToPath22(url)).split(path54.sep).join("/");
|
|
400179
400761
|
text = relative && !relative.startsWith("..") ? pkg.getModel?.(relative)?.getCompiledSourceText?.() : undefined;
|
|
400180
400762
|
}
|
|
400181
400763
|
} catch {
|
|
@@ -401098,6 +401680,8 @@ var init_response2 = __esm(() => {
|
|
|
401098
401680
|
});
|
|
401099
401681
|
|
|
401100
401682
|
// src/retrieval/model/catalog.ts
|
|
401683
|
+
import { isSourceDef as isSourceDef21 } from "@malloydata/malloy";
|
|
401684
|
+
import { createHash as createHash20 } from "crypto";
|
|
401101
401685
|
function byText(a, b) {
|
|
401102
401686
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
401103
401687
|
}
|
|
@@ -401495,10 +402079,9 @@ function buildCatalog(input) {
|
|
|
401495
402079
|
const id = splitSourceId(compiled?.sourceID);
|
|
401496
402080
|
const definedIn = (id && id.source === name ? modelPathOfUrl(id.url, modelPaths) : undefined) ?? modelPath;
|
|
401497
402081
|
const parent = splitSourceId(compiled?.extends);
|
|
401498
|
-
const parentIn = parent ? modelPathOfUrl(parent.url, modelPaths) : undefined;
|
|
401499
402082
|
return {
|
|
401500
402083
|
definedIn,
|
|
401501
|
-
extendsKey: parent
|
|
402084
|
+
extendsKey: parent ? sourceKeyOf(parent.source, modelPathOfUrl(parent.url, modelPaths) ?? modelPath) : undefined
|
|
401502
402085
|
};
|
|
401503
402086
|
};
|
|
401504
402087
|
const extendsOf = new Map;
|
|
@@ -401518,6 +402101,7 @@ function buildCatalog(input) {
|
|
|
401518
402101
|
const key = sourceKeyOf(e.name, definedIn);
|
|
401519
402102
|
sourceKeyByContext.set(sourceContextKey(e.modelPath, e.name), key);
|
|
401520
402103
|
const gated = input.gatedByContext.get(sourceContextKey(e.modelPath, e.name)) ?? false;
|
|
402104
|
+
const partitionKey = gated ? input.partitionKeyByContext?.get(sourceContextKey(e.modelPath, e.name)) : undefined;
|
|
401521
402105
|
const existing = sources.get(key);
|
|
401522
402106
|
if (existing) {
|
|
401523
402107
|
existing.modelPaths.push(e.modelPath);
|
|
@@ -401525,9 +402109,12 @@ function buildCatalog(input) {
|
|
|
401525
402109
|
existing.node.entities.push(e);
|
|
401526
402110
|
if (e.modelPath === definedIn) {
|
|
401527
402111
|
existing.gated = gated;
|
|
402112
|
+
setPartitionKey(existing, partitionKey);
|
|
401528
402113
|
gatedByDefinition.add(key);
|
|
401529
402114
|
} else if (!gatedByDefinition.has(key)) {
|
|
402115
|
+
const agreed = !existing.gated ? partitionKey : !gated ? existing.partitionKey : samePartitionKey(existing.partitionKey, partitionKey) ? partitionKey : undefined;
|
|
401530
402116
|
existing.gated ||= gated;
|
|
402117
|
+
setPartitionKey(existing, agreed);
|
|
401531
402118
|
}
|
|
401532
402119
|
continue;
|
|
401533
402120
|
}
|
|
@@ -401554,6 +402141,9 @@ function buildCatalog(input) {
|
|
|
401554
402141
|
indexed: false,
|
|
401555
402142
|
entities: [e]
|
|
401556
402143
|
};
|
|
402144
|
+
const readDefinition = readDefinitionOf(model?.modelDef, e.name);
|
|
402145
|
+
const readGivens = readGivensOf(model?.modelDef, e.name);
|
|
402146
|
+
const hasAuthorize = input.authorizedByContext?.has(sourceContextKey(e.modelPath, e.name)) ?? false;
|
|
401557
402147
|
sources.set(key, {
|
|
401558
402148
|
key,
|
|
401559
402149
|
name: e.name,
|
|
@@ -401561,6 +402151,10 @@ function buildCatalog(input) {
|
|
|
401561
402151
|
definedIn,
|
|
401562
402152
|
node,
|
|
401563
402153
|
gated,
|
|
402154
|
+
...partitionKey ? { partitionKey } : {},
|
|
402155
|
+
...readDefinition ? { readDefinition } : {},
|
|
402156
|
+
...readGivens ? { readGivens } : {},
|
|
402157
|
+
...hasAuthorize ? { hasAuthorize } : {},
|
|
401564
402158
|
fields: []
|
|
401565
402159
|
});
|
|
401566
402160
|
nodes.set(node.key, node);
|
|
@@ -401947,13 +402541,29 @@ async function catalogInputOf(pkgIndex) {
|
|
|
401947
402541
|
});
|
|
401948
402542
|
}
|
|
401949
402543
|
const gatedByContext = new Map;
|
|
402544
|
+
const partitionKeyByContext = new Map;
|
|
402545
|
+
const authorizedByContext = new Set;
|
|
402546
|
+
const lockedByContext = (key) => {
|
|
402547
|
+
if (pkgIndex.droppedSources?.has(key))
|
|
402548
|
+
return true;
|
|
402549
|
+
const ctx = pkgIndex.sourceContext.get(key);
|
|
402550
|
+
return Boolean(ctx?.authorize?.length) || (ctx?.givens ?? []).some(isSecureGiven);
|
|
402551
|
+
};
|
|
401950
402552
|
for (const [key, ctx] of pkgIndex.sourceContext) {
|
|
401951
|
-
gatedByContext.set(key, Boolean(ctx.accessFilter?.length) || Boolean(ctx.authorize?.length) || (ctx.givens ?? []).some(
|
|
402553
|
+
gatedByContext.set(key, Boolean(ctx.accessFilter?.length) || Boolean(ctx.authorize?.length) || (ctx.givens ?? []).some(isSecureGiven));
|
|
402554
|
+
if (ctx.authorize?.length)
|
|
402555
|
+
authorizedByContext.add(key);
|
|
402556
|
+
const joinsLocked = (pkgIndex.topology.get(key) ?? []).some((r) => lockedByContext(sourceContextKey(r.targetModelPath, r.targetSource)));
|
|
402557
|
+
const partitionKey = joinsLocked ? undefined : partitionKeyOf(ctx);
|
|
402558
|
+
if (partitionKey)
|
|
402559
|
+
partitionKeyByContext.set(key, partitionKey);
|
|
401952
402560
|
}
|
|
401953
402561
|
return {
|
|
401954
402562
|
entities: pkgIndex.directEntities,
|
|
401955
402563
|
topology: pkgIndex.topology,
|
|
401956
402564
|
gatedByContext,
|
|
402565
|
+
partitionKeyByContext,
|
|
402566
|
+
authorizedByContext,
|
|
401957
402567
|
droppedSources: pkgIndex.droppedSources,
|
|
401958
402568
|
models,
|
|
401959
402569
|
modelCode: modelCodeReader(pkgIndex.pkg)
|
|
@@ -401970,7 +402580,124 @@ function modelCodeReader(pkg) {
|
|
|
401970
402580
|
return codes.get(url);
|
|
401971
402581
|
};
|
|
401972
402582
|
}
|
|
401973
|
-
|
|
402583
|
+
function isOtherNote(x) {
|
|
402584
|
+
if (!x || typeof x !== "object" || Array.isArray(x))
|
|
402585
|
+
return false;
|
|
402586
|
+
const keys = Object.keys(x);
|
|
402587
|
+
const text = x.text;
|
|
402588
|
+
return typeof text === "string" && keys.every((k) => k === "text" || k === "at") && !GATE_NOTE.test(text);
|
|
402589
|
+
}
|
|
402590
|
+
function isTableColumn(x) {
|
|
402591
|
+
if (!x || typeof x !== "object" || Array.isArray(x))
|
|
402592
|
+
return false;
|
|
402593
|
+
const f = x;
|
|
402594
|
+
return typeof f.name === "string" && typeof f.type === "string" && f.e === undefined && !isSourceDef21(x);
|
|
402595
|
+
}
|
|
402596
|
+
function compareFieldNames(a, b) {
|
|
402597
|
+
const x = String(a?.name ?? "");
|
|
402598
|
+
const y = String(b?.name ?? "");
|
|
402599
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
402600
|
+
}
|
|
402601
|
+
function readDefinitionOf(modelDef, name) {
|
|
402602
|
+
const compiled = compiledSource(modelDef, name);
|
|
402603
|
+
if (!compiled)
|
|
402604
|
+
return;
|
|
402605
|
+
const text = JSON.stringify([compiled, modelDef?.givens ?? null], (key, value) => {
|
|
402606
|
+
if (key === "location" || key === "at")
|
|
402607
|
+
return;
|
|
402608
|
+
if (typeof value === "string")
|
|
402609
|
+
return value.replace(QUERY_SOURCE_NAME, "QuerySource");
|
|
402610
|
+
if (!Array.isArray(value))
|
|
402611
|
+
return value;
|
|
402612
|
+
const kept = value.filter((v) => !isOtherNote(v));
|
|
402613
|
+
return key === "fields" ? kept.map((f) => isTableColumn(f) ? { name: f.name } : f).sort((a, b) => compareFieldNames(a, b)) : kept;
|
|
402614
|
+
});
|
|
402615
|
+
return createHash20("sha256").update(text, "utf8").digest("hex");
|
|
402616
|
+
}
|
|
402617
|
+
function isSecureGiven(g) {
|
|
402618
|
+
return (g.annotations ?? []).some((a) => /secure/i.test(a));
|
|
402619
|
+
}
|
|
402620
|
+
function partitionKeyOf(ctx) {
|
|
402621
|
+
const givens = ctx.givens ?? [];
|
|
402622
|
+
if (givens.some(isSecureGiven))
|
|
402623
|
+
return;
|
|
402624
|
+
if (!ctx.accessFilter?.length)
|
|
402625
|
+
return ctx.authorize?.length ? [] : undefined;
|
|
402626
|
+
const givenTypes = new Map(givens.flatMap((g) => g.type ? [[g.name, g.type]] : []));
|
|
402627
|
+
const byColumn = new Map;
|
|
402628
|
+
for (const gate of ctx.accessFilter) {
|
|
402629
|
+
const terms = accessFilterTerms(gate.expression, givenTypes);
|
|
402630
|
+
if (!terms?.length)
|
|
402631
|
+
return;
|
|
402632
|
+
for (const term of terms) {
|
|
402633
|
+
if (term.op !== "=")
|
|
402634
|
+
return;
|
|
402635
|
+
if (!SCALAR_GIVEN_TYPES2.has(givenTypes.get(term.given) ?? ""))
|
|
402636
|
+
return;
|
|
402637
|
+
const seen = byColumn.get(term.field_path);
|
|
402638
|
+
if (seen !== undefined && seen !== term.given)
|
|
402639
|
+
return;
|
|
402640
|
+
byColumn.set(term.field_path, term.given);
|
|
402641
|
+
}
|
|
402642
|
+
}
|
|
402643
|
+
return [...byColumn].sort(([a], [b]) => compareText(a, b)).map(([column, given]) => ({
|
|
402644
|
+
column,
|
|
402645
|
+
given,
|
|
402646
|
+
type: givenTypes.get(given) ?? "string"
|
|
402647
|
+
}));
|
|
402648
|
+
}
|
|
402649
|
+
function readGivensOf(modelDef, name) {
|
|
402650
|
+
const compiled = compiledSource(modelDef, name);
|
|
402651
|
+
if (!compiled)
|
|
402652
|
+
return;
|
|
402653
|
+
const declared = modelDef?.givens ?? {};
|
|
402654
|
+
const nameOf = (id) => declared[id]?.name;
|
|
402655
|
+
const names = new Set;
|
|
402656
|
+
const ids = [];
|
|
402657
|
+
JSON.stringify(compiled, (_key, value) => {
|
|
402658
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
402659
|
+
const v = value;
|
|
402660
|
+
if (v.node === "given" && typeof v.id === "string")
|
|
402661
|
+
ids.push(v.id);
|
|
402662
|
+
if (v.node === "given" && typeof v.refName === "string")
|
|
402663
|
+
names.add(v.refName);
|
|
402664
|
+
}
|
|
402665
|
+
if (typeof value === "string") {
|
|
402666
|
+
for (const m of value.matchAll(GIVEN_IN_TEXT))
|
|
402667
|
+
names.add(m[1]);
|
|
402668
|
+
}
|
|
402669
|
+
return value;
|
|
402670
|
+
});
|
|
402671
|
+
for (let i = 0;i < ids.length; i += 1) {
|
|
402672
|
+
const given = declared[ids[i]];
|
|
402673
|
+
if (!given)
|
|
402674
|
+
continue;
|
|
402675
|
+
names.add(given.name);
|
|
402676
|
+
for (const u of given.givenUsage ?? []) {
|
|
402677
|
+
if (!ids.includes(u.id))
|
|
402678
|
+
ids.push(u.id);
|
|
402679
|
+
}
|
|
402680
|
+
}
|
|
402681
|
+
for (const n of [...names]) {
|
|
402682
|
+
const id = Object.keys(declared).find((k) => nameOf(k) === n);
|
|
402683
|
+
for (const u of id && declared[id]?.givenUsage || []) {
|
|
402684
|
+
const other = nameOf(u.id);
|
|
402685
|
+
if (other)
|
|
402686
|
+
names.add(other);
|
|
402687
|
+
}
|
|
402688
|
+
}
|
|
402689
|
+
return [...names].sort();
|
|
402690
|
+
}
|
|
402691
|
+
function samePartitionKey(a, b) {
|
|
402692
|
+
return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
|
|
402693
|
+
}
|
|
402694
|
+
function setPartitionKey(source, key) {
|
|
402695
|
+
if (key)
|
|
402696
|
+
source.partitionKey = key;
|
|
402697
|
+
else
|
|
402698
|
+
delete source.partitionKey;
|
|
402699
|
+
}
|
|
402700
|
+
var JOIN_WALK_MAX_HOPS = 8, JOIN_WALK_MAX_PATHS = 1000, ROUTE_MAX_DEPTH = 2, OWN_GATE, REFERENCED_PATH_SKIPPED_KEYS, GATE_NOTE, QUERY_SOURCE_NAME, SCALAR_GIVEN_TYPES2, GIVEN_IN_TEXT;
|
|
401974
402701
|
var init_catalog = __esm(() => {
|
|
401975
402702
|
init_annotation_reader();
|
|
401976
402703
|
init_array_query();
|
|
@@ -401978,8 +402705,19 @@ var init_catalog = __esm(() => {
|
|
|
401978
402705
|
init_model_text();
|
|
401979
402706
|
init_package_entities();
|
|
401980
402707
|
init_response2();
|
|
402708
|
+
init_access_gates();
|
|
401981
402709
|
OWN_GATE = /^#\|?\s*[([{<]?\s*(access_filter|authorize)\b/;
|
|
401982
402710
|
REFERENCED_PATH_SKIPPED_KEYS = new Set(["at", "path"]);
|
|
402711
|
+
GATE_NOTE = /#\|?\s*[([{<]?\s*(access_filter|authorize)\b/;
|
|
402712
|
+
QUERY_SOURCE_NAME = /QuerySource-[0-9a-f-]{36}/g;
|
|
402713
|
+
SCALAR_GIVEN_TYPES2 = new Set([
|
|
402714
|
+
"number",
|
|
402715
|
+
"string",
|
|
402716
|
+
"boolean",
|
|
402717
|
+
"date",
|
|
402718
|
+
"timestamp"
|
|
402719
|
+
]);
|
|
402720
|
+
GIVEN_IN_TEXT = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
|
|
401983
402721
|
});
|
|
401984
402722
|
|
|
401985
402723
|
// src/retrieval/index/catalog_store.ts
|
|
@@ -402040,12 +402778,13 @@ var init_catalog_store = __esm(() => {
|
|
|
402040
402778
|
"node_questions",
|
|
402041
402779
|
"catalog_embeddings",
|
|
402042
402780
|
"dimension_values",
|
|
402043
|
-
"value_embeddings"
|
|
402781
|
+
"value_embeddings",
|
|
402782
|
+
"dimension_value_reads"
|
|
402044
402783
|
];
|
|
402045
402784
|
});
|
|
402046
402785
|
|
|
402047
402786
|
// src/retrieval/llm/prompts/source_summary.ts
|
|
402048
|
-
import { createHash as
|
|
402787
|
+
import { createHash as createHash21 } from "crypto";
|
|
402049
402788
|
function undocumentedOneLine(sourceName) {
|
|
402050
402789
|
return `The \`${sourceName}\` source.`;
|
|
402051
402790
|
}
|
|
@@ -402065,7 +402804,7 @@ function renderSourceSummaryUserPrompt(input) {
|
|
|
402065
402804
|
`);
|
|
402066
402805
|
}
|
|
402067
402806
|
function sourceSummaryPromptHash(instructions) {
|
|
402068
|
-
return
|
|
402807
|
+
return createHash21("sha256").update(instructions).update("\x00").update(renderSourceSummaryUserPrompt({ source: "", doc: "", fields: "" })).digest("hex");
|
|
402069
402808
|
}
|
|
402070
402809
|
var ONE_LINE_SUMMARY_MAX_CHARS2 = 120, NO_SOURCE_DOCS = "No source docs.", DEFAULT_SOURCE_SUMMARY_INSTRUCTIONS, REPLY_FORMAT = `Reply with one JSON object and nothing else:
|
|
402071
402810
|
{"summary": "<prose>", "one_line_summary": "<one sentence>"}`;
|
|
@@ -402223,7 +402962,7 @@ var init_llm_calls = __esm(() => {
|
|
|
402223
402962
|
});
|
|
402224
402963
|
|
|
402225
402964
|
// src/retrieval/index/source_summaries.ts
|
|
402226
|
-
import { createHash as
|
|
402965
|
+
import { createHash as createHash22 } from "crypto";
|
|
402227
402966
|
function resolveSourceSummarySettings(pkg, chatSlot) {
|
|
402228
402967
|
const retrieval = pkg?.getRetrievalSettings?.() ?? DEFAULT_PACKAGE_RETRIEVAL;
|
|
402229
402968
|
if (sourceSummaryConfigOf(retrieval).enabled === false)
|
|
@@ -402420,7 +403159,7 @@ function boundedPrompt(name, doc, own, resolve, maxPromptChars) {
|
|
|
402420
403159
|
}
|
|
402421
403160
|
}
|
|
402422
403161
|
function sourceSummaryInputHash(input, settings) {
|
|
402423
|
-
return
|
|
403162
|
+
return createHash22("sha256").update(settings.promptHash).update("\x00").update(settings.modelId).update("\x00").update(input.prompt).digest("hex");
|
|
402424
403163
|
}
|
|
402425
403164
|
function currentSummaryHashes(entities, settings, hashesCache) {
|
|
402426
403165
|
const frozen = Object.isFrozen(entities);
|
|
@@ -402747,9 +403486,9 @@ var init_derived_text = __esm(() => {
|
|
|
402747
403486
|
});
|
|
402748
403487
|
|
|
402749
403488
|
// src/retrieval/llm/llm_cache.ts
|
|
402750
|
-
import { createHash as
|
|
403489
|
+
import { createHash as createHash23 } from "crypto";
|
|
402751
403490
|
function sha256(text) {
|
|
402752
|
-
return
|
|
403491
|
+
return createHash23("sha256").update(text).digest("hex");
|
|
402753
403492
|
}
|
|
402754
403493
|
async function generateCached(args) {
|
|
402755
403494
|
const { db, table, environmentName, packageName } = args;
|
|
@@ -403280,6 +404019,9 @@ async function queryDistinctValues(request, deps) {
|
|
|
403280
404019
|
if (request.stem && !LIKE_SAFE_STEM.test(request.stem)) {
|
|
403281
404020
|
throw new Error("A value-scan stem may contain only letters and digits");
|
|
403282
404021
|
}
|
|
404022
|
+
if (request.partitionColumns?.length && (!request.system || !request.givens)) {
|
|
404023
|
+
throw new Error("Only the index build reads a keyed source's values, and only with the givens that name its keys");
|
|
404024
|
+
}
|
|
403283
404025
|
let refusal;
|
|
403284
404026
|
const queryModelResolver = deps.queryModelResolver ?? plainQueryModelResolver;
|
|
403285
404027
|
try {
|
|
@@ -403295,14 +404037,17 @@ async function queryDistinctValues(request, deps) {
|
|
|
403295
404037
|
const dim = typeof request.dimension === "string" ? quotedIdentifier(request.dimension) : request.dimension.map(quotedIdentifier).join(".");
|
|
403296
404038
|
const where = request.stem ? `${dim} != null and lower(${dim}) ~ ${stringLiteral(`%${request.stem}%`)}` : `${dim} != null`;
|
|
403297
404039
|
const limit = Math.trunc(request.limit) + 1;
|
|
403298
|
-
const
|
|
404040
|
+
const keys = (request.partitionColumns ?? []).map((column, i) => `, k${i} is ${column.split(".").map(quotedIdentifier).join(".")}`);
|
|
404041
|
+
const groupBy = `group_by: v is ${dim}${keys.join("")}`;
|
|
404042
|
+
const body = request.counted ? `where: ${where} ${groupBy} aggregate: n is count() order_by: n desc limit: ${limit}` : `where: ${where} ${groupBy} limit: ${limit}`;
|
|
403299
404043
|
const query = `run: ${quotedIdentifier(request.source)} -> { ${body} }`;
|
|
404044
|
+
const givens = request.system ? declaredOnly(request.givens, found.model.getGivens()) : request.givens;
|
|
403300
404045
|
const slot = deps.querySlots.tryAcquire(request.routeLabel);
|
|
403301
404046
|
try {
|
|
403302
404047
|
const { compactResult } = await runWithQueryTimeout((signal) => found.model.runQuery(audit, {
|
|
403303
404048
|
query,
|
|
403304
404049
|
filterParams: request.filterParams,
|
|
403305
|
-
givens
|
|
404050
|
+
givens,
|
|
403306
404051
|
abortSignal: signal,
|
|
403307
404052
|
responseShape: "compact"
|
|
403308
404053
|
}, QueryPrivileges.none), request.timeoutMs);
|
|
@@ -403325,6 +404070,13 @@ async function queryDistinctValues(request, deps) {
|
|
|
403325
404070
|
throw error;
|
|
403326
404071
|
}
|
|
403327
404072
|
}
|
|
404073
|
+
function declaredOnly(givens, declared) {
|
|
404074
|
+
if (!givens)
|
|
404075
|
+
return;
|
|
404076
|
+
const names = new Set(declared.map((g) => g.name));
|
|
404077
|
+
const kept = Object.entries(givens).filter(([name]) => names.has(name));
|
|
404078
|
+
return kept.length > 0 ? Object.fromEntries(kept) : undefined;
|
|
404079
|
+
}
|
|
403328
404080
|
var plainQueryModelResolver = async (environmentStore, environmentName, packageName, modelPath) => {
|
|
403329
404081
|
const { environment, pkg, model } = await resolveQueryModel(environmentStore, { environmentName, packageName, modelPath });
|
|
403330
404082
|
if (!model || model.getType() === "notebook") {
|
|
@@ -403509,6 +404261,62 @@ var init_vectors = __esm(() => {
|
|
|
403509
404261
|
});
|
|
403510
404262
|
|
|
403511
404263
|
// src/retrieval/index/values_index.ts
|
|
404264
|
+
import { createHash as createHash24 } from "crypto";
|
|
404265
|
+
function partitionKeyPart(raw, type) {
|
|
404266
|
+
const v = Array.isArray(raw) && raw.length === 1 ? raw[0] : raw;
|
|
404267
|
+
if (v === null || v === undefined || Array.isArray(v))
|
|
404268
|
+
return;
|
|
404269
|
+
if (v instanceof Date) {
|
|
404270
|
+
const iso = v.toISOString();
|
|
404271
|
+
return iso.endsWith("T00:00:00.000Z") ? iso.slice(0, 10) : iso;
|
|
404272
|
+
}
|
|
404273
|
+
if (type !== "number")
|
|
404274
|
+
return String(v);
|
|
404275
|
+
if (typeof v === "bigint")
|
|
404276
|
+
return v.toString();
|
|
404277
|
+
const text = String(v).trim();
|
|
404278
|
+
if (/^[+-]?\d+$/.test(text))
|
|
404279
|
+
return BigInt(text).toString();
|
|
404280
|
+
const n = Number(text);
|
|
404281
|
+
return text !== "" && Number.isFinite(n) ? String(n) : text;
|
|
404282
|
+
}
|
|
404283
|
+
function callerKeyOf(catalog, givens, refused = new Set) {
|
|
404284
|
+
return (dimension) => {
|
|
404285
|
+
const node = catalog.nodes.get(dimension);
|
|
404286
|
+
if (!node || refused.has(node.sourceKey))
|
|
404287
|
+
return;
|
|
404288
|
+
const key = catalog.sources.get(node.sourceKey)?.partitionKey;
|
|
404289
|
+
if (!key)
|
|
404290
|
+
return;
|
|
404291
|
+
return partitionKeyText(key.map((p) => givens?.[p.given]), key.map((p) => p.type));
|
|
404292
|
+
};
|
|
404293
|
+
}
|
|
404294
|
+
async function lockedSourcesFor(catalog, givens, modelOf) {
|
|
404295
|
+
const refused = new Set;
|
|
404296
|
+
for (const source of catalog.sources.values()) {
|
|
404297
|
+
if (!source.hasAuthorize || !source.partitionKey)
|
|
404298
|
+
continue;
|
|
404299
|
+
const model = modelOf(source.modelPaths[0]);
|
|
404300
|
+
try {
|
|
404301
|
+
if (!model)
|
|
404302
|
+
throw new Error("no model");
|
|
404303
|
+
await model.assertAuthorized(source.name, givens ?? {});
|
|
404304
|
+
} catch {
|
|
404305
|
+
refused.add(source.key);
|
|
404306
|
+
}
|
|
404307
|
+
}
|
|
404308
|
+
return refused;
|
|
404309
|
+
}
|
|
404310
|
+
function partitionKeyText(parts, types) {
|
|
404311
|
+
const out = [];
|
|
404312
|
+
for (const [i, raw] of parts.entries()) {
|
|
404313
|
+
const part = partitionKeyPart(raw, types[i] ?? "string");
|
|
404314
|
+
if (part === undefined)
|
|
404315
|
+
return;
|
|
404316
|
+
out.push(part);
|
|
404317
|
+
}
|
|
404318
|
+
return out.join("\x00");
|
|
404319
|
+
}
|
|
403512
404320
|
function trigrams(normalized) {
|
|
403513
404321
|
const t = ` ${normalized} `;
|
|
403514
404322
|
const out = new Set;
|
|
@@ -403591,7 +404399,7 @@ class ValueIndex {
|
|
|
403591
404399
|
const score = dot(vec, m.matrix.subarray(t * m.dims, (t + 1) * m.dims));
|
|
403592
404400
|
if (score < floor)
|
|
403593
404401
|
continue;
|
|
403594
|
-
if (!m.rows[t].some((i) => allow
|
|
404402
|
+
if (!m.rows[t].some((i) => allowed(allow, this.values[i])))
|
|
403595
404403
|
continue;
|
|
403596
404404
|
hits.push({ t, score });
|
|
403597
404405
|
}
|
|
@@ -403605,7 +404413,7 @@ class ValueIndex {
|
|
|
403605
404413
|
break;
|
|
403606
404414
|
for (const i of m.rows[h.t]) {
|
|
403607
404415
|
const v = this.values[i];
|
|
403608
|
-
if (!allow
|
|
404416
|
+
if (!allowed(allow, v))
|
|
403609
404417
|
continue;
|
|
403610
404418
|
out.push({
|
|
403611
404419
|
value: v.value,
|
|
@@ -403621,14 +404429,14 @@ class ValueIndex {
|
|
|
403621
404429
|
const norm = normalizeText(phrase);
|
|
403622
404430
|
if (!norm)
|
|
403623
404431
|
return [];
|
|
403624
|
-
const exact = (this.byNormalized.get(norm) ?? []).map((i) => this.values[i]).filter((v) => allow
|
|
404432
|
+
const exact = (this.byNormalized.get(norm) ?? []).map((i) => this.values[i]).filter((v) => allowed(allow, v)).map((v) => ({
|
|
403625
404433
|
value: v.value,
|
|
403626
404434
|
dimension: v.dimension,
|
|
403627
404435
|
score: v.value === phrase ? 1 : 0.98,
|
|
403628
404436
|
how: "exact"
|
|
403629
404437
|
}));
|
|
403630
404438
|
const done = new Set(exact.map((m) => m.dimension));
|
|
403631
|
-
const open = (
|
|
404439
|
+
const open = (v) => allowed(allow, v) && !done.has(v.dimension);
|
|
403632
404440
|
const candidates = new Set;
|
|
403633
404441
|
const words = norm.split(" ").filter(Boolean);
|
|
403634
404442
|
for (const w of words) {
|
|
@@ -403649,7 +404457,7 @@ class ValueIndex {
|
|
|
403649
404457
|
const byWords = [];
|
|
403650
404458
|
for (const i of candidates) {
|
|
403651
404459
|
const v = this.values[i];
|
|
403652
|
-
if (!open(v
|
|
404460
|
+
if (!open(v))
|
|
403653
404461
|
continue;
|
|
403654
404462
|
const score = scoreValue(phrase, v.value);
|
|
403655
404463
|
if (score >= VALUE_MATCH_FLOOR) {
|
|
@@ -403676,7 +404484,7 @@ class ValueIndex {
|
|
|
403676
404484
|
const byGrams = [];
|
|
403677
404485
|
for (const [i, shared] of overlap) {
|
|
403678
404486
|
const v = this.values[i];
|
|
403679
|
-
if (!open(v
|
|
404487
|
+
if (!open(v))
|
|
403680
404488
|
continue;
|
|
403681
404489
|
const theirs = trigrams(v.normalized).size;
|
|
403682
404490
|
const jaccard = shared / (grams.size + theirs - shared);
|
|
@@ -403718,6 +404526,38 @@ class ValueIndex {
|
|
|
403718
404526
|
return [...byDim.values()].sort((a, b) => b.score - a.score || (a.dimension < b.dimension ? -1 : a.dimension > b.dimension ? 1 : 0));
|
|
403719
404527
|
}
|
|
403720
404528
|
}
|
|
404529
|
+
function combinationsOf(givens) {
|
|
404530
|
+
const entries = Object.entries(givens ?? {});
|
|
404531
|
+
if (entries.length === 0)
|
|
404532
|
+
return [undefined];
|
|
404533
|
+
let out = [{}];
|
|
404534
|
+
for (const [name, list] of entries) {
|
|
404535
|
+
out = out.flatMap((c) => list.map((v) => ({ ...c, [name]: v })));
|
|
404536
|
+
}
|
|
404537
|
+
return out;
|
|
404538
|
+
}
|
|
404539
|
+
async function readEachCombination(combinations, read) {
|
|
404540
|
+
if (combinations.length === 1)
|
|
404541
|
+
return read(combinations[0], 0);
|
|
404542
|
+
const merged = new Map;
|
|
404543
|
+
let truncated = false;
|
|
404544
|
+
for (const [i, givens] of combinations.entries()) {
|
|
404545
|
+
const got = await read(givens, i);
|
|
404546
|
+
truncated ||= got.truncated;
|
|
404547
|
+
for (const v of got.values) {
|
|
404548
|
+
const id = `${v.key ?? ""}\x00${v.value}`;
|
|
404549
|
+
const seen = merged.get(id);
|
|
404550
|
+
if (seen)
|
|
404551
|
+
seen.count += v.count;
|
|
404552
|
+
else
|
|
404553
|
+
merged.set(id, { ...v });
|
|
404554
|
+
}
|
|
404555
|
+
}
|
|
404556
|
+
return { values: [...merged.values()], truncated };
|
|
404557
|
+
}
|
|
404558
|
+
function allowed(allow, v) {
|
|
404559
|
+
return v.key === undefined ? allow(v.dimension) : allow(v.dimension, v.key);
|
|
404560
|
+
}
|
|
403721
404561
|
function push(map, key, i) {
|
|
403722
404562
|
const list = map.get(key);
|
|
403723
404563
|
if (list)
|
|
@@ -403741,12 +404581,20 @@ function sortMatches(list) {
|
|
|
403741
404581
|
function isTransientReadFailure(error) {
|
|
403742
404582
|
return error instanceof ServiceUnavailableError || error instanceof QueryTimeoutError;
|
|
403743
404583
|
}
|
|
403744
|
-
function readable2(catalog, node) {
|
|
404584
|
+
function readable2(catalog, node, givens, packageName) {
|
|
403745
404585
|
if (!node.indexed)
|
|
403746
404586
|
return { ok: false, reason: "not tagged #(index)" };
|
|
403747
404587
|
if (node.joinPath)
|
|
403748
404588
|
return { ok: false, reason: "a field of a join" };
|
|
403749
|
-
|
|
404589
|
+
const owner = catalog.sources.get(node.sourceKey);
|
|
404590
|
+
const unlisted = owner?.partitionKey?.map((p) => p.given).filter((g) => !givens?.[g]);
|
|
404591
|
+
if (unlisted?.length) {
|
|
404592
|
+
return {
|
|
404593
|
+
ok: false,
|
|
404594
|
+
reason: `its source's rows are split by ${unlisted.join(", ")}, and reading every value of it scans the whole table. ` + `Fix: list the ones to index in publisher.config.json, "retrieval": { "dimensionValues": { "givens": { "${packageName ?? "<package>"}": { "${unlisted[0]}": [...] } } } }`
|
|
404595
|
+
};
|
|
404596
|
+
}
|
|
404597
|
+
if (owner?.gated && !owner.partitionKey) {
|
|
403750
404598
|
return {
|
|
403751
404599
|
ok: false,
|
|
403752
404600
|
reason: "its source has an access gate; values are read only through a query with the caller's givens"
|
|
@@ -403763,16 +404611,12 @@ function readable2(catalog, node) {
|
|
|
403763
404611
|
async function buildValueIndex(args) {
|
|
403764
404612
|
const started = Date.now();
|
|
403765
404613
|
const budgetMs = args.readBudgetMs ?? VALUE_READ_BUDGET_MS;
|
|
403766
|
-
const
|
|
403767
|
-
const
|
|
403768
|
-
|
|
403769
|
-
|
|
403770
|
-
continue;
|
|
403771
|
-
const list = previousValues.get(v.dimension) ?? [];
|
|
403772
|
-
list.push(v);
|
|
403773
|
-
previousValues.set(v.dimension, list);
|
|
403774
|
-
}
|
|
404614
|
+
const maxAgeMs = args.reuseMaxAgeMs ?? VALUE_REUSE_MAX_AGE_MS;
|
|
404615
|
+
const stored = args.db && args.read ? await loadReads(args.db, args.read.environmentName, args.read.packageName) : new Map;
|
|
404616
|
+
const reads = [];
|
|
404617
|
+
const connections = args.read ? await connectionsDigest(args.read) : "";
|
|
403775
404618
|
const values = [];
|
|
404619
|
+
const givenCombinations = combinationsOf(args.givens);
|
|
403776
404620
|
const report = {
|
|
403777
404621
|
dimensionsRead: 0,
|
|
403778
404622
|
dimensionsReused: 0,
|
|
@@ -403801,7 +404645,7 @@ async function buildValueIndex(args) {
|
|
|
403801
404645
|
}
|
|
403802
404646
|
if (!node.indexed)
|
|
403803
404647
|
continue;
|
|
403804
|
-
const check = readable2(args.catalog, node);
|
|
404648
|
+
const check = readable2(args.catalog, node, args.givens, args.read?.packageName);
|
|
403805
404649
|
if (!check.ok) {
|
|
403806
404650
|
report.skipped.push({ dimension: node.key, reason: check.reason });
|
|
403807
404651
|
continue;
|
|
@@ -403815,17 +404659,18 @@ async function buildValueIndex(args) {
|
|
|
403815
404659
|
}
|
|
403816
404660
|
if (args.shouldStop?.())
|
|
403817
404661
|
break;
|
|
403818
|
-
|
|
403819
|
-
|
|
403820
|
-
|
|
403821
|
-
|
|
403822
|
-
|
|
403823
|
-
|
|
403824
|
-
|
|
403825
|
-
|
|
403826
|
-
|
|
403827
|
-
}
|
|
403828
|
-
|
|
404662
|
+
const source = args.catalog.sources.get(node.sourceKey);
|
|
404663
|
+
const partitionKey = source?.partitionKey;
|
|
404664
|
+
const readKey = source?.readDefinition ? readKeyOf(source.readDefinition, node, args.cap, partitionKey, connections) : undefined;
|
|
404665
|
+
const combinations = combinationsFor(givenCombinations, source?.readGivens, partitionKey);
|
|
404666
|
+
const givenIds = combinations.map(givensId);
|
|
404667
|
+
const now = Date.now();
|
|
404668
|
+
const kept = givenIds.map((id) => {
|
|
404669
|
+
const old = stored.get(`${node.key}\x00${id}`);
|
|
404670
|
+
return readKey && old?.readKey === readKey && now - old.readAt < maxAgeMs ? old : undefined;
|
|
404671
|
+
});
|
|
404672
|
+
const allKept = kept.every((k) => k !== undefined);
|
|
404673
|
+
if (!allKept && Date.now() - started >= budgetMs) {
|
|
403829
404674
|
report.failed.push({
|
|
403830
404675
|
dimension: node.key,
|
|
403831
404676
|
reason: `not read: this build's value reads used their ${Math.round(budgetMs / 1000)} s budget`
|
|
@@ -403834,20 +404679,51 @@ async function buildValueIndex(args) {
|
|
|
403834
404679
|
}
|
|
403835
404680
|
const fetcher = args.read.fetcher;
|
|
403836
404681
|
try {
|
|
403837
|
-
const got = await
|
|
403838
|
-
|
|
403839
|
-
|
|
403840
|
-
|
|
403841
|
-
|
|
403842
|
-
|
|
403843
|
-
|
|
403844
|
-
|
|
403845
|
-
|
|
403846
|
-
|
|
403847
|
-
|
|
404682
|
+
const got = await readEachCombination(combinations, async (givens, i) => {
|
|
404683
|
+
const old = kept[i];
|
|
404684
|
+
if (old) {
|
|
404685
|
+
reads.push(old);
|
|
404686
|
+
return { values: old.values, truncated: old.truncated };
|
|
404687
|
+
}
|
|
404688
|
+
if (Date.now() - started >= budgetMs)
|
|
404689
|
+
throw new BudgetSpent;
|
|
404690
|
+
const fresh = await fetcher({
|
|
404691
|
+
environmentStore: args.read.environmentStore,
|
|
404692
|
+
environmentName: args.read.environmentName,
|
|
404693
|
+
packageName: args.read.packageName,
|
|
404694
|
+
modelPath: node.modelPaths[0],
|
|
404695
|
+
source: node.source,
|
|
404696
|
+
dimension: node.name,
|
|
404697
|
+
limit: args.cap,
|
|
404698
|
+
timeoutMs: VALUE_READ_TIMEOUT_MS,
|
|
404699
|
+
...givens ? { givens } : {},
|
|
404700
|
+
...partitionKey ? {
|
|
404701
|
+
partitionColumns: partitionKey.map((p) => p.column),
|
|
404702
|
+
partitionTypes: partitionKey.map((p) => p.type)
|
|
404703
|
+
} : {}
|
|
404704
|
+
});
|
|
404705
|
+
if (readKey) {
|
|
404706
|
+
reads.push({
|
|
404707
|
+
dimension: node.key,
|
|
404708
|
+
givens: givenIds[i],
|
|
404709
|
+
readKey,
|
|
404710
|
+
truncated: fresh.truncated,
|
|
404711
|
+
values: fresh.values,
|
|
404712
|
+
readAt: Date.now()
|
|
404713
|
+
});
|
|
404714
|
+
}
|
|
404715
|
+
return fresh;
|
|
404716
|
+
});
|
|
404717
|
+
if (allKept)
|
|
404718
|
+
report.dimensionsReused += 1;
|
|
404719
|
+
else
|
|
404720
|
+
report.dimensionsRead += 1;
|
|
403848
404721
|
if (got.truncated)
|
|
403849
404722
|
report.cut.push({ dimension: node.key, kept: got.values.length });
|
|
403850
|
-
for (const { value, count } of got.values) {
|
|
404723
|
+
for (const { value, count, key: readKeyText } of got.values) {
|
|
404724
|
+
const key = !partitionKey ? undefined : partitionKey.length === 0 ? "" : readKeyText;
|
|
404725
|
+
if (partitionKey && key === undefined)
|
|
404726
|
+
continue;
|
|
403851
404727
|
const normalized = normalizeText(value);
|
|
403852
404728
|
if (!normalized)
|
|
403853
404729
|
continue;
|
|
@@ -403856,20 +404732,31 @@ async function buildValueIndex(args) {
|
|
|
403856
404732
|
normalized,
|
|
403857
404733
|
count,
|
|
403858
404734
|
dimension: node.key,
|
|
403859
|
-
origin: "data"
|
|
404735
|
+
origin: "data",
|
|
404736
|
+
...key !== undefined ? { key } : {}
|
|
403860
404737
|
});
|
|
403861
404738
|
report.valuesFromData += 1;
|
|
403862
404739
|
}
|
|
403863
404740
|
} catch (error) {
|
|
404741
|
+
if (error instanceof BudgetSpent) {
|
|
404742
|
+
report.failed.push({
|
|
404743
|
+
dimension: node.key,
|
|
404744
|
+
reason: `not read in full: this build's value reads used their ${Math.round(budgetMs / 1000)} s budget`
|
|
404745
|
+
});
|
|
404746
|
+
continue;
|
|
404747
|
+
}
|
|
404748
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
404749
|
+
const unset = /Given '([^']+)' has no value and no default/.exec(message);
|
|
403864
404750
|
(isTransientReadFailure(error) ? report.failed : report.skipped).push({
|
|
403865
404751
|
dimension: node.key,
|
|
403866
|
-
reason: `the read
|
|
404752
|
+
reason: unset ? `the read needs the given ${unset[1]}, which has no default. Fix: name its values for this package in publisher.config.json, "retrieval": { "dimensionValues": { "givens": { "${args.read.packageName}": { "${unset[1]}": [...] } } } }` : `the read failed: ${message.slice(0, 200)}`
|
|
403867
404753
|
});
|
|
403868
404754
|
}
|
|
403869
404755
|
}
|
|
403870
404756
|
if (args.db && args.read) {
|
|
403871
404757
|
try {
|
|
403872
404758
|
await saveValues(args.db, args.read.environmentName, args.read.packageName, values);
|
|
404759
|
+
await saveReads(args.db, args.read.environmentName, args.read.packageName, reads);
|
|
403873
404760
|
} catch (error) {
|
|
403874
404761
|
logger.warn("[get_context fcj] The value index could not be written to its table", {
|
|
403875
404762
|
error: error instanceof Error ? error.message : String(error)
|
|
@@ -403879,6 +404766,116 @@ async function buildValueIndex(args) {
|
|
|
403879
404766
|
report.ms = Date.now() - started;
|
|
403880
404767
|
return { index: new ValueIndex(values), report };
|
|
403881
404768
|
}
|
|
404769
|
+
function givensId(givens) {
|
|
404770
|
+
if (!givens)
|
|
404771
|
+
return "";
|
|
404772
|
+
return JSON.stringify(Object.keys(givens).sort().map((k) => [k, givens[k]]));
|
|
404773
|
+
}
|
|
404774
|
+
function combinationsFor(combinations, readGivens, partitionKey) {
|
|
404775
|
+
if (!readGivens)
|
|
404776
|
+
return [...combinations];
|
|
404777
|
+
const needed = new Set([
|
|
404778
|
+
...readGivens,
|
|
404779
|
+
...(partitionKey ?? []).map((p) => p.given)
|
|
404780
|
+
]);
|
|
404781
|
+
const out = new Map;
|
|
404782
|
+
for (const c of combinations) {
|
|
404783
|
+
const kept = Object.entries(c ?? {}).filter(([k]) => needed.has(k));
|
|
404784
|
+
const projected = kept.length ? Object.fromEntries(kept) : undefined;
|
|
404785
|
+
const id = givensId(projected);
|
|
404786
|
+
if (!out.has(id))
|
|
404787
|
+
out.set(id, projected);
|
|
404788
|
+
}
|
|
404789
|
+
return [...out.values()];
|
|
404790
|
+
}
|
|
404791
|
+
async function connectionsDigest(read) {
|
|
404792
|
+
try {
|
|
404793
|
+
const environment = await read.environmentStore.getEnvironment(parseEnvironmentName(read.environmentName));
|
|
404794
|
+
const text = JSON.stringify(environment.listApiConnections(), (key, value) => key && CREDENTIAL_KEY.test(key) ? undefined : value);
|
|
404795
|
+
return createHash24("sha256").update(text, "utf8").digest("hex");
|
|
404796
|
+
} catch (error) {
|
|
404797
|
+
logger.warn("[get_context fcj] The connections could not be read for the value read key; every dimension is read", { error: error instanceof Error ? error.message : String(error) });
|
|
404798
|
+
return `unknown-${Date.now()}`;
|
|
404799
|
+
}
|
|
404800
|
+
}
|
|
404801
|
+
function readKeyOf(readDefinition, node, cap, partitionKey, connections) {
|
|
404802
|
+
return createHash24("sha256").update(JSON.stringify([
|
|
404803
|
+
readDefinition,
|
|
404804
|
+
node.modelPaths[0],
|
|
404805
|
+
node.source,
|
|
404806
|
+
node.name,
|
|
404807
|
+
cap,
|
|
404808
|
+
(partitionKey ?? []).map((p) => [p.column, p.type]),
|
|
404809
|
+
connections
|
|
404810
|
+
]), "utf8").digest("hex");
|
|
404811
|
+
}
|
|
404812
|
+
async function loadReads(db, environmentName, packageName) {
|
|
404813
|
+
const out = new Map;
|
|
404814
|
+
let rows;
|
|
404815
|
+
try {
|
|
404816
|
+
rows = await db.all(`SELECT dimension_key, givens, read_key, truncated, read_values, epoch_ms(read_at) AS read_ms
|
|
404817
|
+
FROM dimension_value_reads WHERE environment_name = ? AND package_name = ?`, [environmentName, packageName]);
|
|
404818
|
+
} catch (error) {
|
|
404819
|
+
logger.warn("[get_context fcj] Stored value reads could not be loaded; every dimension is read", { error: error instanceof Error ? error.message : String(error) });
|
|
404820
|
+
return out;
|
|
404821
|
+
}
|
|
404822
|
+
for (const row of rows) {
|
|
404823
|
+
let parsed;
|
|
404824
|
+
try {
|
|
404825
|
+
parsed = JSON.parse(String(row.read_values));
|
|
404826
|
+
} catch {
|
|
404827
|
+
continue;
|
|
404828
|
+
}
|
|
404829
|
+
if (!Array.isArray(parsed))
|
|
404830
|
+
continue;
|
|
404831
|
+
const values = [];
|
|
404832
|
+
for (const v of parsed) {
|
|
404833
|
+
if (!Array.isArray(v) || typeof v[0] !== "string")
|
|
404834
|
+
continue;
|
|
404835
|
+
values.push({
|
|
404836
|
+
value: v[0],
|
|
404837
|
+
count: Number(v[1]) || 0,
|
|
404838
|
+
...typeof v[2] === "string" ? { key: v[2] } : {}
|
|
404839
|
+
});
|
|
404840
|
+
}
|
|
404841
|
+
const read = {
|
|
404842
|
+
dimension: String(row.dimension_key),
|
|
404843
|
+
givens: String(row.givens),
|
|
404844
|
+
readKey: String(row.read_key),
|
|
404845
|
+
truncated: Boolean(row.truncated),
|
|
404846
|
+
values,
|
|
404847
|
+
readAt: Number(row.read_ms)
|
|
404848
|
+
};
|
|
404849
|
+
out.set(`${read.dimension}\x00${read.givens}`, read);
|
|
404850
|
+
}
|
|
404851
|
+
return out;
|
|
404852
|
+
}
|
|
404853
|
+
async function saveReads(db, environmentName, packageName, reads) {
|
|
404854
|
+
await db.run(`DELETE FROM dimension_value_reads WHERE environment_name = ? AND package_name = ?`, [environmentName, packageName]);
|
|
404855
|
+
const seen = new Set;
|
|
404856
|
+
const rows = [];
|
|
404857
|
+
for (const r of reads) {
|
|
404858
|
+
const id = `${r.dimension}\x00${r.givens}`;
|
|
404859
|
+
if (seen.has(id))
|
|
404860
|
+
continue;
|
|
404861
|
+
seen.add(id);
|
|
404862
|
+
rows.push([
|
|
404863
|
+
environmentName,
|
|
404864
|
+
packageName,
|
|
404865
|
+
r.dimension,
|
|
404866
|
+
r.givens,
|
|
404867
|
+
r.readKey,
|
|
404868
|
+
r.truncated,
|
|
404869
|
+
JSON.stringify(r.values.map((v) => v.key === undefined ? [v.value, v.count] : [v.value, v.count, v.key])),
|
|
404870
|
+
new Date(r.readAt).toISOString()
|
|
404871
|
+
]);
|
|
404872
|
+
}
|
|
404873
|
+
for (let i = 0;i < rows.length; i += 50) {
|
|
404874
|
+
const batch = rows.slice(i, i + 50);
|
|
404875
|
+
await db.run(`INSERT INTO dimension_value_reads (environment_name, package_name, dimension_key, givens, read_key, truncated, read_values, read_at)
|
|
404876
|
+
VALUES ${batch.map(() => "(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}`, batch.flat());
|
|
404877
|
+
}
|
|
404878
|
+
}
|
|
403882
404879
|
async function saveValues(db, environmentName, packageName, values) {
|
|
403883
404880
|
await db.run(`DELETE FROM dimension_values WHERE environment_name = ? AND package_name = ?`, [environmentName, packageName]);
|
|
403884
404881
|
const now = new Date().toISOString();
|
|
@@ -403906,7 +404903,7 @@ async function saveValues(db, environmentName, packageName, values) {
|
|
|
403906
404903
|
VALUES ${batch.map(() => "(?, ?, ?, ?, ?, ?, ?, ?)").join(", ")}`, batch.flat());
|
|
403907
404904
|
}
|
|
403908
404905
|
}
|
|
403909
|
-
var VALUE_READ_TIMEOUT_MS = 60000, VALUE_READ_BUDGET_MS = 300000, indexValueFetcherFor = (deps) => async (request) => {
|
|
404906
|
+
var VALUE_READ_TIMEOUT_MS = 60000, VALUE_READ_BUDGET_MS = 300000, VALUE_REUSE_MAX_AGE_MS, indexValueFetcherFor = (deps) => async (request) => {
|
|
403910
404907
|
const rows = await queryDistinctValues({
|
|
403911
404908
|
...request,
|
|
403912
404909
|
counted: true,
|
|
@@ -403914,26 +404911,39 @@ var VALUE_READ_TIMEOUT_MS = 60000, VALUE_READ_BUDGET_MS = 300000, indexValueFetc
|
|
|
403914
404911
|
routeLabel: "mcp:getContext:valueIndex"
|
|
403915
404912
|
}, deps);
|
|
403916
404913
|
const values = [];
|
|
404914
|
+
const keyCount = request.partitionColumns?.length ?? 0;
|
|
403917
404915
|
for (const row of rows.slice(0, request.limit)) {
|
|
403918
404916
|
const text = usableValue(row.v);
|
|
403919
404917
|
if (text === undefined)
|
|
403920
404918
|
continue;
|
|
403921
|
-
|
|
404919
|
+
if (keyCount === 0) {
|
|
404920
|
+
values.push({ value: text, count: Number(row.n) || 0 });
|
|
404921
|
+
continue;
|
|
404922
|
+
}
|
|
404923
|
+
const key = partitionKeyText(Array.from({ length: keyCount }, (_, i) => row[`k${i}`]), request.partitionTypes ?? []);
|
|
404924
|
+
if (key === undefined)
|
|
404925
|
+
continue;
|
|
404926
|
+
values.push({ value: text, count: Number(row.n) || 0, key });
|
|
403922
404927
|
}
|
|
403923
404928
|
return { values, truncated: rows.length > request.limit };
|
|
403924
|
-
}, NGRAM_MIN_CHARS = 6, NGRAM_MIN_OVERLAP = 0.5, MEANING_FLOOR = 0.5, MEANING_SHORT_FLOOR = 0.7, MEANING_SHORT_CHARS = 3, MEANING_MARGIN = 0.15, MEANING_MAX_VALUES = 20;
|
|
404929
|
+
}, NGRAM_MIN_CHARS = 6, NGRAM_MIN_OVERLAP = 0.5, MEANING_FLOOR = 0.5, MEANING_SHORT_FLOOR = 0.7, MEANING_SHORT_CHARS = 3, MEANING_MARGIN = 0.15, MEANING_MAX_VALUES = 20, BudgetSpent, CREDENTIAL_KEY;
|
|
403925
404930
|
var init_values_index = __esm(() => {
|
|
403926
404931
|
init_errors2();
|
|
403927
404932
|
init_logger();
|
|
404933
|
+
init_identity();
|
|
403928
404934
|
init_values();
|
|
403929
404935
|
init_vectors();
|
|
404936
|
+
VALUE_REUSE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
404937
|
+
BudgetSpent = class BudgetSpent extends Error {
|
|
404938
|
+
};
|
|
404939
|
+
CREDENTIAL_KEY = /pass|secret|token|private|credential|apikey|api_key|accesskey/i;
|
|
403930
404940
|
});
|
|
403931
404941
|
|
|
403932
404942
|
// src/retrieval/index/index_build.ts
|
|
403933
|
-
function questionLineValues(index, parts
|
|
404943
|
+
function questionLineValues(index, parts) {
|
|
403934
404944
|
const stored = new Map;
|
|
403935
|
-
for (const v of
|
|
403936
|
-
if (v.origin !== "data")
|
|
404945
|
+
for (const v of index.values) {
|
|
404946
|
+
if (v.origin !== "data" || v.key !== undefined)
|
|
403937
404947
|
continue;
|
|
403938
404948
|
const list = stored.get(v.dimension) ?? [];
|
|
403939
404949
|
list.push({ value: v.value, count: v.count });
|
|
@@ -404013,7 +405023,9 @@ async function buildFcjIndex(args) {
|
|
|
404013
405023
|
derived.set(node.key, derivedText(node, textCtx));
|
|
404014
405024
|
}
|
|
404015
405025
|
let values = new ValueIndex([]);
|
|
404016
|
-
const
|
|
405026
|
+
const valueSettings = getDimensionValueSettings();
|
|
405027
|
+
const operatorValues = valueSettings.enabled;
|
|
405028
|
+
const valueGivens = valueSettings.givens[packageName];
|
|
404017
405029
|
let valueReport = {
|
|
404018
405030
|
skipped: operatorValues ? "retrieval.fcj.values is false" : "retrieval.dimensionValues.enabled is false in publisher.config.json"
|
|
404019
405031
|
};
|
|
@@ -404032,15 +405044,14 @@ async function buildFcjIndex(args) {
|
|
|
404032
405044
|
}
|
|
404033
405045
|
} : {},
|
|
404034
405046
|
...args.shouldStop ? { shouldStop: args.shouldStop } : {},
|
|
404035
|
-
...
|
|
405047
|
+
...valueGivens ? { givens: valueGivens } : {}
|
|
404036
405048
|
});
|
|
404037
405049
|
values = built.index;
|
|
404038
405050
|
valueReport = built.report;
|
|
404039
405051
|
}
|
|
404040
405052
|
const perNode = settings.questionsPerNode ?? QUESTIONS_PER_NODE;
|
|
404041
405053
|
const variant = settings.questionsPrompt ?? "questions";
|
|
404042
|
-
const
|
|
404043
|
-
const lineValues = promptShowsValues(variant) ? questionLineValues(values, parts, valuesLeave) : undefined;
|
|
405054
|
+
const lineValues = promptShowsValues(variant) ? questionLineValues(values, parts) : undefined;
|
|
404044
405055
|
const questions = new Map;
|
|
404045
405056
|
const qLlm = llmFor(settings.questions);
|
|
404046
405057
|
const questionNodes = searched.filter(wantsQuestions);
|
|
@@ -404133,7 +405144,6 @@ async function buildFcjIndex(args) {
|
|
|
404133
405144
|
packageName,
|
|
404134
405145
|
values,
|
|
404135
405146
|
enabled: settings.values && settings.valueEmbeddings,
|
|
404136
|
-
egressFull: valuesLeave,
|
|
404137
405147
|
...args.shouldStop ? { shouldStop: args.shouldStop } : {}
|
|
404138
405148
|
});
|
|
404139
405149
|
const keyword = new KeywordIndex(searched.map((node) => ({
|
|
@@ -404205,12 +405215,6 @@ async function embedValues(args) {
|
|
|
404205
405215
|
if (!args.enabled) {
|
|
404206
405216
|
return { ...report, skipped: "retrieval.fcj.valueEmbeddings is false" };
|
|
404207
405217
|
}
|
|
404208
|
-
if (!args.egressFull) {
|
|
404209
|
-
return {
|
|
404210
|
-
...report,
|
|
404211
|
-
skipped: 'egress.preset is "default": stored values are sent to the embedding provider only under "full"'
|
|
404212
|
-
};
|
|
404213
|
-
}
|
|
404214
405218
|
if (!args.provider) {
|
|
404215
405219
|
return { ...report, skipped: "no embedding provider is configured" };
|
|
404216
405220
|
}
|
|
@@ -404325,7 +405329,7 @@ function kickFcjBuild(args) {
|
|
|
404325
405329
|
return;
|
|
404326
405330
|
}
|
|
404327
405331
|
try {
|
|
404328
|
-
const index = await buildFor(args,
|
|
405332
|
+
const index = await buildFor(args, (progress, lastWrittenAt) => {
|
|
404329
405333
|
building.progress = progress;
|
|
404330
405334
|
building.lastSyncedAt = lastWrittenAt;
|
|
404331
405335
|
});
|
|
@@ -404401,8 +405405,7 @@ function rebuildForValues(args, state) {
|
|
|
404401
405405
|
return;
|
|
404402
405406
|
}
|
|
404403
405407
|
try {
|
|
404404
|
-
const
|
|
404405
|
-
const index = await buildFor(args, "failed" in previous ? { index: state.index.values, report: previous } : undefined);
|
|
405408
|
+
const index = await buildFor(args);
|
|
404406
405409
|
if (await droppedDuringBuild(args, states))
|
|
404407
405410
|
return;
|
|
404408
405411
|
states.set(pkg, readyState(index, environmentName, packageName, state.valueFailures ?? 0));
|
|
@@ -404423,7 +405426,7 @@ function rebuildForValues(args, state) {
|
|
|
404423
405426
|
}
|
|
404424
405427
|
});
|
|
404425
405428
|
}
|
|
404426
|
-
async function buildFor(args,
|
|
405429
|
+
async function buildFor(args, onVectorProgress) {
|
|
404427
405430
|
const { registry, environmentStore, environmentName, packageName, pkg } = args;
|
|
404428
405431
|
const pkgIndex = await getPackageIndex(registry.packageIndexes, environmentStore, environmentName, packageName);
|
|
404429
405432
|
const db = args.catalog.getDuckDbConnection();
|
|
@@ -404478,7 +405481,6 @@ async function buildFor(args, previousValues, onVectorProgress) {
|
|
|
404478
405481
|
...storedSummaries ? { storedSummaries } : {},
|
|
404479
405482
|
valueRead: { environmentStore, fetcher },
|
|
404480
405483
|
budget,
|
|
404481
|
-
...previousValues ? { previousValues } : {},
|
|
404482
405484
|
shouldStop,
|
|
404483
405485
|
...onVectorProgress ? { onVectorProgress } : {}
|
|
404484
405486
|
});
|
|
@@ -405011,9 +406013,10 @@ function rankTarget(index, target, query, allow, options) {
|
|
|
405011
406013
|
}
|
|
405012
406014
|
const keyword = options.keyword ? index.keyword.search(target.text, (k) => admitted.has(k)) : [];
|
|
405013
406015
|
const phrases = options.values ? valuePhrasesOf(target) : [];
|
|
405014
|
-
const
|
|
406016
|
+
const valueAllow = (d, key) => admitted.has(d) && (key === undefined || options.callerKey?.(d) === key);
|
|
406017
|
+
const nominations = phrases.length > 0 ? index.values.nominate(phrases, valueAllow) : [];
|
|
405015
406018
|
const meaning = options.valueMeaning && query && index.values.embedded > 0 ? phrases.map((phrase) => ({ phrase, vec: query })) : [];
|
|
405016
|
-
const meaningNoms = meaning.length > 0 ? index.values.nominateByMeaning(meaning,
|
|
406019
|
+
const meaningNoms = meaning.length > 0 ? index.values.nominateByMeaning(meaning, valueAllow) : [];
|
|
405017
406020
|
const closeTop = close.slice(0, options.depth);
|
|
405018
406021
|
const keywordTop = keyword.slice(0, options.depth);
|
|
405019
406022
|
const valueTop = nominations.slice(0, options.depth);
|
|
@@ -405082,7 +406085,8 @@ function find(args) {
|
|
|
405082
406085
|
keyword: args.keyword,
|
|
405083
406086
|
values: args.values,
|
|
405084
406087
|
depth: LIST_DEPTH,
|
|
405085
|
-
...args.valueMeaning ? { valueMeaning: true } : {}
|
|
406088
|
+
...args.valueMeaning ? { valueMeaning: true } : {},
|
|
406089
|
+
...args.callerKey ? { callerKey: args.callerKey } : {}
|
|
405086
406090
|
});
|
|
405087
406091
|
const beyond = k > 0 ? ranked.all.map((c, i) => ({ ...c, fusedRank: i + 1 })).slice(args.perTarget).filter((c) => inListTop(c, k)) : [];
|
|
405088
406092
|
return {
|
|
@@ -405343,7 +406347,7 @@ function connect(args) {
|
|
|
405343
406347
|
const inPool = (node) => args.allow(node) && (pool.has(node.sourceKey) || (node.copies ?? []).some((k) => pool.has(index.catalog.nodes.get(k)?.sourceKey ?? "")));
|
|
405344
406348
|
const candidates = new Map;
|
|
405345
406349
|
for (const target of targets) {
|
|
405346
|
-
candidates.set(target.index, rankInCluster(index, target, args.queries.get(target.index), inPool, pool, settings, args.valueMeaning));
|
|
406350
|
+
candidates.set(target.index, rankInCluster(index, target, args.queries.get(target.index), inPool, pool, settings, args.valueMeaning, args.callerKey));
|
|
405347
406351
|
}
|
|
405348
406352
|
const extras = extrasOf(index, score.source, [score.source], pool, candidates, targets, args.allow);
|
|
405349
406353
|
return {
|
|
@@ -405461,12 +406465,13 @@ function connectList(args) {
|
|
|
405461
406465
|
considered: []
|
|
405462
406466
|
};
|
|
405463
406467
|
}
|
|
405464
|
-
function rankInCluster(index, target, query, inPool, pool, settings, valueMeaning) {
|
|
406468
|
+
function rankInCluster(index, target, query, inPool, pool, settings, valueMeaning, callerKey) {
|
|
405465
406469
|
const ranked = rankTarget(index, target, query, inPool, {
|
|
405466
406470
|
keyword: settings.keyword,
|
|
405467
406471
|
values: settings.values,
|
|
405468
406472
|
depth: Number.MAX_SAFE_INTEGER,
|
|
405469
|
-
...valueMeaning ? { valueMeaning } : {}
|
|
406473
|
+
...valueMeaning ? { valueMeaning } : {},
|
|
406474
|
+
...callerKey ? { callerKey } : {}
|
|
405470
406475
|
});
|
|
405471
406476
|
return ranked.all.map((c) => {
|
|
405472
406477
|
const node = index.catalog.nodes.get(c.key);
|
|
@@ -405563,9 +406568,8 @@ var MEASURE_RULE = `- For a measure target, pick the measure that computes what
|
|
|
405563
406568
|
{"picks": [{"target": <target number>, "candidates": [<candidate numbers, best first>], "best": <the one candidate number that best answers the target>, "reason": "<one short sentence>", "readings": <true only when you picked the same field on several sources because the question could mean either set of rows>}, ...], "caveats": ["<one short sentence>", ...]}
|
|
405564
406569
|
Give one element per target, with an empty "candidates" list for a target this group cannot answer. Use only the candidate numbers listed under that target or under "Also in this group". List "candidates" best first; "best" is one of them, the field on the source whose doc best matches the population or breakdown the target and the question ask for. Leave "readings" out unless it is true.`, JUDGE_SPLIT_RULES = `- A target marked "one item of the list in target N" asks for that item of target N's list alone. Pick the candidates that serve that item under it; they answer target N too, so they need not be repeated there.
|
|
405565
406570
|
- An item is about its own subject: "buyer organization domain" asks for the buyer's domain. When no candidate is about the item's own subject, give the item an empty list. Never pick the nearest field of another entity for it (a vendor's or a product's domain is not the buyer's).
|
|
405566
|
-
- You see the top candidates of one search, not the whole data model. Never write that a field or data is unavailable, missing, absent or does not exist. When nothing listed serves a target or an item, give it an empty list and say it was not found by this search.`,
|
|
406571
|
+
- You see the top candidates of one search, not the whole data model. Never write that a field or data is unavailable, missing, absent or does not exist. When nothing listed serves a target or an item, give it an empty list and say it was not found by this search.`, JUDGE_VALUE_RULES = `- For a value target (type dimensional_value), each candidate field lists the stored values that matched the target, each with a label (such as "3a"), how it matched (exact, words, typo or meaning) and a score. Pick a field when one of its listed values is the target's value or a form of it: a typo, a different case, an abbreviation or a synonym. In that target's pick, add "values": [<the labels of the values you mean>]. A listed value you do not name is left out of the answer.
|
|
405567
406572
|
- When no listed value is the target's value or a form of it, pick nothing for the target. A value that only looks alike (another city, another product) does not answer it.
|
|
405568
|
-
- A field listed with no stored values has no values indexed. Pick it only when its doc says it holds values like the target's.`, JUDGE_VALUE_RULES = `- For a value target (type dimensional_value), each candidate field says how its stored values matched the target (exact, words, typo or meaning) and their scores; the values themselves are not shown. An exact or words match is strong; a typo or meaning match is weaker, so read the field's doc as well. Pick nothing for the target when no candidate's values matched well and no doc says the field holds values like it.
|
|
405569
406573
|
- A field listed with no stored values has no values indexed. Pick it only when its doc says it holds values like the target's.`, JUDGE_READINGS_RULES = `- For any target, of any type: when its phrase has more than one plausible reading and the candidates' docs do not say which field to use, pick a field for each reading and say in the reason which reading each one serves. The agent will ask the user which one they meant; a reading left out cannot be offered.
|
|
405570
406574
|
- For a rate or per-unit target (a share, a ratio, an average per order or per customer), also pick the measures it is computed from (its numerator and its denominator), beside the rate itself.`;
|
|
405571
406575
|
var init_judge = __esm(() => {
|
|
@@ -405626,8 +406630,6 @@ function matchedValues(cluster, t, key) {
|
|
|
405626
406630
|
}
|
|
405627
406631
|
function valueLabels(cluster, targets, options) {
|
|
405628
406632
|
const out = new Map;
|
|
405629
|
-
if (getEgressPreset() !== "full")
|
|
405630
|
-
return out;
|
|
405631
406633
|
for (const t of targets) {
|
|
405632
406634
|
if (t.type !== "dimensional_value")
|
|
405633
406635
|
continue;
|
|
@@ -405790,7 +406792,6 @@ function sourceDocStart(index, key, max = JUDGE_SOURCE_DOC_MAX_CHARS, unlessSumm
|
|
|
405790
406792
|
return summary === undefined || out === summary ? undefined : out;
|
|
405791
406793
|
}
|
|
405792
406794
|
function renderJudgePrompt(index, cluster, targets, options, routeCap = 0) {
|
|
405793
|
-
const full = getEgressPreset() === "full";
|
|
405794
406795
|
const nameOf = (s) => index.catalog.sources.get(s)?.name ?? s;
|
|
405795
406796
|
const lines = cluster.peers ? peerLines(index, cluster) : homeLines(index, cluster);
|
|
405796
406797
|
const noteOf = (t, o) => {
|
|
@@ -405798,8 +406799,6 @@ function renderJudgePrompt(index, cluster, targets, options, routeCap = 0) {
|
|
|
405798
406799
|
if (values.length === 0)
|
|
405799
406800
|
return t.type === "dimensional_value" ? "no stored values" : undefined;
|
|
405800
406801
|
const how = (v) => `${HOW_SHOWN[v.how]}, ${v.score.toFixed(2)}`;
|
|
405801
|
-
if (!full)
|
|
405802
|
-
return `stored values matched the target (${values.slice(0, JUDGE_VALUES_SHOWN).map(how).join("; ")}); the values are not shown`;
|
|
405803
406802
|
const shown = values.slice(0, JUDGE_VALUES_SHOWN).map((v, i) => t.type === "dimensional_value" ? `${valueLabel(o.number, i)} ${JSON.stringify(v.value)} (${how(v)})` : `${JSON.stringify(v.value)} (${how(v)})`);
|
|
405804
406803
|
const more = values.length - shown.length;
|
|
405805
406804
|
return `stored values matching the target: ${shown.join(", ")}${more > 0 ? `, and ${more} more not shown` : ""}`;
|
|
@@ -406034,9 +407033,7 @@ async function judge(args) {
|
|
|
406034
407033
|
});
|
|
406035
407034
|
const base = args.instructions ?? (cluster.peers ? cap > 0 ? DEFAULT_JUDGE_LIST_ROUTES_INSTRUCTIONS : DEFAULT_JUDGE_LIST_INSTRUCTIONS : DEFAULT_JUDGE_INSTRUCTIONS);
|
|
406036
407035
|
const labels = valueLabels(cluster, args.targets, options);
|
|
406037
|
-
const valueRules = args.targets.some((t) => t.type === "dimensional_value") ? [
|
|
406038
|
-
getEgressPreset() === "full" ? JUDGE_VALUE_RULES_FULL : JUDGE_VALUE_RULES
|
|
406039
|
-
] : [];
|
|
407036
|
+
const valueRules = args.targets.some((t) => t.type === "dimensional_value") ? [JUDGE_VALUE_RULES] : [];
|
|
406040
407037
|
const system = [
|
|
406041
407038
|
base,
|
|
406042
407039
|
...valueRules,
|
|
@@ -406065,7 +407062,6 @@ async function judge(args) {
|
|
|
406065
407062
|
var JUDGE_VALUES_SHOWN = 5, HOW_SHOWN, JUDGE_DOC_MAX_CHARS = 1500, PATHS_SHOWN = 5, ROUTES_SHOWN = 8, ROUTE_NOTE_MAX_CHARS = 200, JUDGE_SOURCE_DOC_MAX_CHARS = 300;
|
|
406066
407063
|
var init_judge2 = __esm(() => {
|
|
406067
407064
|
init_judge();
|
|
406068
|
-
init_config();
|
|
406069
407065
|
init_llm_calls();
|
|
406070
407066
|
init_derived_text();
|
|
406071
407067
|
init_routes();
|
|
@@ -406078,7 +407074,7 @@ var init_judge2 = __esm(() => {
|
|
|
406078
407074
|
});
|
|
406079
407075
|
|
|
406080
407076
|
// src/retrieval/search/pages.ts
|
|
406081
|
-
import { createHash as
|
|
407077
|
+
import { createHash as createHash25 } from "node:crypto";
|
|
406082
407078
|
function pageAt(cards, offset, options) {
|
|
406083
407079
|
const room = options.maxChars - options.reserveChars;
|
|
406084
407080
|
let used = 2;
|
|
@@ -406170,7 +407166,7 @@ function resultKey(request) {
|
|
|
406170
407166
|
givens: request.givens ?? null,
|
|
406171
407167
|
filterParams: request.filterParams ?? null
|
|
406172
407168
|
};
|
|
406173
|
-
return
|
|
407169
|
+
return createHash25("sha256").update(canonicalJson2(normal)).digest("hex");
|
|
406174
407170
|
}
|
|
406175
407171
|
function canonicalJson2(value) {
|
|
406176
407172
|
if (Array.isArray(value)) {
|
|
@@ -407120,6 +408116,7 @@ async function runFcjSearch(args) {
|
|
|
407120
408116
|
retrieval_reason: "provider-error"
|
|
407121
408117
|
});
|
|
407122
408118
|
}
|
|
408119
|
+
const callerKey = callerKeyOf(index.catalog, request.givens, await lockedSourcesFor(index.catalog, request.givens, (path) => pkg.getModel?.(path)));
|
|
407123
408120
|
const foundAll = withPinnedDimensions(index, find({
|
|
407124
408121
|
index,
|
|
407125
408122
|
targets: searched,
|
|
@@ -407129,7 +408126,8 @@ async function runFcjSearch(args) {
|
|
|
407129
408126
|
keyword: settings2.keyword,
|
|
407130
408127
|
values: settings2.values,
|
|
407131
408128
|
allow,
|
|
407132
|
-
unionTopK: settings2.connect === "list" ? settings2.listUnion : 0
|
|
408129
|
+
unionTopK: settings2.connect === "list" ? settings2.listUnion : 0,
|
|
408130
|
+
callerKey
|
|
407133
408131
|
}), request, allow);
|
|
407134
408132
|
const found = split ? fusedFound(split, foundAll) : foundAll;
|
|
407135
408133
|
const foundForConnect = split ? forConnect(split, foundAll) : foundAll;
|
|
@@ -407150,7 +408148,8 @@ async function runFcjSearch(args) {
|
|
|
407150
408148
|
queries,
|
|
407151
408149
|
...valueMeaning ? { valueMeaning } : {},
|
|
407152
408150
|
settings: settings2,
|
|
407153
|
-
allow
|
|
408151
|
+
allow,
|
|
408152
|
+
callerKey
|
|
407154
408153
|
});
|
|
407155
408154
|
stages.push({
|
|
407156
408155
|
name: "connect",
|
|
@@ -407619,6 +408618,7 @@ var init_engine = __esm(() => {
|
|
|
407619
408618
|
init_date_range();
|
|
407620
408619
|
init_engine_state();
|
|
407621
408620
|
init_find();
|
|
408621
|
+
init_values_index();
|
|
407622
408622
|
init_connect();
|
|
407623
408623
|
init_judge2();
|
|
407624
408624
|
init_held_results();
|
|
@@ -440154,7 +441154,7 @@ var init_lossless_widening = __esm(() => {
|
|
|
440154
441154
|
});
|
|
440155
441155
|
|
|
440156
441156
|
// src/service/materialization/run/storage_table_load.ts
|
|
440157
|
-
import
|
|
441157
|
+
import path55 from "path";
|
|
440158
441158
|
function readerSql(uri, format, options = {}) {
|
|
440159
441159
|
const path = `'${escapeSQL(uri)}'`;
|
|
440160
441160
|
const args = [];
|
|
@@ -440203,8 +441203,8 @@ function assertUnderDataPath(uri, dataPath) {
|
|
|
440203
441203
|
throw outside();
|
|
440204
441204
|
}
|
|
440205
441205
|
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(uri)) {
|
|
440206
|
-
const resolved =
|
|
440207
|
-
if (!resolved.startsWith(`${
|
|
441206
|
+
const resolved = path55.resolve(uri);
|
|
441207
|
+
if (!resolved.startsWith(`${path55.resolve(root)}${path55.sep}`)) {
|
|
440208
441208
|
throw outside();
|
|
440209
441209
|
}
|
|
440210
441210
|
}
|
|
@@ -440595,7 +441595,7 @@ function objectUnreadable(error, uris, byName = false) {
|
|
|
440595
441595
|
logInternalFailure("Load could not read an object", error, "warn");
|
|
440596
441596
|
const said = error.message.split(ECHOED_SQL)[0];
|
|
440597
441597
|
const object = uris.findIndex((uri) => said.includes(uri));
|
|
440598
|
-
const words = readerWords(error, uris.map((uri, i) => [uri, byName ?
|
|
441598
|
+
const words = readerWords(error, uris.map((uri, i) => [uri, byName ? path55.posix.basename(uri) : `objects[${i}]`]));
|
|
440599
441599
|
if (byName)
|
|
440600
441600
|
return new LoadRefusalError("OBJECT_UNREADABLE", words);
|
|
440601
441601
|
return new LoadRefusalError("OBJECT_UNREADABLE", object < 0 ? `An object of the load could not be read: ${words}` : `objects[${object}] could not be read: ${words}`, object < 0 ? undefined : { object });
|
|
@@ -440948,7 +441948,7 @@ var init_storage_table_load = __esm(() => {
|
|
|
440948
441948
|
});
|
|
440949
441949
|
|
|
440950
441950
|
// src/service/catalog_admin.ts
|
|
440951
|
-
import { createHash as
|
|
441951
|
+
import { createHash as createHash26, randomUUID as randomUUID6 } from "crypto";
|
|
440952
441952
|
async function withLoadSlot(fn) {
|
|
440953
441953
|
const slot = loadSlots.tryAcquire();
|
|
440954
441954
|
if (!slot) {
|
|
@@ -441810,7 +442810,7 @@ function idempotencyKeyDigest(key) {
|
|
|
441810
442810
|
if (key === "" || key.length > MAX_IDEMPOTENCY_KEY) {
|
|
441811
442811
|
throw badRequest(`'Idempotency-Key' must be 1 to ${MAX_IDEMPOTENCY_KEY} characters.`);
|
|
441812
442812
|
}
|
|
441813
|
-
return
|
|
442813
|
+
return createHash26("sha256").update(key).digest("hex");
|
|
441814
442814
|
}
|
|
441815
442815
|
function decodeCursor(after) {
|
|
441816
442816
|
const id = /^[A-Za-z0-9_-]+$/.test(after) ? Buffer.from(after, "base64url").toString() : "";
|
|
@@ -449248,7 +450248,7 @@ var require_ip_address = __commonJS(function(exports) {
|
|
|
449248
450248
|
import { isIPv6 } from "node:net";
|
|
449249
450249
|
import { isIPv6 as isIPv62 } from "node:net";
|
|
449250
450250
|
import { Buffer as Buffer4 } from "node:buffer";
|
|
449251
|
-
import { createHash as
|
|
450251
|
+
import { createHash as createHash27 } from "node:crypto";
|
|
449252
450252
|
import { isIP as isIP2 } from "node:net";
|
|
449253
450253
|
function ipKeyGenerator(ip, ipv6Subnet = 56) {
|
|
449254
450254
|
if (isIPv6(ip)) {
|
|
@@ -449346,7 +450346,7 @@ var import_ip_address, import_debug2, ipv4CompatibleSubnet, MemoryStore = class
|
|
|
449346
450346
|
}
|
|
449347
450347
|
return resetSeconds;
|
|
449348
450348
|
}, getPartitionKey = (key) => {
|
|
449349
|
-
const hash =
|
|
450349
|
+
const hash = createHash27("sha256");
|
|
449350
450350
|
hash.update(key);
|
|
449351
450351
|
const partitionKey = hash.digest("hex").slice(0, 12);
|
|
449352
450352
|
return Buffer4.from(partitionKey).toString("base64");
|
|
@@ -450186,9 +451186,9 @@ var init_server_old = __esm(() => {
|
|
|
450186
451186
|
});
|
|
450187
451187
|
|
|
450188
451188
|
// src/authorize_bypass_header.ts
|
|
450189
|
-
import { createHash as
|
|
451189
|
+
import { createHash as createHash28, timingSafeEqual } from "node:crypto";
|
|
450190
451190
|
var BYPASS_AUTHORIZE_HEADER = "x-publisher-bypass-authorize", secretsMatch = (presented, configured) => {
|
|
450191
|
-
const digest = (value) =>
|
|
451191
|
+
const digest = (value) => createHash28("sha256").update(value, "utf8").digest();
|
|
450192
451192
|
return timingSafeEqual(digest(presented), digest(configured));
|
|
450193
451193
|
}, readBypassAuthorize = (req) => {
|
|
450194
451194
|
const configured = settings.get("authorize.bypassSecret");
|
|
@@ -450666,7 +451666,7 @@ var init_api = __esm(() => {
|
|
|
450666
451666
|
|
|
450667
451667
|
// src/routes/data_apps.ts
|
|
450668
451668
|
import * as fsp from "fs/promises";
|
|
450669
|
-
import * as
|
|
451669
|
+
import * as path56 from "path";
|
|
450670
451670
|
import { pathToFileURL as pathToFileURL27 } from "url";
|
|
450671
451671
|
async function serveFromPackage(environmentStore, req, res) {
|
|
450672
451672
|
const subPathRaw = req.params["0"] ?? "";
|
|
@@ -450676,7 +451676,7 @@ async function serveFromPackage(environmentStore, req, res) {
|
|
|
450676
451676
|
const pkg = await environment.getPackage(parsePackageName(req.params.packageName), false, {
|
|
450677
451677
|
versionId: VersionRef.parse(staticVersionId)
|
|
450678
451678
|
});
|
|
450679
|
-
const publicRoot =
|
|
451679
|
+
const publicRoot = path56.join(pkg.getPackagePath(), "public");
|
|
450680
451680
|
let subPath = subPathRaw;
|
|
450681
451681
|
if (subPath === "" || subPath.endsWith("/")) {
|
|
450682
451682
|
subPath = subPath + "index.html";
|
|
@@ -450744,7 +451744,7 @@ function registerDataAppListRoute(app, apiPrefix, environmentStore) {
|
|
|
450744
451744
|
app.get(`${apiPrefix}${DATA_APPS_ROUTE}`, apiRoute(async (req) => {
|
|
450745
451745
|
const environment = await environmentStore.getEnvironment(parseEnvironmentName(req.params.environmentName), false);
|
|
450746
451746
|
const pkg = await environment.getPackage(parsePackageName(req.params.packageName), false, { versionId: versionRefOf(req) });
|
|
450747
|
-
return listPackageDataApps(req.params.environmentName, req.params.packageName,
|
|
451747
|
+
return listPackageDataApps(req.params.environmentName, req.params.packageName, path56.join(pkg.getPackagePath(), "public"), pkg.getPackageMetadata().versionId);
|
|
450748
451748
|
}));
|
|
450749
451749
|
}
|
|
450750
451750
|
function stripNonTagText(input) {
|
|
@@ -450759,7 +451759,7 @@ function stripNonTagText(input) {
|
|
|
450759
451759
|
async function servedPublic(publicRoot) {
|
|
450760
451760
|
let real;
|
|
450761
451761
|
try {
|
|
450762
|
-
real = await confinedPackagePath(
|
|
451762
|
+
real = await confinedPackagePath(path56.dirname(publicRoot), pathToFileURL27(publicRoot));
|
|
450763
451763
|
} catch {
|
|
450764
451764
|
return { kind: "outside" };
|
|
450765
451765
|
}
|
|
@@ -450771,11 +451771,11 @@ async function servedPublic(publicRoot) {
|
|
|
450771
451771
|
async function insidePublic(publicRoot, realPublic, file) {
|
|
450772
451772
|
let real;
|
|
450773
451773
|
try {
|
|
450774
|
-
real = await confinedPackagePath(
|
|
451774
|
+
real = await confinedPackagePath(path56.dirname(publicRoot), pathToFileURL27(file));
|
|
450775
451775
|
} catch {
|
|
450776
451776
|
return;
|
|
450777
451777
|
}
|
|
450778
|
-
return stepsOutside(
|
|
451778
|
+
return stepsOutside(path56.relative(realPublic, real)) ? undefined : real;
|
|
450779
451779
|
}
|
|
450780
451780
|
async function listPackageDataApps(environmentName, packageName, publicRoot, versionId) {
|
|
450781
451781
|
const out = [];
|
|
@@ -450795,14 +451795,14 @@ async function listPackageDataApps(environmentName, packageName, publicRoot, ver
|
|
|
450795
451795
|
for (const entry of entries) {
|
|
450796
451796
|
if (entry.name.startsWith(".") || entry.name === "node_modules")
|
|
450797
451797
|
continue;
|
|
450798
|
-
const full =
|
|
451798
|
+
const full = path56.join(dir, entry.name);
|
|
450799
451799
|
const real = await insidePublic(publicRoot, realPublic, full);
|
|
450800
451800
|
if (real === undefined)
|
|
450801
451801
|
continue;
|
|
450802
451802
|
if (entry.isDirectory()) {
|
|
450803
451803
|
await walk(full, real, depth + 1);
|
|
450804
451804
|
} else if (entry.isFile() && (entry.name.endsWith(".html") || entry.name.endsWith(".htm"))) {
|
|
450805
|
-
const rel =
|
|
451805
|
+
const rel = path56.relative(publicRoot, full).replace(/\\/g, "/");
|
|
450806
451806
|
let title = rel;
|
|
450807
451807
|
let fit;
|
|
450808
451808
|
try {
|
|
@@ -450981,9 +451981,9 @@ var init_spa_fallback = __esm(() => {
|
|
|
450981
451981
|
});
|
|
450982
451982
|
|
|
450983
451983
|
// src/routes/spa.ts
|
|
450984
|
-
import * as
|
|
451984
|
+
import * as path57 from "path";
|
|
450985
451985
|
function registerSpaFallback(app, apiPrefix, appRoot, environmentStore) {
|
|
450986
|
-
const SPA_INDEX =
|
|
451986
|
+
const SPA_INDEX = path57.resolve(appRoot, "index.html");
|
|
450987
451987
|
const escapeHtml = (value) => value.replace(/[<>&]/g, (c) => ({ "<": "<", ">": ">", "&": "&" })[c] ?? c);
|
|
450988
451988
|
const loadedPackage = (environmentName, packageName) => environmentStore.getLoadedEnvironments().find((environment) => environment.getEnvironmentName() === environmentName)?.peekPackage(packageName);
|
|
450989
451989
|
const loadedRoutes = {
|
|
@@ -451045,7 +452045,7 @@ var init_spa = __esm(() => {
|
|
|
451045
452045
|
});
|
|
451046
452046
|
|
|
451047
452047
|
// src/routes/main_app.ts
|
|
451048
|
-
import * as
|
|
452048
|
+
import * as path58 from "path";
|
|
451049
452049
|
function createMainApp(options) {
|
|
451050
452050
|
const { controllers } = options;
|
|
451051
452051
|
const { environmentStore } = controllers;
|
|
@@ -451059,7 +452059,7 @@ function createMainApp(options) {
|
|
|
451059
452059
|
registerDataAppStaticRoutes(app, environmentStore, options.dataAppRuntimePath);
|
|
451060
452060
|
if (options.consoleRoot) {
|
|
451061
452061
|
app.use("/", import_express2.default.static(options.consoleRoot));
|
|
451062
|
-
app.use("/api-doc.html", import_express2.default.static(
|
|
452062
|
+
app.use("/api-doc.html", import_express2.default.static(path58.join(options.consoleRoot, "api-doc.html")));
|
|
451063
452063
|
}
|
|
451064
452064
|
if (options.proxyConsoleToDevServer) {
|
|
451065
452065
|
app.use(import_http_proxy_middleware.createProxyMiddleware({
|
|
@@ -480915,8 +481915,8 @@ var init_experimental_dialects = __esm(() => {
|
|
|
480915
481915
|
|
|
480916
481916
|
// src/main_server.ts
|
|
480917
481917
|
import * as http5 from "http";
|
|
480918
|
-
import * as
|
|
480919
|
-
import { fileURLToPath as
|
|
481918
|
+
import * as path59 from "path";
|
|
481919
|
+
import { fileURLToPath as fileURLToPath23 } from "url";
|
|
480920
481920
|
function startMaterializationSchedulerFromEnv(store, service) {
|
|
480921
481921
|
const config = getMaterializationSchedulerConfig();
|
|
480922
481922
|
if (!config)
|
|
@@ -480951,9 +481951,9 @@ async function buildApp(settings) {
|
|
|
480951
481951
|
const MCP_CONFIG_ENABLED = mcpConfigEnabled();
|
|
480952
481952
|
const SHUTDOWN_DRAIN_DURATION_SECONDS = settings.get("shutdown.drainDurationSeconds");
|
|
480953
481953
|
const SHUTDOWN_GRACEFUL_CLOSE_TIMEOUT_SECONDS = settings.get("shutdown.gracefulCloseTimeoutSeconds");
|
|
480954
|
-
const __filename_esm =
|
|
480955
|
-
const ROOT =
|
|
480956
|
-
const SERVER_ROOT =
|
|
481954
|
+
const __filename_esm = fileURLToPath23(import.meta.url);
|
|
481955
|
+
const ROOT = path59.join(path59.dirname(__filename_esm), "app");
|
|
481956
|
+
const SERVER_ROOT = path59.resolve(process.cwd(), settings.get("root"));
|
|
480957
481957
|
const isDevelopment = externalEnv("NODE_ENV") === "development";
|
|
480958
481958
|
checkHeapConfiguration();
|
|
480959
481959
|
const environmentStore = new EnvironmentStore(SERVER_ROOT);
|
|
@@ -481058,7 +482058,7 @@ async function buildApp(settings) {
|
|
|
481058
482058
|
const mcpApp = createMcpApp(appServices);
|
|
481059
482059
|
const app = createMainApp({
|
|
481060
482060
|
controllers: appServices,
|
|
481061
|
-
dataAppRuntimePath:
|
|
482061
|
+
dataAppRuntimePath: path59.join(path59.dirname(__filename_esm), "runtime", "publisher.js"),
|
|
481062
482062
|
consoleRoot: isDevelopment ? undefined : ROOT,
|
|
481063
482063
|
proxyConsoleToDevServer: isDevelopment,
|
|
481064
482064
|
frameAncestors: settings.get("frameAncestors"),
|