@platforma-sdk/tengo-builder 4.0.10 → 4.0.11
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/cli.cjs +0 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/commands/build.cjs +3 -3
- package/dist/commands/build.cjs.map +1 -1
- package/dist/commands/build.js.map +1 -1
- package/dist/commands/check.cjs +0 -1
- package/dist/commands/check.cjs.map +1 -1
- package/dist/commands/check.js.map +1 -1
- package/dist/commands/dump/artifacts.cjs +0 -1
- package/dist/commands/dump/artifacts.cjs.map +1 -1
- package/dist/commands/dump/artifacts.js.map +1 -1
- package/dist/commands/dump/software.cjs +0 -1
- package/dist/commands/dump/software.cjs.map +1 -1
- package/dist/commands/dump/software.js.map +1 -1
- package/dist/commands/test.cjs +0 -1
- package/dist/commands/test.cjs.map +1 -1
- package/dist/commands/test.js.map +1 -1
- package/dist/compiler/artifactset.cjs +2 -0
- package/dist/compiler/artifactset.cjs.map +1 -1
- package/dist/compiler/artifactset.js +2 -1
- package/dist/compiler/artifactset.js.map +1 -1
- package/dist/compiler/compiler.cjs +1 -0
- package/dist/compiler/compiler.cjs.map +1 -1
- package/dist/compiler/compiler.js +1 -0
- package/dist/compiler/compiler.js.map +1 -1
- package/dist/compiler/compileroptions.cjs +1 -0
- package/dist/compiler/compileroptions.cjs.map +1 -1
- package/dist/compiler/compileroptions.js +1 -1
- package/dist/compiler/compileroptions.js.map +1 -1
- package/dist/compiler/main.cjs +5 -3
- package/dist/compiler/main.cjs.map +1 -1
- package/dist/compiler/main.js +1 -1
- package/dist/compiler/main.js.map +1 -1
- package/dist/compiler/pack_limits.cjs +2 -0
- package/dist/compiler/pack_limits.cjs.map +1 -1
- package/dist/compiler/pack_limits.js +1 -1
- package/dist/compiler/pack_limits.js.map +1 -1
- package/dist/compiler/package.cjs.map +1 -1
- package/dist/compiler/package.js.map +1 -1
- package/dist/compiler/source.cjs +10 -1
- package/dist/compiler/source.cjs.map +1 -1
- package/dist/compiler/source.js +8 -1
- package/dist/compiler/source.js.map +1 -1
- package/dist/compiler/template.cjs +0 -1
- package/dist/compiler/template.cjs.map +1 -1
- package/dist/compiler/template.js.map +1 -1
- package/dist/compiler/util.cjs +3 -3
- package/dist/compiler/util.cjs.map +1 -1
- package/dist/compiler/util.js.map +1 -1
- package/dist/shared/basecmd.cjs +0 -1
- package/dist/shared/basecmd.cjs.map +1 -1
- package/dist/shared/basecmd.js.map +1 -1
- package/dist/shared/dump.cjs.map +1 -1
- package/dist/shared/dump.js.map +1 -1
- package/dist/shared/proc.cjs +0 -1
- package/dist/shared/proc.cjs.map +1 -1
- package/dist/shared/proc.js.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pack_limits.cjs","names":["fullNameToString"],"sources":["../../src/compiler/pack_limits.ts"],"sourcesContent":["import type { CompiledTemplateV3, TemplateDataV3 } from \"@milaboratories/pl-model-backend\";\n\nimport type { FullArtifactName } from \"./package\";\nimport { fullNameToString } from \"./package\";\n\n// Build-time size guards mirroring the two backend caps that gate template\n// ingestion. Hardcoded because tengo-builder runs at block build time and has\n// no connection to a running backend; if pl ever changes the caps, update the\n// constants here in lockstep with the source-of-truth lines pointed at below.\n//\n// Source of truth (`core/pl` repo):\n// - platform/core/transaction/assertions.go : `maxResourceDataSize`\n// 3 MiB per value resource, checked on every CreateValue marshal.\n// Hits the WasmV1 resource after the controller unpacks a template pack\n// into its constituent libs/software/wasm resources.\n// - controllers/workflow/pkg/cfg/config.go : `TemplatePackSizeLimit`\n// 3.5 MiB per gzipped template pack, checked before the pack itself is\n// stored as a TengoTemplatePackV1 value resource.\n\n// Cap on the gzipped wasm payload that ends up in WasmV1Data.Code on the\n// backend. 2 MiB gzipped → ~2.67 MiB base64 + JSON wrapper → comfortably\n// under the 3 MiB per-value-resource cap with ~330 KiB headroom for the\n// WasmV1Data wrapper (Name, Version, Runtime, DefaultMemoryLimit, JSON\n// syntax). WasmV1Data.Code is a Go `[]byte`, which encoding/json serialises\n// as base64 — that's where the 4/3 expansion comes from.\n//\n// The tengo-builder gzips wasm files before adding them to the pack; this\n// cap therefore admits raw .wasm files several times larger than 2 MiB\n// (real wasm components compress to ~30-40 % of their raw size).\nexport const MAX_WASM_FILE_BYTES = 2 * 1024 * 1024;\n\n// 100 KiB below the backend's 3.5 MiB so blocks don't break on small\n// platform-side metadata overhead, or if pl tightens the limit slightly.\nexport const MAX_TEMPLATE_PACK_BYTES_GZIPPED = 3.5 * 1024 * 1024 - 100 * 1024;\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;\n return `${(n / 1024 / 1024).toFixed(2)} MiB`;\n}\n\nexport function assertWasmFileSize(\n file: string,\n byteLength: number,\n fullName: FullArtifactName,\n): void {\n if (byteLength <= MAX_WASM_FILE_BYTES) return;\n throw new Error(\n `WASM artefact ${fullNameToString(fullName)} from ${file} is ${formatBytes(byteLength)} ` +\n `gzipped, which exceeds tengo-builder's ${formatBytes(MAX_WASM_FILE_BYTES)} per-WASM cap. ` +\n `The backend stores each WASM as a single value resource (3 MiB hard cap after base64+JSON ` +\n `marshal — see maxResourceDataSize in pl: platform/core/transaction/assertions.go). ` +\n `Strip debug info or run \\`wasm-opt -Oz\\` to shrink it.`,\n );\n}\n\nexport interface WasmContribution {\n /** Artefact name as stored under TemplateDataV3.wasm (e.g. \"@pkg:id\"). */\n readonly name: string;\n /**\n * Bytes this artefact contributes to the pack, measured after gzip and\n * before base64 — i.e. the size of the binary payload stored on the\n * backend in WasmV1Data.Code. Decoded from the base64-encoded source in\n * hashToSource.\n */\n readonly storedBytes: number;\n}\n\n/**\n * Walks a compiled template tree and reports every WASM artefact embedded\n * directly or transitively. Used only by the too-large-pack error message —\n * never on the success path. Deduplicates by artefact name (sub-templates can\n * import the same WASM via different aliases and we want to attribute weight\n * only once).\n */\nexport function collectWasmContributions(tpl: CompiledTemplateV3): WasmContribution[] {\n const seen = new Map<string, WasmContribution>();\n function walk(t: TemplateDataV3) {\n for (const [name, ref] of Object.entries(t.wasm ?? {})) {\n if (seen.has(name)) continue;\n const base64 = tpl.hashToSource[ref.sourceHash];\n // base64 encodes 3 binary bytes per 4 chars; the off-by-padding is at\n // most 2 bytes per artefact — fine for a human-readable size breakdown.\n const storedBytes = base64 != null ? Math.floor((base64.length * 3) / 4) : 0;\n seen.set(name, { name, storedBytes });\n }\n for (const sub of Object.values(t.templates ?? {})) walk(sub);\n }\n walk(tpl.template);\n return [...seen.values()];\n}\n\nexport function assertTemplatePackSize(\n templateName: string,\n gzippedByteLength: number,\n wasmContributions: readonly WasmContribution[],\n): void {\n if (gzippedByteLength <= MAX_TEMPLATE_PACK_BYTES_GZIPPED) return;\n const ranked = [...wasmContributions].sort((a, b) => b.storedBytes - a.storedBytes);\n const breakdown =\n ranked.length === 0\n ? \"\\n (no WASM artefacts in this pack — heavy libs, software descriptors, or sub-templates are the likely cause.)\"\n : \"\\nWASM artefacts in this pack (gzipped, pre-base64):\\n\" +\n ranked.map((w) => ` - ${w.name} — ${formatBytes(w.storedBytes)}`).join(\"\\n\");\n throw new Error(\n `Template pack ${templateName} is ${formatBytes(gzippedByteLength)} gzipped, ` +\n `which exceeds tengo-builder's ${formatBytes(MAX_TEMPLATE_PACK_BYTES_GZIPPED)} per-pack cap. ` +\n `The backend caps gzipped packs at 3.5 MiB (see TemplatePackSizeLimit in pl: ` +\n `controllers/workflow/pkg/cfg/config.go).` +\n breakdown +\n \"\\nShrink WASM artefacts (wasm-opt -Oz), or split this template into smaller pieces.\",\n );\n}\n"],"mappings":";;AA6BA,MAAa,sBAAsB,IAAI,OAAO;AAI9C,MAAa,kCAAkC,MAAM,OAAO,OAAO,MAAM;AAEzE,SAAS,YAAY,GAAmB;
|
|
1
|
+
{"version":3,"file":"pack_limits.cjs","names":["fullNameToString"],"sources":["../../src/compiler/pack_limits.ts"],"sourcesContent":["import type { CompiledTemplateV3, TemplateDataV3 } from \"@milaboratories/pl-model-backend\";\n\nimport type { FullArtifactName } from \"./package\";\nimport { fullNameToString } from \"./package\";\n\n// Build-time size guards mirroring the two backend caps that gate template\n// ingestion. Hardcoded because tengo-builder runs at block build time and has\n// no connection to a running backend; if pl ever changes the caps, update the\n// constants here in lockstep with the source-of-truth lines pointed at below.\n//\n// Source of truth (`core/pl` repo):\n// - platform/core/transaction/assertions.go : `maxResourceDataSize`\n// 3 MiB per value resource, checked on every CreateValue marshal.\n// Hits the WasmV1 resource after the controller unpacks a template pack\n// into its constituent libs/software/wasm resources.\n// - controllers/workflow/pkg/cfg/config.go : `TemplatePackSizeLimit`\n// 3.5 MiB per gzipped template pack, checked before the pack itself is\n// stored as a TengoTemplatePackV1 value resource.\n\n// Cap on the gzipped wasm payload that ends up in WasmV1Data.Code on the\n// backend. 2 MiB gzipped → ~2.67 MiB base64 + JSON wrapper → comfortably\n// under the 3 MiB per-value-resource cap with ~330 KiB headroom for the\n// WasmV1Data wrapper (Name, Version, Runtime, DefaultMemoryLimit, JSON\n// syntax). WasmV1Data.Code is a Go `[]byte`, which encoding/json serialises\n// as base64 — that's where the 4/3 expansion comes from.\n//\n// The tengo-builder gzips wasm files before adding them to the pack; this\n// cap therefore admits raw .wasm files several times larger than 2 MiB\n// (real wasm components compress to ~30-40 % of their raw size).\nexport const MAX_WASM_FILE_BYTES = 2 * 1024 * 1024;\n\n// 100 KiB below the backend's 3.5 MiB so blocks don't break on small\n// platform-side metadata overhead, or if pl tightens the limit slightly.\nexport const MAX_TEMPLATE_PACK_BYTES_GZIPPED = 3.5 * 1024 * 1024 - 100 * 1024;\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;\n return `${(n / 1024 / 1024).toFixed(2)} MiB`;\n}\n\nexport function assertWasmFileSize(\n file: string,\n byteLength: number,\n fullName: FullArtifactName,\n): void {\n if (byteLength <= MAX_WASM_FILE_BYTES) return;\n throw new Error(\n `WASM artefact ${fullNameToString(fullName)} from ${file} is ${formatBytes(byteLength)} ` +\n `gzipped, which exceeds tengo-builder's ${formatBytes(MAX_WASM_FILE_BYTES)} per-WASM cap. ` +\n `The backend stores each WASM as a single value resource (3 MiB hard cap after base64+JSON ` +\n `marshal — see maxResourceDataSize in pl: platform/core/transaction/assertions.go). ` +\n `Strip debug info or run \\`wasm-opt -Oz\\` to shrink it.`,\n );\n}\n\nexport interface WasmContribution {\n /** Artefact name as stored under TemplateDataV3.wasm (e.g. \"@pkg:id\"). */\n readonly name: string;\n /**\n * Bytes this artefact contributes to the pack, measured after gzip and\n * before base64 — i.e. the size of the binary payload stored on the\n * backend in WasmV1Data.Code. Decoded from the base64-encoded source in\n * hashToSource.\n */\n readonly storedBytes: number;\n}\n\n/**\n * Walks a compiled template tree and reports every WASM artefact embedded\n * directly or transitively. Used only by the too-large-pack error message —\n * never on the success path. Deduplicates by artefact name (sub-templates can\n * import the same WASM via different aliases and we want to attribute weight\n * only once).\n */\nexport function collectWasmContributions(tpl: CompiledTemplateV3): WasmContribution[] {\n const seen = new Map<string, WasmContribution>();\n function walk(t: TemplateDataV3) {\n for (const [name, ref] of Object.entries(t.wasm ?? {})) {\n if (seen.has(name)) continue;\n const base64 = tpl.hashToSource[ref.sourceHash];\n // base64 encodes 3 binary bytes per 4 chars; the off-by-padding is at\n // most 2 bytes per artefact — fine for a human-readable size breakdown.\n const storedBytes = base64 != null ? Math.floor((base64.length * 3) / 4) : 0;\n seen.set(name, { name, storedBytes });\n }\n for (const sub of Object.values(t.templates ?? {})) walk(sub);\n }\n walk(tpl.template);\n return [...seen.values()];\n}\n\nexport function assertTemplatePackSize(\n templateName: string,\n gzippedByteLength: number,\n wasmContributions: readonly WasmContribution[],\n): void {\n if (gzippedByteLength <= MAX_TEMPLATE_PACK_BYTES_GZIPPED) return;\n const ranked = [...wasmContributions].sort((a, b) => b.storedBytes - a.storedBytes);\n const breakdown =\n ranked.length === 0\n ? \"\\n (no WASM artefacts in this pack — heavy libs, software descriptors, or sub-templates are the likely cause.)\"\n : \"\\nWASM artefacts in this pack (gzipped, pre-base64):\\n\" +\n ranked.map((w) => ` - ${w.name} — ${formatBytes(w.storedBytes)}`).join(\"\\n\");\n throw new Error(\n `Template pack ${templateName} is ${formatBytes(gzippedByteLength)} gzipped, ` +\n `which exceeds tengo-builder's ${formatBytes(MAX_TEMPLATE_PACK_BYTES_GZIPPED)} per-pack cap. ` +\n `The backend caps gzipped packs at 3.5 MiB (see TemplatePackSizeLimit in pl: ` +\n `controllers/workflow/pkg/cfg/config.go).` +\n breakdown +\n \"\\nShrink WASM artefacts (wasm-opt -Oz), or split this template into smaller pieces.\",\n );\n}\n"],"mappings":";;AA6BA,MAAa,sBAAsB,IAAI,OAAO;AAI9C,MAAa,kCAAkC,MAAM,OAAO,OAAO,MAAM;AAEzE,SAAS,YAAY,GAAmB;CACtC,IAAI,IAAI,MAAM,OAAO,GAAG,EAAE;CAC1B,IAAI,IAAI,OAAO,MAAM,OAAO,IAAI,IAAI,KAAA,CAAM,QAAQ,CAAC,EAAE;CACrD,OAAO,IAAI,IAAI,OAAO,KAAA,CAAM,QAAQ,CAAC,EAAE;AACzC;AAEA,SAAgB,mBACd,MACA,YACA,UACM;CACN,IAAI,cAAA,SAAmC;CACvC,MAAM,IAAI,MACR,iBAAiBA,gBAAAA,iBAAiB,QAAQ,EAAE,QAAQ,KAAK,MAAM,YAAY,UAAU,EAAE,0CAC3C,YAAY,mBAAmB,EAAE,mPAI/E;AACF;;;;;;;;AAqBA,SAAgB,yBAAyB,KAA6C;CACpF,MAAM,uBAAO,IAAI,IAA8B;CAC/C,SAAS,KAAK,GAAmB;EAC/B,KAAK,MAAM,CAAC,MAAM,QAAQ,OAAO,QAAQ,EAAE,QAAQ,CAAC,CAAC,GAAG;GACtD,IAAI,KAAK,IAAI,IAAI,GAAG;GACpB,MAAM,SAAS,IAAI,aAAa,IAAI;GAGpC,MAAM,cAAc,UAAU,OAAO,KAAK,MAAO,OAAO,SAAS,IAAK,CAAC,IAAI;GAC3E,KAAK,IAAI,MAAM;IAAE;IAAM;GAAY,CAAC;EACtC;EACA,KAAK,MAAM,OAAO,OAAO,OAAO,EAAE,aAAa,CAAC,CAAC,GAAG,KAAK,GAAG;CAC9D;CACA,KAAK,IAAI,QAAQ;CACjB,OAAO,CAAC,GAAG,KAAK,OAAO,CAAC;AAC1B;AAEA,SAAgB,uBACd,cACA,mBACA,mBACM;CACN,IAAI,qBAAA,SAAsD;CAC1D,MAAM,SAAS,CAAC,GAAG,iBAAiB,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,cAAc,EAAE,WAAW;CAClF,MAAM,YACJ,OAAO,WAAW,IACd,oHACA,2DACA,OAAO,KAAK,MAAM,OAAO,EAAE,KAAK,KAAK,YAAY,EAAE,WAAW,GAAG,CAAC,CAAC,KAAK,IAAI;CAClF,MAAM,IAAI,MACR,iBAAiB,aAAa,MAAM,YAAY,iBAAiB,EAAE,0CAChC,YAAY,+BAA+B,EAAE,uIAG9E,YACA,qFACJ;AACF"}
|
|
@@ -42,6 +42,6 @@ function assertTemplatePackSize(templateName, gzippedByteLength, wasmContributio
|
|
|
42
42
|
throw new Error(`Template pack ${templateName} is ${formatBytes(gzippedByteLength)} gzipped, which exceeds tengo-builder's ${formatBytes(MAX_TEMPLATE_PACK_BYTES_GZIPPED)} per-pack cap. The backend caps gzipped packs at 3.5 MiB (see TemplatePackSizeLimit in pl: controllers/workflow/pkg/cfg/config.go).` + breakdown + "\nShrink WASM artefacts (wasm-opt -Oz), or split this template into smaller pieces.");
|
|
43
43
|
}
|
|
44
44
|
//#endregion
|
|
45
|
-
export { assertTemplatePackSize, assertWasmFileSize, collectWasmContributions };
|
|
45
|
+
export { MAX_TEMPLATE_PACK_BYTES_GZIPPED, MAX_WASM_FILE_BYTES, assertTemplatePackSize, assertWasmFileSize, collectWasmContributions };
|
|
46
46
|
|
|
47
47
|
//# sourceMappingURL=pack_limits.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pack_limits.js","names":[],"sources":["../../src/compiler/pack_limits.ts"],"sourcesContent":["import type { CompiledTemplateV3, TemplateDataV3 } from \"@milaboratories/pl-model-backend\";\n\nimport type { FullArtifactName } from \"./package\";\nimport { fullNameToString } from \"./package\";\n\n// Build-time size guards mirroring the two backend caps that gate template\n// ingestion. Hardcoded because tengo-builder runs at block build time and has\n// no connection to a running backend; if pl ever changes the caps, update the\n// constants here in lockstep with the source-of-truth lines pointed at below.\n//\n// Source of truth (`core/pl` repo):\n// - platform/core/transaction/assertions.go : `maxResourceDataSize`\n// 3 MiB per value resource, checked on every CreateValue marshal.\n// Hits the WasmV1 resource after the controller unpacks a template pack\n// into its constituent libs/software/wasm resources.\n// - controllers/workflow/pkg/cfg/config.go : `TemplatePackSizeLimit`\n// 3.5 MiB per gzipped template pack, checked before the pack itself is\n// stored as a TengoTemplatePackV1 value resource.\n\n// Cap on the gzipped wasm payload that ends up in WasmV1Data.Code on the\n// backend. 2 MiB gzipped → ~2.67 MiB base64 + JSON wrapper → comfortably\n// under the 3 MiB per-value-resource cap with ~330 KiB headroom for the\n// WasmV1Data wrapper (Name, Version, Runtime, DefaultMemoryLimit, JSON\n// syntax). WasmV1Data.Code is a Go `[]byte`, which encoding/json serialises\n// as base64 — that's where the 4/3 expansion comes from.\n//\n// The tengo-builder gzips wasm files before adding them to the pack; this\n// cap therefore admits raw .wasm files several times larger than 2 MiB\n// (real wasm components compress to ~30-40 % of their raw size).\nexport const MAX_WASM_FILE_BYTES = 2 * 1024 * 1024;\n\n// 100 KiB below the backend's 3.5 MiB so blocks don't break on small\n// platform-side metadata overhead, or if pl tightens the limit slightly.\nexport const MAX_TEMPLATE_PACK_BYTES_GZIPPED = 3.5 * 1024 * 1024 - 100 * 1024;\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;\n return `${(n / 1024 / 1024).toFixed(2)} MiB`;\n}\n\nexport function assertWasmFileSize(\n file: string,\n byteLength: number,\n fullName: FullArtifactName,\n): void {\n if (byteLength <= MAX_WASM_FILE_BYTES) return;\n throw new Error(\n `WASM artefact ${fullNameToString(fullName)} from ${file} is ${formatBytes(byteLength)} ` +\n `gzipped, which exceeds tengo-builder's ${formatBytes(MAX_WASM_FILE_BYTES)} per-WASM cap. ` +\n `The backend stores each WASM as a single value resource (3 MiB hard cap after base64+JSON ` +\n `marshal — see maxResourceDataSize in pl: platform/core/transaction/assertions.go). ` +\n `Strip debug info or run \\`wasm-opt -Oz\\` to shrink it.`,\n );\n}\n\nexport interface WasmContribution {\n /** Artefact name as stored under TemplateDataV3.wasm (e.g. \"@pkg:id\"). */\n readonly name: string;\n /**\n * Bytes this artefact contributes to the pack, measured after gzip and\n * before base64 — i.e. the size of the binary payload stored on the\n * backend in WasmV1Data.Code. Decoded from the base64-encoded source in\n * hashToSource.\n */\n readonly storedBytes: number;\n}\n\n/**\n * Walks a compiled template tree and reports every WASM artefact embedded\n * directly or transitively. Used only by the too-large-pack error message —\n * never on the success path. Deduplicates by artefact name (sub-templates can\n * import the same WASM via different aliases and we want to attribute weight\n * only once).\n */\nexport function collectWasmContributions(tpl: CompiledTemplateV3): WasmContribution[] {\n const seen = new Map<string, WasmContribution>();\n function walk(t: TemplateDataV3) {\n for (const [name, ref] of Object.entries(t.wasm ?? {})) {\n if (seen.has(name)) continue;\n const base64 = tpl.hashToSource[ref.sourceHash];\n // base64 encodes 3 binary bytes per 4 chars; the off-by-padding is at\n // most 2 bytes per artefact — fine for a human-readable size breakdown.\n const storedBytes = base64 != null ? Math.floor((base64.length * 3) / 4) : 0;\n seen.set(name, { name, storedBytes });\n }\n for (const sub of Object.values(t.templates ?? {})) walk(sub);\n }\n walk(tpl.template);\n return [...seen.values()];\n}\n\nexport function assertTemplatePackSize(\n templateName: string,\n gzippedByteLength: number,\n wasmContributions: readonly WasmContribution[],\n): void {\n if (gzippedByteLength <= MAX_TEMPLATE_PACK_BYTES_GZIPPED) return;\n const ranked = [...wasmContributions].sort((a, b) => b.storedBytes - a.storedBytes);\n const breakdown =\n ranked.length === 0\n ? \"\\n (no WASM artefacts in this pack — heavy libs, software descriptors, or sub-templates are the likely cause.)\"\n : \"\\nWASM artefacts in this pack (gzipped, pre-base64):\\n\" +\n ranked.map((w) => ` - ${w.name} — ${formatBytes(w.storedBytes)}`).join(\"\\n\");\n throw new Error(\n `Template pack ${templateName} is ${formatBytes(gzippedByteLength)} gzipped, ` +\n `which exceeds tengo-builder's ${formatBytes(MAX_TEMPLATE_PACK_BYTES_GZIPPED)} per-pack cap. ` +\n `The backend caps gzipped packs at 3.5 MiB (see TemplatePackSizeLimit in pl: ` +\n `controllers/workflow/pkg/cfg/config.go).` +\n breakdown +\n \"\\nShrink WASM artefacts (wasm-opt -Oz), or split this template into smaller pieces.\",\n );\n}\n"],"mappings":";;AA6BA,MAAa,sBAAsB,IAAI,OAAO;AAI9C,MAAa,kCAAkC,MAAM,OAAO,OAAO,MAAM;AAEzE,SAAS,YAAY,GAAmB;
|
|
1
|
+
{"version":3,"file":"pack_limits.js","names":[],"sources":["../../src/compiler/pack_limits.ts"],"sourcesContent":["import type { CompiledTemplateV3, TemplateDataV3 } from \"@milaboratories/pl-model-backend\";\n\nimport type { FullArtifactName } from \"./package\";\nimport { fullNameToString } from \"./package\";\n\n// Build-time size guards mirroring the two backend caps that gate template\n// ingestion. Hardcoded because tengo-builder runs at block build time and has\n// no connection to a running backend; if pl ever changes the caps, update the\n// constants here in lockstep with the source-of-truth lines pointed at below.\n//\n// Source of truth (`core/pl` repo):\n// - platform/core/transaction/assertions.go : `maxResourceDataSize`\n// 3 MiB per value resource, checked on every CreateValue marshal.\n// Hits the WasmV1 resource after the controller unpacks a template pack\n// into its constituent libs/software/wasm resources.\n// - controllers/workflow/pkg/cfg/config.go : `TemplatePackSizeLimit`\n// 3.5 MiB per gzipped template pack, checked before the pack itself is\n// stored as a TengoTemplatePackV1 value resource.\n\n// Cap on the gzipped wasm payload that ends up in WasmV1Data.Code on the\n// backend. 2 MiB gzipped → ~2.67 MiB base64 + JSON wrapper → comfortably\n// under the 3 MiB per-value-resource cap with ~330 KiB headroom for the\n// WasmV1Data wrapper (Name, Version, Runtime, DefaultMemoryLimit, JSON\n// syntax). WasmV1Data.Code is a Go `[]byte`, which encoding/json serialises\n// as base64 — that's where the 4/3 expansion comes from.\n//\n// The tengo-builder gzips wasm files before adding them to the pack; this\n// cap therefore admits raw .wasm files several times larger than 2 MiB\n// (real wasm components compress to ~30-40 % of their raw size).\nexport const MAX_WASM_FILE_BYTES = 2 * 1024 * 1024;\n\n// 100 KiB below the backend's 3.5 MiB so blocks don't break on small\n// platform-side metadata overhead, or if pl tightens the limit slightly.\nexport const MAX_TEMPLATE_PACK_BYTES_GZIPPED = 3.5 * 1024 * 1024 - 100 * 1024;\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;\n return `${(n / 1024 / 1024).toFixed(2)} MiB`;\n}\n\nexport function assertWasmFileSize(\n file: string,\n byteLength: number,\n fullName: FullArtifactName,\n): void {\n if (byteLength <= MAX_WASM_FILE_BYTES) return;\n throw new Error(\n `WASM artefact ${fullNameToString(fullName)} from ${file} is ${formatBytes(byteLength)} ` +\n `gzipped, which exceeds tengo-builder's ${formatBytes(MAX_WASM_FILE_BYTES)} per-WASM cap. ` +\n `The backend stores each WASM as a single value resource (3 MiB hard cap after base64+JSON ` +\n `marshal — see maxResourceDataSize in pl: platform/core/transaction/assertions.go). ` +\n `Strip debug info or run \\`wasm-opt -Oz\\` to shrink it.`,\n );\n}\n\nexport interface WasmContribution {\n /** Artefact name as stored under TemplateDataV3.wasm (e.g. \"@pkg:id\"). */\n readonly name: string;\n /**\n * Bytes this artefact contributes to the pack, measured after gzip and\n * before base64 — i.e. the size of the binary payload stored on the\n * backend in WasmV1Data.Code. Decoded from the base64-encoded source in\n * hashToSource.\n */\n readonly storedBytes: number;\n}\n\n/**\n * Walks a compiled template tree and reports every WASM artefact embedded\n * directly or transitively. Used only by the too-large-pack error message —\n * never on the success path. Deduplicates by artefact name (sub-templates can\n * import the same WASM via different aliases and we want to attribute weight\n * only once).\n */\nexport function collectWasmContributions(tpl: CompiledTemplateV3): WasmContribution[] {\n const seen = new Map<string, WasmContribution>();\n function walk(t: TemplateDataV3) {\n for (const [name, ref] of Object.entries(t.wasm ?? {})) {\n if (seen.has(name)) continue;\n const base64 = tpl.hashToSource[ref.sourceHash];\n // base64 encodes 3 binary bytes per 4 chars; the off-by-padding is at\n // most 2 bytes per artefact — fine for a human-readable size breakdown.\n const storedBytes = base64 != null ? Math.floor((base64.length * 3) / 4) : 0;\n seen.set(name, { name, storedBytes });\n }\n for (const sub of Object.values(t.templates ?? {})) walk(sub);\n }\n walk(tpl.template);\n return [...seen.values()];\n}\n\nexport function assertTemplatePackSize(\n templateName: string,\n gzippedByteLength: number,\n wasmContributions: readonly WasmContribution[],\n): void {\n if (gzippedByteLength <= MAX_TEMPLATE_PACK_BYTES_GZIPPED) return;\n const ranked = [...wasmContributions].sort((a, b) => b.storedBytes - a.storedBytes);\n const breakdown =\n ranked.length === 0\n ? \"\\n (no WASM artefacts in this pack — heavy libs, software descriptors, or sub-templates are the likely cause.)\"\n : \"\\nWASM artefacts in this pack (gzipped, pre-base64):\\n\" +\n ranked.map((w) => ` - ${w.name} — ${formatBytes(w.storedBytes)}`).join(\"\\n\");\n throw new Error(\n `Template pack ${templateName} is ${formatBytes(gzippedByteLength)} gzipped, ` +\n `which exceeds tengo-builder's ${formatBytes(MAX_TEMPLATE_PACK_BYTES_GZIPPED)} per-pack cap. ` +\n `The backend caps gzipped packs at 3.5 MiB (see TemplatePackSizeLimit in pl: ` +\n `controllers/workflow/pkg/cfg/config.go).` +\n breakdown +\n \"\\nShrink WASM artefacts (wasm-opt -Oz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ACJ,OAAO,WAAW,IACd,oHACA,2DACA,OAAO,KAAK,MAAM,OAAO,EAAE,KAAK,KAAK,YAAY,EAAE,WAAW,GAAG,CAAC,CAAC,KAAK,IAAI;CAClF,MAAM,IAAI,MACR,iBAAiB,aAAa,MAAM,YAAY,iBAAiB,EAAE,0CAChC,YAAY,+BAA+B,EAAE,uIAG9E,YACA,qFACJ;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package.cjs","names":[],"sources":["../../src/compiler/package.ts"],"sourcesContent":["/*\n Package \"@milaboratory/current-tengo-package\".\n\n Structure:\n\n src/\n local-template.pl.tengo <- this one will be compiled and put into ./dist/tengo/tpl/local-template.pl.pkg\n local-library.tengo <- this one will be normalized and put into ./dist/tengo/lib/local-library.tengo\n main.tpl.tengo <- this one will be compiled into ./dist/tengo/tpl/main.pl.pkg and published by external tool\n\n Code of \"main.tpl.tengo\":\n\n plapi := import(\"plapi\")\n\n plapi.getTemplateId(\"@milaboratory/some-tengo-template\") // -> getTemplateId(\"@milaboratory/some-tengo-template:main\")\n import(\"@milaboratory/some-tengo-library\") // -> import(\"@milaboratory/some-tengo-library:main\")\n\n */\n\nexport type CompileMode = \"dist\";\n\nexport type CompilerOption = {\n /** Option name, like 'hash_override' */\n name: string; // we can't use strict literals typing here as we will break compatibility of the code through the lifetime of the compiler.\n\n /** Arguments of the option. Everything that follows option name */\n args: string[];\n};\n\nexport type ArtifactType = \"library\" | \"template\" | \"test\" | \"software\" | \"asset\" | \"wasm\";\n\n/** Artifact Name including package version */\nexport interface FullArtifactName {\n /** Dependency type */\n type: ArtifactType;\n\n /** Fully qualified package */\n pkg: string;\n\n /** Id of the artifact inside the package */\n id: string;\n\n /** Package version */\n version: string;\n}\n\nexport type FullArtifactNameWithoutType = Omit<FullArtifactName, \"type\">;\n\nexport type TypedArtifactName = Pick<FullArtifactName, \"type\" | \"pkg\" | \"id\">;\n\nexport type PackageName = Pick<FullArtifactName, \"pkg\" | \"version\">;\n\nexport type ArtifactName = Pick<FullArtifactName, \"pkg\" | \"id\">;\n\nexport function artifactKey(name: TypedArtifactName): string {\n return `${name.type}||${name.pkg}||${name.id}`;\n}\n\nexport function fullNameToString(name: FullArtifactName): string {\n return `${name.type}:${name.pkg}:${name.id}:${name.version}`;\n}\n\n/** used for exceptions */\nexport function typedArtifactNameToString(name: TypedArtifactName): string {\n return `${name.type}:${name.pkg}:${name.id}`;\n}\n\nexport function typedArtifactNamesEquals(\n name1: TypedArtifactName,\n name2: TypedArtifactName,\n): boolean {\n return name1.type == name2.type && name1.pkg == name2.pkg && name1.id == name2.id;\n}\n\nexport function fullNameEquals(name1: FullArtifactName, name2: FullArtifactName): boolean {\n return (\n name1.type == name2.type &&\n name1.pkg == name2.pkg &&\n name1.id == name2.id &&\n name1.version == name2.version\n );\n}\n\n/** used to format artefact name while generating output files */\nexport function artifactNameToString(name: ArtifactName): string {\n return `${name.pkg}:${name.id}`;\n}\n\n/** used to format artefact name and version while generating output files */\nexport function formatArtefactNameAndVersion(name: FullArtifactName): {\n name: string;\n version: string;\n} {\n return { name: artifactNameToString(name), version: name.version };\n}\n\n/** used to format artefact name and version while generating output files */\nexport function parseArtefactNameAndVersion(nameAndVersion: {\n name: string;\n version: string;\n}): FullArtifactNameWithoutType {\n const match = nameAndVersion.name.match(/^(?<pkg>[^:]*):(?<id>[^:]*)$/);\n if (!match) throw new Error(`malformed artifact name: ${nameAndVersion.name}`);\n return { pkg: match.groups![\"pkg\"], id: match.groups![\"id\"], version: nameAndVersion.version };\n}\n\nexport function fullNameWithoutTypeToString(name: FullArtifactNameWithoutType): string {\n return `${name.pkg}:${name.id}:${name.version}`;\n}\n\nexport function fullNameWithoutType(name: FullArtifactName): FullArtifactNameWithoutType {\n return { pkg: name.pkg, id: name.id, version: name.version };\n}\n"],"mappings":";AAsDA,SAAgB,YAAY,MAAiC;
|
|
1
|
+
{"version":3,"file":"package.cjs","names":[],"sources":["../../src/compiler/package.ts"],"sourcesContent":["/*\n Package \"@milaboratory/current-tengo-package\".\n\n Structure:\n\n src/\n local-template.pl.tengo <- this one will be compiled and put into ./dist/tengo/tpl/local-template.pl.pkg\n local-library.tengo <- this one will be normalized and put into ./dist/tengo/lib/local-library.tengo\n main.tpl.tengo <- this one will be compiled into ./dist/tengo/tpl/main.pl.pkg and published by external tool\n\n Code of \"main.tpl.tengo\":\n\n plapi := import(\"plapi\")\n\n plapi.getTemplateId(\"@milaboratory/some-tengo-template\") // -> getTemplateId(\"@milaboratory/some-tengo-template:main\")\n import(\"@milaboratory/some-tengo-library\") // -> import(\"@milaboratory/some-tengo-library:main\")\n\n */\n\nexport type CompileMode = \"dist\";\n\nexport type CompilerOption = {\n /** Option name, like 'hash_override' */\n name: string; // we can't use strict literals typing here as we will break compatibility of the code through the lifetime of the compiler.\n\n /** Arguments of the option. Everything that follows option name */\n args: string[];\n};\n\nexport type ArtifactType = \"library\" | \"template\" | \"test\" | \"software\" | \"asset\" | \"wasm\";\n\n/** Artifact Name including package version */\nexport interface FullArtifactName {\n /** Dependency type */\n type: ArtifactType;\n\n /** Fully qualified package */\n pkg: string;\n\n /** Id of the artifact inside the package */\n id: string;\n\n /** Package version */\n version: string;\n}\n\nexport type FullArtifactNameWithoutType = Omit<FullArtifactName, \"type\">;\n\nexport type TypedArtifactName = Pick<FullArtifactName, \"type\" | \"pkg\" | \"id\">;\n\nexport type PackageName = Pick<FullArtifactName, \"pkg\" | \"version\">;\n\nexport type ArtifactName = Pick<FullArtifactName, \"pkg\" | \"id\">;\n\nexport function artifactKey(name: TypedArtifactName): string {\n return `${name.type}||${name.pkg}||${name.id}`;\n}\n\nexport function fullNameToString(name: FullArtifactName): string {\n return `${name.type}:${name.pkg}:${name.id}:${name.version}`;\n}\n\n/** used for exceptions */\nexport function typedArtifactNameToString(name: TypedArtifactName): string {\n return `${name.type}:${name.pkg}:${name.id}`;\n}\n\nexport function typedArtifactNamesEquals(\n name1: TypedArtifactName,\n name2: TypedArtifactName,\n): boolean {\n return name1.type == name2.type && name1.pkg == name2.pkg && name1.id == name2.id;\n}\n\nexport function fullNameEquals(name1: FullArtifactName, name2: FullArtifactName): boolean {\n return (\n name1.type == name2.type &&\n name1.pkg == name2.pkg &&\n name1.id == name2.id &&\n name1.version == name2.version\n );\n}\n\n/** used to format artefact name while generating output files */\nexport function artifactNameToString(name: ArtifactName): string {\n return `${name.pkg}:${name.id}`;\n}\n\n/** used to format artefact name and version while generating output files */\nexport function formatArtefactNameAndVersion(name: FullArtifactName): {\n name: string;\n version: string;\n} {\n return { name: artifactNameToString(name), version: name.version };\n}\n\n/** used to format artefact name and version while generating output files */\nexport function parseArtefactNameAndVersion(nameAndVersion: {\n name: string;\n version: string;\n}): FullArtifactNameWithoutType {\n const match = nameAndVersion.name.match(/^(?<pkg>[^:]*):(?<id>[^:]*)$/);\n if (!match) throw new Error(`malformed artifact name: ${nameAndVersion.name}`);\n return { pkg: match.groups![\"pkg\"], id: match.groups![\"id\"], version: nameAndVersion.version };\n}\n\nexport function fullNameWithoutTypeToString(name: FullArtifactNameWithoutType): string {\n return `${name.pkg}:${name.id}:${name.version}`;\n}\n\nexport function fullNameWithoutType(name: FullArtifactName): FullArtifactNameWithoutType {\n return { pkg: name.pkg, id: name.id, version: name.version };\n}\n"],"mappings":";AAsDA,SAAgB,YAAY,MAAiC;CAC3D,OAAO,GAAG,KAAK,KAAK,IAAI,KAAK,IAAI,IAAI,KAAK;AAC5C;AAEA,SAAgB,iBAAiB,MAAgC;CAC/D,OAAO,GAAG,KAAK,KAAK,GAAG,KAAK,IAAI,GAAG,KAAK,GAAG,GAAG,KAAK;AACrD;;AAGA,SAAgB,0BAA0B,MAAiC;CACzE,OAAO,GAAG,KAAK,KAAK,GAAG,KAAK,IAAI,GAAG,KAAK;AAC1C;AAEA,SAAgB,yBACd,OACA,OACS;CACT,OAAO,MAAM,QAAQ,MAAM,QAAQ,MAAM,OAAO,MAAM,OAAO,MAAM,MAAM,MAAM;AACjF;AAEA,SAAgB,eAAe,OAAyB,OAAkC;CACxF,OACE,MAAM,QAAQ,MAAM,QACpB,MAAM,OAAO,MAAM,OACnB,MAAM,MAAM,MAAM,MAClB,MAAM,WAAW,MAAM;AAE3B;;AAGA,SAAgB,qBAAqB,MAA4B;CAC/D,OAAO,GAAG,KAAK,IAAI,GAAG,KAAK;AAC7B;;AAGA,SAAgB,6BAA6B,MAG3C;CACA,OAAO;EAAE,MAAM,qBAAqB,IAAI;EAAG,SAAS,KAAK;CAAQ;AACnE;;AAGA,SAAgB,4BAA4B,gBAGZ;CAC9B,MAAM,QAAQ,eAAe,KAAK,MAAM,8BAA8B;CACtE,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,4BAA4B,eAAe,MAAM;CAC7E,OAAO;EAAE,KAAK,MAAM,OAAQ;EAAQ,IAAI,MAAM,OAAQ;EAAO,SAAS,eAAe;CAAQ;AAC/F;AAEA,SAAgB,4BAA4B,MAA2C;CACrF,OAAO,GAAG,KAAK,IAAI,GAAG,KAAK,GAAG,GAAG,KAAK;AACxC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package.js","names":[],"sources":["../../src/compiler/package.ts"],"sourcesContent":["/*\n Package \"@milaboratory/current-tengo-package\".\n\n Structure:\n\n src/\n local-template.pl.tengo <- this one will be compiled and put into ./dist/tengo/tpl/local-template.pl.pkg\n local-library.tengo <- this one will be normalized and put into ./dist/tengo/lib/local-library.tengo\n main.tpl.tengo <- this one will be compiled into ./dist/tengo/tpl/main.pl.pkg and published by external tool\n\n Code of \"main.tpl.tengo\":\n\n plapi := import(\"plapi\")\n\n plapi.getTemplateId(\"@milaboratory/some-tengo-template\") // -> getTemplateId(\"@milaboratory/some-tengo-template:main\")\n import(\"@milaboratory/some-tengo-library\") // -> import(\"@milaboratory/some-tengo-library:main\")\n\n */\n\nexport type CompileMode = \"dist\";\n\nexport type CompilerOption = {\n /** Option name, like 'hash_override' */\n name: string; // we can't use strict literals typing here as we will break compatibility of the code through the lifetime of the compiler.\n\n /** Arguments of the option. Everything that follows option name */\n args: string[];\n};\n\nexport type ArtifactType = \"library\" | \"template\" | \"test\" | \"software\" | \"asset\" | \"wasm\";\n\n/** Artifact Name including package version */\nexport interface FullArtifactName {\n /** Dependency type */\n type: ArtifactType;\n\n /** Fully qualified package */\n pkg: string;\n\n /** Id of the artifact inside the package */\n id: string;\n\n /** Package version */\n version: string;\n}\n\nexport type FullArtifactNameWithoutType = Omit<FullArtifactName, \"type\">;\n\nexport type TypedArtifactName = Pick<FullArtifactName, \"type\" | \"pkg\" | \"id\">;\n\nexport type PackageName = Pick<FullArtifactName, \"pkg\" | \"version\">;\n\nexport type ArtifactName = Pick<FullArtifactName, \"pkg\" | \"id\">;\n\nexport function artifactKey(name: TypedArtifactName): string {\n return `${name.type}||${name.pkg}||${name.id}`;\n}\n\nexport function fullNameToString(name: FullArtifactName): string {\n return `${name.type}:${name.pkg}:${name.id}:${name.version}`;\n}\n\n/** used for exceptions */\nexport function typedArtifactNameToString(name: TypedArtifactName): string {\n return `${name.type}:${name.pkg}:${name.id}`;\n}\n\nexport function typedArtifactNamesEquals(\n name1: TypedArtifactName,\n name2: TypedArtifactName,\n): boolean {\n return name1.type == name2.type && name1.pkg == name2.pkg && name1.id == name2.id;\n}\n\nexport function fullNameEquals(name1: FullArtifactName, name2: FullArtifactName): boolean {\n return (\n name1.type == name2.type &&\n name1.pkg == name2.pkg &&\n name1.id == name2.id &&\n name1.version == name2.version\n );\n}\n\n/** used to format artefact name while generating output files */\nexport function artifactNameToString(name: ArtifactName): string {\n return `${name.pkg}:${name.id}`;\n}\n\n/** used to format artefact name and version while generating output files */\nexport function formatArtefactNameAndVersion(name: FullArtifactName): {\n name: string;\n version: string;\n} {\n return { name: artifactNameToString(name), version: name.version };\n}\n\n/** used to format artefact name and version while generating output files */\nexport function parseArtefactNameAndVersion(nameAndVersion: {\n name: string;\n version: string;\n}): FullArtifactNameWithoutType {\n const match = nameAndVersion.name.match(/^(?<pkg>[^:]*):(?<id>[^:]*)$/);\n if (!match) throw new Error(`malformed artifact name: ${nameAndVersion.name}`);\n return { pkg: match.groups![\"pkg\"], id: match.groups![\"id\"], version: nameAndVersion.version };\n}\n\nexport function fullNameWithoutTypeToString(name: FullArtifactNameWithoutType): string {\n return `${name.pkg}:${name.id}:${name.version}`;\n}\n\nexport function fullNameWithoutType(name: FullArtifactName): FullArtifactNameWithoutType {\n return { pkg: name.pkg, id: name.id, version: name.version };\n}\n"],"mappings":";AAsDA,SAAgB,YAAY,MAAiC;
|
|
1
|
+
{"version":3,"file":"package.js","names":[],"sources":["../../src/compiler/package.ts"],"sourcesContent":["/*\n Package \"@milaboratory/current-tengo-package\".\n\n Structure:\n\n src/\n local-template.pl.tengo <- this one will be compiled and put into ./dist/tengo/tpl/local-template.pl.pkg\n local-library.tengo <- this one will be normalized and put into ./dist/tengo/lib/local-library.tengo\n main.tpl.tengo <- this one will be compiled into ./dist/tengo/tpl/main.pl.pkg and published by external tool\n\n Code of \"main.tpl.tengo\":\n\n plapi := import(\"plapi\")\n\n plapi.getTemplateId(\"@milaboratory/some-tengo-template\") // -> getTemplateId(\"@milaboratory/some-tengo-template:main\")\n import(\"@milaboratory/some-tengo-library\") // -> import(\"@milaboratory/some-tengo-library:main\")\n\n */\n\nexport type CompileMode = \"dist\";\n\nexport type CompilerOption = {\n /** Option name, like 'hash_override' */\n name: string; // we can't use strict literals typing here as we will break compatibility of the code through the lifetime of the compiler.\n\n /** Arguments of the option. Everything that follows option name */\n args: string[];\n};\n\nexport type ArtifactType = \"library\" | \"template\" | \"test\" | \"software\" | \"asset\" | \"wasm\";\n\n/** Artifact Name including package version */\nexport interface FullArtifactName {\n /** Dependency type */\n type: ArtifactType;\n\n /** Fully qualified package */\n pkg: string;\n\n /** Id of the artifact inside the package */\n id: string;\n\n /** Package version */\n version: string;\n}\n\nexport type FullArtifactNameWithoutType = Omit<FullArtifactName, \"type\">;\n\nexport type TypedArtifactName = Pick<FullArtifactName, \"type\" | \"pkg\" | \"id\">;\n\nexport type PackageName = Pick<FullArtifactName, \"pkg\" | \"version\">;\n\nexport type ArtifactName = Pick<FullArtifactName, \"pkg\" | \"id\">;\n\nexport function artifactKey(name: TypedArtifactName): string {\n return `${name.type}||${name.pkg}||${name.id}`;\n}\n\nexport function fullNameToString(name: FullArtifactName): string {\n return `${name.type}:${name.pkg}:${name.id}:${name.version}`;\n}\n\n/** used for exceptions */\nexport function typedArtifactNameToString(name: TypedArtifactName): string {\n return `${name.type}:${name.pkg}:${name.id}`;\n}\n\nexport function typedArtifactNamesEquals(\n name1: TypedArtifactName,\n name2: TypedArtifactName,\n): boolean {\n return name1.type == name2.type && name1.pkg == name2.pkg && name1.id == name2.id;\n}\n\nexport function fullNameEquals(name1: FullArtifactName, name2: FullArtifactName): boolean {\n return (\n name1.type == name2.type &&\n name1.pkg == name2.pkg &&\n name1.id == name2.id &&\n name1.version == name2.version\n );\n}\n\n/** used to format artefact name while generating output files */\nexport function artifactNameToString(name: ArtifactName): string {\n return `${name.pkg}:${name.id}`;\n}\n\n/** used to format artefact name and version while generating output files */\nexport function formatArtefactNameAndVersion(name: FullArtifactName): {\n name: string;\n version: string;\n} {\n return { name: artifactNameToString(name), version: name.version };\n}\n\n/** used to format artefact name and version while generating output files */\nexport function parseArtefactNameAndVersion(nameAndVersion: {\n name: string;\n version: string;\n}): FullArtifactNameWithoutType {\n const match = nameAndVersion.name.match(/^(?<pkg>[^:]*):(?<id>[^:]*)$/);\n if (!match) throw new Error(`malformed artifact name: ${nameAndVersion.name}`);\n return { pkg: match.groups![\"pkg\"], id: match.groups![\"id\"], version: nameAndVersion.version };\n}\n\nexport function fullNameWithoutTypeToString(name: FullArtifactNameWithoutType): string {\n return `${name.pkg}:${name.id}:${name.version}`;\n}\n\nexport function fullNameWithoutType(name: FullArtifactName): FullArtifactNameWithoutType {\n return { pkg: name.pkg, id: name.id, version: name.version };\n}\n"],"mappings":";AAsDA,SAAgB,YAAY,MAAiC;CAC3D,OAAO,GAAG,KAAK,KAAK,IAAI,KAAK,IAAI,IAAI,KAAK;AAC5C;AAEA,SAAgB,iBAAiB,MAAgC;CAC/D,OAAO,GAAG,KAAK,KAAK,GAAG,KAAK,IAAI,GAAG,KAAK,GAAG,GAAG,KAAK;AACrD;;AAGA,SAAgB,0BAA0B,MAAiC;CACzE,OAAO,GAAG,KAAK,KAAK,GAAG,KAAK,IAAI,GAAG,KAAK;AAC1C;AAEA,SAAgB,yBACd,OACA,OACS;CACT,OAAO,MAAM,QAAQ,MAAM,QAAQ,MAAM,OAAO,MAAM,OAAO,MAAM,MAAM,MAAM;AACjF;AAEA,SAAgB,eAAe,OAAyB,OAAkC;CACxF,OACE,MAAM,QAAQ,MAAM,QACpB,MAAM,OAAO,MAAM,OACnB,MAAM,MAAM,MAAM,MAClB,MAAM,WAAW,MAAM;AAE3B;;AAGA,SAAgB,qBAAqB,MAA4B;CAC/D,OAAO,GAAG,KAAK,IAAI,GAAG,KAAK;AAC7B;;AAGA,SAAgB,6BAA6B,MAG3C;CACA,OAAO;EAAE,MAAM,qBAAqB,IAAI;EAAG,SAAS,KAAK;CAAQ;AACnE;;AAGA,SAAgB,4BAA4B,gBAGZ;CAC9B,MAAM,QAAQ,eAAe,KAAK,MAAM,8BAA8B;CACtE,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,4BAA4B,eAAe,MAAM;CAC7E,OAAO;EAAE,KAAK,MAAM,OAAQ;EAAQ,IAAI,MAAM,OAAQ;EAAO,SAAS,eAAe;CAAQ;AAC/F;AAEA,SAAgB,4BAA4B,MAA2C;CACrF,OAAO,GAAG,KAAK,IAAI,GAAG,KAAK,GAAG,GAAG,KAAK;AACxC"}
|
package/dist/compiler/source.cjs
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
require("../_virtual/_rolldown/runtime.cjs");
|
|
2
1
|
const require_package = require("./package.cjs");
|
|
3
2
|
const require_artifactset = require("./artifactset.cjs");
|
|
4
3
|
let node_fs = require("node:fs");
|
|
@@ -50,6 +49,13 @@ const parseComplierOption = (opt) => {
|
|
|
50
49
|
};
|
|
51
50
|
};
|
|
52
51
|
var ArtifactSource = class {
|
|
52
|
+
compileMode;
|
|
53
|
+
fullName;
|
|
54
|
+
sourceHash;
|
|
55
|
+
src;
|
|
56
|
+
srcName;
|
|
57
|
+
dependencies;
|
|
58
|
+
compilerOptions;
|
|
53
59
|
constructor(compileMode, fullName, sourceHash, src, srcName, dependencies, compilerOptions) {
|
|
54
60
|
this.compileMode = compileMode;
|
|
55
61
|
this.fullName = fullName;
|
|
@@ -283,6 +289,9 @@ function getSha256(source) {
|
|
|
283
289
|
//#endregion
|
|
284
290
|
exports.ArtifactSource = ArtifactSource;
|
|
285
291
|
exports.getSha256 = getSha256;
|
|
292
|
+
exports.newGetSoftwareInfoRE = newGetSoftwareInfoRE;
|
|
293
|
+
exports.newGetTemplateIdRE = newGetTemplateIdRE;
|
|
294
|
+
exports.parseSingleSourceLine = parseSingleSourceLine;
|
|
286
295
|
exports.parseSourceFile = parseSourceFile;
|
|
287
296
|
|
|
288
297
|
//# sourceMappingURL=source.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"source.cjs","names":["createArtifactNameSet","fullNameToString"],"sources":["../../src/compiler/source.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport {\n type TypedArtifactName,\n type FullArtifactName,\n type ArtifactType,\n type CompileMode,\n type CompilerOption,\n fullNameToString,\n} from \"./package\";\nimport type { ArtifactMap } from \"./artifactset\";\nimport { createArtifactNameSet } from \"./artifactset\";\nimport { createHash } from \"node:crypto\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\n\n// matches any valid name in tengo. Don't forget to use '\\b' when needed to limit the boundaries!\nconst namePattern = \"[_a-zA-Z][_a-zA-Z0-9]*\";\n\nconst functionCallRE = (moduleName: string, fnName: string) => {\n // `fnCall` captures from the function name through the first string\n // argument (including the closing quote and any trailing whitespace);\n // the closing-paren-or-comma check is a non-consuming lookahead, so\n // any extra args (`assets.importWasm(\"name\", { memoryLimit: ... })`)\n // survive the rewrite in `compiler.ts` — only the literal is\n // build-time material, anything past it is runtime config.\n return new RegExp(\n `\\\\b${moduleName}\\\\.(?<fnCall>(?<fnName>` +\n fnName +\n `)\\\\s*\\\\(\\\\s*\"(?<templateName>[^\"]+)\"\\\\s*)(?=[,)])`,\n \"g\",\n );\n};\n\nconst functionCallLikeRE = (moduleName: string, fnName: string) => {\n return new RegExp(`\\\\b${moduleName}\\\\.(?<fnName>` + fnName + `)\\\\s*\\\\(`, \"g\");\n};\n\nexport const newGetTemplateIdRE = (moduleName: string) =>\n functionCallRE(moduleName, \"getTemplateId\");\nexport const newGetSoftwareInfoRE = (moduleName: string) =>\n functionCallRE(moduleName, \"getSoftwareInfo\");\n\nconst newImportTemplateRE = (moduleName: string) => functionCallRE(moduleName, \"importTemplate\");\nconst newImportTemplateDetector = (moduleName: string) =>\n functionCallLikeRE(moduleName, \"importTemplate\");\nconst newImportSoftwareRE = (moduleName: string) => functionCallRE(moduleName, \"importSoftware\");\nconst newImportSoftwareDetector = (moduleName: string) =>\n functionCallLikeRE(moduleName, \"importSoftware\");\nconst newImportAssetRE = (moduleName: string) => functionCallRE(moduleName, \"importAsset\");\nconst newImportAssetDetector = (moduleName: string) =>\n functionCallLikeRE(moduleName, \"importAsset\");\nconst newImportWasmRE = (moduleName: string) => functionCallRE(moduleName, \"importWasm\");\nconst newImportWasmDetector = (moduleName: string) => functionCallLikeRE(moduleName, \"importWasm\");\n\nconst emptyLineRE = /^\\s*$/;\nconst compilerOptionRE = /^\\/\\/tengo:[\\w]/;\nconst wrongCompilerOptionRE = /^\\s*\\/\\/\\s*tengo:\\s*./;\nconst singlelineCommentRE = /^\\s*(\\/\\/)/;\nconst singlelineTerminatedCommentRE = /^\\s*\\/\\*.*\\*\\/\\s*$/; // matches '^/* ... */$' comment lines as a special case of singleline comments.\nconst multilineCommentStartRE = /^\\s*\\/\\*/;\nconst multilineCommentEndRE = /\\*\\//;\nconst multilineStatementRE = /[.,]\\s*$/; // it is hard to consistently treat (\\n\"a\"\\n) multiline statements, we forbid them for now.\n\n// import could only be an assignment in a statement,\n// other ways could break a compilation.\nconst importRE = /\\s*:=\\s*import\\s*\\(\\s*\"(?<moduleName>[^\"]+)\"\\s*\\)/;\nconst importNameRE = new RegExp(\n `\\\\b(?<importName>${namePattern}(\\\\.${namePattern})*)${importRE.source}`,\n);\nconst dependencyRE = /(?<pkgName>[^\"]+)?:(?<depID>[^\"]+)/; // use it to parse <moduleName> from importPattern or <templateName> from getTemplateID\n\n/**\n * Parse compiler option string representation\n * Compiler option line is a comment starting with '//tengo:', say\n * //tengo:hash_override tralala\n *\n * The common compiler option syntax is:\n * //tengo:<option name> [<option arg1> [<option arg 2> [...]]]\n */\nconst parseComplierOption = (opt: string): CompilerOption => {\n const parts = opt.split(\" \");\n const namePart = parts[0].split(\":\");\n if (namePart.length != 2) {\n throw new Error(\n \"compiler option format is wrong: expect to have option name after 'tengo:' prefix, like 'tengo:MyOption'\",\n );\n }\n const optName = namePart[1];\n\n return {\n name: optName,\n args: parts.slice(1),\n };\n};\n\nexport class ArtifactSource {\n constructor(\n /** The mode this artifact was built (dev or dist) */\n public readonly compileMode: CompileMode,\n /** Full artifact id, including package version */\n public readonly fullName: FullArtifactName,\n /** Hash of the source code */\n public readonly sourceHash: string,\n /** Normalized source code */\n public readonly src: string,\n /** Path to source file where artifact came from */\n public readonly srcName: string,\n /** List of dependencies */\n public readonly dependencies: TypedArtifactName[],\n /** Additional compiler options detected in source code */\n public readonly compilerOptions: CompilerOption[],\n ) {}\n}\n\nexport function parseSourceFile(\n logger: MiLogger,\n mode: CompileMode,\n srcFile: string,\n fullSourceName: FullArtifactName,\n normalize: boolean,\n): ArtifactSource {\n const src = readFileSync(srcFile).toString();\n const { deps, normalized, opts } = parseSourceData(logger, src, fullSourceName, normalize);\n\n return new ArtifactSource(\n mode,\n fullSourceName,\n getSha256(normalized),\n normalized,\n srcFile,\n deps.array,\n opts,\n );\n}\n\nexport function parseSource(\n logger: MiLogger,\n mode: CompileMode,\n src: string,\n fullSourceName: FullArtifactName,\n normalize: boolean,\n): ArtifactSource {\n const { deps, normalized, opts } = parseSourceData(logger, src, fullSourceName, normalize);\n\n return new ArtifactSource(\n mode,\n fullSourceName,\n getSha256(normalized),\n normalized,\n \"\",\n deps.array,\n opts,\n );\n}\n\n/**\n * Reads src\n * returns normalized source code,\n * gets dependencies from imports,\n * maps imports to global names if globalizeImports is true,\n * and collects compiler options like hashOverride.\n */\nfunction parseSourceData(\n logger: MiLogger,\n src: string,\n fullSourceName: FullArtifactName,\n globalizeImports: boolean,\n): {\n normalized: string;\n deps: ArtifactMap<TypedArtifactName>;\n opts: CompilerOption[];\n} {\n const dependencySet = createArtifactNameSet();\n const optionList: CompilerOption[] = [];\n\n // iterating over lines\n const lines = src.split(\"\\n\");\n\n // processedLines keep all the original lines from <src>.\n // If <globalizeImport>==true, the parser modifies 'import' and 'getTemplateId' lines\n // with Platforma Tengo lib and template usages, resolving local names (\":<item>\") to\n // global (\"@milaboratory/pkg:<item>\")\n const processedLines: string[] = [];\n let parserContext: sourceParserContext = {\n isInCommentBlock: false,\n canDetectOptions: true,\n artifactImportREs: new Map<string, [ArtifactType, RegExp][]>(),\n importLikeREs: new Map<string, [ArtifactType, RegExp][]>(),\n multilineStatement: \"\",\n lineNo: 0,\n };\n\n for (const line of lines) {\n parserContext.lineNo++;\n\n try {\n const {\n line: processedLine,\n context: newContext,\n artifacts,\n option,\n } = parseSingleSourceLine(logger, line, parserContext, fullSourceName.pkg, globalizeImports);\n processedLines.push(processedLine);\n parserContext = newContext;\n\n for (const artifact of artifacts ?? []) {\n dependencySet.add(artifact);\n }\n if (option) {\n optionList.push(option);\n }\n } catch (error: unknown) {\n const err = error as Error;\n throw new Error(\n `[line ${parserContext.lineNo} in ${fullNameToString(fullSourceName)}]: ${err.message}\\n\\t${line}`,\n { cause: err },\n );\n }\n }\n\n return {\n normalized: processedLines.join(\"\\n\"),\n deps: dependencySet,\n opts: optionList,\n };\n}\n\nexport type sourceParserContext = {\n isInCommentBlock: boolean;\n canDetectOptions: boolean;\n artifactImportREs: Map<string, [ArtifactType, RegExp][]>;\n importLikeREs: Map<string, [ArtifactType, RegExp][]>;\n multilineStatement: string;\n lineNo: number;\n};\n\nexport type lineProcessingResult = {\n line: string;\n context: sourceParserContext;\n artifacts: TypedArtifactName[];\n option: CompilerOption | undefined;\n};\n\nexport function parseSingleSourceLine(\n logger: MiLogger,\n line: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean,\n): lineProcessingResult {\n if (context.isInCommentBlock) {\n if (multilineCommentEndRE.exec(line)) {\n context.isInCommentBlock = false;\n }\n return { line: \"\", context, artifacts: [], option: undefined };\n }\n\n if (compilerOptionRE.exec(line)) {\n if (!context.canDetectOptions) {\n logger.error(\n `[line ${context.lineNo}]: compiler option '//tengo:' was detected, but it cannot be applied as compiler options can be set only at the file header, before any code line'`,\n );\n throw new Error(\n \"tengo compiler options ('//tengo:' comments) can be set only in file header\",\n );\n }\n return { line, context, artifacts: [], option: parseComplierOption(line) };\n }\n\n if (wrongCompilerOptionRE.exec(line) && context.canDetectOptions) {\n logger.warn(\n `[line ${context.lineNo}]: text simillar to compiler option ('//tengo:...') was detected, but it has wrong format. Leave it as is, if you did not mean to use a line as compiler option. Or format it to '//tengo:<option>' otherwise (no spaces between '//' and 'tengo', no spaces between ':' and option name)`,\n );\n return { line, context, artifacts: [], option: undefined };\n }\n\n if (singlelineCommentRE.test(line) || singlelineTerminatedCommentRE.test(line)) {\n return { line: \"\", context, artifacts: [], option: undefined };\n }\n\n const canBeInlinedComment = line.includes(\"*/\");\n if (multilineCommentStartRE.exec(line) && !canBeInlinedComment) {\n context.isInCommentBlock = true;\n return { line: \"\", context, artifacts: [], option: undefined };\n }\n\n const statement = context.multilineStatement + line.trim();\n\n const mayContainAComment = line.includes(\"//\") || line.includes(\"/*\");\n if (multilineStatementRE.test(line) && !mayContainAComment) {\n // We accumulate multiline statements into single line before analyzing them.\n // This dramatically simplifies parsing logic: things like\n //\n // assets.\n // importSoftware(\"a:b\");\n //\n // become simple 'assets.importSoftware(\"a:b\");' for parser checks.\n //\n // For safety reasons, we never consider anything that 'may look like a comment'\n // as a part of multiline statement to prevent joining things like\n //\n // someFnCall() // looks like multiline statement because of dot in the end of a comment.\n //\n // This problem also appears in multiline string literals, but I hope this will not\n // cause problems in real life.\n\n // We still try to process each line to globalize imports in case of complex constructions, when\n // statements are stacked one into another:\n // a.\n // use(assets.importSoftware(\":soft1\")).\n // use(assets.importSoftware(\":soft2\")).\n // run()\n // It is multiline, and it still requires import globalization mid-way, not just for the last line of statement\n const result = processAssetImport(line, statement, context, localPackageName, globalizeImports);\n context.multilineStatement += result.line.trim(); // accumulate the line after imports globalization.\n return result;\n }\n\n context.multilineStatement = \"\"; // reset accumulated multiline statement parts once we reach statement end.\n\n if (emptyLineRE.exec(statement)) {\n return { line, context, artifacts: [], option: undefined };\n }\n\n // options could be only at the top of the file.\n context.canDetectOptions = false;\n\n return processAssetImport(line, statement, context, localPackageName, globalizeImports);\n}\n\nfunction processModuleImport(\n importInstruction: RegExpExecArray,\n originalLine: string,\n statement: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean,\n): lineProcessingResult {\n const iInfo = parseImport(statement);\n\n // If we have plapi, ll or assets, then try to parse\n // getTemplateId, getSoftwareInfo, getSoftware and getAsset calls.\n\n if (iInfo.module === \"plapi\") {\n if (!context.artifactImportREs.has(iInfo.module)) {\n context.artifactImportREs.set(iInfo.module, [\n [\"template\", newGetTemplateIdRE(iInfo.alias)],\n [\"software\", newGetSoftwareInfoRE(iInfo.alias)],\n ]);\n }\n return { line: originalLine, context, artifacts: [], option: undefined };\n }\n\n if (\n iInfo.module === \"@milaboratory/tengo-sdk:ll\" ||\n iInfo.module === \"@platforma-sdk/workflow-tengo:ll\" ||\n ((localPackageName === \"@milaboratory/tengo-sdk\" ||\n localPackageName === \"@platforma-sdk/workflow-tengo\") &&\n iInfo.module === \":ll\")\n ) {\n if (!context.artifactImportREs.has(iInfo.module)) {\n context.artifactImportREs.set(iInfo.module, [\n [\"template\", newImportTemplateRE(iInfo.alias)],\n [\"software\", newImportSoftwareRE(iInfo.alias)],\n ]);\n }\n }\n\n if (\n iInfo.module === \"@milaboratory/tengo-sdk:assets\" ||\n iInfo.module === \"@platforma-sdk/workflow-tengo:assets\" ||\n ((localPackageName === \"@milaboratory/tengo-sdk\" ||\n localPackageName === \"@platforma-sdk/workflow-tengo\") &&\n iInfo.module === \":assets\")\n ) {\n if (!context.artifactImportREs.has(iInfo.module)) {\n context.artifactImportREs.set(iInfo.module, [\n [\"template\", newImportTemplateRE(iInfo.alias)],\n [\"software\", newImportSoftwareRE(iInfo.alias)],\n [\"asset\", newImportAssetRE(iInfo.alias)],\n [\"wasm\", newImportWasmRE(iInfo.alias)],\n ]);\n context.importLikeREs.set(iInfo.module, [\n [\"template\", newImportTemplateDetector(iInfo.alias)],\n [\"software\", newImportSoftwareDetector(iInfo.alias)],\n [\"asset\", newImportAssetDetector(iInfo.alias)],\n [\"wasm\", newImportWasmDetector(iInfo.alias)],\n ]);\n }\n }\n\n const artifact = parseArtifactName(iInfo.module, \"library\", localPackageName);\n if (!artifact) {\n // not a Platforma Tengo library import\n return { line: originalLine, context, artifacts: [], option: undefined };\n }\n\n if (globalizeImports) {\n originalLine = originalLine.replace(\n importInstruction[0],\n ` := import(\"${artifact.pkg}:${artifact.id}\")`,\n );\n }\n\n return { line: originalLine, context, artifacts: [artifact], option: undefined };\n}\n\nfunction processAssetImport(\n originalLine: string,\n statement: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean,\n): lineProcessingResult {\n if (emptyLineRE.exec(statement)) {\n return { line: originalLine, context, artifacts: [], option: undefined };\n }\n\n // options could be only at the top of the file.\n context.canDetectOptions = false;\n\n const importInstruction = importRE.exec(statement);\n\n if (importInstruction) {\n return processModuleImport(\n importInstruction,\n originalLine,\n statement,\n context,\n localPackageName,\n globalizeImports,\n );\n }\n\n if (context.artifactImportREs.size > 0) {\n for (const [_, artifactRE] of context.artifactImportREs) {\n for (const [artifactType, re] of artifactRE) {\n // Find all matches in the statement\n const matches = Array.from(statement.matchAll(re));\n if (matches.length === 0) {\n continue;\n }\n\n const artifacts: TypedArtifactName[] = [];\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n if (!match || !match.groups) {\n continue;\n }\n\n const { fnCall, templateName, fnName } = match.groups;\n\n if (!fnCall || !templateName || !fnName) {\n throw Error(`failed to parse template import statement`);\n }\n\n const artifact = parseArtifactName(templateName, artifactType, localPackageName);\n if (!artifact) {\n throw Error(`failed to parse artifact name in ${fnName} import statement`);\n }\n artifacts.push(artifact);\n\n if (globalizeImports) {\n // Replace all occurrences of this fnCall in originalLine.\n // fnCall ends right after the literal's closing quote + ws;\n // the trailing `)` or `,` is preserved from the original\n // line, so multi-arg calls (`fn(\"name\", opts)`) keep their\n // remaining args intact.\n originalLine = originalLine.replaceAll(\n fnCall,\n `${fnName}(\"${artifact.pkg}:${artifact.id}\"`,\n );\n }\n }\n\n return { line: originalLine, context, artifacts, option: undefined };\n }\n }\n }\n\n if (context.importLikeREs.size > 0) {\n for (const [_, artifactRE] of context.importLikeREs) {\n for (const [artifactType, re] of artifactRE) {\n const match = re.exec(statement);\n if (!match || !match.groups) {\n continue;\n }\n\n throw Error(\n `incorrect '${artifactType}' import statement: use string literal as ID (variables are not allowed) in the same line with brackets (i.e. 'importSoftware(\"sw:main\")').`,\n );\n }\n }\n }\n\n return { line: originalLine, context, artifacts: [], option: undefined };\n}\n\ninterface ImportInfo {\n module: string; // the module name without wrapping quotes: import(\"<module>\")\n alias: string; // the name of variable that keeps imported module: <alias> := import(\"<module>\")\n}\n\nfunction parseImport(line: string): ImportInfo {\n const match = importNameRE.exec(line);\n\n if (!match || !match.groups) {\n throw Error(`failed to parse 'import' statement`);\n }\n\n const { importName, moduleName } = match.groups;\n if (!importName || !moduleName) {\n throw Error(`failed to parse 'import' statement`);\n }\n\n return {\n module: moduleName, // the module name without wrapping quotes: import(\"<module>\")\n alias: importName, // the name of variable that keeps imported module: <alias> := import(\"<module>\")\n };\n}\n\nfunction parseArtifactName(\n moduleName: string,\n aType: ArtifactType,\n localPackageName: string,\n): TypedArtifactName | undefined {\n const depInfo = dependencyRE.exec(moduleName);\n if (!depInfo) {\n return;\n }\n\n if (!depInfo.groups) {\n throw Error(\n `failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'`,\n );\n }\n\n const { pkgName, depID } = depInfo.groups;\n if (!depID) {\n throw Error(\n `failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'`,\n );\n }\n\n return { type: aType, pkg: pkgName ?? localPackageName, id: depID };\n}\n\nexport function getSha256(source: string): string {\n return createHash(\"sha256\").update(source).digest(\"hex\");\n}\n"],"mappings":";;;;;;AAeA,MAAM,cAAc;AAEpB,MAAM,kBAAkB,YAAoB,WAAmB;AAO7D,QAAO,IAAI,OACT,MAAM,WAAW,2BACf,SACA,qDACF,IACD;;AAGH,MAAM,sBAAsB,YAAoB,WAAmB;AACjE,QAAO,IAAI,OAAO,MAAM,WAAW,iBAAiB,SAAS,YAAY,IAAI;;AAG/E,MAAa,sBAAsB,eACjC,eAAe,YAAY,gBAAgB;AAC7C,MAAa,wBAAwB,eACnC,eAAe,YAAY,kBAAkB;AAE/C,MAAM,uBAAuB,eAAuB,eAAe,YAAY,iBAAiB;AAChG,MAAM,6BAA6B,eACjC,mBAAmB,YAAY,iBAAiB;AAClD,MAAM,uBAAuB,eAAuB,eAAe,YAAY,iBAAiB;AAChG,MAAM,6BAA6B,eACjC,mBAAmB,YAAY,iBAAiB;AAClD,MAAM,oBAAoB,eAAuB,eAAe,YAAY,cAAc;AAC1F,MAAM,0BAA0B,eAC9B,mBAAmB,YAAY,cAAc;AAC/C,MAAM,mBAAmB,eAAuB,eAAe,YAAY,aAAa;AACxF,MAAM,yBAAyB,eAAuB,mBAAmB,YAAY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;EAAS,WAAW,EAAE;EAAE,QAAQ,KAAA;EAAW;;AAQ1E,SAAS,YAAY,MAA0B;CAC7C,MAAM,QAAQ,aAAa,KAAK,KAAK;AAErC,KAAI,CAAC,SAAS,CAAC,MAAM,OACnB,OAAM,MAAM,qCAAqC;CAGnD,MAAM,EAAE,YAAY,eAAe,MAAM;AACzC,KAAI,CAAC,cAAc,CAAC,WAClB,OAAM,MAAM,qCAAqC;AAGnD,QAAO;EACL,QAAQ;EACR,OAAO;EACR;;AAGH,SAAS,kBACP,YACA,OACA,kBAC+B;CAC/B,MAAM,UAAU,aAAa,KAAK,WAAW;AAC7C,KAAI,CAAC,QACH;AAGF,KAAI,CAAC,QAAQ,OACX,OAAM,MACJ,+HACD;CAGH,MAAM,EAAE,SAAS,UAAU,QAAQ;AACnC,KAAI,CAAC,MACH,OAAM,MACJ,+HACD;AAGH,QAAO;EAAE,MAAM;EAAO,KAAK,WAAW;EAAkB,IAAI;EAAO;;AAGrE,SAAgB,UAAU,QAAwB;AAChD,SAAA,GAAA,YAAA,YAAkB,SAAS,CAAC,OAAO,OAAO,CAAC,OAAO,MAAM"}
|
|
1
|
+
{"version":3,"file":"source.cjs","names":["createArtifactNameSet","fullNameToString"],"sources":["../../src/compiler/source.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport {\n type TypedArtifactName,\n type FullArtifactName,\n type ArtifactType,\n type CompileMode,\n type CompilerOption,\n fullNameToString,\n} from \"./package\";\nimport type { ArtifactMap } from \"./artifactset\";\nimport { createArtifactNameSet } from \"./artifactset\";\nimport { createHash } from \"node:crypto\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\n\n// matches any valid name in tengo. Don't forget to use '\\b' when needed to limit the boundaries!\nconst namePattern = \"[_a-zA-Z][_a-zA-Z0-9]*\";\n\nconst functionCallRE = (moduleName: string, fnName: string) => {\n // `fnCall` captures from the function name through the first string\n // argument (including the closing quote and any trailing whitespace);\n // the closing-paren-or-comma check is a non-consuming lookahead, so\n // any extra args (`assets.importWasm(\"name\", { memoryLimit: ... })`)\n // survive the rewrite in `compiler.ts` — only the literal is\n // build-time material, anything past it is runtime config.\n return new RegExp(\n `\\\\b${moduleName}\\\\.(?<fnCall>(?<fnName>` +\n fnName +\n `)\\\\s*\\\\(\\\\s*\"(?<templateName>[^\"]+)\"\\\\s*)(?=[,)])`,\n \"g\",\n );\n};\n\nconst functionCallLikeRE = (moduleName: string, fnName: string) => {\n return new RegExp(`\\\\b${moduleName}\\\\.(?<fnName>` + fnName + `)\\\\s*\\\\(`, \"g\");\n};\n\nexport const newGetTemplateIdRE = (moduleName: string) =>\n functionCallRE(moduleName, \"getTemplateId\");\nexport const newGetSoftwareInfoRE = (moduleName: string) =>\n functionCallRE(moduleName, \"getSoftwareInfo\");\n\nconst newImportTemplateRE = (moduleName: string) => functionCallRE(moduleName, \"importTemplate\");\nconst newImportTemplateDetector = (moduleName: string) =>\n functionCallLikeRE(moduleName, \"importTemplate\");\nconst newImportSoftwareRE = (moduleName: string) => functionCallRE(moduleName, \"importSoftware\");\nconst newImportSoftwareDetector = (moduleName: string) =>\n functionCallLikeRE(moduleName, \"importSoftware\");\nconst newImportAssetRE = (moduleName: string) => functionCallRE(moduleName, \"importAsset\");\nconst newImportAssetDetector = (moduleName: string) =>\n functionCallLikeRE(moduleName, \"importAsset\");\nconst newImportWasmRE = (moduleName: string) => functionCallRE(moduleName, \"importWasm\");\nconst newImportWasmDetector = (moduleName: string) => functionCallLikeRE(moduleName, \"importWasm\");\n\nconst emptyLineRE = /^\\s*$/;\nconst compilerOptionRE = /^\\/\\/tengo:[\\w]/;\nconst wrongCompilerOptionRE = /^\\s*\\/\\/\\s*tengo:\\s*./;\nconst singlelineCommentRE = /^\\s*(\\/\\/)/;\nconst singlelineTerminatedCommentRE = /^\\s*\\/\\*.*\\*\\/\\s*$/; // matches '^/* ... */$' comment lines as a special case of singleline comments.\nconst multilineCommentStartRE = /^\\s*\\/\\*/;\nconst multilineCommentEndRE = /\\*\\//;\nconst multilineStatementRE = /[.,]\\s*$/; // it is hard to consistently treat (\\n\"a\"\\n) multiline statements, we forbid them for now.\n\n// import could only be an assignment in a statement,\n// other ways could break a compilation.\nconst importRE = /\\s*:=\\s*import\\s*\\(\\s*\"(?<moduleName>[^\"]+)\"\\s*\\)/;\nconst importNameRE = new RegExp(\n `\\\\b(?<importName>${namePattern}(\\\\.${namePattern})*)${importRE.source}`,\n);\nconst dependencyRE = /(?<pkgName>[^\"]+)?:(?<depID>[^\"]+)/; // use it to parse <moduleName> from importPattern or <templateName> from getTemplateID\n\n/**\n * Parse compiler option string representation\n * Compiler option line is a comment starting with '//tengo:', say\n * //tengo:hash_override tralala\n *\n * The common compiler option syntax is:\n * //tengo:<option name> [<option arg1> [<option arg 2> [...]]]\n */\nconst parseComplierOption = (opt: string): CompilerOption => {\n const parts = opt.split(\" \");\n const namePart = parts[0].split(\":\");\n if (namePart.length != 2) {\n throw new Error(\n \"compiler option format is wrong: expect to have option name after 'tengo:' prefix, like 'tengo:MyOption'\",\n );\n }\n const optName = namePart[1];\n\n return {\n name: optName,\n args: parts.slice(1),\n };\n};\n\nexport class ArtifactSource {\n constructor(\n /** The mode this artifact was built (dev or dist) */\n public readonly compileMode: CompileMode,\n /** Full artifact id, including package version */\n public readonly fullName: FullArtifactName,\n /** Hash of the source code */\n public readonly sourceHash: string,\n /** Normalized source code */\n public readonly src: string,\n /** Path to source file where artifact came from */\n public readonly srcName: string,\n /** List of dependencies */\n public readonly dependencies: TypedArtifactName[],\n /** Additional compiler options detected in source code */\n public readonly compilerOptions: CompilerOption[],\n ) {}\n}\n\nexport function parseSourceFile(\n logger: MiLogger,\n mode: CompileMode,\n srcFile: string,\n fullSourceName: FullArtifactName,\n normalize: boolean,\n): ArtifactSource {\n const src = readFileSync(srcFile).toString();\n const { deps, normalized, opts } = parseSourceData(logger, src, fullSourceName, normalize);\n\n return new ArtifactSource(\n mode,\n fullSourceName,\n getSha256(normalized),\n normalized,\n srcFile,\n deps.array,\n opts,\n );\n}\n\nexport function parseSource(\n logger: MiLogger,\n mode: CompileMode,\n src: string,\n fullSourceName: FullArtifactName,\n normalize: boolean,\n): ArtifactSource {\n const { deps, normalized, opts } = parseSourceData(logger, src, fullSourceName, normalize);\n\n return new ArtifactSource(\n mode,\n fullSourceName,\n getSha256(normalized),\n normalized,\n \"\",\n deps.array,\n opts,\n );\n}\n\n/**\n * Reads src\n * returns normalized source code,\n * gets dependencies from imports,\n * maps imports to global names if globalizeImports is true,\n * and collects compiler options like hashOverride.\n */\nfunction parseSourceData(\n logger: MiLogger,\n src: string,\n fullSourceName: FullArtifactName,\n globalizeImports: boolean,\n): {\n normalized: string;\n deps: ArtifactMap<TypedArtifactName>;\n opts: CompilerOption[];\n} {\n const dependencySet = createArtifactNameSet();\n const optionList: CompilerOption[] = [];\n\n // iterating over lines\n const lines = src.split(\"\\n\");\n\n // processedLines keep all the original lines from <src>.\n // If <globalizeImport>==true, the parser modifies 'import' and 'getTemplateId' lines\n // with Platforma Tengo lib and template usages, resolving local names (\":<item>\") to\n // global (\"@milaboratory/pkg:<item>\")\n const processedLines: string[] = [];\n let parserContext: sourceParserContext = {\n isInCommentBlock: false,\n canDetectOptions: true,\n artifactImportREs: new Map<string, [ArtifactType, RegExp][]>(),\n importLikeREs: new Map<string, [ArtifactType, RegExp][]>(),\n multilineStatement: \"\",\n lineNo: 0,\n };\n\n for (const line of lines) {\n parserContext.lineNo++;\n\n try {\n const {\n line: processedLine,\n context: newContext,\n artifacts,\n option,\n } = parseSingleSourceLine(logger, line, parserContext, fullSourceName.pkg, globalizeImports);\n processedLines.push(processedLine);\n parserContext = newContext;\n\n for (const artifact of artifacts ?? []) {\n dependencySet.add(artifact);\n }\n if (option) {\n optionList.push(option);\n }\n } catch (error: unknown) {\n const err = error as Error;\n throw new Error(\n `[line ${parserContext.lineNo} in ${fullNameToString(fullSourceName)}]: ${err.message}\\n\\t${line}`,\n { cause: err },\n );\n }\n }\n\n return {\n normalized: processedLines.join(\"\\n\"),\n deps: dependencySet,\n opts: optionList,\n };\n}\n\nexport type sourceParserContext = {\n isInCommentBlock: boolean;\n canDetectOptions: boolean;\n artifactImportREs: Map<string, [ArtifactType, RegExp][]>;\n importLikeREs: Map<string, [ArtifactType, RegExp][]>;\n multilineStatement: string;\n lineNo: number;\n};\n\nexport type lineProcessingResult = {\n line: string;\n context: sourceParserContext;\n artifacts: TypedArtifactName[];\n option: CompilerOption | undefined;\n};\n\nexport function parseSingleSourceLine(\n logger: MiLogger,\n line: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean,\n): lineProcessingResult {\n if (context.isInCommentBlock) {\n if (multilineCommentEndRE.exec(line)) {\n context.isInCommentBlock = false;\n }\n return { line: \"\", context, artifacts: [], option: undefined };\n }\n\n if (compilerOptionRE.exec(line)) {\n if (!context.canDetectOptions) {\n logger.error(\n `[line ${context.lineNo}]: compiler option '//tengo:' was detected, but it cannot be applied as compiler options can be set only at the file header, before any code line'`,\n );\n throw new Error(\n \"tengo compiler options ('//tengo:' comments) can be set only in file header\",\n );\n }\n return { line, context, artifacts: [], option: parseComplierOption(line) };\n }\n\n if (wrongCompilerOptionRE.exec(line) && context.canDetectOptions) {\n logger.warn(\n `[line ${context.lineNo}]: text simillar to compiler option ('//tengo:...') was detected, but it has wrong format. Leave it as is, if you did not mean to use a line as compiler option. Or format it to '//tengo:<option>' otherwise (no spaces between '//' and 'tengo', no spaces between ':' and option name)`,\n );\n return { line, context, artifacts: [], option: undefined };\n }\n\n if (singlelineCommentRE.test(line) || singlelineTerminatedCommentRE.test(line)) {\n return { line: \"\", context, artifacts: [], option: undefined };\n }\n\n const canBeInlinedComment = line.includes(\"*/\");\n if (multilineCommentStartRE.exec(line) && !canBeInlinedComment) {\n context.isInCommentBlock = true;\n return { line: \"\", context, artifacts: [], option: undefined };\n }\n\n const statement = context.multilineStatement + line.trim();\n\n const mayContainAComment = line.includes(\"//\") || line.includes(\"/*\");\n if (multilineStatementRE.test(line) && !mayContainAComment) {\n // We accumulate multiline statements into single line before analyzing them.\n // This dramatically simplifies parsing logic: things like\n //\n // assets.\n // importSoftware(\"a:b\");\n //\n // become simple 'assets.importSoftware(\"a:b\");' for parser checks.\n //\n // For safety reasons, we never consider anything that 'may look like a comment'\n // as a part of multiline statement to prevent joining things like\n //\n // someFnCall() // looks like multiline statement because of dot in the end of a comment.\n //\n // This problem also appears in multiline string literals, but I hope this will not\n // cause problems in real life.\n\n // We still try to process each line to globalize imports in case of complex constructions, when\n // statements are stacked one into another:\n // a.\n // use(assets.importSoftware(\":soft1\")).\n // use(assets.importSoftware(\":soft2\")).\n // run()\n // It is multiline, and it still requires import globalization mid-way, not just for the last line of statement\n const result = processAssetImport(line, statement, context, localPackageName, globalizeImports);\n context.multilineStatement += result.line.trim(); // accumulate the line after imports globalization.\n return result;\n }\n\n context.multilineStatement = \"\"; // reset accumulated multiline statement parts once we reach statement end.\n\n if (emptyLineRE.exec(statement)) {\n return { line, context, artifacts: [], option: undefined };\n }\n\n // options could be only at the top of the file.\n context.canDetectOptions = false;\n\n return processAssetImport(line, statement, context, localPackageName, globalizeImports);\n}\n\nfunction processModuleImport(\n importInstruction: RegExpExecArray,\n originalLine: string,\n statement: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean,\n): lineProcessingResult {\n const iInfo = parseImport(statement);\n\n // If we have plapi, ll or assets, then try to parse\n // getTemplateId, getSoftwareInfo, getSoftware and getAsset calls.\n\n if (iInfo.module === \"plapi\") {\n if (!context.artifactImportREs.has(iInfo.module)) {\n context.artifactImportREs.set(iInfo.module, [\n [\"template\", newGetTemplateIdRE(iInfo.alias)],\n [\"software\", newGetSoftwareInfoRE(iInfo.alias)],\n ]);\n }\n return { line: originalLine, context, artifacts: [], option: undefined };\n }\n\n if (\n iInfo.module === \"@milaboratory/tengo-sdk:ll\" ||\n iInfo.module === \"@platforma-sdk/workflow-tengo:ll\" ||\n ((localPackageName === \"@milaboratory/tengo-sdk\" ||\n localPackageName === \"@platforma-sdk/workflow-tengo\") &&\n iInfo.module === \":ll\")\n ) {\n if (!context.artifactImportREs.has(iInfo.module)) {\n context.artifactImportREs.set(iInfo.module, [\n [\"template\", newImportTemplateRE(iInfo.alias)],\n [\"software\", newImportSoftwareRE(iInfo.alias)],\n ]);\n }\n }\n\n if (\n iInfo.module === \"@milaboratory/tengo-sdk:assets\" ||\n iInfo.module === \"@platforma-sdk/workflow-tengo:assets\" ||\n ((localPackageName === \"@milaboratory/tengo-sdk\" ||\n localPackageName === \"@platforma-sdk/workflow-tengo\") &&\n iInfo.module === \":assets\")\n ) {\n if (!context.artifactImportREs.has(iInfo.module)) {\n context.artifactImportREs.set(iInfo.module, [\n [\"template\", newImportTemplateRE(iInfo.alias)],\n [\"software\", newImportSoftwareRE(iInfo.alias)],\n [\"asset\", newImportAssetRE(iInfo.alias)],\n [\"wasm\", newImportWasmRE(iInfo.alias)],\n ]);\n context.importLikeREs.set(iInfo.module, [\n [\"template\", newImportTemplateDetector(iInfo.alias)],\n [\"software\", newImportSoftwareDetector(iInfo.alias)],\n [\"asset\", newImportAssetDetector(iInfo.alias)],\n [\"wasm\", newImportWasmDetector(iInfo.alias)],\n ]);\n }\n }\n\n const artifact = parseArtifactName(iInfo.module, \"library\", localPackageName);\n if (!artifact) {\n // not a Platforma Tengo library import\n return { line: originalLine, context, artifacts: [], option: undefined };\n }\n\n if (globalizeImports) {\n originalLine = originalLine.replace(\n importInstruction[0],\n ` := import(\"${artifact.pkg}:${artifact.id}\")`,\n );\n }\n\n return { line: originalLine, context, artifacts: [artifact], option: undefined };\n}\n\nfunction processAssetImport(\n originalLine: string,\n statement: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean,\n): lineProcessingResult {\n if (emptyLineRE.exec(statement)) {\n return { line: originalLine, context, artifacts: [], option: undefined };\n }\n\n // options could be only at the top of the file.\n context.canDetectOptions = false;\n\n const importInstruction = importRE.exec(statement);\n\n if (importInstruction) {\n return processModuleImport(\n importInstruction,\n originalLine,\n statement,\n context,\n localPackageName,\n globalizeImports,\n );\n }\n\n if (context.artifactImportREs.size > 0) {\n for (const [_, artifactRE] of context.artifactImportREs) {\n for (const [artifactType, re] of artifactRE) {\n // Find all matches in the statement\n const matches = Array.from(statement.matchAll(re));\n if (matches.length === 0) {\n continue;\n }\n\n const artifacts: TypedArtifactName[] = [];\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n if (!match || !match.groups) {\n continue;\n }\n\n const { fnCall, templateName, fnName } = match.groups;\n\n if (!fnCall || !templateName || !fnName) {\n throw Error(`failed to parse template import statement`);\n }\n\n const artifact = parseArtifactName(templateName, artifactType, localPackageName);\n if (!artifact) {\n throw Error(`failed to parse artifact name in ${fnName} import statement`);\n }\n artifacts.push(artifact);\n\n if (globalizeImports) {\n // Replace all occurrences of this fnCall in originalLine.\n // fnCall ends right after the literal's closing quote + ws;\n // the trailing `)` or `,` is preserved from the original\n // line, so multi-arg calls (`fn(\"name\", opts)`) keep their\n // remaining args intact.\n originalLine = originalLine.replaceAll(\n fnCall,\n `${fnName}(\"${artifact.pkg}:${artifact.id}\"`,\n );\n }\n }\n\n return { line: originalLine, context, artifacts, option: undefined };\n }\n }\n }\n\n if (context.importLikeREs.size > 0) {\n for (const [_, artifactRE] of context.importLikeREs) {\n for (const [artifactType, re] of artifactRE) {\n const match = re.exec(statement);\n if (!match || !match.groups) {\n continue;\n }\n\n throw Error(\n `incorrect '${artifactType}' import statement: use string literal as ID (variables are not allowed) in the same line with brackets (i.e. 'importSoftware(\"sw:main\")').`,\n );\n }\n }\n }\n\n return { line: originalLine, context, artifacts: [], option: undefined };\n}\n\ninterface ImportInfo {\n module: string; // the module name without wrapping quotes: import(\"<module>\")\n alias: string; // the name of variable that keeps imported module: <alias> := import(\"<module>\")\n}\n\nfunction parseImport(line: string): ImportInfo {\n const match = importNameRE.exec(line);\n\n if (!match || !match.groups) {\n throw Error(`failed to parse 'import' statement`);\n }\n\n const { importName, moduleName } = match.groups;\n if (!importName || !moduleName) {\n throw Error(`failed to parse 'import' statement`);\n }\n\n return {\n module: moduleName, // the module name without wrapping quotes: import(\"<module>\")\n alias: importName, // the name of variable that keeps imported module: <alias> := import(\"<module>\")\n };\n}\n\nfunction parseArtifactName(\n moduleName: string,\n aType: ArtifactType,\n localPackageName: string,\n): TypedArtifactName | undefined {\n const depInfo = dependencyRE.exec(moduleName);\n if (!depInfo) {\n return;\n }\n\n if (!depInfo.groups) {\n throw Error(\n `failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'`,\n );\n }\n\n const { pkgName, depID } = depInfo.groups;\n if (!depID) {\n throw Error(\n `failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'`,\n );\n }\n\n return { type: aType, pkg: pkgName ?? localPackageName, id: depID };\n}\n\nexport function getSha256(source: string): string {\n return createHash(\"sha256\").update(source).digest(\"hex\");\n}\n"],"mappings":";;;;;AAeA,MAAM,cAAc;AAEpB,MAAM,kBAAkB,YAAoB,WAAmB;CAO7D,OAAO,IAAI,OACT,MAAM,WAAW,2BACf,SACA,qDACF,GACF;AACF;AAEA,MAAM,sBAAsB,YAAoB,WAAmB;CACjE,OAAO,IAAI,OAAO,MAAM,WAAW,iBAAiB,SAAS,YAAY,GAAG;AAC9E;AAEA,MAAa,sBAAsB,eACjC,eAAe,YAAY,eAAe;AAC5C,MAAa,wBAAwB,eACnC,eAAe,YAAY,iBAAiB;AAE9C,MAAM,uBAAuB,eAAuB,eAAe,YAAY,gBAAgB;AAC/F,MAAM,6BAA6B,eACjC,mBAAmB,YAAY,gBAAgB;AACjD,MAAM,uBAAuB,eAAuB,eAAe,YAAY,gBAAgB;AAC/F,MAAM,6BAA6B,eACjC,mBAAmB,YAAY,gBAAgB;AACjD,MAAM,oBAAoB,eAAuB,eAAe,YAAY,aAAa;AACzF,MAAM,0BAA0B,eAC9B,mBAAmB,YAAY,aAAa;AAC9C,MAAM,mBAAmB,eAAuB,eAAe,YAAY,YAAY;AACvF,MAAM,yBAA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AM,CAAC,cAAc,OAAO,YAAY;EAC3C,MAAM,QAAQ,GAAG,KAAK,SAAS;EAC/B,IAAI,CAAC,SAAS,CAAC,MAAM,QACnB;EAGF,MAAM,MACJ,cAAc,aAAa,4IAC7B;CACF;CAIJ,OAAO;EAAE,MAAM;EAAc;EAAS,WAAW,CAAC;EAAG,QAAQ,KAAA;CAAU;AACzE;AAOA,SAAS,YAAY,MAA0B;CAC7C,MAAM,QAAQ,aAAa,KAAK,IAAI;CAEpC,IAAI,CAAC,SAAS,CAAC,MAAM,QACnB,MAAM,MAAM,oCAAoC;CAGlD,MAAM,EAAE,YAAY,eAAe,MAAM;CACzC,IAAI,CAAC,cAAc,CAAC,YAClB,MAAM,MAAM,oCAAoC;CAGlD,OAAO;EACL,QAAQ;EACR,OAAO;CACT;AACF;AAEA,SAAS,kBACP,YACA,OACA,kBAC+B;CAC/B,MAAM,UAAU,aAAa,KAAK,UAAU;CAC5C,IAAI,CAAC,SACH;CAGF,IAAI,CAAC,QAAQ,QACX,MAAM,MACJ,8HACF;CAGF,MAAM,EAAE,SAAS,UAAU,QAAQ;CACnC,IAAI,CAAC,OACH,MAAM,MACJ,8HACF;CAGF,OAAO;EAAE,MAAM;EAAO,KAAK,WAAW;EAAkB,IAAI;CAAM;AACpE;AAEA,SAAgB,UAAU,QAAwB;CAChD,QAAA,GAAA,YAAA,WAAA,CAAkB,QAAQ,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC,OAAO,KAAK;AACzD"}
|
package/dist/compiler/source.js
CHANGED
|
@@ -49,6 +49,13 @@ const parseComplierOption = (opt) => {
|
|
|
49
49
|
};
|
|
50
50
|
};
|
|
51
51
|
var ArtifactSource = class {
|
|
52
|
+
compileMode;
|
|
53
|
+
fullName;
|
|
54
|
+
sourceHash;
|
|
55
|
+
src;
|
|
56
|
+
srcName;
|
|
57
|
+
dependencies;
|
|
58
|
+
compilerOptions;
|
|
52
59
|
constructor(compileMode, fullName, sourceHash, src, srcName, dependencies, compilerOptions) {
|
|
53
60
|
this.compileMode = compileMode;
|
|
54
61
|
this.fullName = fullName;
|
|
@@ -280,6 +287,6 @@ function getSha256(source) {
|
|
|
280
287
|
return createHash("sha256").update(source).digest("hex");
|
|
281
288
|
}
|
|
282
289
|
//#endregion
|
|
283
|
-
export { ArtifactSource, getSha256, parseSourceFile };
|
|
290
|
+
export { ArtifactSource, getSha256, newGetSoftwareInfoRE, newGetTemplateIdRE, parseSingleSourceLine, parseSourceFile };
|
|
284
291
|
|
|
285
292
|
//# sourceMappingURL=source.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"source.js","names":[],"sources":["../../src/compiler/source.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport {\n type TypedArtifactName,\n type FullArtifactName,\n type ArtifactType,\n type CompileMode,\n type CompilerOption,\n fullNameToString,\n} from \"./package\";\nimport type { ArtifactMap } from \"./artifactset\";\nimport { createArtifactNameSet } from \"./artifactset\";\nimport { createHash } from \"node:crypto\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\n\n// matches any valid name in tengo. Don't forget to use '\\b' when needed to limit the boundaries!\nconst namePattern = \"[_a-zA-Z][_a-zA-Z0-9]*\";\n\nconst functionCallRE = (moduleName: string, fnName: string) => {\n // `fnCall` captures from the function name through the first string\n // argument (including the closing quote and any trailing whitespace);\n // the closing-paren-or-comma check is a non-consuming lookahead, so\n // any extra args (`assets.importWasm(\"name\", { memoryLimit: ... })`)\n // survive the rewrite in `compiler.ts` — only the literal is\n // build-time material, anything past it is runtime config.\n return new RegExp(\n `\\\\b${moduleName}\\\\.(?<fnCall>(?<fnName>` +\n fnName +\n `)\\\\s*\\\\(\\\\s*\"(?<templateName>[^\"]+)\"\\\\s*)(?=[,)])`,\n \"g\",\n );\n};\n\nconst functionCallLikeRE = (moduleName: string, fnName: string) => {\n return new RegExp(`\\\\b${moduleName}\\\\.(?<fnName>` + fnName + `)\\\\s*\\\\(`, \"g\");\n};\n\nexport const newGetTemplateIdRE = (moduleName: string) =>\n functionCallRE(moduleName, \"getTemplateId\");\nexport const newGetSoftwareInfoRE = (moduleName: string) =>\n functionCallRE(moduleName, \"getSoftwareInfo\");\n\nconst newImportTemplateRE = (moduleName: string) => functionCallRE(moduleName, \"importTemplate\");\nconst newImportTemplateDetector = (moduleName: string) =>\n functionCallLikeRE(moduleName, \"importTemplate\");\nconst newImportSoftwareRE = (moduleName: string) => functionCallRE(moduleName, \"importSoftware\");\nconst newImportSoftwareDetector = (moduleName: string) =>\n functionCallLikeRE(moduleName, \"importSoftware\");\nconst newImportAssetRE = (moduleName: string) => functionCallRE(moduleName, \"importAsset\");\nconst newImportAssetDetector = (moduleName: string) =>\n functionCallLikeRE(moduleName, \"importAsset\");\nconst newImportWasmRE = (moduleName: string) => functionCallRE(moduleName, \"importWasm\");\nconst newImportWasmDetector = (moduleName: string) => functionCallLikeRE(moduleName, \"importWasm\");\n\nconst emptyLineRE = /^\\s*$/;\nconst compilerOptionRE = /^\\/\\/tengo:[\\w]/;\nconst wrongCompilerOptionRE = /^\\s*\\/\\/\\s*tengo:\\s*./;\nconst singlelineCommentRE = /^\\s*(\\/\\/)/;\nconst singlelineTerminatedCommentRE = /^\\s*\\/\\*.*\\*\\/\\s*$/; // matches '^/* ... */$' comment lines as a special case of singleline comments.\nconst multilineCommentStartRE = /^\\s*\\/\\*/;\nconst multilineCommentEndRE = /\\*\\//;\nconst multilineStatementRE = /[.,]\\s*$/; // it is hard to consistently treat (\\n\"a\"\\n) multiline statements, we forbid them for now.\n\n// import could only be an assignment in a statement,\n// other ways could break a compilation.\nconst importRE = /\\s*:=\\s*import\\s*\\(\\s*\"(?<moduleName>[^\"]+)\"\\s*\\)/;\nconst importNameRE = new RegExp(\n `\\\\b(?<importName>${namePattern}(\\\\.${namePattern})*)${importRE.source}`,\n);\nconst dependencyRE = /(?<pkgName>[^\"]+)?:(?<depID>[^\"]+)/; // use it to parse <moduleName> from importPattern or <templateName> from getTemplateID\n\n/**\n * Parse compiler option string representation\n * Compiler option line is a comment starting with '//tengo:', say\n * //tengo:hash_override tralala\n *\n * The common compiler option syntax is:\n * //tengo:<option name> [<option arg1> [<option arg 2> [...]]]\n */\nconst parseComplierOption = (opt: string): CompilerOption => {\n const parts = opt.split(\" \");\n const namePart = parts[0].split(\":\");\n if (namePart.length != 2) {\n throw new Error(\n \"compiler option format is wrong: expect to have option name after 'tengo:' prefix, like 'tengo:MyOption'\",\n );\n }\n const optName = namePart[1];\n\n return {\n name: optName,\n args: parts.slice(1),\n };\n};\n\nexport class ArtifactSource {\n constructor(\n /** The mode this artifact was built (dev or dist) */\n public readonly compileMode: CompileMode,\n /** Full artifact id, including package version */\n public readonly fullName: FullArtifactName,\n /** Hash of the source code */\n public readonly sourceHash: string,\n /** Normalized source code */\n public readonly src: string,\n /** Path to source file where artifact came from */\n public readonly srcName: string,\n /** List of dependencies */\n public readonly dependencies: TypedArtifactName[],\n /** Additional compiler options detected in source code */\n public readonly compilerOptions: CompilerOption[],\n ) {}\n}\n\nexport function parseSourceFile(\n logger: MiLogger,\n mode: CompileMode,\n srcFile: string,\n fullSourceName: FullArtifactName,\n normalize: boolean,\n): ArtifactSource {\n const src = readFileSync(srcFile).toString();\n const { deps, normalized, opts } = parseSourceData(logger, src, fullSourceName, normalize);\n\n return new ArtifactSource(\n mode,\n fullSourceName,\n getSha256(normalized),\n normalized,\n srcFile,\n deps.array,\n opts,\n );\n}\n\nexport function parseSource(\n logger: MiLogger,\n mode: CompileMode,\n src: string,\n fullSourceName: FullArtifactName,\n normalize: boolean,\n): ArtifactSource {\n const { deps, normalized, opts } = parseSourceData(logger, src, fullSourceName, normalize);\n\n return new ArtifactSource(\n mode,\n fullSourceName,\n getSha256(normalized),\n normalized,\n \"\",\n deps.array,\n opts,\n );\n}\n\n/**\n * Reads src\n * returns normalized source code,\n * gets dependencies from imports,\n * maps imports to global names if globalizeImports is true,\n * and collects compiler options like hashOverride.\n */\nfunction parseSourceData(\n logger: MiLogger,\n src: string,\n fullSourceName: FullArtifactName,\n globalizeImports: boolean,\n): {\n normalized: string;\n deps: ArtifactMap<TypedArtifactName>;\n opts: CompilerOption[];\n} {\n const dependencySet = createArtifactNameSet();\n const optionList: CompilerOption[] = [];\n\n // iterating over lines\n const lines = src.split(\"\\n\");\n\n // processedLines keep all the original lines from <src>.\n // If <globalizeImport>==true, the parser modifies 'import' and 'getTemplateId' lines\n // with Platforma Tengo lib and template usages, resolving local names (\":<item>\") to\n // global (\"@milaboratory/pkg:<item>\")\n const processedLines: string[] = [];\n let parserContext: sourceParserContext = {\n isInCommentBlock: false,\n canDetectOptions: true,\n artifactImportREs: new Map<string, [ArtifactType, RegExp][]>(),\n importLikeREs: new Map<string, [ArtifactType, RegExp][]>(),\n multilineStatement: \"\",\n lineNo: 0,\n };\n\n for (const line of lines) {\n parserContext.lineNo++;\n\n try {\n const {\n line: processedLine,\n context: newContext,\n artifacts,\n option,\n } = parseSingleSourceLine(logger, line, parserContext, fullSourceName.pkg, globalizeImports);\n processedLines.push(processedLine);\n parserContext = newContext;\n\n for (const artifact of artifacts ?? []) {\n dependencySet.add(artifact);\n }\n if (option) {\n optionList.push(option);\n }\n } catch (error: unknown) {\n const err = error as Error;\n throw new Error(\n `[line ${parserContext.lineNo} in ${fullNameToString(fullSourceName)}]: ${err.message}\\n\\t${line}`,\n { cause: err },\n );\n }\n }\n\n return {\n normalized: processedLines.join(\"\\n\"),\n deps: dependencySet,\n opts: optionList,\n };\n}\n\nexport type sourceParserContext = {\n isInCommentBlock: boolean;\n canDetectOptions: boolean;\n artifactImportREs: Map<string, [ArtifactType, RegExp][]>;\n importLikeREs: Map<string, [ArtifactType, RegExp][]>;\n multilineStatement: string;\n lineNo: number;\n};\n\nexport type lineProcessingResult = {\n line: string;\n context: sourceParserContext;\n artifacts: TypedArtifactName[];\n option: CompilerOption | undefined;\n};\n\nexport function parseSingleSourceLine(\n logger: MiLogger,\n line: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean,\n): lineProcessingResult {\n if (context.isInCommentBlock) {\n if (multilineCommentEndRE.exec(line)) {\n context.isInCommentBlock = false;\n }\n return { line: \"\", context, artifacts: [], option: undefined };\n }\n\n if (compilerOptionRE.exec(line)) {\n if (!context.canDetectOptions) {\n logger.error(\n `[line ${context.lineNo}]: compiler option '//tengo:' was detected, but it cannot be applied as compiler options can be set only at the file header, before any code line'`,\n );\n throw new Error(\n \"tengo compiler options ('//tengo:' comments) can be set only in file header\",\n );\n }\n return { line, context, artifacts: [], option: parseComplierOption(line) };\n }\n\n if (wrongCompilerOptionRE.exec(line) && context.canDetectOptions) {\n logger.warn(\n `[line ${context.lineNo}]: text simillar to compiler option ('//tengo:...') was detected, but it has wrong format. Leave it as is, if you did not mean to use a line as compiler option. Or format it to '//tengo:<option>' otherwise (no spaces between '//' and 'tengo', no spaces between ':' and option name)`,\n );\n return { line, context, artifacts: [], option: undefined };\n }\n\n if (singlelineCommentRE.test(line) || singlelineTerminatedCommentRE.test(line)) {\n return { line: \"\", context, artifacts: [], option: undefined };\n }\n\n const canBeInlinedComment = line.includes(\"*/\");\n if (multilineCommentStartRE.exec(line) && !canBeInlinedComment) {\n context.isInCommentBlock = true;\n return { line: \"\", context, artifacts: [], option: undefined };\n }\n\n const statement = context.multilineStatement + line.trim();\n\n const mayContainAComment = line.includes(\"//\") || line.includes(\"/*\");\n if (multilineStatementRE.test(line) && !mayContainAComment) {\n // We accumulate multiline statements into single line before analyzing them.\n // This dramatically simplifies parsing logic: things like\n //\n // assets.\n // importSoftware(\"a:b\");\n //\n // become simple 'assets.importSoftware(\"a:b\");' for parser checks.\n //\n // For safety reasons, we never consider anything that 'may look like a comment'\n // as a part of multiline statement to prevent joining things like\n //\n // someFnCall() // looks like multiline statement because of dot in the end of a comment.\n //\n // This problem also appears in multiline string literals, but I hope this will not\n // cause problems in real life.\n\n // We still try to process each line to globalize imports in case of complex constructions, when\n // statements are stacked one into another:\n // a.\n // use(assets.importSoftware(\":soft1\")).\n // use(assets.importSoftware(\":soft2\")).\n // run()\n // It is multiline, and it still requires import globalization mid-way, not just for the last line of statement\n const result = processAssetImport(line, statement, context, localPackageName, globalizeImports);\n context.multilineStatement += result.line.trim(); // accumulate the line after imports globalization.\n return result;\n }\n\n context.multilineStatement = \"\"; // reset accumulated multiline statement parts once we reach statement end.\n\n if (emptyLineRE.exec(statement)) {\n return { line, context, artifacts: [], option: undefined };\n }\n\n // options could be only at the top of the file.\n context.canDetectOptions = false;\n\n return processAssetImport(line, statement, context, localPackageName, globalizeImports);\n}\n\nfunction processModuleImport(\n importInstruction: RegExpExecArray,\n originalLine: string,\n statement: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean,\n): lineProcessingResult {\n const iInfo = parseImport(statement);\n\n // If we have plapi, ll or assets, then try to parse\n // getTemplateId, getSoftwareInfo, getSoftware and getAsset calls.\n\n if (iInfo.module === \"plapi\") {\n if (!context.artifactImportREs.has(iInfo.module)) {\n context.artifactImportREs.set(iInfo.module, [\n [\"template\", newGetTemplateIdRE(iInfo.alias)],\n [\"software\", newGetSoftwareInfoRE(iInfo.alias)],\n ]);\n }\n return { line: originalLine, context, artifacts: [], option: undefined };\n }\n\n if (\n iInfo.module === \"@milaboratory/tengo-sdk:ll\" ||\n iInfo.module === \"@platforma-sdk/workflow-tengo:ll\" ||\n ((localPackageName === \"@milaboratory/tengo-sdk\" ||\n localPackageName === \"@platforma-sdk/workflow-tengo\") &&\n iInfo.module === \":ll\")\n ) {\n if (!context.artifactImportREs.has(iInfo.module)) {\n context.artifactImportREs.set(iInfo.module, [\n [\"template\", newImportTemplateRE(iInfo.alias)],\n [\"software\", newImportSoftwareRE(iInfo.alias)],\n ]);\n }\n }\n\n if (\n iInfo.module === \"@milaboratory/tengo-sdk:assets\" ||\n iInfo.module === \"@platforma-sdk/workflow-tengo:assets\" ||\n ((localPackageName === \"@milaboratory/tengo-sdk\" ||\n localPackageName === \"@platforma-sdk/workflow-tengo\") &&\n iInfo.module === \":assets\")\n ) {\n if (!context.artifactImportREs.has(iInfo.module)) {\n context.artifactImportREs.set(iInfo.module, [\n [\"template\", newImportTemplateRE(iInfo.alias)],\n [\"software\", newImportSoftwareRE(iInfo.alias)],\n [\"asset\", newImportAssetRE(iInfo.alias)],\n [\"wasm\", newImportWasmRE(iInfo.alias)],\n ]);\n context.importLikeREs.set(iInfo.module, [\n [\"template\", newImportTemplateDetector(iInfo.alias)],\n [\"software\", newImportSoftwareDetector(iInfo.alias)],\n [\"asset\", newImportAssetDetector(iInfo.alias)],\n [\"wasm\", newImportWasmDetector(iInfo.alias)],\n ]);\n }\n }\n\n const artifact = parseArtifactName(iInfo.module, \"library\", localPackageName);\n if (!artifact) {\n // not a Platforma Tengo library import\n return { line: originalLine, context, artifacts: [], option: undefined };\n }\n\n if (globalizeImports) {\n originalLine = originalLine.replace(\n importInstruction[0],\n ` := import(\"${artifact.pkg}:${artifact.id}\")`,\n );\n }\n\n return { line: originalLine, context, artifacts: [artifact], option: undefined };\n}\n\nfunction processAssetImport(\n originalLine: string,\n statement: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean,\n): lineProcessingResult {\n if (emptyLineRE.exec(statement)) {\n return { line: originalLine, context, artifacts: [], option: undefined };\n }\n\n // options could be only at the top of the file.\n context.canDetectOptions = false;\n\n const importInstruction = importRE.exec(statement);\n\n if (importInstruction) {\n return processModuleImport(\n importInstruction,\n originalLine,\n statement,\n context,\n localPackageName,\n globalizeImports,\n );\n }\n\n if (context.artifactImportREs.size > 0) {\n for (const [_, artifactRE] of context.artifactImportREs) {\n for (const [artifactType, re] of artifactRE) {\n // Find all matches in the statement\n const matches = Array.from(statement.matchAll(re));\n if (matches.length === 0) {\n continue;\n }\n\n const artifacts: TypedArtifactName[] = [];\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n if (!match || !match.groups) {\n continue;\n }\n\n const { fnCall, templateName, fnName } = match.groups;\n\n if (!fnCall || !templateName || !fnName) {\n throw Error(`failed to parse template import statement`);\n }\n\n const artifact = parseArtifactName(templateName, artifactType, localPackageName);\n if (!artifact) {\n throw Error(`failed to parse artifact name in ${fnName} import statement`);\n }\n artifacts.push(artifact);\n\n if (globalizeImports) {\n // Replace all occurrences of this fnCall in originalLine.\n // fnCall ends right after the literal's closing quote + ws;\n // the trailing `)` or `,` is preserved from the original\n // line, so multi-arg calls (`fn(\"name\", opts)`) keep their\n // remaining args intact.\n originalLine = originalLine.replaceAll(\n fnCall,\n `${fnName}(\"${artifact.pkg}:${artifact.id}\"`,\n );\n }\n }\n\n return { line: originalLine, context, artifacts, option: undefined };\n }\n }\n }\n\n if (context.importLikeREs.size > 0) {\n for (const [_, artifactRE] of context.importLikeREs) {\n for (const [artifactType, re] of artifactRE) {\n const match = re.exec(statement);\n if (!match || !match.groups) {\n continue;\n }\n\n throw Error(\n `incorrect '${artifactType}' import statement: use string literal as ID (variables are not allowed) in the same line with brackets (i.e. 'importSoftware(\"sw:main\")').`,\n );\n }\n }\n }\n\n return { line: originalLine, context, artifacts: [], option: undefined };\n}\n\ninterface ImportInfo {\n module: string; // the module name without wrapping quotes: import(\"<module>\")\n alias: string; // the name of variable that keeps imported module: <alias> := import(\"<module>\")\n}\n\nfunction parseImport(line: string): ImportInfo {\n const match = importNameRE.exec(line);\n\n if (!match || !match.groups) {\n throw Error(`failed to parse 'import' statement`);\n }\n\n const { importName, moduleName } = match.groups;\n if (!importName || !moduleName) {\n throw Error(`failed to parse 'import' statement`);\n }\n\n return {\n module: moduleName, // the module name without wrapping quotes: import(\"<module>\")\n alias: importName, // the name of variable that keeps imported module: <alias> := import(\"<module>\")\n };\n}\n\nfunction parseArtifactName(\n moduleName: string,\n aType: ArtifactType,\n localPackageName: string,\n): TypedArtifactName | undefined {\n const depInfo = dependencyRE.exec(moduleName);\n if (!depInfo) {\n return;\n }\n\n if (!depInfo.groups) {\n throw Error(\n `failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'`,\n );\n }\n\n const { pkgName, depID } = depInfo.groups;\n if (!depID) {\n throw Error(\n `failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'`,\n );\n }\n\n return { type: aType, pkg: pkgName ?? localPackageName, id: depID };\n}\n\nexport function getSha256(source: string): string {\n return createHash(\"sha256\").update(source).digest(\"hex\");\n}\n"],"mappings":";;;;;AAeA,MAAM,cAAc;AAEpB,MAAM,kBAAkB,YAAoB,WAAmB;AAO7D,QAAO,IAAI,OACT,MAAM,WAAW,2BACf,SACA,qDACF,IACD;;AAGH,MAAM,sBAAsB,YAAoB,WAAmB;AACjE,QAAO,IAAI,OAAO,MAAM,WAAW,iBAAiB,SAAS,YAAY,IAAI;;AAG/E,MAAa,sBAAsB,eACjC,eAAe,YAAY,gBAAgB;AAC7C,MAAa,wBAAwB,eACnC,eAAe,YAAY,kBAAkB;AAE/C,MAAM,uBAAuB,eAAuB,eAAe,YAAY,iBAAiB;AAChG,MAAM,6BAA6B,eACjC,mBAAmB,YAAY,iBAAiB;AAClD,MAAM,uBAAuB,eAAuB,eAAe,YAAY,iBAAiB;AAChG,MAAM,6BAA6B,eACjC,mBAAmB,YAAY,iBAAiB;AAClD,MAAM,oBAAoB,eAAuB,eAAe,YAAY,cAAc;AAC1F,MAAM,0BAA0B,eAC9B,mBAAmB,YAAY,cAAc;AAC/C,MAAM,mBAAmB,eAAuB,eAAe,YAAY,aAAa;AACxF,MAAM,yBAAyB,eAAuB,mBAAmB,YAAY,aAAa;AAElG,MAAM,cAAc;AACpB,MAAM,mBAAmB;AACzB,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AAC5B,MAAM,gCAAgC;AACtC,MAAM,0BAA0B;AAChC,MAAM,wBAAwB;AAC9B,MAAM,uBAAuB;AAI7B,MAAM,WAAW;AACjB,MAAM,eAAe,IAAI,OACvB,oBAAoB,YAAY,MAAM,YAAY,KAAK,SAAS,SACjE;AACD,MAAM,eAAe;;;;;;;;;AAUrB,MAAM,uBAAuB,QAAgC;CAC3D,MAAM,QAAQ,IAAI,MA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;AAC7C,KAAI,CAAC,QACH;AAGF,KAAI,CAAC,QAAQ,OACX,OAAM,MACJ,+HACD;CAGH,MAAM,EAAE,SAAS,UAAU,QAAQ;AACnC,KAAI,CAAC,MACH,OAAM,MACJ,+HACD;AAGH,QAAO;EAAE,MAAM;EAAO,KAAK,WAAW;EAAkB,IAAI;EAAO;;AAGrE,SAAgB,UAAU,QAAwB;AAChD,QAAO,WAAW,SAAS,CAAC,OAAO,OAAO,CAAC,OAAO,MAAM"}
|
|
1
|
+
{"version":3,"file":"source.js","names":[],"sources":["../../src/compiler/source.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport {\n type TypedArtifactName,\n type FullArtifactName,\n type ArtifactType,\n type CompileMode,\n type CompilerOption,\n fullNameToString,\n} from \"./package\";\nimport type { ArtifactMap } from \"./artifactset\";\nimport { createArtifactNameSet } from \"./artifactset\";\nimport { createHash } from \"node:crypto\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\n\n// matches any valid name in tengo. Don't forget to use '\\b' when needed to limit the boundaries!\nconst namePattern = \"[_a-zA-Z][_a-zA-Z0-9]*\";\n\nconst functionCallRE = (moduleName: string, fnName: string) => {\n // `fnCall` captures from the function name through the first string\n // argument (including the closing quote and any trailing whitespace);\n // the closing-paren-or-comma check is a non-consuming lookahead, so\n // any extra args (`assets.importWasm(\"name\", { memoryLimit: ... })`)\n // survive the rewrite in `compiler.ts` — only the literal is\n // build-time material, anything past it is runtime config.\n return new RegExp(\n `\\\\b${moduleName}\\\\.(?<fnCall>(?<fnName>` +\n fnName +\n `)\\\\s*\\\\(\\\\s*\"(?<templateName>[^\"]+)\"\\\\s*)(?=[,)])`,\n \"g\",\n );\n};\n\nconst functionCallLikeRE = (moduleName: string, fnName: string) => {\n return new RegExp(`\\\\b${moduleName}\\\\.(?<fnName>` + fnName + `)\\\\s*\\\\(`, \"g\");\n};\n\nexport const newGetTemplateIdRE = (moduleName: string) =>\n functionCallRE(moduleName, \"getTemplateId\");\nexport const newGetSoftwareInfoRE = (moduleName: string) =>\n functionCallRE(moduleName, \"getSoftwareInfo\");\n\nconst newImportTemplateRE = (moduleName: string) => functionCallRE(moduleName, \"importTemplate\");\nconst newImportTemplateDetector = (moduleName: string) =>\n functionCallLikeRE(moduleName, \"importTemplate\");\nconst newImportSoftwareRE = (moduleName: string) => functionCallRE(moduleName, \"importSoftware\");\nconst newImportSoftwareDetector = (moduleName: string) =>\n functionCallLikeRE(moduleName, \"importSoftware\");\nconst newImportAssetRE = (moduleName: string) => functionCallRE(moduleName, \"importAsset\");\nconst newImportAssetDetector = (moduleName: string) =>\n functionCallLikeRE(moduleName, \"importAsset\");\nconst newImportWasmRE = (moduleName: string) => functionCallRE(moduleName, \"importWasm\");\nconst newImportWasmDetector = (moduleName: string) => functionCallLikeRE(moduleName, \"importWasm\");\n\nconst emptyLineRE = /^\\s*$/;\nconst compilerOptionRE = /^\\/\\/tengo:[\\w]/;\nconst wrongCompilerOptionRE = /^\\s*\\/\\/\\s*tengo:\\s*./;\nconst singlelineCommentRE = /^\\s*(\\/\\/)/;\nconst singlelineTerminatedCommentRE = /^\\s*\\/\\*.*\\*\\/\\s*$/; // matches '^/* ... */$' comment lines as a special case of singleline comments.\nconst multilineCommentStartRE = /^\\s*\\/\\*/;\nconst multilineCommentEndRE = /\\*\\//;\nconst multilineStatementRE = /[.,]\\s*$/; // it is hard to consistently treat (\\n\"a\"\\n) multiline statements, we forbid them for now.\n\n// import could only be an assignment in a statement,\n// other ways could break a compilation.\nconst importRE = /\\s*:=\\s*import\\s*\\(\\s*\"(?<moduleName>[^\"]+)\"\\s*\\)/;\nconst importNameRE = new RegExp(\n `\\\\b(?<importName>${namePattern}(\\\\.${namePattern})*)${importRE.source}`,\n);\nconst dependencyRE = /(?<pkgName>[^\"]+)?:(?<depID>[^\"]+)/; // use it to parse <moduleName> from importPattern or <templateName> from getTemplateID\n\n/**\n * Parse compiler option string representation\n * Compiler option line is a comment starting with '//tengo:', say\n * //tengo:hash_override tralala\n *\n * The common compiler option syntax is:\n * //tengo:<option name> [<option arg1> [<option arg 2> [...]]]\n */\nconst parseComplierOption = (opt: string): CompilerOption => {\n const parts = opt.split(\" \");\n const namePart = parts[0].split(\":\");\n if (namePart.length != 2) {\n throw new Error(\n \"compiler option format is wrong: expect to have option name after 'tengo:' prefix, like 'tengo:MyOption'\",\n );\n }\n const optName = namePart[1];\n\n return {\n name: optName,\n args: parts.slice(1),\n };\n};\n\nexport class ArtifactSource {\n constructor(\n /** The mode this artifact was built (dev or dist) */\n public readonly compileMode: CompileMode,\n /** Full artifact id, including package version */\n public readonly fullName: FullArtifactName,\n /** Hash of the source code */\n public readonly sourceHash: string,\n /** Normalized source code */\n public readonly src: string,\n /** Path to source file where artifact came from */\n public readonly srcName: string,\n /** List of dependencies */\n public readonly dependencies: TypedArtifactName[],\n /** Additional compiler options detected in source code */\n public readonly compilerOptions: CompilerOption[],\n ) {}\n}\n\nexport function parseSourceFile(\n logger: MiLogger,\n mode: CompileMode,\n srcFile: string,\n fullSourceName: FullArtifactName,\n normalize: boolean,\n): ArtifactSource {\n const src = readFileSync(srcFile).toString();\n const { deps, normalized, opts } = parseSourceData(logger, src, fullSourceName, normalize);\n\n return new ArtifactSource(\n mode,\n fullSourceName,\n getSha256(normalized),\n normalized,\n srcFile,\n deps.array,\n opts,\n );\n}\n\nexport function parseSource(\n logger: MiLogger,\n mode: CompileMode,\n src: string,\n fullSourceName: FullArtifactName,\n normalize: boolean,\n): ArtifactSource {\n const { deps, normalized, opts } = parseSourceData(logger, src, fullSourceName, normalize);\n\n return new ArtifactSource(\n mode,\n fullSourceName,\n getSha256(normalized),\n normalized,\n \"\",\n deps.array,\n opts,\n );\n}\n\n/**\n * Reads src\n * returns normalized source code,\n * gets dependencies from imports,\n * maps imports to global names if globalizeImports is true,\n * and collects compiler options like hashOverride.\n */\nfunction parseSourceData(\n logger: MiLogger,\n src: string,\n fullSourceName: FullArtifactName,\n globalizeImports: boolean,\n): {\n normalized: string;\n deps: ArtifactMap<TypedArtifactName>;\n opts: CompilerOption[];\n} {\n const dependencySet = createArtifactNameSet();\n const optionList: CompilerOption[] = [];\n\n // iterating over lines\n const lines = src.split(\"\\n\");\n\n // processedLines keep all the original lines from <src>.\n // If <globalizeImport>==true, the parser modifies 'import' and 'getTemplateId' lines\n // with Platforma Tengo lib and template usages, resolving local names (\":<item>\") to\n // global (\"@milaboratory/pkg:<item>\")\n const processedLines: string[] = [];\n let parserContext: sourceParserContext = {\n isInCommentBlock: false,\n canDetectOptions: true,\n artifactImportREs: new Map<string, [ArtifactType, RegExp][]>(),\n importLikeREs: new Map<string, [ArtifactType, RegExp][]>(),\n multilineStatement: \"\",\n lineNo: 0,\n };\n\n for (const line of lines) {\n parserContext.lineNo++;\n\n try {\n const {\n line: processedLine,\n context: newContext,\n artifacts,\n option,\n } = parseSingleSourceLine(logger, line, parserContext, fullSourceName.pkg, globalizeImports);\n processedLines.push(processedLine);\n parserContext = newContext;\n\n for (const artifact of artifacts ?? []) {\n dependencySet.add(artifact);\n }\n if (option) {\n optionList.push(option);\n }\n } catch (error: unknown) {\n const err = error as Error;\n throw new Error(\n `[line ${parserContext.lineNo} in ${fullNameToString(fullSourceName)}]: ${err.message}\\n\\t${line}`,\n { cause: err },\n );\n }\n }\n\n return {\n normalized: processedLines.join(\"\\n\"),\n deps: dependencySet,\n opts: optionList,\n };\n}\n\nexport type sourceParserContext = {\n isInCommentBlock: boolean;\n canDetectOptions: boolean;\n artifactImportREs: Map<string, [ArtifactType, RegExp][]>;\n importLikeREs: Map<string, [ArtifactType, RegExp][]>;\n multilineStatement: string;\n lineNo: number;\n};\n\nexport type lineProcessingResult = {\n line: string;\n context: sourceParserContext;\n artifacts: TypedArtifactName[];\n option: CompilerOption | undefined;\n};\n\nexport function parseSingleSourceLine(\n logger: MiLogger,\n line: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean,\n): lineProcessingResult {\n if (context.isInCommentBlock) {\n if (multilineCommentEndRE.exec(line)) {\n context.isInCommentBlock = false;\n }\n return { line: \"\", context, artifacts: [], option: undefined };\n }\n\n if (compilerOptionRE.exec(line)) {\n if (!context.canDetectOptions) {\n logger.error(\n `[line ${context.lineNo}]: compiler option '//tengo:' was detected, but it cannot be applied as compiler options can be set only at the file header, before any code line'`,\n );\n throw new Error(\n \"tengo compiler options ('//tengo:' comments) can be set only in file header\",\n );\n }\n return { line, context, artifacts: [], option: parseComplierOption(line) };\n }\n\n if (wrongCompilerOptionRE.exec(line) && context.canDetectOptions) {\n logger.warn(\n `[line ${context.lineNo}]: text simillar to compiler option ('//tengo:...') was detected, but it has wrong format. Leave it as is, if you did not mean to use a line as compiler option. Or format it to '//tengo:<option>' otherwise (no spaces between '//' and 'tengo', no spaces between ':' and option name)`,\n );\n return { line, context, artifacts: [], option: undefined };\n }\n\n if (singlelineCommentRE.test(line) || singlelineTerminatedCommentRE.test(line)) {\n return { line: \"\", context, artifacts: [], option: undefined };\n }\n\n const canBeInlinedComment = line.includes(\"*/\");\n if (multilineCommentStartRE.exec(line) && !canBeInlinedComment) {\n context.isInCommentBlock = true;\n return { line: \"\", context, artifacts: [], option: undefined };\n }\n\n const statement = context.multilineStatement + line.trim();\n\n const mayContainAComment = line.includes(\"//\") || line.includes(\"/*\");\n if (multilineStatementRE.test(line) && !mayContainAComment) {\n // We accumulate multiline statements into single line before analyzing them.\n // This dramatically simplifies parsing logic: things like\n //\n // assets.\n // importSoftware(\"a:b\");\n //\n // become simple 'assets.importSoftware(\"a:b\");' for parser checks.\n //\n // For safety reasons, we never consider anything that 'may look like a comment'\n // as a part of multiline statement to prevent joining things like\n //\n // someFnCall() // looks like multiline statement because of dot in the end of a comment.\n //\n // This problem also appears in multiline string literals, but I hope this will not\n // cause problems in real life.\n\n // We still try to process each line to globalize imports in case of complex constructions, when\n // statements are stacked one into another:\n // a.\n // use(assets.importSoftware(\":soft1\")).\n // use(assets.importSoftware(\":soft2\")).\n // run()\n // It is multiline, and it still requires import globalization mid-way, not just for the last line of statement\n const result = processAssetImport(line, statement, context, localPackageName, globalizeImports);\n context.multilineStatement += result.line.trim(); // accumulate the line after imports globalization.\n return result;\n }\n\n context.multilineStatement = \"\"; // reset accumulated multiline statement parts once we reach statement end.\n\n if (emptyLineRE.exec(statement)) {\n return { line, context, artifacts: [], option: undefined };\n }\n\n // options could be only at the top of the file.\n context.canDetectOptions = false;\n\n return processAssetImport(line, statement, context, localPackageName, globalizeImports);\n}\n\nfunction processModuleImport(\n importInstruction: RegExpExecArray,\n originalLine: string,\n statement: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean,\n): lineProcessingResult {\n const iInfo = parseImport(statement);\n\n // If we have plapi, ll or assets, then try to parse\n // getTemplateId, getSoftwareInfo, getSoftware and getAsset calls.\n\n if (iInfo.module === \"plapi\") {\n if (!context.artifactImportREs.has(iInfo.module)) {\n context.artifactImportREs.set(iInfo.module, [\n [\"template\", newGetTemplateIdRE(iInfo.alias)],\n [\"software\", newGetSoftwareInfoRE(iInfo.alias)],\n ]);\n }\n return { line: originalLine, context, artifacts: [], option: undefined };\n }\n\n if (\n iInfo.module === \"@milaboratory/tengo-sdk:ll\" ||\n iInfo.module === \"@platforma-sdk/workflow-tengo:ll\" ||\n ((localPackageName === \"@milaboratory/tengo-sdk\" ||\n localPackageName === \"@platforma-sdk/workflow-tengo\") &&\n iInfo.module === \":ll\")\n ) {\n if (!context.artifactImportREs.has(iInfo.module)) {\n context.artifactImportREs.set(iInfo.module, [\n [\"template\", newImportTemplateRE(iInfo.alias)],\n [\"software\", newImportSoftwareRE(iInfo.alias)],\n ]);\n }\n }\n\n if (\n iInfo.module === \"@milaboratory/tengo-sdk:assets\" ||\n iInfo.module === \"@platforma-sdk/workflow-tengo:assets\" ||\n ((localPackageName === \"@milaboratory/tengo-sdk\" ||\n localPackageName === \"@platforma-sdk/workflow-tengo\") &&\n iInfo.module === \":assets\")\n ) {\n if (!context.artifactImportREs.has(iInfo.module)) {\n context.artifactImportREs.set(iInfo.module, [\n [\"template\", newImportTemplateRE(iInfo.alias)],\n [\"software\", newImportSoftwareRE(iInfo.alias)],\n [\"asset\", newImportAssetRE(iInfo.alias)],\n [\"wasm\", newImportWasmRE(iInfo.alias)],\n ]);\n context.importLikeREs.set(iInfo.module, [\n [\"template\", newImportTemplateDetector(iInfo.alias)],\n [\"software\", newImportSoftwareDetector(iInfo.alias)],\n [\"asset\", newImportAssetDetector(iInfo.alias)],\n [\"wasm\", newImportWasmDetector(iInfo.alias)],\n ]);\n }\n }\n\n const artifact = parseArtifactName(iInfo.module, \"library\", localPackageName);\n if (!artifact) {\n // not a Platforma Tengo library import\n return { line: originalLine, context, artifacts: [], option: undefined };\n }\n\n if (globalizeImports) {\n originalLine = originalLine.replace(\n importInstruction[0],\n ` := import(\"${artifact.pkg}:${artifact.id}\")`,\n );\n }\n\n return { line: originalLine, context, artifacts: [artifact], option: undefined };\n}\n\nfunction processAssetImport(\n originalLine: string,\n statement: string,\n context: sourceParserContext,\n localPackageName: string,\n globalizeImports?: boolean,\n): lineProcessingResult {\n if (emptyLineRE.exec(statement)) {\n return { line: originalLine, context, artifacts: [], option: undefined };\n }\n\n // options could be only at the top of the file.\n context.canDetectOptions = false;\n\n const importInstruction = importRE.exec(statement);\n\n if (importInstruction) {\n return processModuleImport(\n importInstruction,\n originalLine,\n statement,\n context,\n localPackageName,\n globalizeImports,\n );\n }\n\n if (context.artifactImportREs.size > 0) {\n for (const [_, artifactRE] of context.artifactImportREs) {\n for (const [artifactType, re] of artifactRE) {\n // Find all matches in the statement\n const matches = Array.from(statement.matchAll(re));\n if (matches.length === 0) {\n continue;\n }\n\n const artifacts: TypedArtifactName[] = [];\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n if (!match || !match.groups) {\n continue;\n }\n\n const { fnCall, templateName, fnName } = match.groups;\n\n if (!fnCall || !templateName || !fnName) {\n throw Error(`failed to parse template import statement`);\n }\n\n const artifact = parseArtifactName(templateName, artifactType, localPackageName);\n if (!artifact) {\n throw Error(`failed to parse artifact name in ${fnName} import statement`);\n }\n artifacts.push(artifact);\n\n if (globalizeImports) {\n // Replace all occurrences of this fnCall in originalLine.\n // fnCall ends right after the literal's closing quote + ws;\n // the trailing `)` or `,` is preserved from the original\n // line, so multi-arg calls (`fn(\"name\", opts)`) keep their\n // remaining args intact.\n originalLine = originalLine.replaceAll(\n fnCall,\n `${fnName}(\"${artifact.pkg}:${artifact.id}\"`,\n );\n }\n }\n\n return { line: originalLine, context, artifacts, option: undefined };\n }\n }\n }\n\n if (context.importLikeREs.size > 0) {\n for (const [_, artifactRE] of context.importLikeREs) {\n for (const [artifactType, re] of artifactRE) {\n const match = re.exec(statement);\n if (!match || !match.groups) {\n continue;\n }\n\n throw Error(\n `incorrect '${artifactType}' import statement: use string literal as ID (variables are not allowed) in the same line with brackets (i.e. 'importSoftware(\"sw:main\")').`,\n );\n }\n }\n }\n\n return { line: originalLine, context, artifacts: [], option: undefined };\n}\n\ninterface ImportInfo {\n module: string; // the module name without wrapping quotes: import(\"<module>\")\n alias: string; // the name of variable that keeps imported module: <alias> := import(\"<module>\")\n}\n\nfunction parseImport(line: string): ImportInfo {\n const match = importNameRE.exec(line);\n\n if (!match || !match.groups) {\n throw Error(`failed to parse 'import' statement`);\n }\n\n const { importName, moduleName } = match.groups;\n if (!importName || !moduleName) {\n throw Error(`failed to parse 'import' statement`);\n }\n\n return {\n module: moduleName, // the module name without wrapping quotes: import(\"<module>\")\n alias: importName, // the name of variable that keeps imported module: <alias> := import(\"<module>\")\n };\n}\n\nfunction parseArtifactName(\n moduleName: string,\n aType: ArtifactType,\n localPackageName: string,\n): TypedArtifactName | undefined {\n const depInfo = dependencyRE.exec(moduleName);\n if (!depInfo) {\n return;\n }\n\n if (!depInfo.groups) {\n throw Error(\n `failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'`,\n );\n }\n\n const { pkgName, depID } = depInfo.groups;\n if (!depID) {\n throw Error(\n `failed to parse dependency name inside 'import' statement. The dependency name should have format '<package>:<templateName>'`,\n );\n }\n\n return { type: aType, pkg: pkgName ?? localPackageName, id: depID };\n}\n\nexport function getSha256(source: string): string {\n return createHash(\"sha256\").update(source).digest(\"hex\");\n}\n"],"mappings":";;;;;AAeA,MAAM,cAAc;AAEpB,MAAM,kBAAkB,YAAoB,WAAmB;CAO7D,OAAO,IAAI,OACT,MAAM,WAAW,2BACf,SACA,qDACF,GACF;AACF;AAEA,MAAM,sBAAsB,YAAoB,WAAmB;CACjE,OAAO,IAAI,OAAO,MAAM,WAAW,iBAAiB,SAAS,YAAY,GAAG;AAC9E;AAEA,MAAa,sBAAsB,eACjC,eAAe,YAAY,eAAe;AAC5C,MAAa,wBAAwB,eACnC,eAAe,YAAY,iBAAiB;AAE9C,MAAM,uBAAuB,eAAuB,eAAe,YAAY,gBAAgB;AAC/F,MAAM,6BAA6B,eACjC,mBAAmB,YAAY,gBAAgB;AACjD,MAAM,uBAAuB,eAAuB,eAAe,YAAY,gBAAgB;AAC/F,MAAM,6BAA6B,eACjC,mBAAmB,YAAY,gBAAgB;AACjD,MAAM,oBAAoB,eAAuB,eAAe,YAAY,aAAa;AACzF,MAAM,0BAA0B,eAC9B,mBAAmB,YAAY,aAAa;AAC9C,MAAM,mBAAmB,eAAuB,eAAe,YAAY,YAAY;AACvF,MAAM,yBAAyB,eAAuB,mBAAmB,YAAY,YAAY;AAEjG,MAAM,cAAc;AACpB,MAAM,mBAAmB;AACzB,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AAC5B,MAAM,gCAAgC;AACtC,MAAM,0BAA0B;AAChC,MAAM,wBAAwB;AAC9B,MAAM,uBAAuB;AAI7B,MAAM,WAAW;AACjB,MAAM,eAAe,IAAI,OACvB,oBAAoB,YAAY,MAAM,YAAY,KAAK,SAAS,QAClE;AACA,MAAM,eAAe;;;;;;;;;AAUrB,MAAM,uBAAuB,QAAgC;CAC3D,MAAM,QAAQ,IAAI,MAAM,GAAG;CAC3B,MAAM,WAAW,MAAM,EAAE,CA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GlD,OAAO;EACL,QAAQ;EACR,OAAO;CACT;AACF;AAEA,SAAS,kBACP,YACA,OACA,kBAC+B;CAC/B,MAAM,UAAU,aAAa,KAAK,UAAU;CAC5C,IAAI,CAAC,SACH;CAGF,IAAI,CAAC,QAAQ,QACX,MAAM,MACJ,8HACF;CAGF,MAAM,EAAE,SAAS,UAAU,QAAQ;CACnC,IAAI,CAAC,OACH,MAAM,MACJ,8HACF;CAGF,OAAO;EAAE,MAAM;EAAO,KAAK,WAAW;EAAkB,IAAI;CAAM;AACpE;AAEA,SAAgB,UAAU,QAAwB;CAChD,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC,OAAO,KAAK;AACzD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"template.cjs","names":["parseArtefactNameAndVersion","fullNameWithoutTypeToString"],"sources":["../../src/compiler/template.ts"],"sourcesContent":["import type { CompileMode, FullArtifactName, FullArtifactNameWithoutType } from \"./package\";\nimport { fullNameWithoutTypeToString, parseArtefactNameAndVersion } from \"./package\";\nimport type { CompiledTemplateV3 } from \"@milaboratories/pl-model-backend\";\nimport { parseTemplate, serializeTemplate } from \"@milaboratories/pl-model-backend\";\n\n/** Just a holder for template data, compilation options, full name and source code.\n * It mimics ArtifactSource interface.\n */\nexport type TemplateWithSource = {\n readonly compileMode: CompileMode;\n readonly fullName: FullArtifactName;\n readonly source: string;\n readonly data: CompiledTemplateV3;\n};\n\nexport function newTemplateWithSource(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n data: CompiledTemplateV3,\n source: string,\n): TemplateWithSource {\n validateTemplateName(fullName, data);\n\n return {\n compileMode,\n fullName,\n data,\n source,\n };\n}\n\nexport type Template = {\n readonly compileMode: CompileMode;\n readonly fullName: FullArtifactName;\n readonly data: CompiledTemplateV3;\n readonly content: Uint8Array;\n};\n\nexport function newTemplateFromData(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n data: CompiledTemplateV3,\n): Template {\n validateTemplateName(fullName, data);\n return {\n compileMode,\n fullName,\n data,\n content: serializeTemplate(data),\n };\n}\n\nexport function newTemplateFromContent(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n content: Uint8Array,\n): Template {\n const data = parseTemplate(content);\n if (data.type !== \"pl.tengo-template.v3\") {\n throw new Error(\"malformed v3 template\");\n }\n\n validateTemplateName(fullName, data);\n return {\n compileMode,\n fullName,\n data,\n content,\n };\n}\n\nexport function templateToSource(tpl: Template): TemplateWithSource {\n return {\n compileMode: tpl.compileMode,\n fullName: tpl.fullName,\n data: tpl.data,\n source: tpl.data.hashToSource[tpl.data.template.sourceHash],\n };\n}\nfunction validateTemplateName(fullName: FullArtifactName, data: CompiledTemplateV3) {\n const nameFromData: FullArtifactNameWithoutType = parseArtefactNameAndVersion(data.template);\n\n if (\n nameFromData.pkg !== fullName.pkg ||\n nameFromData.id !== fullName.id ||\n nameFromData.version !== fullName.version\n )\n throw new Error(\n `Compiled template name don't match it's package and file names: ` +\n `${fullNameWithoutTypeToString(nameFromData)} != ${fullNameWithoutTypeToString(fullName)}`,\n );\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"template.cjs","names":["parseArtefactNameAndVersion","fullNameWithoutTypeToString"],"sources":["../../src/compiler/template.ts"],"sourcesContent":["import type { CompileMode, FullArtifactName, FullArtifactNameWithoutType } from \"./package\";\nimport { fullNameWithoutTypeToString, parseArtefactNameAndVersion } from \"./package\";\nimport type { CompiledTemplateV3 } from \"@milaboratories/pl-model-backend\";\nimport { parseTemplate, serializeTemplate } from \"@milaboratories/pl-model-backend\";\n\n/** Just a holder for template data, compilation options, full name and source code.\n * It mimics ArtifactSource interface.\n */\nexport type TemplateWithSource = {\n readonly compileMode: CompileMode;\n readonly fullName: FullArtifactName;\n readonly source: string;\n readonly data: CompiledTemplateV3;\n};\n\nexport function newTemplateWithSource(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n data: CompiledTemplateV3,\n source: string,\n): TemplateWithSource {\n validateTemplateName(fullName, data);\n\n return {\n compileMode,\n fullName,\n data,\n source,\n };\n}\n\nexport type Template = {\n readonly compileMode: CompileMode;\n readonly fullName: FullArtifactName;\n readonly data: CompiledTemplateV3;\n readonly content: Uint8Array;\n};\n\nexport function newTemplateFromData(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n data: CompiledTemplateV3,\n): Template {\n validateTemplateName(fullName, data);\n return {\n compileMode,\n fullName,\n data,\n content: serializeTemplate(data),\n };\n}\n\nexport function newTemplateFromContent(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n content: Uint8Array,\n): Template {\n const data = parseTemplate(content);\n if (data.type !== \"pl.tengo-template.v3\") {\n throw new Error(\"malformed v3 template\");\n }\n\n validateTemplateName(fullName, data);\n return {\n compileMode,\n fullName,\n data,\n content,\n };\n}\n\nexport function templateToSource(tpl: Template): TemplateWithSource {\n return {\n compileMode: tpl.compileMode,\n fullName: tpl.fullName,\n data: tpl.data,\n source: tpl.data.hashToSource[tpl.data.template.sourceHash],\n };\n}\nfunction validateTemplateName(fullName: FullArtifactName, data: CompiledTemplateV3) {\n const nameFromData: FullArtifactNameWithoutType = parseArtefactNameAndVersion(data.template);\n\n if (\n nameFromData.pkg !== fullName.pkg ||\n nameFromData.id !== fullName.id ||\n nameFromData.version !== fullName.version\n )\n throw new Error(\n `Compiled template name don't match it's package and file names: ` +\n `${fullNameWithoutTypeToString(nameFromData)} != ${fullNameWithoutTypeToString(fullName)}`,\n );\n}\n"],"mappings":";;;AAeA,SAAgB,sBACd,aACA,UACA,MACA,QACoB;CACpB,qBAAqB,UAAU,IAAI;CAEnC,OAAO;EACL;EACA;EACA;EACA;CACF;AACF;AAuBA,SAAgB,uBACd,aACA,UACA,SACU;CACV,MAAM,QAAA,GAAA,iCAAA,cAAA,CAAqB,OAAO;CAClC,IAAI,KAAK,SAAS,wBAChB,MAAM,IAAI,MAAM,uBAAuB;CAGzC,qBAAqB,UAAU,IAAI;CACnC,OAAO;EACL;EACA;EACA;EACA;CACF;AACF;AAEA,SAAgB,iBAAiB,KAAmC;CAClE,OAAO;EACL,aAAa,IAAI;EACjB,UAAU,IAAI;EACd,MAAM,IAAI;EACV,QAAQ,IAAI,KAAK,aAAa,IAAI,KAAK,SAAS;CAClD;AACF;AACA,SAAS,qBAAqB,UAA4B,MAA0B;CAClF,MAAM,eAA4CA,gBAAAA,4BAA4B,KAAK,QAAQ;CAE3F,IACE,aAAa,QAAQ,SAAS,OAC9B,aAAa,OAAO,SAAS,MAC7B,aAAa,YAAY,SAAS,SAElC,MAAM,IAAI,MACR,mEACKC,gBAAAA,4BAA4B,YAAY,EAAE,MAAMA,gBAAAA,4BAA4B,QAAQ,GAC3F;AACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"template.js","names":[],"sources":["../../src/compiler/template.ts"],"sourcesContent":["import type { CompileMode, FullArtifactName, FullArtifactNameWithoutType } from \"./package\";\nimport { fullNameWithoutTypeToString, parseArtefactNameAndVersion } from \"./package\";\nimport type { CompiledTemplateV3 } from \"@milaboratories/pl-model-backend\";\nimport { parseTemplate, serializeTemplate } from \"@milaboratories/pl-model-backend\";\n\n/** Just a holder for template data, compilation options, full name and source code.\n * It mimics ArtifactSource interface.\n */\nexport type TemplateWithSource = {\n readonly compileMode: CompileMode;\n readonly fullName: FullArtifactName;\n readonly source: string;\n readonly data: CompiledTemplateV3;\n};\n\nexport function newTemplateWithSource(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n data: CompiledTemplateV3,\n source: string,\n): TemplateWithSource {\n validateTemplateName(fullName, data);\n\n return {\n compileMode,\n fullName,\n data,\n source,\n };\n}\n\nexport type Template = {\n readonly compileMode: CompileMode;\n readonly fullName: FullArtifactName;\n readonly data: CompiledTemplateV3;\n readonly content: Uint8Array;\n};\n\nexport function newTemplateFromData(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n data: CompiledTemplateV3,\n): Template {\n validateTemplateName(fullName, data);\n return {\n compileMode,\n fullName,\n data,\n content: serializeTemplate(data),\n };\n}\n\nexport function newTemplateFromContent(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n content: Uint8Array,\n): Template {\n const data = parseTemplate(content);\n if (data.type !== \"pl.tengo-template.v3\") {\n throw new Error(\"malformed v3 template\");\n }\n\n validateTemplateName(fullName, data);\n return {\n compileMode,\n fullName,\n data,\n content,\n };\n}\n\nexport function templateToSource(tpl: Template): TemplateWithSource {\n return {\n compileMode: tpl.compileMode,\n fullName: tpl.fullName,\n data: tpl.data,\n source: tpl.data.hashToSource[tpl.data.template.sourceHash],\n };\n}\nfunction validateTemplateName(fullName: FullArtifactName, data: CompiledTemplateV3) {\n const nameFromData: FullArtifactNameWithoutType = parseArtefactNameAndVersion(data.template);\n\n if (\n nameFromData.pkg !== fullName.pkg ||\n nameFromData.id !== fullName.id ||\n nameFromData.version !== fullName.version\n )\n throw new Error(\n `Compiled template name don't match it's package and file names: ` +\n `${fullNameWithoutTypeToString(nameFromData)} != ${fullNameWithoutTypeToString(fullName)}`,\n );\n}\n"],"mappings":";;;AAeA,SAAgB,sBACd,aACA,UACA,MACA,QACoB;
|
|
1
|
+
{"version":3,"file":"template.js","names":[],"sources":["../../src/compiler/template.ts"],"sourcesContent":["import type { CompileMode, FullArtifactName, FullArtifactNameWithoutType } from \"./package\";\nimport { fullNameWithoutTypeToString, parseArtefactNameAndVersion } from \"./package\";\nimport type { CompiledTemplateV3 } from \"@milaboratories/pl-model-backend\";\nimport { parseTemplate, serializeTemplate } from \"@milaboratories/pl-model-backend\";\n\n/** Just a holder for template data, compilation options, full name and source code.\n * It mimics ArtifactSource interface.\n */\nexport type TemplateWithSource = {\n readonly compileMode: CompileMode;\n readonly fullName: FullArtifactName;\n readonly source: string;\n readonly data: CompiledTemplateV3;\n};\n\nexport function newTemplateWithSource(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n data: CompiledTemplateV3,\n source: string,\n): TemplateWithSource {\n validateTemplateName(fullName, data);\n\n return {\n compileMode,\n fullName,\n data,\n source,\n };\n}\n\nexport type Template = {\n readonly compileMode: CompileMode;\n readonly fullName: FullArtifactName;\n readonly data: CompiledTemplateV3;\n readonly content: Uint8Array;\n};\n\nexport function newTemplateFromData(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n data: CompiledTemplateV3,\n): Template {\n validateTemplateName(fullName, data);\n return {\n compileMode,\n fullName,\n data,\n content: serializeTemplate(data),\n };\n}\n\nexport function newTemplateFromContent(\n compileMode: CompileMode,\n fullName: FullArtifactName,\n content: Uint8Array,\n): Template {\n const data = parseTemplate(content);\n if (data.type !== \"pl.tengo-template.v3\") {\n throw new Error(\"malformed v3 template\");\n }\n\n validateTemplateName(fullName, data);\n return {\n compileMode,\n fullName,\n data,\n content,\n };\n}\n\nexport function templateToSource(tpl: Template): TemplateWithSource {\n return {\n compileMode: tpl.compileMode,\n fullName: tpl.fullName,\n data: tpl.data,\n source: tpl.data.hashToSource[tpl.data.template.sourceHash],\n };\n}\nfunction validateTemplateName(fullName: FullArtifactName, data: CompiledTemplateV3) {\n const nameFromData: FullArtifactNameWithoutType = parseArtefactNameAndVersion(data.template);\n\n if (\n nameFromData.pkg !== fullName.pkg ||\n nameFromData.id !== fullName.id ||\n nameFromData.version !== fullName.version\n )\n throw new Error(\n `Compiled template name don't match it's package and file names: ` +\n `${fullNameWithoutTypeToString(nameFromData)} != ${fullNameWithoutTypeToString(fullName)}`,\n );\n}\n"],"mappings":";;;AAeA,SAAgB,sBACd,aACA,UACA,MACA,QACoB;CACpB,qBAAqB,UAAU,IAAI;CAEnC,OAAO;EACL;EACA;EACA;EACA;CACF;AACF;AAuBA,SAAgB,uBACd,aACA,UACA,SACU;CACV,MAAM,OAAO,cAAc,OAAO;CAClC,IAAI,KAAK,SAAS,wBAChB,MAAM,IAAI,MAAM,uBAAuB;CAGzC,qBAAqB,UAAU,IAAI;CACnC,OAAO;EACL;EACA;EACA;EACA;CACF;AACF;AAEA,SAAgB,iBAAiB,KAAmC;CAClE,OAAO;EACL,aAAa,IAAI;EACjB,UAAU,IAAI;EACd,MAAM,IAAI;EACV,QAAQ,IAAI,KAAK,aAAa,IAAI,KAAK,SAAS;CAClD;AACF;AACA,SAAS,qBAAqB,UAA4B,MAA0B;CAClF,MAAM,eAA4C,4BAA4B,KAAK,QAAQ;CAE3F,IACE,aAAa,QAAQ,SAAS,OAC9B,aAAa,OAAO,SAAS,MAC7B,aAAa,YAAY,SAAS,SAElC,MAAM,IAAI,MACR,mEACK,4BAA4B,YAAY,EAAE,MAAM,4BAA4B,QAAQ,GAC3F;AACJ"}
|
package/dist/compiler/util.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
2
2
|
let node_path = require("node:path");
|
|
3
|
-
node_path = require_runtime.__toESM(node_path);
|
|
3
|
+
node_path = require_runtime.__toESM(node_path, 1);
|
|
4
4
|
let node_fs = require("node:fs");
|
|
5
|
-
node_fs = require_runtime.__toESM(node_fs);
|
|
5
|
+
node_fs = require_runtime.__toESM(node_fs, 1);
|
|
6
6
|
let winston = require("winston");
|
|
7
|
-
winston = require_runtime.__toESM(winston);
|
|
7
|
+
winston = require_runtime.__toESM(winston, 1);
|
|
8
8
|
//#region src/compiler/util.ts
|
|
9
9
|
function assertNever(x) {
|
|
10
10
|
throw new Error("Unexpected object: " + x);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"util.cjs","names":["fs"],"sources":["../../src/compiler/util.ts"],"sourcesContent":["import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport * as winston from \"winston\";\n\nexport function assertNever(x: never): never {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n throw new Error(\"Unexpected object: \" + x);\n}\n\nexport function createLogger(level: string = \"debug\"): winston.Logger {\n return winston.createLogger({\n level: level,\n format: winston.format.combine(\n winston.format.errors({ stack: true }),\n winston.format.printf(({ level, message, stack }) => {\n const baseMessage = `${level.padStart(6, \" \")}: ${message as string}`;\n return stack ? `${baseMessage}\\n${stack as string}` : baseMessage;\n }),\n ),\n transports: [\n new winston.transports.Console({\n stderrLevels: [\"error\", \"warn\", \"info\", \"debug\"],\n handleExceptions: true,\n }),\n ],\n });\n}\n\nexport function findNodeModules(): string {\n let currentDir = process.cwd();\n\n while (currentDir) {\n const possibleNodeModulesPath = path.join(currentDir, \"node_modules\");\n\n if (fs.existsSync(possibleNodeModulesPath)) return possibleNodeModulesPath;\n\n const parentDir = path.resolve(currentDir, \"..\");\n if (parentDir === currentDir) break; // reached the root directory\n\n currentDir = parentDir;\n }\n\n throw new Error(\"Unable to find node_modules directory.\");\n}\n\nexport type PathType = \"absent\" | \"file\" | \"dir\" | \"link\" | \"unknown\";\n\nexport function pathType(path: string): PathType {\n try {\n const s = fs.statSync(path);\n if (s.isDirectory()) return \"dir\";\n if (s.isFile()) return \"file\";\n if (s.isSymbolicLink()) return \"link\";\n return \"unknown\";\n } catch (error: unknown) {\n const err = error as NodeJS.ErrnoException;\n if (err.code == \"ENOENT\") return \"absent\";\n if (err.code == \"ENOTDIR\") return \"absent\";\n else throw err;\n }\n}\n\nexport function isUUID(uuid: string): boolean {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return uuidRegex.test(uuid.toLowerCase());\n}\n"],"mappings":";;;;;;;;AAIA,SAAgB,YAAY,GAAiB;
|
|
1
|
+
{"version":3,"file":"util.cjs","names":["fs"],"sources":["../../src/compiler/util.ts"],"sourcesContent":["import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport * as winston from \"winston\";\n\nexport function assertNever(x: never): never {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n throw new Error(\"Unexpected object: \" + x);\n}\n\nexport function createLogger(level: string = \"debug\"): winston.Logger {\n return winston.createLogger({\n level: level,\n format: winston.format.combine(\n winston.format.errors({ stack: true }),\n winston.format.printf(({ level, message, stack }) => {\n const baseMessage = `${level.padStart(6, \" \")}: ${message as string}`;\n return stack ? `${baseMessage}\\n${stack as string}` : baseMessage;\n }),\n ),\n transports: [\n new winston.transports.Console({\n stderrLevels: [\"error\", \"warn\", \"info\", \"debug\"],\n handleExceptions: true,\n }),\n ],\n });\n}\n\nexport function findNodeModules(): string {\n let currentDir = process.cwd();\n\n while (currentDir) {\n const possibleNodeModulesPath = path.join(currentDir, \"node_modules\");\n\n if (fs.existsSync(possibleNodeModulesPath)) return possibleNodeModulesPath;\n\n const parentDir = path.resolve(currentDir, \"..\");\n if (parentDir === currentDir) break; // reached the root directory\n\n currentDir = parentDir;\n }\n\n throw new Error(\"Unable to find node_modules directory.\");\n}\n\nexport type PathType = \"absent\" | \"file\" | \"dir\" | \"link\" | \"unknown\";\n\nexport function pathType(path: string): PathType {\n try {\n const s = fs.statSync(path);\n if (s.isDirectory()) return \"dir\";\n if (s.isFile()) return \"file\";\n if (s.isSymbolicLink()) return \"link\";\n return \"unknown\";\n } catch (error: unknown) {\n const err = error as NodeJS.ErrnoException;\n if (err.code == \"ENOENT\") return \"absent\";\n if (err.code == \"ENOTDIR\") return \"absent\";\n else throw err;\n }\n}\n\nexport function isUUID(uuid: string): boolean {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return uuidRegex.test(uuid.toLowerCase());\n}\n"],"mappings":";;;;;;;;AAIA,SAAgB,YAAY,GAAiB;CAE3C,MAAM,IAAI,MAAM,wBAAwB,CAAC;AAC3C;AAEA,SAAgB,aAAa,QAAgB,SAAyB;CACpE,OAAO,QAAQ,aAAa;EACnB;EACP,QAAQ,QAAQ,OAAO,QACrB,QAAQ,OAAO,OAAO,EAAE,OAAO,KAAK,CAAC,GACrC,QAAQ,OAAO,QAAQ,EAAE,OAAO,SAAS,YAAY;GACnD,MAAM,cAAc,GAAG,MAAM,SAAS,GAAG,GAAG,EAAE,IAAI;GAClD,OAAO,QAAQ,GAAG,YAAY,IAAI,UAAoB;EACxD,CAAC,CACH;EACA,YAAY,CACV,IAAI,QAAQ,WAAW,QAAQ;GAC7B,cAAc;IAAC;IAAS;IAAQ;IAAQ;GAAO;GAC/C,kBAAkB;EACpB,CAAC,CACH;CACF,CAAC;AACH;AAqBA,SAAgB,SAAS,MAAwB;CAC/C,IAAI;EACF,MAAM,IAAIA,QAAG,SAAS,IAAI;EAC1B,IAAI,EAAE,YAAY,GAAG,OAAO;EAC5B,IAAI,EAAE,OAAO,GAAG,OAAO;EACvB,IAAI,EAAE,eAAe,GAAG,OAAO;EAC/B,OAAO;CACT,SAAS,OAAgB;EACvB,MAAM,MAAM;EACZ,IAAI,IAAI,QAAQ,UAAU,OAAO;EACjC,IAAI,IAAI,QAAQ,WAAW,OAAO;OAC7B,MAAM;CACb;AACF;AAEA,SAAgB,OAAO,MAAuB;CAE5C,OAAO,6EAAU,KAAK,KAAK,YAAY,CAAC;AAC1C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"util.js","names":[],"sources":["../../src/compiler/util.ts"],"sourcesContent":["import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport * as winston from \"winston\";\n\nexport function assertNever(x: never): never {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n throw new Error(\"Unexpected object: \" + x);\n}\n\nexport function createLogger(level: string = \"debug\"): winston.Logger {\n return winston.createLogger({\n level: level,\n format: winston.format.combine(\n winston.format.errors({ stack: true }),\n winston.format.printf(({ level, message, stack }) => {\n const baseMessage = `${level.padStart(6, \" \")}: ${message as string}`;\n return stack ? `${baseMessage}\\n${stack as string}` : baseMessage;\n }),\n ),\n transports: [\n new winston.transports.Console({\n stderrLevels: [\"error\", \"warn\", \"info\", \"debug\"],\n handleExceptions: true,\n }),\n ],\n });\n}\n\nexport function findNodeModules(): string {\n let currentDir = process.cwd();\n\n while (currentDir) {\n const possibleNodeModulesPath = path.join(currentDir, \"node_modules\");\n\n if (fs.existsSync(possibleNodeModulesPath)) return possibleNodeModulesPath;\n\n const parentDir = path.resolve(currentDir, \"..\");\n if (parentDir === currentDir) break; // reached the root directory\n\n currentDir = parentDir;\n }\n\n throw new Error(\"Unable to find node_modules directory.\");\n}\n\nexport type PathType = \"absent\" | \"file\" | \"dir\" | \"link\" | \"unknown\";\n\nexport function pathType(path: string): PathType {\n try {\n const s = fs.statSync(path);\n if (s.isDirectory()) return \"dir\";\n if (s.isFile()) return \"file\";\n if (s.isSymbolicLink()) return \"link\";\n return \"unknown\";\n } catch (error: unknown) {\n const err = error as NodeJS.ErrnoException;\n if (err.code == \"ENOENT\") return \"absent\";\n if (err.code == \"ENOTDIR\") return \"absent\";\n else throw err;\n }\n}\n\nexport function isUUID(uuid: string): boolean {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return uuidRegex.test(uuid.toLowerCase());\n}\n"],"mappings":";;;;AAIA,SAAgB,YAAY,GAAiB;
|
|
1
|
+
{"version":3,"file":"util.js","names":[],"sources":["../../src/compiler/util.ts"],"sourcesContent":["import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport * as winston from \"winston\";\n\nexport function assertNever(x: never): never {\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n throw new Error(\"Unexpected object: \" + x);\n}\n\nexport function createLogger(level: string = \"debug\"): winston.Logger {\n return winston.createLogger({\n level: level,\n format: winston.format.combine(\n winston.format.errors({ stack: true }),\n winston.format.printf(({ level, message, stack }) => {\n const baseMessage = `${level.padStart(6, \" \")}: ${message as string}`;\n return stack ? `${baseMessage}\\n${stack as string}` : baseMessage;\n }),\n ),\n transports: [\n new winston.transports.Console({\n stderrLevels: [\"error\", \"warn\", \"info\", \"debug\"],\n handleExceptions: true,\n }),\n ],\n });\n}\n\nexport function findNodeModules(): string {\n let currentDir = process.cwd();\n\n while (currentDir) {\n const possibleNodeModulesPath = path.join(currentDir, \"node_modules\");\n\n if (fs.existsSync(possibleNodeModulesPath)) return possibleNodeModulesPath;\n\n const parentDir = path.resolve(currentDir, \"..\");\n if (parentDir === currentDir) break; // reached the root directory\n\n currentDir = parentDir;\n }\n\n throw new Error(\"Unable to find node_modules directory.\");\n}\n\nexport type PathType = \"absent\" | \"file\" | \"dir\" | \"link\" | \"unknown\";\n\nexport function pathType(path: string): PathType {\n try {\n const s = fs.statSync(path);\n if (s.isDirectory()) return \"dir\";\n if (s.isFile()) return \"file\";\n if (s.isSymbolicLink()) return \"link\";\n return \"unknown\";\n } catch (error: unknown) {\n const err = error as NodeJS.ErrnoException;\n if (err.code == \"ENOENT\") return \"absent\";\n if (err.code == \"ENOTDIR\") return \"absent\";\n else throw err;\n }\n}\n\nexport function isUUID(uuid: string): boolean {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return uuidRegex.test(uuid.toLowerCase());\n}\n"],"mappings":";;;;AAIA,SAAgB,YAAY,GAAiB;CAE3C,MAAM,IAAI,MAAM,wBAAwB,CAAC;AAC3C;AAEA,SAAgB,aAAa,QAAgB,SAAyB;CACpE,OAAO,QAAQ,aAAa;EACnB;EACP,QAAQ,QAAQ,OAAO,QACrB,QAAQ,OAAO,OAAO,EAAE,OAAO,KAAK,CAAC,GACrC,QAAQ,OAAO,QAAQ,EAAE,OAAO,SAAS,YAAY;GACnD,MAAM,cAAc,GAAG,MAAM,SAAS,GAAG,GAAG,EAAE,IAAI;GAClD,OAAO,QAAQ,GAAG,YAAY,IAAI,UAAoB;EACxD,CAAC,CACH;EACA,YAAY,CACV,IAAI,QAAQ,WAAW,QAAQ;GAC7B,cAAc;IAAC;IAAS;IAAQ;IAAQ;GAAO;GAC/C,kBAAkB;EACpB,CAAC,CACH;CACF,CAAC;AACH;AAqBA,SAAgB,SAAS,MAAwB;CAC/C,IAAI;EACF,MAAM,IAAI,GAAG,SAAS,IAAI;EAC1B,IAAI,EAAE,YAAY,GAAG,OAAO;EAC5B,IAAI,EAAE,OAAO,GAAG,OAAO;EACvB,IAAI,EAAE,eAAe,GAAG,OAAO;EAC/B,OAAO;CACT,SAAS,OAAgB;EACvB,MAAM,MAAM;EACZ,IAAI,IAAI,QAAQ,UAAU,OAAO;EACjC,IAAI,IAAI,QAAQ,WAAW,OAAO;OAC7B,MAAM;CACb;AACF;AAEA,SAAgB,OAAO,MAAuB;CAE5C,OAAO,6EAAU,KAAK,KAAK,YAAY,CAAC;AAC1C"}
|
package/dist/shared/basecmd.cjs
CHANGED