@akanjs/devkit 3.3.0-rc.8 → 3.3.0-rc.81
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/DEV_RUNTIME_KNOBS.md +1 -1
- package/README.ko.md +7 -1
- package/README.md +7 -1
- package/akanApp/akanApp.host.test.ts +3 -1
- package/akanApp/akanApp.host.ts +26 -2
- package/akanApp/akanApp.host.wiring.test.ts +111 -0
- package/akanApp/devHostPolicy.ts +5 -0
- package/akanApp/devMetadataRestart.ts +93 -0
- package/akanApp/devRecycler.test.ts +2 -0
- package/akanApp/devRecycler.ts +9 -0
- package/akanConfig/akanBin.ts +4 -0
- package/akanConfig/akanConfig.test.ts +307 -18
- package/akanConfig/akanConfig.ts +104 -210
- package/akanConfig/akanPreview.test.ts +28 -0
- package/akanConfig/akanPreview.ts +24 -0
- package/akanConfig/akanWorkers.test.ts +73 -0
- package/akanConfig/akanWorkers.ts +61 -0
- package/akanConfig/desktopServerConfig.ts +96 -0
- package/akanConfig/dockerImage.ts +233 -0
- package/akanConfig/index.ts +3 -0
- package/akanConfig/nativeFileSettings.ts +33 -0
- package/akanConfig/types.ts +4 -0
- package/app/appBin.test.ts +63 -0
- package/app/appBin.ts +50 -0
- package/app/applicationBuildReporter.test.ts +51 -1
- package/app/applicationBuildReporter.ts +6 -1
- package/app/applicationBuildRunner.test.ts +436 -5
- package/app/applicationBuildRunner.ts +237 -37
- package/app/clientServerBoundary.test.ts +115 -0
- package/app/clientServerBoundary.ts +89 -0
- package/app/dictionarySizes.test.ts +40 -0
- package/app/dictionarySizes.ts +95 -0
- package/app/routeFilesReport.test.ts +59 -0
- package/app/routeFilesReport.ts +46 -0
- package/app/routeJsBudget.ts +18 -4
- package/artifact/implicitRootLayout.test.ts +19 -0
- package/artifact/implicitRootLayout.ts +16 -2
- package/artifact/implicitRootLayoutRender.test.tsx +7 -2
- package/artifact/storeBootstrap.test.ts +28 -0
- package/artifact/storeBootstrap.ts +64 -8
- package/biome.base.json +7 -5
- package/codeAgent/index.ts +1 -34
- package/codeAgent/skills/akan-agent/SKILL.md +2 -2
- package/codeAgent/skills/akan-debug/SKILL.md +11 -5
- package/codeAgent/skills/akan-deps/SKILL.md +10 -3
- package/codeAgent/skills/akan-err/SKILL.md +13 -8
- package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
- package/codeAgent/skills/akan-module/SKILL.md +2 -2
- package/codeAgent/skills/akan-page/SKILL.md +65 -30
- package/codeAgent/skills/akan-query/SKILL.md +13 -20
- package/codeAgent/skills/akan-runtime/SKILL.md +21 -1
- package/codeAgent/skills/akan-service/SKILL.md +21 -20
- package/codeAgent/skills/akan-transport/SKILL.md +5 -14
- package/codeAgent/skills/akan-ui/SKILL.md +16 -21
- package/codeAgent/skills/akan-validate/SKILL.md +8 -2
- package/commandDecorators/command.ts +28 -12
- package/commandDecorators/commandBuilder.ts +8 -1
- package/commandDecorators/commandDecorators.test.ts +70 -3
- package/commandDecorators/helpFormatter.ts +14 -12
- package/context/akanContext.ts +2 -0
- package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
- package/csrE2e/ssrRegistry.e2e.test.ts +108 -22
- package/docs/apiReference.test.ts +25 -0
- package/docs/apiReference.ts +38 -5
- package/docs/declarationReader.ts +30 -0
- package/executors/appExecutor.ts +26 -12
- package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
- package/executors/clientRuntimeKeys.fixture.json +393 -0
- package/executors/clientRuntimeKeys.test.ts +1690 -0
- package/executors/executor.ts +14 -6
- package/executors/executors.test.ts +155 -1
- package/executors/pkgExecutor.ts +2 -1
- package/executors/sysExecutor.ts +112 -8
- package/executors/workspaceExecutor.ts +7 -4
- package/frontendBuild/allRoutesBuilder.ts +99 -7
- package/frontendBuild/autoImportSync.ts +3 -2
- package/frontendBuild/buildRouteClient.test.ts +684 -6
- package/frontendBuild/clientBuildTypes.ts +26 -0
- package/frontendBuild/clientEntriesBundler.test.ts +79 -0
- package/frontendBuild/clientEntriesBundler.ts +70 -1
- package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
- package/frontendBuild/clientEntryDiscovery.ts +134 -12
- package/frontendBuild/clientEntryGroups.test.ts +77 -0
- package/frontendBuild/clientEntryGroups.ts +61 -0
- package/frontendBuild/csrDevArtifactWriter.ts +2 -2
- package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
- package/frontendBuild/csrDevModuleCompiler.ts +44 -8
- package/frontendBuild/csrDevPatcher.test.ts +4 -5
- package/frontendBuild/csrDevPatcher.ts +37 -11
- package/frontendBuild/csrDevTypes.ts +9 -0
- package/frontendBuild/cssCandidateCache.test.ts +12 -0
- package/frontendBuild/cssCandidateCache.ts +5 -3
- package/frontendBuild/cssCompiler.test.ts +14 -0
- package/frontendBuild/devBarrelImports.test.ts +124 -0
- package/frontendBuild/devBarrelImports.ts +81 -21
- package/frontendBuild/devChangePlanner.ts +0 -1
- package/frontendBuild/devRegistryBundler.ts +4 -2
- package/frontendBuild/devRouteRuntime.test.ts +492 -0
- package/frontendBuild/devRouteRuntime.ts +167 -0
- package/frontendBuild/dictionaryAssetBuilder.test.ts +408 -0
- package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
- package/frontendBuild/dictionaryConstants.ts +136 -0
- package/frontendBuild/dictionaryOwnParts.ts +88 -0
- package/frontendBuild/dictionaryPackState.ts +131 -0
- package/frontendBuild/dictionaryPacking.test.ts +207 -0
- package/frontendBuild/dictionaryPacking.ts +160 -0
- package/frontendBuild/dictionaryRoutes.test.ts +251 -0
- package/frontendBuild/dictionaryRoutes.ts +227 -0
- package/frontendBuild/frontendBuild.test.ts +5 -3
- package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
- package/frontendBuild/pagesBundleBuilder.ts +78 -2
- package/frontendBuild/precompressArtifacts.test.ts +22 -0
- package/frontendBuild/precompressArtifacts.ts +34 -8
- package/frontendBuild/registryMetadataFingerprint.ts +3 -3
- package/frontendBuild/renderedEntries.ts +144 -0
- package/frontendBuild/routeClientBuilder.ts +407 -43
- package/frontendBuild/routeHandoffs.test.ts +155 -0
- package/frontendBuild/routeHandoffs.ts +117 -0
- package/frontendBuild/routeModulePreloads.test.ts +32 -0
- package/frontendBuild/routeModulePreloads.ts +20 -11
- package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
- package/frontendBuild/routeRuntimeCheck.ts +248 -0
- package/frontendBuild/routeRuntimePays.test.ts +143 -0
- package/frontendBuild/routeRuntimePays.ts +117 -0
- package/frontendBuild/ssrBaseArtifactBuilder.ts +30 -35
- package/frontendBuild/ssrDevBundler.test.ts +150 -1
- package/frontendBuild/ssrDevBundler.ts +66 -11
- package/frontendBuild/vendorFileImports.test.ts +254 -0
- package/frontendBuild/vendorFileImports.ts +163 -0
- package/frontendBuild/vendorNarrowing.test.ts +47 -3
- package/frontendBuild/vendorNarrowing.ts +38 -2
- package/frontendBuild/vendorSpecifiers.ts +2 -0
- package/frontendBuild/workerChunks.ts +61 -0
- package/guideline/agentAssets.ts +1 -1
- package/incrementalBuilder/buildBatch.proc.ts +27 -1
- package/incrementalBuilder/buildBatchProtocol.ts +1 -0
- package/incrementalBuilder/builderWatch.ts +11 -1
- package/incrementalBuilder/incrementalBuilder.proc.test.ts +159 -0
- package/incrementalBuilder/incrementalBuilder.proc.ts +31 -3
- package/incrementalBuilder/pendingMetadata.test.ts +27 -0
- package/incrementalBuilder/pendingMetadata.ts +19 -0
- package/integration/devResourceProbe.ts +14 -0
- package/integration/devStability.integration.test.ts +46 -21
- package/integration/renderAdmissionSoak.ts +6 -0
- package/integration/ssrMemoryProbe.ts +5 -0
- package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
- package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
- package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
- package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
- package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
- package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
- package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
- package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
- package/lint/biomeBase.test.ts +50 -3
- package/lint/biomeBase.ts +1 -1
- package/lint/biomeCheck.test.ts +162 -0
- package/lint/biomeCheck.ts +131 -0
- package/lint/linter.test.ts +16 -11
- package/lint/no-arbitrary-color.grit +5 -0
- package/lint/no-conditional-st-hook.grit +5 -1
- package/lint/no-daisyui-legacy-class.grit +8 -0
- package/lint/no-document-cookie.grit +3 -0
- package/lint/no-inline-color.grit +10 -2
- package/lint/no-oversized-list-limit.grit +2 -0
- package/lint/no-raw-palette-class.grit +7 -0
- package/lint/no-unpublished-form-setter.grit +2 -0
- package/lint/no-web-only-api-outside-webkit.grit +5 -0
- package/lint/no-web-storage.grit +3 -0
- package/lint/withheldEnvFile.ts +17 -0
- package/mobile/desktopBin.ts +2 -2
- package/mobile/desktopServerStage.test.ts +18 -3
- package/mobile/desktopServerStage.ts +7 -2
- package/mobile/nativeApp.test.ts +13 -5
- package/mobile/nativeApp.ts +9 -4
- package/mobile/nativeConfig.test.ts +17 -1
- package/mobile/nativeConfig.ts +11 -6
- package/mobile/nativePublicEnv.ts +1 -1
- package/mobile/serverBundleSecrets.ts +43 -0
- package/package.json +11 -12
- package/packageExports.test.ts +3 -2
- package/preview/PreviewView.ts +43 -6
- package/preview/previewView.test.ts +31 -0
- package/quality/dictionaryKeys.test.ts +356 -0
- package/quality/dictionaryKeys.ts +488 -0
- package/quality/objectImportReport.test.ts +36 -0
- package/quality/objectImportReport.ts +105 -0
- package/quality/qualityScanner.ts +1 -1
- package/quality/routeRuntimeReport.test.ts +91 -0
- package/quality/routeRuntimeReport.ts +121 -0
- package/quality/runtimeConstantFacts.ts +71 -0
- package/quality/runtimeConstantGraph.ts +123 -0
- package/quality/runtimeConstantReads.ts +116 -0
- package/quality/runtimeImports.test.ts +190 -0
- package/quality/runtimeImports.ts +233 -0
- package/quality/runtimeKeyNames.ts +46 -0
- package/quality/runtimeLexicalScope.ts +132 -0
- package/quality/runtimeMarkerReach.test.ts +84 -0
- package/quality/runtimeMarkerReach.ts +255 -0
- package/quality/runtimeModuleFacts.ts +290 -0
- package/quality/runtimeNameTable.test.ts +172 -0
- package/quality/runtimeNameTable.ts +477 -0
- package/quality/runtimeScopeReport.test.ts +123 -0
- package/quality/runtimeScopeReport.ts +167 -0
- package/quality/runtimeSliceKey.ts +269 -0
- package/quality/runtimeSyntax.ts +133 -0
- package/quality/runtimeTable.fixture.ts +189 -0
- package/quality/runtimeUse.test.ts +737 -0
- package/quality/runtimeUse.ts +696 -0
- package/quality/runtimeUseReadable.test.ts +393 -0
- package/quality/ssrScanner.test.ts +13 -0
- package/quality/ssrScanner.ts +1 -1
- package/quality/translatorBindings.ts +187 -0
- package/test/fakeTerminal.ts +45 -0
- package/test/secretEnvFixture.ts +134 -0
- package/test/testHelpers.ts +11 -0
- package/transforms/barrelAnalyzer.ts +24 -2
- package/transforms/barrelImportsPlugin.ts +121 -32
- package/transforms/exportReach.test.ts +162 -0
- package/transforms/exportReach.ts +308 -0
- package/transforms/frameworkObjects.fixture.tsx +58 -0
- package/transforms/frameworkObjects.test.ts +54 -0
- package/transforms/modelReference.test.ts +196 -0
- package/transforms/modelReference.ts +39 -0
- package/transforms/moduleParts.test.ts +225 -0
- package/transforms/moduleParts.ts +418 -0
- package/transforms/objectImportEdits.ts +150 -0
- package/transforms/objectMemberImports.test.ts +633 -0
- package/transforms/objectMemberImports.ts +571 -0
- package/transforms/objectMemberLookup.ts +150 -0
- package/transforms/objectModule.test.ts +307 -0
- package/transforms/objectModule.ts +482 -0
- package/transforms/objectModuleAnalyzer.ts +104 -0
- package/transforms/partImports.test.ts +76 -0
- package/transforms/partImports.ts +110 -0
- package/transforms/partModules.test.ts +187 -0
- package/transforms/partModules.ts +90 -0
- package/transforms/partPurity.ts +124 -0
- package/transforms/reactIconImports.test.ts +231 -0
- package/transforms/reactIconImports.ts +325 -0
- package/transforms/routeConstants.ts +122 -0
- package/transforms/routeRuntime.test.ts +835 -0
- package/transforms/routeRuntime.ts +703 -0
- package/transforms/routeRuntimeEdits.ts +92 -0
- package/transforms/routeRuntimeGraph.ts +66 -0
- package/transforms/routeRuntimePlan.ts +244 -0
- package/transforms/secretEnvDeclaration.test.ts +211 -0
- package/transforms/secretEnvDeclaration.ts +219 -0
- package/transforms/secretEnvFile.test.ts +117 -0
- package/transforms/secretEnvFile.ts +113 -0
- package/transforms/secretEnvName.test.ts +54 -0
- package/transforms/secretEnvName.ts +29 -0
- package/transforms/secretEnvSource.test.ts +152 -0
- package/transforms/secretEnvSource.ts +197 -0
- package/transforms/serverEnvEvaluationError.ts +11 -0
- package/transforms/serverEnvPlugin.test.ts +155 -1
- package/transforms/serverEnvPlugin.ts +123 -19
- package/transforms/serverEnvProfile.test.ts +129 -2
- package/transforms/serverEnvProfile.ts +133 -43
- package/transforms/serverEnvSecrets.test.ts +268 -0
- package/transforms/signalDescriptors.test.ts +280 -0
- package/transforms/signalDescriptors.ts +227 -0
- package/transforms/thisFreeExports.ts +87 -0
- package/transforms/transforms.test.ts +177 -0
- package/transforms/tsconfigPackageResolver.test.ts +1 -0
- package/tunnel/createTunnel.ts +5 -1
- package/tunnel/ssh2Module.test.ts +37 -0
- package/tunnel/ssh2Module.ts +28 -0
- package/tunnel/sshTunnel.ts +4 -2
- package/typecheck/projectTypecheck.test.ts +32 -1
- package/typecheck/projectTypecheck.ts +3 -3
- package/typecheck/typeChecker.test.ts +49 -0
- package/typecheck/typeChecker.ts +9 -7
- package/typecheck/withheldDiagnostics.ts +41 -0
- package/util/devInstallCommand.ts +7 -0
- package/util/jsonFormatter.test.ts +13 -9
- package/workflow/executor.ts +6 -2
- package/workflow/index.ts +1 -0
- package/workflow/plan.ts +36 -7
- package/workflow/types.ts +1 -1
- package/workflow/uiTarget.ts +50 -0
- package/workspace/envSeed.test.ts +30 -1
- package/workspace/envSeed.ts +30 -1
- package/workspace/mainCheckout.test.ts +55 -0
- package/workspace/mainCheckout.ts +38 -0
- package/workspace/scanInfo.test.ts +39 -0
- package/workspace/scanInfo.ts +55 -6
- package/workspace/slicePlanner.ts +2 -1
- package/workspace/workspaceLayout.test.ts +22 -1
- package/workspace/workspaceLayout.ts +3 -3
- package/CHANGELOG.md +0 -2903
- package/codeAgent/agent/AkanCodeCompaction.ts +0 -49
- package/codeAgent/agent/AkanCodeServices.ts +0 -122
- package/codeAgent/agent/AkanContextFiles.ts +0 -94
- package/codeAgent/agent/CodeAgent.ts +0 -626
- package/codeAgent/agent/CodeAgentAllowed.ts +0 -35
- package/codeAgent/agent/CodeAgentAsks.ts +0 -66
- package/codeAgent/agent/CodeAgentCommandLine.ts +0 -372
- package/codeAgent/agent/CodeAgentEventMapper.ts +0 -225
- package/codeAgent/agent/CodeAgentGate.ts +0 -258
- package/codeAgent/agent/CodeAgentProxy.ts +0 -83
- package/codeAgent/agent/CodeAgentRpcHost.ts +0 -109
- package/codeAgent/agent/CodeAgentRpcListener.ts +0 -195
- package/codeAgent/agent/CodeAgentStreamPrinter.ts +0 -86
- package/codeAgent/agent/CodeAgentSuspended.ts +0 -85
- package/codeAgent/agent/CodeAgentUi.ts +0 -47
- package/codeAgent/agent/CodeMailbox.ts +0 -148
- package/codeAgent/agent/CodeSessionFork.ts +0 -56
- package/codeAgent/agent/CodeSessionIndex.ts +0 -78
- package/codeAgent/agent/SubagentPool.ts +0 -219
- package/codeAgent/agent/WorkspaceTrust.ts +0 -200
- package/codeAgent/agent/akanCodeCompaction.test.ts +0 -36
- package/codeAgent/agent/akanCodeModel.ts +0 -47
- package/codeAgent/agent/akanCodeServices.test.ts +0 -54
- package/codeAgent/agent/akanContextFiles.test.ts +0 -116
- package/codeAgent/agent/akanSystemPrompt.ts +0 -50
- package/codeAgent/agent/codeAgent.test.ts +0 -337
- package/codeAgent/agent/codeAgentCommandLine.test.ts +0 -212
- package/codeAgent/agent/codeAgentContract.test.ts +0 -755
- package/codeAgent/agent/codeAgentHosts.ts +0 -30
- package/codeAgent/agent/codeAgentProxy.test.ts +0 -126
- package/codeAgent/agent/codeAgentRpcListener.test.ts +0 -215
- package/codeAgent/agent/codeAgentSuspended.test.ts +0 -47
- package/codeAgent/agent/codeMailbox.test.ts +0 -76
- package/codeAgent/agent/codeSessionFork.test.ts +0 -58
- package/codeAgent/agent/codeSessionIndex.test.ts +0 -77
- package/codeAgent/agent/consoleToStderr.ts +0 -8
- package/codeAgent/agent/jsonLines.ts +0 -29
- package/codeAgent/agent/stringArg.ts +0 -5
- package/codeAgent/feedback/DevLogFeedback.ts +0 -82
- package/codeAgent/feedback/PreviewFeedback.ts +0 -46
- package/codeAgent/feedback/TurnFeedback.ts +0 -98
- package/codeAgent/feedback/VerifyFeedback.ts +0 -39
- package/codeAgent/tools/AkanCli.ts +0 -51
- package/codeAgent/tools/AkanCodePlugins.ts +0 -142
- package/codeAgent/tools/AkanEditScope.ts +0 -53
- package/codeAgent/tools/AkanEnvKeys.ts +0 -50
- package/codeAgent/tools/AkanToolPack.ts +0 -86
- package/codeAgent/tools/AkanVerifier.ts +0 -30
- package/codeAgent/tools/AskToolPack.ts +0 -99
- package/codeAgent/tools/DeepSeekWeb.ts +0 -127
- package/codeAgent/tools/MailToolPack.ts +0 -76
- package/codeAgent/tools/McpClient.ts +0 -209
- package/codeAgent/tools/McpOAuth.ts +0 -233
- package/codeAgent/tools/McpOAuthLoopback.ts +0 -64
- package/codeAgent/tools/McpServerConfig.ts +0 -131
- package/codeAgent/tools/McpSignIn.ts +0 -158
- package/codeAgent/tools/McpTokenStore.ts +0 -128
- package/codeAgent/tools/McpToolPack.ts +0 -206
- package/codeAgent/tools/SessionToolPack.ts +0 -91
- package/codeAgent/tools/WebToolPack.ts +0 -315
- package/codeAgent/tools/akanCodePlugins.test.ts +0 -954
- package/codeAgent/tools/askToolPack.test.ts +0 -116
- package/codeAgent/tools/deepSeekWeb.test.ts +0 -113
- package/codeAgent/tools/mcpOAuth.test.ts +0 -648
- package/codeAgent/tools/mcpServerConfig.test.ts +0 -341
- package/piDependencyPins.test.ts +0 -45
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
2
3
|
import { mkdir, readdir, writeFile } from "node:fs/promises";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import type { App } from "../commandDecorators";
|
|
5
6
|
import { tempDirs } from "../test/testHelpers";
|
|
6
7
|
import { DictionaryAssetBuilder } from "./dictionaryAssetBuilder";
|
|
8
|
+
import { dictionaryBrotliBytesOf } from "./precompressArtifacts";
|
|
7
9
|
|
|
8
10
|
const tempRoot = tempDirs("akan-devkit-dict-asset-");
|
|
9
11
|
|
|
@@ -23,6 +25,117 @@ const makeApp = async (dictSource?: string) => {
|
|
|
23
25
|
|
|
24
26
|
const dictSourceOf = (dictionary: object) => `export const getAllDictionary = () => (${JSON.stringify(dictionary)});\n`;
|
|
25
27
|
|
|
28
|
+
const workspaceRoot = path.resolve(import.meta.dir, "../../../..");
|
|
29
|
+
const i18n = { defaultLocale: "en", locales: ["en", "ko"] };
|
|
30
|
+
|
|
31
|
+
interface LocaleBuild {
|
|
32
|
+
whole: Record<string, Record<string, unknown>>;
|
|
33
|
+
page: Record<string, Record<string, unknown>>;
|
|
34
|
+
api: Record<string, Record<string, unknown>>;
|
|
35
|
+
parts: unknown;
|
|
36
|
+
apiUrl: string;
|
|
37
|
+
server: unknown;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
//? In a process of its own: a sample app's `dict.ts` resolves `@libs/*` by the tsconfig its process read first.
|
|
41
|
+
const buildBothWays = async (cwdPath: string, outDir: string): Promise<Record<string, LocaleBuild>> => {
|
|
42
|
+
const script = `
|
|
43
|
+
import path from "node:path";
|
|
44
|
+
import { DictionaryAssetBuilder } from ${JSON.stringify(path.join(import.meta.dir, "dictionaryAssetBuilder.ts"))};
|
|
45
|
+
import { WebArtifact } from ${JSON.stringify(path.join(workspaceRoot, "pkgs/akanjs/server/webArtifact.ts"))};
|
|
46
|
+
import { TranslatorState } from ${JSON.stringify(path.join(workspaceRoot, "pkgs/akanjs/client/translatorState.ts"))};
|
|
47
|
+
const app = { cwdPath: ${JSON.stringify(cwdPath)}, verbose: () => undefined };
|
|
48
|
+
const i18n = ${JSON.stringify(i18n)};
|
|
49
|
+
const wholeDir = ${JSON.stringify(path.join(outDir, "whole"))};
|
|
50
|
+
const splitDir = ${JSON.stringify(path.join(outDir, "split"))};
|
|
51
|
+
const whole = await new DictionaryAssetBuilder(app, wholeDir).build(i18n);
|
|
52
|
+
const split = await new DictionaryAssetBuilder(app, splitDir).build(i18n, { splitApi: true });
|
|
53
|
+
await WebArtifact.seedDictionaries({ dictAssets: split }, splitDir);
|
|
54
|
+
const result = {};
|
|
55
|
+
for (const lang of i18n.locales) {
|
|
56
|
+
const page = await import(path.join(splitDir, split[lang].relPath));
|
|
57
|
+
result[lang] = {
|
|
58
|
+
whole: (await import(path.join(wholeDir, whole[lang].relPath))).default,
|
|
59
|
+
page: page.default,
|
|
60
|
+
parts: page.parts,
|
|
61
|
+
api: (await import(path.join(splitDir, split[lang].parts.api.relPath))).default,
|
|
62
|
+
apiUrl: split[lang].parts.api.url,
|
|
63
|
+
server: TranslatorState.get().langDictionaryMap.get(lang),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
console.log(JSON.stringify(result));
|
|
67
|
+
`;
|
|
68
|
+
const proc = Bun.spawn([process.execPath, "-e", script], {
|
|
69
|
+
cwd: workspaceRoot,
|
|
70
|
+
env: {
|
|
71
|
+
...process.env,
|
|
72
|
+
AKAN_PUBLIC_REPO_NAME: "repo",
|
|
73
|
+
AKAN_PUBLIC_SERVE_DOMAIN: "localhost",
|
|
74
|
+
AKAN_PUBLIC_ENV: "local",
|
|
75
|
+
},
|
|
76
|
+
stdout: "pipe",
|
|
77
|
+
stderr: "pipe",
|
|
78
|
+
});
|
|
79
|
+
const [code, stdout, stderr] = await Promise.all([
|
|
80
|
+
proc.exited,
|
|
81
|
+
new Response(proc.stdout).text(),
|
|
82
|
+
new Response(proc.stderr).text(),
|
|
83
|
+
]);
|
|
84
|
+
if (code !== 0) throw new Error(`the dictionary did not build:\n${stderr}`);
|
|
85
|
+
return JSON.parse(stdout.trim().split("\n").at(-1) ?? "{}") as Record<string, LocaleBuild>;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const isNode = (value: unknown): value is Record<string, unknown> =>
|
|
89
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
90
|
+
const mergeOf = (target: Record<string, unknown>, source: Record<string, unknown>): Record<string, unknown> =>
|
|
91
|
+
Object.fromEntries(
|
|
92
|
+
[...new Set([...Object.keys(target), ...Object.keys(source)])].map((key) => {
|
|
93
|
+
const [own, added] = [target[key], source[key]];
|
|
94
|
+
return [key, isNode(own) && isNode(added) ? mergeOf(own, added) : (added ?? own)];
|
|
95
|
+
}),
|
|
96
|
+
);
|
|
97
|
+
const signalEntriesOf = (dictionary: Record<string, Record<string, unknown>>) =>
|
|
98
|
+
Object.values(dictionary).flatMap((node) => (isNode(node.signal) ? Object.values(node.signal) : []));
|
|
99
|
+
|
|
100
|
+
const expectSplitOf = (build: LocaleBuild) => {
|
|
101
|
+
expect(mergeOf(build.page, build.api)).toEqual(build.whole);
|
|
102
|
+
expect(build.server).toEqual(build.whole);
|
|
103
|
+
expect(build.parts).toEqual({ api: build.apiUrl });
|
|
104
|
+
const pageEntries = signalEntriesOf(build.page).filter(isNode);
|
|
105
|
+
expect(pageEntries.length).toBeGreaterThan(0);
|
|
106
|
+
expect(pageEntries.filter((entry) => "desc" in entry || "arg" in entry)).toEqual([]);
|
|
107
|
+
expect(Object.values(build.api).every((node) => Object.keys(node).join() === "signal")).toBe(true);
|
|
108
|
+
const apiEntries = signalEntriesOf(build.api).filter(isNode);
|
|
109
|
+
expect(apiEntries.length).toBeGreaterThan(0);
|
|
110
|
+
expect(apiEntries.filter((entry) => Object.keys(entry).some((key) => key !== "desc" && key !== "arg"))).toEqual([]);
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const libAndAppDictSource = (dictionaryIndex: string) => `
|
|
114
|
+
import { makeDictionary, makeTrans, registerServiceTrans, serviceDictionary } from ${JSON.stringify(dictionaryIndex)};
|
|
115
|
+
const libShop = serviceDictionary(["en", "ko"])
|
|
116
|
+
.endpoint((fn) => ({
|
|
117
|
+
order: fn(["Order", "주문"])
|
|
118
|
+
.desc(["Places an order", "주문한다"])
|
|
119
|
+
.arg((t) => ({ itemId: t(["Item", "상품"]).desc(["The item to order", "주문할 상품"]) })),
|
|
120
|
+
refund: fn(["Refund", "환불"]).desc(["Refunds an order", "주문을 환불한다"]),
|
|
121
|
+
}))
|
|
122
|
+
.translate({ title: ["Shop", "상점"] });
|
|
123
|
+
const libCart = serviceDictionary(["en"]).endpoint((fn) => ({
|
|
124
|
+
addItem: fn(["Add Item"]).desc(["Adds an item to the cart"]).arg((t) => ({ itemId: t(["Item"]) })),
|
|
125
|
+
}));
|
|
126
|
+
const appShop = serviceDictionary(["en", "ko"])
|
|
127
|
+
.endpoint((fn) => ({
|
|
128
|
+
order: fn(["Order now", "바로 주문"])
|
|
129
|
+
.desc(["Places an order at once", "바로 주문한다"])
|
|
130
|
+
.arg((t) => ({ coupon: t(["Coupon", "쿠폰"]).desc(["A coupon code", "쿠폰 코드"]) })),
|
|
131
|
+
track: fn(["Track", "배송 조회"]),
|
|
132
|
+
}))
|
|
133
|
+
.translate({ title: ["My shop", "내 상점"] });
|
|
134
|
+
const lib = makeDictionary({ shop: registerServiceTrans(libShop), cart: registerServiceTrans(libCart) });
|
|
135
|
+
export const dictionary = makeDictionary(lib, { shop: registerServiceTrans(appShop) });
|
|
136
|
+
export const { getAllDictionary } = makeTrans(dictionary);
|
|
137
|
+
`;
|
|
138
|
+
|
|
26
139
|
describe("DictionaryAssetBuilder", () => {
|
|
27
140
|
test("writes one module per locale, the default locale's text filled into the gaps", async () => {
|
|
28
141
|
const { app, artifactDir } = await makeApp(dictSourceOf(allDictionary));
|
|
@@ -68,6 +181,301 @@ describe("DictionaryAssetBuilder", () => {
|
|
|
68
181
|
);
|
|
69
182
|
});
|
|
70
183
|
|
|
184
|
+
test("writes a locale's file as it always did when the API descriptions are not split out", async () => {
|
|
185
|
+
const { app, artifactDir } = await makeApp(dictSourceOf(allDictionary));
|
|
186
|
+
const assets = await new DictionaryAssetBuilder(app, artifactDir).build({ defaultLocale: "en", locales: ["en"] });
|
|
187
|
+
|
|
188
|
+
expect(assets.en.parts).toBeUndefined();
|
|
189
|
+
expect(await Bun.file(path.join(artifactDir, assets.en.relPath)).text()).toBe(
|
|
190
|
+
`export const lang = "en";\nexport default JSON.parse(${JSON.stringify(JSON.stringify(allDictionary.en))});\n`,
|
|
191
|
+
);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test("moves each endpoint's description and arguments to a file of their own, leaving its label", async () => {
|
|
195
|
+
const dictionary = {
|
|
196
|
+
en: {
|
|
197
|
+
memo: {
|
|
198
|
+
t: "Memo",
|
|
199
|
+
title: { t: "Title", desc: { t: "A field's own description stays" } },
|
|
200
|
+
signal: {
|
|
201
|
+
createMemo: { t: "Create Memo", desc: { t: "Creates a memo" }, arg: { data: { t: "Data" } } },
|
|
202
|
+
removeMemo: { t: "Remove Memo" },
|
|
203
|
+
},
|
|
204
|
+
},
|
|
205
|
+
util: { t: "Util" },
|
|
206
|
+
},
|
|
207
|
+
};
|
|
208
|
+
const { app, artifactDir } = await makeApp(dictSourceOf(dictionary));
|
|
209
|
+
const assets = await new DictionaryAssetBuilder(app, artifactDir).build(
|
|
210
|
+
{ defaultLocale: "en", locales: ["en"] },
|
|
211
|
+
{ splitApi: true },
|
|
212
|
+
);
|
|
213
|
+
|
|
214
|
+
const api = assets.en.parts?.api;
|
|
215
|
+
expect(api?.url).toMatch(/^\/_akan\/dict\/en-api-[a-z0-9]+\.js$/);
|
|
216
|
+
const page = (await import(path.join(artifactDir, assets.en.relPath))) as { default: object; parts: object };
|
|
217
|
+
expect(page.parts).toEqual({ api: api?.url });
|
|
218
|
+
expect(page.default).toEqual({
|
|
219
|
+
memo: {
|
|
220
|
+
t: "Memo",
|
|
221
|
+
title: { t: "Title", desc: { t: "A field's own description stays" } },
|
|
222
|
+
signal: { createMemo: { t: "Create Memo" }, removeMemo: { t: "Remove Memo" } },
|
|
223
|
+
},
|
|
224
|
+
util: { t: "Util" },
|
|
225
|
+
});
|
|
226
|
+
expect((await import(path.join(artifactDir, api?.relPath ?? ""))).default).toEqual({
|
|
227
|
+
memo: { signal: { createMemo: { desc: { t: "Creates a memo" }, arg: { data: { t: "Data" } } } } },
|
|
228
|
+
});
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
test("writes the whole file when the split leaves nothing to move", async () => {
|
|
232
|
+
const { app, artifactDir } = await makeApp(dictSourceOf(allDictionary));
|
|
233
|
+
const assets = await new DictionaryAssetBuilder(app, artifactDir).build(i18n, { splitApi: true });
|
|
234
|
+
|
|
235
|
+
expect(assets.en.parts).toBeUndefined();
|
|
236
|
+
expect((await readdir(path.join(artifactDir, "dict"))).length).toBe(2);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
test("splits a lib's and an app's description of the same module into files that merge back to the whole", async () => {
|
|
240
|
+
const { app } = await makeApp(libAndAppDictSource(path.join(workspaceRoot, "pkgs/akanjs/dictionary/index.ts")));
|
|
241
|
+
const builds = await buildBothWays(app.cwdPath, await tempRoot());
|
|
242
|
+
|
|
243
|
+
expect(Object.keys(builds)).toEqual(["en", "ko"]);
|
|
244
|
+
for (const build of Object.values(builds)) expectSplitOf(build);
|
|
245
|
+
expect(builds.ko.whole.cart).toEqual(builds.en.whole.cart);
|
|
246
|
+
expect(builds.ko.page.shop).toEqual({
|
|
247
|
+
error: {},
|
|
248
|
+
signal: { order: { t: "바로 주문" }, track: { t: "배송 조회" } },
|
|
249
|
+
title: { t: "내 상점" },
|
|
250
|
+
});
|
|
251
|
+
}, 30_000);
|
|
252
|
+
|
|
253
|
+
//? `lib/dict.ts` is written by `akan sync`, which the package test job of CI does not run.
|
|
254
|
+
for (const name of ["minimal", "akan"])
|
|
255
|
+
test.skipIf(!existsSync(path.join(workspaceRoot, "apps", name, "lib/dict.ts")))(
|
|
256
|
+
`splits apps/${name}'s dictionary into files that merge back to the whole`,
|
|
257
|
+
async () => {
|
|
258
|
+
const builds = await buildBothWays(path.join(workspaceRoot, "apps", name), await tempRoot());
|
|
259
|
+
|
|
260
|
+
expect(Object.keys(builds)).toEqual(["en", "ko"]);
|
|
261
|
+
for (const build of Object.values(builds)) expectSplitOf(build);
|
|
262
|
+
},
|
|
263
|
+
60_000,
|
|
264
|
+
);
|
|
265
|
+
|
|
266
|
+
describe("for the routes it is handed", () => {
|
|
267
|
+
//? Texts brotli cannot fold away: with a few words per group a route's own files outweigh the whole file.
|
|
268
|
+
const long = (group: string) => ({
|
|
269
|
+
t: Array.from({ length: 80 }, (_, idx) => Bun.hash(`${group}${idx}`).toString(36)).join(" "),
|
|
270
|
+
});
|
|
271
|
+
const routedDictionary = {
|
|
272
|
+
en: {
|
|
273
|
+
base: { t: "Base", ok: { t: "OK" }, long: long("base") },
|
|
274
|
+
memo: {
|
|
275
|
+
t: "Memo",
|
|
276
|
+
long: long("memo"),
|
|
277
|
+
signal: { getMemo: { t: "Get Memo", desc: { t: "Reads a memo" } } },
|
|
278
|
+
},
|
|
279
|
+
user: { t: "User", long: long("user") },
|
|
280
|
+
util: { t: "Util", long: long("util") },
|
|
281
|
+
},
|
|
282
|
+
ko: { base: { t: "기본" }, memo: { t: "메모" } },
|
|
283
|
+
};
|
|
284
|
+
const routes = new Map([
|
|
285
|
+
["/:lang/memo", ["base", "memo"]],
|
|
286
|
+
["/:lang/user", ["base", "user", "unknownGroup"]],
|
|
287
|
+
]);
|
|
288
|
+
interface PartModule {
|
|
289
|
+
default: Record<string, unknown>;
|
|
290
|
+
groups: string[];
|
|
291
|
+
table: string;
|
|
292
|
+
parts?: object;
|
|
293
|
+
}
|
|
294
|
+
const importOf = async <Module>(artifactDir: string, url: string) =>
|
|
295
|
+
(await import(path.join(artifactDir, url.replace(/^\/_akan\//, "")))) as Module;
|
|
296
|
+
|
|
297
|
+
test("writes the files each route loads, and the table naming each group's file, for every locale", async () => {
|
|
298
|
+
const { app, artifactDir } = await makeApp(dictSourceOf(routedDictionary));
|
|
299
|
+
const built = await new DictionaryAssetBuilder(app, artifactDir).buildAll(i18n, { splitApi: true, routes });
|
|
300
|
+
|
|
301
|
+
expect(Object.keys(built.routes ?? {})).toEqual(["/:lang/memo", "/:lang/user"]);
|
|
302
|
+
for (const lang of i18n.locales) {
|
|
303
|
+
const asset = built.assets[lang];
|
|
304
|
+
const routeParts = asset?.routeParts;
|
|
305
|
+
if (!asset || !routeParts) throw new Error(`no route files for ${lang}`);
|
|
306
|
+
const table = await importOf<{ files: string[]; default: Record<string, number> }>(
|
|
307
|
+
artifactDir,
|
|
308
|
+
routeParts.table.url,
|
|
309
|
+
);
|
|
310
|
+
expect(table.files).toEqual(routeParts.files.map(({ url }) => url));
|
|
311
|
+
const page = await importOf<PartModule>(artifactDir, asset.url);
|
|
312
|
+
expect(page.table).toBe(routeParts.table.url);
|
|
313
|
+
for (const [routeId, shown] of routes) {
|
|
314
|
+
const merged: Record<string, unknown> = {};
|
|
315
|
+
for (const idx of built.routes?.[routeId] ?? []) {
|
|
316
|
+
const part = await importOf<PartModule>(artifactDir, table.files[idx] ?? "");
|
|
317
|
+
expect(part.table).toBe(routeParts.table.url);
|
|
318
|
+
expect(part.parts).toEqual(page.parts);
|
|
319
|
+
for (const group of part.groups) expect(table.default[group]).toBe(idx);
|
|
320
|
+
Object.assign(merged, part.default);
|
|
321
|
+
}
|
|
322
|
+
for (const group of shown.filter((group) => group in page.default))
|
|
323
|
+
expect(merged[group]).toEqual(page.default[group]);
|
|
324
|
+
expect(merged.util).toBeUndefined();
|
|
325
|
+
}
|
|
326
|
+
expect(Object.keys(table.default).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))).toEqual([
|
|
327
|
+
"base",
|
|
328
|
+
"memo",
|
|
329
|
+
"user",
|
|
330
|
+
"util",
|
|
331
|
+
]);
|
|
332
|
+
expect(built.routes?.["/:lang/memo"]).not.toContain(table.default.util);
|
|
333
|
+
expect(built.routes?.["/:lang/user"]).not.toContain(table.default.util);
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
test("writes the one page file unchanged when no route is handed", async () => {
|
|
338
|
+
const { app, artifactDir } = await makeApp(dictSourceOf(routedDictionary));
|
|
339
|
+
const plain = await new DictionaryAssetBuilder(app, path.join(artifactDir, "plain")).buildAll(i18n, {
|
|
340
|
+
splitApi: true,
|
|
341
|
+
});
|
|
342
|
+
const routed = await new DictionaryAssetBuilder(app, path.join(artifactDir, "routed")).buildAll(i18n, {
|
|
343
|
+
splitApi: true,
|
|
344
|
+
routes: new Map(),
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
expect(routed).toEqual(plain);
|
|
348
|
+
expect(plain.routes).toBeUndefined();
|
|
349
|
+
expect(plain.assets.en.routeParts).toBeUndefined();
|
|
350
|
+
expect((await readdir(path.join(artifactDir, "plain/dict"))).length).toBe(4);
|
|
351
|
+
const api = await importOf<{ part?: string }>(
|
|
352
|
+
path.join(artifactDir, "plain"),
|
|
353
|
+
plain.assets.ko.parts?.api?.url ?? "",
|
|
354
|
+
);
|
|
355
|
+
expect(api.part).toBeUndefined();
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
test("adds the API description file to a route whose components show those texts, in a build and in development", async () => {
|
|
359
|
+
const { app, artifactDir } = await makeApp(dictSourceOf(routedDictionary));
|
|
360
|
+
const { apiGroup } = DictionaryAssetBuilder;
|
|
361
|
+
const withApi = new Map([...routes, ["/:lang/memo/api", ["base", "memo", apiGroup]]]);
|
|
362
|
+
const built = await new DictionaryAssetBuilder(app, path.join(artifactDir, "build")).buildAll(i18n, {
|
|
363
|
+
splitApi: true,
|
|
364
|
+
routes: withApi,
|
|
365
|
+
});
|
|
366
|
+
const dev = await new DictionaryAssetBuilder(app, path.join(artifactDir, "dev")).buildAll(i18n, {
|
|
367
|
+
splitApi: true,
|
|
368
|
+
everyGroupAlone: true,
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
for (const { assets } of [built, dev])
|
|
372
|
+
for (const lang of i18n.locales) expect(assets[lang].routeParts?.files.at(-1)).toEqual(assets[lang].parts?.api);
|
|
373
|
+
const apiIdx = (built.assets.en.routeParts?.files.length ?? 0) - 1;
|
|
374
|
+
expect(built.routes?.["/:lang/memo/api"]).toEqual([...(built.routes?.["/:lang/memo"] ?? []), apiIdx]);
|
|
375
|
+
expect(built.routes?.["/:lang/memo"]).not.toContain(apiIdx);
|
|
376
|
+
expect(dev.groups?.[apiGroup]).toBe((dev.assets.en.routeParts?.files.length ?? 0) - 1);
|
|
377
|
+
const api = await importOf<{ part: string; default: object }>(
|
|
378
|
+
path.join(artifactDir, "build"),
|
|
379
|
+
built.assets.ko.parts?.api?.url ?? "",
|
|
380
|
+
);
|
|
381
|
+
expect(api.part).toBe(DictionaryAssetBuilder.apiPart);
|
|
382
|
+
expect(api.default).toEqual({ memo: { signal: { getMemo: { desc: { t: "Reads a memo" } } } } });
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
test("records what each page file of a build costs a browser, in every locale, and nothing in development", async () => {
|
|
386
|
+
const { app, artifactDir } = await makeApp(dictSourceOf(routedDictionary));
|
|
387
|
+
const built = await new DictionaryAssetBuilder(app, path.join(artifactDir, "build")).buildAll(i18n, {
|
|
388
|
+
splitApi: true,
|
|
389
|
+
routes,
|
|
390
|
+
});
|
|
391
|
+
const dev = await new DictionaryAssetBuilder(app, path.join(artifactDir, "dev")).buildAll(i18n, {
|
|
392
|
+
splitApi: true,
|
|
393
|
+
everyGroupAlone: true,
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
for (const lang of i18n.locales) {
|
|
397
|
+
const asset = built.assets[lang];
|
|
398
|
+
const pageFiles = (asset?.routeParts?.files ?? []).filter(({ url }) => url !== asset?.parts?.api?.url);
|
|
399
|
+
expect(pageFiles.length).toBeGreaterThan(1);
|
|
400
|
+
for (const file of [asset, ...pageFiles]) {
|
|
401
|
+
const source = await Bun.file(path.join(artifactDir, "build", file?.relPath ?? "")).bytes();
|
|
402
|
+
const brotli = dictionaryBrotliBytesOf(new TextDecoder().decode(source));
|
|
403
|
+
expect(file?.bytes).toBe(Math.min(source.byteLength, brotli));
|
|
404
|
+
}
|
|
405
|
+
expect(dev.assets[lang]?.bytes).toBeUndefined();
|
|
406
|
+
for (const file of dev.assets[lang]?.routeParts?.files ?? []) expect(file.bytes).toBeUndefined();
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
test("gives a route past the bound a file of its own, which the table never names, and records what each file costs", async () => {
|
|
411
|
+
let seed = 3;
|
|
412
|
+
const word = () => {
|
|
413
|
+
seed = (seed * 48271) % 2147483647;
|
|
414
|
+
return seed.toString(36);
|
|
415
|
+
};
|
|
416
|
+
const textOf = () => Array.from({ length: 400 }, word).join(" ");
|
|
417
|
+
const modules = Array.from({ length: 6 }, (_, idx) => idx);
|
|
418
|
+
const en = Object.fromEntries(
|
|
419
|
+
modules.flatMap((idx) => [
|
|
420
|
+
[`g${idx}`, { t: textOf() }],
|
|
421
|
+
[`h${idx}`, { t: textOf() }],
|
|
422
|
+
]),
|
|
423
|
+
);
|
|
424
|
+
const heavy = "/:lang/heavy";
|
|
425
|
+
const wide = new Map([
|
|
426
|
+
[heavy, modules.map((idx) => `g${idx}`)],
|
|
427
|
+
...modules.map((idx) => [`/:lang/light${idx}`, [`g${idx}`, `h${idx}`]] as [string, string[]]),
|
|
428
|
+
]);
|
|
429
|
+
const { app, artifactDir } = await makeApp(dictSourceOf({ en, ko: en }));
|
|
430
|
+
const built = await new DictionaryAssetBuilder(app, path.join(artifactDir, "build")).buildAll(i18n, {
|
|
431
|
+
routes: wide,
|
|
432
|
+
});
|
|
433
|
+
const dev = await new DictionaryAssetBuilder(app, path.join(artifactDir, "dev")).buildAll(i18n, {
|
|
434
|
+
everyGroupAlone: true,
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
const held = built.routes?.[heavy] ?? [];
|
|
438
|
+
expect(held).toHaveLength(4);
|
|
439
|
+
for (const lang of i18n.locales) {
|
|
440
|
+
const asset = built.assets[lang];
|
|
441
|
+
const files = asset?.routeParts?.files ?? [];
|
|
442
|
+
const table = await importOf<{ default: Record<string, number> }>(
|
|
443
|
+
path.join(artifactDir, "build"),
|
|
444
|
+
asset?.routeParts?.table.url ?? "",
|
|
445
|
+
);
|
|
446
|
+
const own = held.at(-1) ?? -1;
|
|
447
|
+
expect(Object.values(table.default)).not.toContain(own);
|
|
448
|
+
for (const [routeId, shown] of wide) {
|
|
449
|
+
const merged: Record<string, unknown> = {};
|
|
450
|
+
for (const idx of built.routes?.[routeId] ?? []) {
|
|
451
|
+
const part = await importOf<PartModule>(path.join(artifactDir, "build"), files[idx]?.url ?? "");
|
|
452
|
+
Object.assign(merged, part.default);
|
|
453
|
+
}
|
|
454
|
+
expect(new Set(Object.keys(merged))).toEqual(new Set(shown));
|
|
455
|
+
}
|
|
456
|
+
expect(asset?.bytes).toBeGreaterThan(0);
|
|
457
|
+
for (const file of files) expect(file.bytes).toBeGreaterThan(0);
|
|
458
|
+
expect(dev.assets[lang]?.bytes).toBeUndefined();
|
|
459
|
+
for (const file of dev.assets[lang]?.routeParts?.files ?? []) expect(file.bytes).toBeUndefined();
|
|
460
|
+
}
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
test("development writes one file per group and the index of each, as each route's groups are read when it builds", async () => {
|
|
464
|
+
const { app, artifactDir } = await makeApp(dictSourceOf(routedDictionary));
|
|
465
|
+
const built = await new DictionaryAssetBuilder(app, artifactDir).buildAll(i18n, { everyGroupAlone: true });
|
|
466
|
+
|
|
467
|
+
expect(built.routes).toBeUndefined();
|
|
468
|
+
expect(built.groups).toEqual({ base: 0, memo: 1, user: 2, util: 3 });
|
|
469
|
+
const files = built.assets.ko?.routeParts?.files ?? [];
|
|
470
|
+
expect(files).toHaveLength(4);
|
|
471
|
+
for (const [group, idx] of Object.entries(built.groups ?? {})) {
|
|
472
|
+
const part = await importOf<PartModule>(artifactDir, files[idx]?.url ?? "");
|
|
473
|
+
expect(part.groups).toEqual([group]);
|
|
474
|
+
expect(Object.keys(part.default)).toEqual([group]);
|
|
475
|
+
}
|
|
476
|
+
});
|
|
477
|
+
});
|
|
478
|
+
|
|
71
479
|
test("writes nothing for an app without a dictionary", async () => {
|
|
72
480
|
const { app, artifactDir } = await makeApp();
|
|
73
481
|
expect(await new DictionaryAssetBuilder(app, artifactDir).build({ defaultLocale: "en", locales: ["en"] })).toEqual(
|
|
@@ -1,11 +1,39 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
-
import { type AllDictionary, Translator } from "akanjs/client";
|
|
2
|
+
import { type AllDictionary, type Dictionary, Translator } from "akanjs/client";
|
|
3
3
|
import type { AkanI18nConfig } from "akanjs/common";
|
|
4
4
|
import type { DictAsset } from "akanjs/server";
|
|
5
5
|
import type { App } from "../commandDecorators";
|
|
6
|
+
import { type DictionaryPack, DictionaryPacking } from "./dictionaryPacking";
|
|
7
|
+
import { dictionaryBrotliBytesOf, dictionaryServedBytesOf } from "./precompressArtifacts";
|
|
8
|
+
|
|
9
|
+
export interface DictionaryAssetBuildOptions {
|
|
10
|
+
/** Each locale's API descriptions go to a file of their own, loaded where shown. */
|
|
11
|
+
splitApi?: boolean;
|
|
12
|
+
/** The groups each route can show; a route left out loads the whole page file. */
|
|
13
|
+
routes?: ReadonlyMap<string, readonly string[]>;
|
|
14
|
+
/** Development: one file per group, as each route's groups are read when it builds. */
|
|
15
|
+
everyGroupAlone?: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface DictionaryAssets {
|
|
19
|
+
assets: Record<string, DictAsset>;
|
|
20
|
+
/** The `routeParts.files` each route loads, by index, the same for every locale. */
|
|
21
|
+
routes?: Record<string, number[]>;
|
|
22
|
+
/** With `everyGroupAlone`: the `routeParts.files` index of each group. */
|
|
23
|
+
groups?: Record<string, number>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface LocalePages {
|
|
27
|
+
lang: string;
|
|
28
|
+
page: Dictionary;
|
|
29
|
+
api: Dictionary;
|
|
30
|
+
}
|
|
6
31
|
|
|
7
32
|
export class DictionaryAssetBuilder {
|
|
8
33
|
static readonly urlPrefix = "/_akan/dict";
|
|
34
|
+
static readonly apiPart = "api";
|
|
35
|
+
//? How a route's groups name the API description file: no module's group is spelled so.
|
|
36
|
+
static readonly apiGroup = "@api";
|
|
9
37
|
readonly #app: App;
|
|
10
38
|
readonly #absArtifactDir: string;
|
|
11
39
|
|
|
@@ -14,16 +42,80 @@ export class DictionaryAssetBuilder {
|
|
|
14
42
|
this.#absArtifactDir = absArtifactDir;
|
|
15
43
|
}
|
|
16
44
|
|
|
17
|
-
async build(i18n: AkanI18nConfig): Promise<Record<string, DictAsset>> {
|
|
45
|
+
async build(i18n: AkanI18nConfig, options: DictionaryAssetBuildOptions = {}): Promise<Record<string, DictAsset>> {
|
|
46
|
+
return (await this.buildAll(i18n, options)).assets;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async buildAll(
|
|
50
|
+
i18n: AkanI18nConfig,
|
|
51
|
+
{ splitApi = false, routes, everyGroupAlone = false }: DictionaryAssetBuildOptions = {},
|
|
52
|
+
): Promise<DictionaryAssets> {
|
|
18
53
|
const allDictionary = await this.#loadAllDictionary();
|
|
19
|
-
if (!allDictionary) return {};
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
);
|
|
25
|
-
|
|
26
|
-
|
|
54
|
+
if (!allDictionary) return { assets: {} };
|
|
55
|
+
const locales: LocalePages[] = i18n.locales.map((lang) => {
|
|
56
|
+
const dictionary = Translator.fillFromDefault(allDictionary, lang, i18n.defaultLocale);
|
|
57
|
+
return { lang, ...(splitApi ? DictionaryAssetBuilder.splitApi(dictionary) : { page: dictionary, api: {} }) };
|
|
58
|
+
});
|
|
59
|
+
const groups = [...new Set(locales.flatMap(({ page }) => Object.keys(page)))].sort();
|
|
60
|
+
const packed = routes?.size ? DictionaryAssetBuilder.#pack(routes, locales, i18n.defaultLocale, groups) : null;
|
|
61
|
+
if (packed?.wholeRoutes.length)
|
|
62
|
+
this.#app.verbose(
|
|
63
|
+
`[dictionary] ${packed.wholeRoutes.length} route(s) load the whole page dictionary: their own files would not be smaller. Routes: ${packed.wholeRoutes.join(", ")}`,
|
|
64
|
+
);
|
|
65
|
+
if (packed?.ownParts.length)
|
|
66
|
+
this.#app.verbose(
|
|
67
|
+
`[dictionary] ${packed.ownParts.length} file(s) hold the texts of a route past its ${DictionaryPacking.bound} files`,
|
|
68
|
+
);
|
|
69
|
+
const pack: DictionaryPack | null =
|
|
70
|
+
packed && Object.keys(packed.partsByRoute).length
|
|
71
|
+
? packed
|
|
72
|
+
: everyGroupAlone
|
|
73
|
+
? { parts: groups.map((group) => [group]), ownParts: [], partsByRoute: {} }
|
|
74
|
+
: null;
|
|
75
|
+
const measured = !!packed && pack === packed;
|
|
76
|
+
const assets = await Promise.all(locales.map((locale) => this.#writeLocale(locale, pack, measured)));
|
|
77
|
+
const files = assets.flatMap(([, asset]) => [
|
|
78
|
+
asset,
|
|
79
|
+
...Object.values(asset.parts ?? {}),
|
|
80
|
+
...(asset.routeParts ? [asset.routeParts.table, ...asset.routeParts.files] : []),
|
|
81
|
+
]);
|
|
82
|
+
this.#app.verbose(`[base-artifact] dictionaries -> ${files.map((asset) => asset.relPath).join(", ")}`);
|
|
83
|
+
if (!pack?.parts.length) return { assets: Object.fromEntries(assets) };
|
|
84
|
+
const { apiPart, apiGroup } = DictionaryAssetBuilder;
|
|
85
|
+
const fileCount = pack.parts.length + pack.ownParts.length;
|
|
86
|
+
const apiFile = assets.every(([, asset]) => asset.parts?.[apiPart]) ? fileCount : null;
|
|
87
|
+
if (!everyGroupAlone || routes?.size) {
|
|
88
|
+
const withApi = (routeId: string, files: number[]) =>
|
|
89
|
+
apiFile !== null && routes?.get(routeId)?.includes(apiGroup) ? [...files, apiFile] : files;
|
|
90
|
+
const routed = Object.entries(pack.partsByRoute).map(([routeId, files]) => [routeId, withApi(routeId, files)]);
|
|
91
|
+
return { assets: Object.fromEntries(assets), routes: Object.fromEntries(routed) };
|
|
92
|
+
}
|
|
93
|
+
const groupFiles = Object.fromEntries(groups.map((group, idx) => [group, idx]));
|
|
94
|
+
return {
|
|
95
|
+
assets: Object.fromEntries(assets),
|
|
96
|
+
groups: apiFile === null ? groupFiles : { ...groupFiles, [apiGroup]: apiFile },
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
//? Sized on the default locale, whose texts every other locale's fill from: the same files hold the same groups.
|
|
101
|
+
static #pack(
|
|
102
|
+
routes: ReadonlyMap<string, readonly string[]>,
|
|
103
|
+
locales: LocalePages[],
|
|
104
|
+
defaultLocale: string,
|
|
105
|
+
groups: string[],
|
|
106
|
+
) {
|
|
107
|
+
const { lang = defaultLocale, page: sizing = {} } =
|
|
108
|
+
locales.find((locale) => locale.lang === defaultLocale) ?? locales[0] ?? {};
|
|
109
|
+
//? The exports a file carries are counted too, its table's name at its longest: the build's names are not known yet.
|
|
110
|
+
const table = `${DictionaryAssetBuilder.urlPrefix}/${lang}-groups-${"x".repeat(13)}.js`;
|
|
111
|
+
const servedBytesOf = (held: readonly string[]) => {
|
|
112
|
+
const texts = Object.fromEntries(held.flatMap((group) => (sizing[group] ? [[group, sizing[group]]] : [])));
|
|
113
|
+
const whole = held.length === groups.length;
|
|
114
|
+
const exports = whole ? { table } : { table, groups: [...held] };
|
|
115
|
+
return dictionaryBrotliBytesOf(DictionaryAssetBuilder.source(lang, texts, undefined, exports));
|
|
116
|
+
};
|
|
117
|
+
const bytesOf = (group: string) => JSON.stringify(sizing[group] ?? {}).length;
|
|
118
|
+
return DictionaryPacking.packUnderWhole(routes, bytesOf, groups, servedBytesOf);
|
|
27
119
|
}
|
|
28
120
|
|
|
29
121
|
//? The same module the root layout's macro evaluates in this process, so the asset and the RSC worker's copy agree.
|
|
@@ -34,16 +126,92 @@ export class DictionaryAssetBuilder {
|
|
|
34
126
|
return getAllDictionary ? getAllDictionary() : null;
|
|
35
127
|
}
|
|
36
128
|
|
|
37
|
-
async #
|
|
38
|
-
|
|
39
|
-
|
|
129
|
+
async #writeLocale(
|
|
130
|
+
{ lang, page, api }: LocalePages,
|
|
131
|
+
pack: DictionaryPack | null,
|
|
132
|
+
measured: boolean,
|
|
133
|
+
): Promise<readonly [string, DictAsset]> {
|
|
134
|
+
const { source, apiPart } = DictionaryAssetBuilder;
|
|
135
|
+
const packed = pack?.parts.length ? [...pack.parts, ...pack.ownParts] : null;
|
|
136
|
+
const apiSource = source(lang, api, undefined, packed ? { part: apiPart } : {});
|
|
137
|
+
const apiAsset = Object.keys(api).length ? await this.#write(`${lang}-api`, apiSource) : null;
|
|
138
|
+
const parts = apiAsset ? { [apiPart]: apiAsset.url } : undefined;
|
|
139
|
+
const withParts = apiAsset ? { parts: { [apiPart]: apiAsset } } : {};
|
|
140
|
+
if (!pack || !packed) return [lang, { ...(await this.#write(lang, source(lang, page, parts))), ...withParts }];
|
|
141
|
+
//? Named for what decides every file it lists, not for their names: each part names the table it belongs to.
|
|
142
|
+
const tableName = `${lang}-groups-${Bun.hash(JSON.stringify([page, packed, parts ?? null])).toString(36)}.js`;
|
|
143
|
+
const table = `${DictionaryAssetBuilder.urlPrefix}/${tableName}`;
|
|
144
|
+
const groupFiles = await Promise.all(
|
|
145
|
+
packed.map((groups, idx) => {
|
|
146
|
+
const held = Object.fromEntries(groups.flatMap((group) => (page[group] ? [[group, page[group]]] : [])));
|
|
147
|
+
return this.#write(`${lang}-${idx}`, source(lang, held, parts, { table, groups }), undefined, measured);
|
|
148
|
+
}),
|
|
149
|
+
);
|
|
150
|
+
const files = apiAsset ? [...groupFiles, apiAsset] : groupFiles;
|
|
151
|
+
//? A route's own file holds groups a shared file holds too: a group missed is fetched from the shared one.
|
|
152
|
+
const groupIndex = Object.fromEntries(pack.parts.flatMap((groups, idx) => groups.map((group) => [group, idx])));
|
|
153
|
+
const tableSource = `export const lang = ${JSON.stringify(lang)};\nexport const files = ${JSON.stringify(files.map(({ url }) => url))};\nexport default ${JSON.stringify(groupIndex)};\n`;
|
|
154
|
+
const tableAsset = await this.#write(lang, tableSource, tableName);
|
|
155
|
+
const whole = await this.#write(lang, source(lang, page, parts, { table }), undefined, measured);
|
|
156
|
+
return [lang, { ...whole, ...withParts, routeParts: { table: tableAsset, files } }];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async #write(stem: string, source: string, fileName?: string, measured = false): Promise<DictAsset> {
|
|
160
|
+
const name = fileName ?? `${stem}-${Bun.hash(source).toString(36)}.js`;
|
|
40
161
|
const relPath = `dict/${name}`;
|
|
41
|
-
await
|
|
42
|
-
|
|
162
|
+
const [bytes] = await Promise.all([
|
|
163
|
+
measured ? dictionaryServedBytesOf(source) : undefined,
|
|
164
|
+
Bun.write(path.join(this.#absArtifactDir, relPath), source),
|
|
165
|
+
]);
|
|
166
|
+
return { url: `${DictionaryAssetBuilder.urlPrefix}/${name}`, relPath, ...(bytes === undefined ? {} : { bytes }) };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
//? An endpoint's own label stays with the page: apps show `l("<model>.signal.<endpoint>")` as a button's text.
|
|
170
|
+
static splitApi(dictionary: Dictionary): { page: Dictionary; api: Dictionary } {
|
|
171
|
+
const page: Dictionary = {};
|
|
172
|
+
const api: Dictionary = {};
|
|
173
|
+
for (const [refName, node] of Object.entries(dictionary)) {
|
|
174
|
+
const signal = node.signal;
|
|
175
|
+
if (!DictionaryAssetBuilder.#isNode(signal)) {
|
|
176
|
+
page[refName] = node;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
const pageSignal: Record<string, unknown> = {};
|
|
180
|
+
const apiSignal: Record<string, unknown> = {};
|
|
181
|
+
for (const [key, entry] of Object.entries(signal)) {
|
|
182
|
+
if (!DictionaryAssetBuilder.#isNode(entry)) {
|
|
183
|
+
pageSignal[key] = entry;
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
const { desc, arg, ...label } = entry;
|
|
187
|
+
pageSignal[key] = label;
|
|
188
|
+
if (desc !== undefined || arg !== undefined)
|
|
189
|
+
apiSignal[key] = { ...(desc === undefined ? {} : { desc }), ...(arg === undefined ? {} : { arg }) };
|
|
190
|
+
}
|
|
191
|
+
page[refName] = { ...node, signal: pageSignal };
|
|
192
|
+
if (Object.keys(apiSignal).length) api[refName] = { signal: apiSignal };
|
|
193
|
+
}
|
|
194
|
+
return { page, api };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
static #isNode(value: unknown): value is Record<string, unknown> {
|
|
198
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
43
199
|
}
|
|
44
200
|
|
|
45
201
|
//? A string for JSON.parse, not an object literal: engines parse the JSON grammar faster than a JS expression.
|
|
46
|
-
static source(
|
|
47
|
-
|
|
202
|
+
static source(
|
|
203
|
+
lang: string,
|
|
204
|
+
dictionary: object,
|
|
205
|
+
parts?: Record<string, string>,
|
|
206
|
+
{ table, groups, part }: { table?: string; groups?: string[]; part?: string } = {},
|
|
207
|
+
): string {
|
|
208
|
+
const lines = [
|
|
209
|
+
`export const lang = ${JSON.stringify(lang)};\n`,
|
|
210
|
+
parts ? `export const parts = ${JSON.stringify(parts)};\n` : "",
|
|
211
|
+
table ? `export const table = ${JSON.stringify(table)};\n` : "",
|
|
212
|
+
groups ? `export const groups = ${JSON.stringify(groups)};\n` : "",
|
|
213
|
+
part ? `export const part = ${JSON.stringify(part)};\n` : "",
|
|
214
|
+
];
|
|
215
|
+
return `${lines.join("")}export default JSON.parse(${JSON.stringify(JSON.stringify(dictionary))});\n`;
|
|
48
216
|
}
|
|
49
217
|
}
|