@supatype/cli 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +259 -0
- package/bin/supatype.js +25 -4
- package/deno.d.ts +1 -1
- package/dist/admin-prompt-state.d.ts +13 -0
- package/dist/admin-prompt-state.d.ts.map +1 -0
- package/dist/admin-prompt-state.js +30 -0
- package/dist/admin-prompt-state.js.map +1 -0
- package/dist/adopt-columns.d.ts.map +1 -1
- package/dist/adopt-columns.js +13 -17
- package/dist/adopt-columns.js.map +1 -1
- package/dist/app-config.d.ts +1 -1
- package/dist/app-config.d.ts.map +1 -1
- package/dist/app-config.js +103 -144
- package/dist/app-config.js.map +1 -1
- package/dist/applied-ast-artifacts.d.ts +16 -0
- package/dist/applied-ast-artifacts.d.ts.map +1 -0
- package/dist/applied-ast-artifacts.js +37 -0
- package/dist/applied-ast-artifacts.js.map +1 -0
- package/dist/archive-extract.d.ts +3 -0
- package/dist/archive-extract.d.ts.map +1 -0
- package/dist/archive-extract.js +19 -0
- package/dist/archive-extract.js.map +1 -0
- package/dist/binary-cache.d.ts +25 -2
- package/dist/binary-cache.d.ts.map +1 -1
- package/dist/binary-cache.js +115 -81
- package/dist/binary-cache.js.map +1 -1
- package/dist/binary-download-lock.d.ts.map +1 -1
- package/dist/binary-download-lock.js +1 -3
- package/dist/binary-download-lock.js.map +1 -1
- package/dist/byo-preflight.d.ts.map +1 -1
- package/dist/byo-preflight.js +2 -10
- package/dist/byo-preflight.js.map +1 -1
- package/dist/cache-pins.d.ts.map +1 -1
- package/dist/cache-pins.js +2 -2
- package/dist/cache-pins.js.map +1 -1
- package/dist/cli-version-embedded.js +1 -1
- package/dist/cloud-credentials.d.ts +6 -0
- package/dist/cloud-credentials.d.ts.map +1 -1
- package/dist/cloud-credentials.js +13 -0
- package/dist/cloud-credentials.js.map +1 -1
- package/dist/commands/admin.d.ts.map +1 -1
- package/dist/commands/admin.js +18 -18
- package/dist/commands/admin.js.map +1 -1
- package/dist/commands/app.d.ts.map +1 -1
- package/dist/commands/app.js +27 -8
- package/dist/commands/app.js.map +1 -1
- package/dist/commands/cache.d.ts.map +1 -1
- package/dist/commands/cache.js +5 -4
- package/dist/commands/cache.js.map +1 -1
- package/dist/commands/cloud.js +2 -4
- package/dist/commands/cloud.js.map +1 -1
- package/dist/commands/db.d.ts.map +1 -1
- package/dist/commands/db.js +116 -106
- package/dist/commands/db.js.map +1 -1
- package/dist/commands/deploy.d.ts.map +1 -1
- package/dist/commands/deploy.js +2 -2
- package/dist/commands/deploy.js.map +1 -1
- package/dist/commands/dev.d.ts +50 -4
- package/dist/commands/dev.d.ts.map +1 -1
- package/dist/commands/dev.js +262 -266
- package/dist/commands/dev.js.map +1 -1
- package/dist/commands/functions.d.ts +30 -0
- package/dist/commands/functions.d.ts.map +1 -1
- package/dist/commands/functions.js +503 -507
- package/dist/commands/functions.js.map +1 -1
- package/dist/commands/generate.d.ts.map +1 -1
- package/dist/commands/generate.js +11 -8
- package/dist/commands/generate.js.map +1 -1
- package/dist/commands/hooks.js +26 -11
- package/dist/commands/hooks.js.map +1 -1
- package/dist/commands/init.d.ts +16 -2
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +237 -143
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/internal.d.ts.map +1 -1
- package/dist/commands/internal.js +2 -1
- package/dist/commands/internal.js.map +1 -1
- package/dist/commands/keys.d.ts +36 -10
- package/dist/commands/keys.d.ts.map +1 -1
- package/dist/commands/keys.js +168 -128
- package/dist/commands/keys.js.map +1 -1
- package/dist/commands/link-helpers.d.ts.map +1 -1
- package/dist/commands/link-helpers.js +30 -9
- package/dist/commands/link-helpers.js.map +1 -1
- package/dist/commands/logs.d.ts.map +1 -1
- package/dist/commands/logs.js +5 -4
- package/dist/commands/logs.js.map +1 -1
- package/dist/commands/migrate.js +1 -1
- package/dist/commands/migrate.js.map +1 -1
- package/dist/commands/pg.js +2 -0
- package/dist/commands/pg.js.map +1 -1
- package/dist/commands/plugins.d.ts.map +1 -1
- package/dist/commands/plugins.js +17 -7
- package/dist/commands/plugins.js.map +1 -1
- package/dist/commands/push.d.ts +37 -0
- package/dist/commands/push.d.ts.map +1 -1
- package/dist/commands/push.js +188 -73
- package/dist/commands/push.js.map +1 -1
- package/dist/commands/seed.d.ts +35 -0
- package/dist/commands/seed.d.ts.map +1 -1
- package/dist/commands/seed.js +72 -38
- package/dist/commands/seed.js.map +1 -1
- package/dist/commands/self-host.d.ts.map +1 -1
- package/dist/commands/self-host.js +61 -29
- package/dist/commands/self-host.js.map +1 -1
- package/dist/commands/status.js +5 -5
- package/dist/commands/status.js.map +1 -1
- package/dist/commands/types.js +2 -5
- package/dist/commands/types.js.map +1 -1
- package/dist/commands/update.d.ts.map +1 -1
- package/dist/commands/update.js +212 -101
- package/dist/commands/update.js.map +1 -1
- package/dist/component-launch.d.ts +11 -0
- package/dist/component-launch.d.ts.map +1 -0
- package/dist/component-launch.js +35 -0
- package/dist/component-launch.js.map +1 -0
- package/dist/components.d.ts +7 -2
- package/dist/components.d.ts.map +1 -1
- package/dist/components.js +7 -2
- package/dist/components.js.map +1 -1
- package/dist/compose-db-roles.d.ts.map +1 -1
- package/dist/compose-db-roles.js +5 -14
- package/dist/compose-db-roles.js.map +1 -1
- package/dist/compose-engine-run.d.ts +6 -5
- package/dist/compose-engine-run.d.ts.map +1 -1
- package/dist/compose-engine-run.js +44 -37
- package/dist/compose-engine-run.js.map +1 -1
- package/dist/compose-engine-service.d.ts +10 -0
- package/dist/compose-engine-service.d.ts.map +1 -0
- package/dist/compose-engine-service.js +16 -0
- package/dist/compose-engine-service.js.map +1 -0
- package/dist/compose-host-path.d.ts +14 -0
- package/dist/compose-host-path.d.ts.map +1 -0
- package/dist/compose-host-path.js +18 -0
- package/dist/compose-host-path.js.map +1 -0
- package/dist/compose-image-pull.d.ts +43 -0
- package/dist/compose-image-pull.d.ts.map +1 -0
- package/dist/compose-image-pull.js +27 -0
- package/dist/compose-image-pull.js.map +1 -0
- package/dist/compose-kong.d.ts.map +1 -1
- package/dist/compose-kong.js +10 -6
- package/dist/compose-kong.js.map +1 -1
- package/dist/compose-local-server-image.d.ts.map +1 -1
- package/dist/compose-local-server-image.js +7 -3
- package/dist/compose-local-server-image.js.map +1 -1
- package/dist/compose-render-mode.d.ts.map +1 -1
- package/dist/compose-render-mode.js +7 -4
- package/dist/compose-render-mode.js.map +1 -1
- package/dist/compose-services.d.ts +12 -2
- package/dist/compose-services.d.ts.map +1 -1
- package/dist/compose-services.js +27 -12
- package/dist/compose-services.js.map +1 -1
- package/dist/config-snapshot.d.ts +6 -0
- package/dist/config-snapshot.d.ts.map +1 -0
- package/dist/config-snapshot.js +23 -0
- package/dist/config-snapshot.js.map +1 -0
- package/dist/config.d.ts +2 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +2 -0
- package/dist/config.js.map +1 -1
- package/dist/database-url-owner.d.ts +57 -0
- package/dist/database-url-owner.d.ts.map +1 -0
- package/dist/database-url-owner.js +130 -0
- package/dist/database-url-owner.js.map +1 -0
- package/dist/db-port-offer.d.ts +18 -0
- package/dist/db-port-offer.d.ts.map +1 -0
- package/dist/db-port-offer.js +68 -0
- package/dist/db-port-offer.js.map +1 -0
- package/dist/db-port.d.ts +40 -18
- package/dist/db-port.d.ts.map +1 -1
- package/dist/db-port.js +33 -31
- package/dist/db-port.js.map +1 -1
- package/dist/db-preflight.d.ts +8 -0
- package/dist/db-preflight.d.ts.map +1 -1
- package/dist/db-preflight.js +18 -1
- package/dist/db-preflight.js.map +1 -1
- package/dist/db-rows.d.ts +11 -0
- package/dist/db-rows.d.ts.map +1 -1
- package/dist/db-rows.js +27 -0
- package/dist/db-rows.js.map +1 -1
- package/dist/debounce.d.ts +11 -0
- package/dist/debounce.d.ts.map +1 -0
- package/dist/debounce.js +23 -0
- package/dist/debounce.js.map +1 -0
- package/dist/dev-api-keys.d.ts +12 -2
- package/dist/dev-api-keys.d.ts.map +1 -1
- package/dist/dev-api-keys.js +33 -17
- package/dist/dev-api-keys.js.map +1 -1
- package/dist/dev-compose.d.ts +5 -12
- package/dist/dev-compose.d.ts.map +1 -1
- package/dist/dev-compose.js +153 -245
- package/dist/dev-compose.js.map +1 -1
- package/dist/dev-db-ready.d.ts.map +1 -1
- package/dist/dev-db-ready.js +2 -1
- package/dist/dev-db-ready.js.map +1 -1
- package/dist/dev-db-reset.d.ts.map +1 -1
- package/dist/dev-db-reset.js +5 -4
- package/dist/dev-db-reset.js.map +1 -1
- package/dist/dev-functions-watch.d.ts.map +1 -1
- package/dist/dev-functions-watch.js +5 -16
- package/dist/dev-functions-watch.js.map +1 -1
- package/dist/dev-ports.d.ts +22 -7
- package/dist/dev-ports.d.ts.map +1 -1
- package/dist/dev-ports.js +61 -38
- package/dist/dev-ports.js.map +1 -1
- package/dist/dev-schema-watch.d.ts.map +1 -1
- package/dist/dev-schema-watch.js +7 -12
- package/dist/dev-schema-watch.js.map +1 -1
- package/dist/dev-session-lock.js +4 -3
- package/dist/dev-session-lock.js.map +1 -1
- package/dist/dev-session.d.ts.map +1 -1
- package/dist/dev-session.js +3 -0
- package/dist/dev-session.js.map +1 -1
- package/dist/dev-shutdown.d.ts +45 -0
- package/dist/dev-shutdown.d.ts.map +1 -1
- package/dist/dev-shutdown.js +206 -31
- package/dist/dev-shutdown.js.map +1 -1
- package/dist/docker-address-pool.d.ts +23 -0
- package/dist/docker-address-pool.d.ts.map +1 -0
- package/dist/docker-address-pool.js +56 -0
- package/dist/docker-address-pool.js.map +1 -0
- package/dist/docker-exec.d.ts +92 -0
- package/dist/docker-exec.d.ts.map +1 -0
- package/dist/docker-exec.js +139 -0
- package/dist/docker-exec.js.map +1 -0
- package/dist/docker-postgres.d.ts +1 -6
- package/dist/docker-postgres.d.ts.map +1 -1
- package/dist/docker-postgres.js +67 -85
- package/dist/docker-postgres.js.map +1 -1
- package/dist/docker-runtime.d.ts +12 -1
- package/dist/docker-runtime.d.ts.map +1 -1
- package/dist/docker-runtime.js +48 -23
- package/dist/docker-runtime.js.map +1 -1
- package/dist/dotenv-parse.d.ts +22 -0
- package/dist/dotenv-parse.d.ts.map +1 -0
- package/dist/dotenv-parse.js +63 -0
- package/dist/dotenv-parse.js.map +1 -0
- package/dist/engine-answers.d.ts +0 -2
- package/dist/engine-answers.d.ts.map +1 -1
- package/dist/engine-answers.js +4 -3
- package/dist/engine-answers.js.map +1 -1
- package/dist/engine-client.d.ts.map +1 -1
- package/dist/engine-client.js +10 -12
- package/dist/engine-client.js.map +1 -1
- package/dist/engine-floor.d.ts +29 -0
- package/dist/engine-floor.d.ts.map +1 -1
- package/dist/engine-floor.js +56 -0
- package/dist/engine-floor.js.map +1 -1
- package/dist/engine-ownership-gate.d.ts +10 -0
- package/dist/engine-ownership-gate.d.ts.map +1 -1
- package/dist/engine-ownership-gate.js +31 -6
- package/dist/engine-ownership-gate.js.map +1 -1
- package/dist/ensure-binary.d.ts +9 -0
- package/dist/ensure-binary.d.ts.map +1 -1
- package/dist/ensure-binary.js +38 -5
- package/dist/ensure-binary.js.map +1 -1
- package/dist/ensure-component-binaries.d.ts.map +1 -1
- package/dist/ensure-component-binaries.js +2 -1
- package/dist/ensure-component-binaries.js.map +1 -1
- package/dist/env-file.d.ts +28 -8
- package/dist/env-file.d.ts.map +1 -1
- package/dist/env-file.js +80 -53
- package/dist/env-file.js.map +1 -1
- package/dist/env-lines.d.ts +11 -0
- package/dist/env-lines.d.ts.map +1 -0
- package/dist/env-lines.js +36 -0
- package/dist/env-lines.js.map +1 -0
- package/dist/error-message.d.ts +34 -1
- package/dist/error-message.d.ts.map +1 -1
- package/dist/error-message.js +102 -2
- package/dist/error-message.js.map +1 -1
- package/dist/fetch-within.d.ts +10 -0
- package/dist/fetch-within.d.ts.map +1 -0
- package/dist/fetch-within.js +12 -0
- package/dist/fetch-within.js.map +1 -0
- package/dist/field-masking-tier.d.ts.map +1 -1
- package/dist/field-masking-tier.js +7 -5
- package/dist/field-masking-tier.js.map +1 -1
- package/dist/functions-context-refresh.d.ts +6 -2
- package/dist/functions-context-refresh.d.ts.map +1 -1
- package/dist/functions-context-refresh.js +11 -3
- package/dist/functions-context-refresh.js.map +1 -1
- package/dist/functions-deno-types.d.ts.map +1 -1
- package/dist/functions-deno-types.js +9 -2
- package/dist/functions-deno-types.js.map +1 -1
- package/dist/{functions-router-gen.d.ts → functions-discovery.d.ts} +8 -10
- package/dist/functions-discovery.d.ts.map +1 -0
- package/dist/functions-discovery.js +87 -0
- package/dist/functions-discovery.js.map +1 -0
- package/dist/functions-template.d.ts.map +1 -1
- package/dist/functions-template.js +20 -12
- package/dist/functions-template.js.map +1 -1
- package/dist/functions-worker-files.d.ts +55 -0
- package/dist/functions-worker-files.d.ts.map +1 -0
- package/dist/functions-worker-files.js +149 -0
- package/dist/functions-worker-files.js.map +1 -0
- package/dist/generated/functions-worker-source.d.ts +2 -0
- package/dist/generated/functions-worker-source.d.ts.map +1 -0
- package/dist/generated/functions-worker-source.js +12 -0
- package/dist/generated/functions-worker-source.js.map +1 -0
- package/dist/generated/release-images.d.ts +18 -0
- package/dist/generated/release-images.d.ts.map +1 -0
- package/dist/generated/release-images.js +8 -0
- package/dist/generated/release-images.js.map +1 -0
- package/dist/generated-files-engine.d.ts +33 -0
- package/dist/generated-files-engine.d.ts.map +1 -0
- package/dist/generated-files-engine.js +45 -0
- package/dist/generated-files-engine.js.map +1 -0
- package/dist/hook-upload.d.ts +29 -15
- package/dist/hook-upload.d.ts.map +1 -1
- package/dist/hook-upload.js +88 -59
- package/dist/hook-upload.js.map +1 -1
- package/dist/hooks-generator.d.ts +5 -0
- package/dist/hooks-generator.d.ts.map +1 -1
- package/dist/hooks-generator.js +7 -2
- package/dist/hooks-generator.js.map +1 -1
- package/dist/host-database.d.ts.map +1 -1
- package/dist/host-database.js +31 -4
- package/dist/host-database.js.map +1 -1
- package/dist/init-dependency-versions.d.ts +3 -1
- package/dist/init-dependency-versions.d.ts.map +1 -1
- package/dist/init-dependency-versions.js +22 -6
- package/dist/init-dependency-versions.js.map +1 -1
- package/dist/init-example.d.ts +48 -0
- package/dist/init-example.d.ts.map +1 -0
- package/dist/init-example.js +110 -0
- package/dist/init-example.js.map +1 -0
- package/dist/init-package-json.d.ts.map +1 -1
- package/dist/init-package-json.js +2 -0
- package/dist/init-package-json.js.map +1 -1
- package/dist/init-setup-steps.d.ts +37 -0
- package/dist/init-setup-steps.d.ts.map +1 -0
- package/dist/init-setup-steps.js +118 -0
- package/dist/init-setup-steps.js.map +1 -0
- package/dist/jwt-secret-length.d.ts +5 -13
- package/dist/jwt-secret-length.d.ts.map +1 -1
- package/dist/jwt-secret-length.js +7 -22
- package/dist/jwt-secret-length.js.map +1 -1
- package/dist/jwt-secret-rules.d.ts +24 -0
- package/dist/jwt-secret-rules.d.ts.map +1 -0
- package/dist/jwt-secret-rules.js +46 -0
- package/dist/jwt-secret-rules.js.map +1 -0
- package/dist/local-gateway.d.ts +3 -6
- package/dist/local-gateway.d.ts.map +1 -1
- package/dist/local-gateway.js +7 -9
- package/dist/local-gateway.js.map +1 -1
- package/dist/local-secrets.d.ts +95 -11
- package/dist/local-secrets.d.ts.map +1 -1
- package/dist/local-secrets.js +153 -18
- package/dist/local-secrets.js.map +1 -1
- package/dist/local-stack.d.ts.map +1 -1
- package/dist/local-stack.js +2 -7
- package/dist/local-stack.js.map +1 -1
- package/dist/local-storage.d.ts +7 -2
- package/dist/local-storage.d.ts.map +1 -1
- package/dist/local-storage.js +11 -3
- package/dist/local-storage.js.map +1 -1
- package/dist/mailer-env.d.ts +37 -0
- package/dist/mailer-env.d.ts.map +1 -0
- package/dist/mailer-env.js +98 -0
- package/dist/mailer-env.js.map +1 -0
- package/dist/model-cache.d.ts +4 -8
- package/dist/model-cache.d.ts.map +1 -1
- package/dist/model-cache.js.map +1 -1
- package/dist/model-hooks.d.ts +17 -7
- package/dist/model-hooks.d.ts.map +1 -1
- package/dist/model-hooks.js +52 -39
- package/dist/model-hooks.js.map +1 -1
- package/dist/native-dev-env.d.ts +37 -1
- package/dist/native-dev-env.d.ts.map +1 -1
- package/dist/native-dev-env.js +64 -2
- package/dist/native-dev-env.js.map +1 -1
- package/dist/native-functions-watch.d.ts +56 -5
- package/dist/native-functions-watch.d.ts.map +1 -1
- package/dist/native-functions-watch.js +119 -38
- package/dist/native-functions-watch.js.map +1 -1
- package/dist/native-keyspace.d.ts.map +1 -1
- package/dist/native-keyspace.js +2 -2
- package/dist/native-keyspace.js.map +1 -1
- package/dist/native-realtime.d.ts +11 -3
- package/dist/native-realtime.d.ts.map +1 -1
- package/dist/native-realtime.js +162 -10
- package/dist/native-realtime.js.map +1 -1
- package/dist/native-roles-sql.d.ts +14 -0
- package/dist/native-roles-sql.d.ts.map +1 -1
- package/dist/native-roles-sql.js +82 -1
- package/dist/native-roles-sql.js.map +1 -1
- package/dist/native-storage-import.d.ts +19 -0
- package/dist/native-storage-import.d.ts.map +1 -0
- package/dist/native-storage-import.js +327 -0
- package/dist/native-storage-import.js.map +1 -0
- package/dist/native-storage.d.ts +45 -0
- package/dist/native-storage.d.ts.map +1 -0
- package/dist/native-storage.js +140 -0
- package/dist/native-storage.js.map +1 -0
- package/dist/native-worker.d.ts +26 -0
- package/dist/native-worker.d.ts.map +1 -0
- package/dist/native-worker.js +63 -0
- package/dist/native-worker.js.map +1 -0
- package/dist/owner-default.d.ts +9 -1
- package/dist/owner-default.d.ts.map +1 -1
- package/dist/owner-default.js +17 -4
- package/dist/owner-default.js.map +1 -1
- package/dist/post-apply.d.ts +3 -0
- package/dist/post-apply.d.ts.map +1 -0
- package/dist/post-apply.js +17 -0
- package/dist/post-apply.js.map +1 -0
- package/dist/postgres-ctl.d.ts +98 -7
- package/dist/postgres-ctl.d.ts.map +1 -1
- package/dist/postgres-ctl.js +273 -40
- package/dist/postgres-ctl.js.map +1 -1
- package/dist/postgres-image.d.ts +15 -3
- package/dist/postgres-image.d.ts.map +1 -1
- package/dist/postgres-image.js +18 -15
- package/dist/postgres-image.js.map +1 -1
- package/dist/postgrest-release.d.ts +9 -0
- package/dist/postgrest-release.d.ts.map +1 -1
- package/dist/postgrest-release.js +23 -0
- package/dist/postgrest-release.js.map +1 -1
- package/dist/process-manager.d.ts.map +1 -1
- package/dist/process-manager.js +3 -1
- package/dist/process-manager.js.map +1 -1
- package/dist/project-config.d.ts +40 -7
- package/dist/project-config.d.ts.map +1 -1
- package/dist/project-config.js +42 -4
- package/dist/project-config.js.map +1 -1
- package/dist/pull-utils.d.ts +15 -0
- package/dist/pull-utils.d.ts.map +1 -1
- package/dist/pull-utils.js +149 -23
- package/dist/pull-utils.js.map +1 -1
- package/dist/push-refusal.d.ts.map +1 -1
- package/dist/push-refusal.js +3 -2
- package/dist/push-refusal.js.map +1 -1
- package/dist/realtime-launch.d.ts +2 -5
- package/dist/realtime-launch.d.ts.map +1 -1
- package/dist/realtime-launch.js +6 -23
- package/dist/realtime-launch.js.map +1 -1
- package/dist/recorded-field-masking-tier.d.ts.map +1 -1
- package/dist/recorded-field-masking-tier.js +4 -3
- package/dist/recorded-field-masking-tier.js.map +1 -1
- package/dist/release-images.d.ts +31 -0
- package/dist/release-images.d.ts.map +1 -0
- package/dist/release-images.js +90 -0
- package/dist/release-images.js.map +1 -0
- package/dist/required-host-components.d.ts.map +1 -1
- package/dist/required-host-components.js +4 -0
- package/dist/required-host-components.js.map +1 -1
- package/dist/resolve-api-url.d.ts +17 -3
- package/dist/resolve-api-url.d.ts.map +1 -1
- package/dist/resolve-api-url.js +71 -30
- package/dist/resolve-api-url.js.map +1 -1
- package/dist/resolve-target.d.ts +62 -0
- package/dist/resolve-target.d.ts.map +1 -1
- package/dist/resolve-target.js +68 -23
- package/dist/resolve-target.js.map +1 -1
- package/dist/rest-ready.d.ts.map +1 -1
- package/dist/rest-ready.js +2 -1
- package/dist/rest-ready.js.map +1 -1
- package/dist/route-manifest.d.ts +25 -2
- package/dist/route-manifest.d.ts.map +1 -1
- package/dist/route-manifest.js +48 -4
- package/dist/route-manifest.js.map +1 -1
- package/dist/run-until-stopped.d.ts +12 -0
- package/dist/run-until-stopped.d.ts.map +1 -0
- package/dist/run-until-stopped.js +42 -0
- package/dist/run-until-stopped.js.map +1 -0
- package/dist/schema-ast-v2.d.ts +2 -1
- package/dist/schema-ast-v2.d.ts.map +1 -1
- package/dist/schema-ast-v2.js.map +1 -1
- package/dist/schema-push-lock.d.ts.map +1 -1
- package/dist/schema-push-lock.js +59 -46
- package/dist/schema-push-lock.js.map +1 -1
- package/dist/schema-sources.d.ts +19 -4
- package/dist/schema-sources.d.ts.map +1 -1
- package/dist/schema-sources.js +56 -35
- package/dist/schema-sources.js.map +1 -1
- package/dist/seed-auth-connect.d.ts +14 -0
- package/dist/seed-auth-connect.d.ts.map +1 -0
- package/dist/seed-auth-connect.js +97 -0
- package/dist/seed-auth-connect.js.map +1 -0
- package/dist/seed-runner.d.ts.map +1 -1
- package/dist/seed-runner.js +22 -1
- package/dist/seed-runner.js.map +1 -1
- package/dist/seed.d.ts +6 -3
- package/dist/seed.d.ts.map +1 -1
- package/dist/self-host-compose.d.ts +32 -30
- package/dist/self-host-compose.d.ts.map +1 -1
- package/dist/self-host-compose.js +252 -152
- package/dist/self-host-compose.js.map +1 -1
- package/dist/service-role-key-file.d.ts +32 -0
- package/dist/service-role-key-file.d.ts.map +1 -0
- package/dist/service-role-key-file.js +90 -0
- package/dist/service-role-key-file.js.map +1 -0
- package/dist/shell-ports.d.ts +13 -2
- package/dist/shell-ports.d.ts.map +1 -1
- package/dist/shell-ports.js +18 -7
- package/dist/shell-ports.js.map +1 -1
- package/dist/stop-signals.d.ts +7 -0
- package/dist/stop-signals.d.ts.map +1 -0
- package/dist/stop-signals.js +12 -0
- package/dist/stop-signals.js.map +1 -0
- package/dist/storage-launch.d.ts +11 -0
- package/dist/storage-launch.d.ts.map +1 -0
- package/dist/storage-launch.js +41 -0
- package/dist/storage-launch.js.map +1 -0
- package/dist/storage-provision.d.ts +50 -5
- package/dist/storage-provision.d.ts.map +1 -1
- package/dist/storage-provision.js +101 -33
- package/dist/storage-provision.js.map +1 -1
- package/dist/systemd.d.ts +1 -1
- package/dist/systemd.d.ts.map +1 -1
- package/dist/systemd.js +26 -11
- package/dist/systemd.js.map +1 -1
- package/dist/tar-reader.d.ts +29 -0
- package/dist/tar-reader.d.ts.map +1 -0
- package/dist/tar-reader.js +99 -0
- package/dist/tar-reader.js.map +1 -0
- package/dist/target-client.d.ts +14 -1
- package/dist/target-client.d.ts.map +1 -1
- package/dist/target-client.js +134 -23
- package/dist/target-client.js.map +1 -1
- package/dist/target-request.d.ts +25 -0
- package/dist/target-request.d.ts.map +1 -0
- package/dist/target-request.js +33 -0
- package/dist/target-request.js.map +1 -0
- package/dist/target-warning.d.ts +7 -0
- package/dist/target-warning.d.ts.map +1 -0
- package/dist/target-warning.js +12 -0
- package/dist/target-warning.js.map +1 -0
- package/dist/type-extractor.d.ts +6 -0
- package/dist/type-extractor.d.ts.map +1 -1
- package/dist/type-extractor.js +118 -59
- package/dist/type-extractor.js.map +1 -1
- package/dist/ui/clack.d.ts.map +1 -1
- package/dist/ui/clack.js +11 -1
- package/dist/ui/clack.js.map +1 -1
- package/dist/ui/dev/DevDashboard.d.ts.map +1 -1
- package/dist/ui/dev/DevDashboard.js +4 -2
- package/dist/ui/dev/DevDashboard.js.map +1 -1
- package/dist/ui/fatal.d.ts.map +1 -1
- package/dist/ui/fatal.js +6 -7
- package/dist/ui/fatal.js.map +1 -1
- package/dist/ui/flows/FlowApp.d.ts.map +1 -1
- package/dist/ui/flows/FlowApp.js +16 -1
- package/dist/ui/flows/FlowApp.js.map +1 -1
- package/dist/ui/flows/prompt-fields.d.ts +5 -0
- package/dist/ui/flows/prompt-fields.d.ts.map +1 -1
- package/dist/ui/flows/prompt-fields.js +8 -1
- package/dist/ui/flows/prompt-fields.js.map +1 -1
- package/dist/ui/messages.d.ts +6 -0
- package/dist/ui/messages.d.ts.map +1 -1
- package/dist/ui/messages.js +17 -0
- package/dist/ui/messages.js.map +1 -1
- package/dist/ui/progress.d.ts +7 -0
- package/dist/ui/progress.d.ts.map +1 -1
- package/dist/ui/progress.js +22 -8
- package/dist/ui/progress.js.map +1 -1
- package/dist/ui/runtime/command-chrome.d.ts.map +1 -1
- package/dist/ui/runtime/command-chrome.js +2 -0
- package/dist/ui/runtime/command-chrome.js.map +1 -1
- package/dist/ui/runtime/prompt-interrupt.d.ts +10 -0
- package/dist/ui/runtime/prompt-interrupt.d.ts.map +1 -0
- package/dist/ui/runtime/prompt-interrupt.js +24 -0
- package/dist/ui/runtime/prompt-interrupt.js.map +1 -0
- package/dist/ui/runtime/run-clack-flow.d.ts.map +1 -1
- package/dist/ui/runtime/run-clack-flow.js +5 -2
- package/dist/ui/runtime/run-clack-flow.js.map +1 -1
- package/dist/ui/runtime/stdin-after-ink.d.ts +14 -1
- package/dist/ui/runtime/stdin-after-ink.d.ts.map +1 -1
- package/dist/ui/runtime/stdin-after-ink.js +44 -3
- package/dist/ui/runtime/stdin-after-ink.js.map +1 -1
- package/dist/url-safe-passwords.d.ts +25 -0
- package/dist/url-safe-passwords.d.ts.map +1 -0
- package/dist/url-safe-passwords.js +70 -0
- package/dist/url-safe-passwords.js.map +1 -0
- package/dist/valkey-sidecar.d.ts +33 -6
- package/dist/valkey-sidecar.d.ts.map +1 -1
- package/dist/valkey-sidecar.js +90 -61
- package/dist/valkey-sidecar.js.map +1 -1
- package/dist/worker-module-files.d.ts +3 -0
- package/dist/worker-module-files.d.ts.map +1 -0
- package/dist/worker-module-files.js +18 -0
- package/dist/worker-module-files.js.map +1 -0
- package/package.json +9 -6
- package/dist/functions-router-gen.d.ts.map +0 -1
- package/dist/functions-router-gen.js +0 -302
- package/dist/functions-router-gen.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"functions-worker-source.d.ts","sourceRoot":"","sources":["../../src/generated/functions-worker-source.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQpE,CAAA"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Generated from packages/functions-worker/*.ts by scripts/functions-worker-source.mjs. Do not
|
|
2
|
+
// edit: the CLI's build regenerates it, and native dev and `functions serve` run these files.
|
|
3
|
+
export const FUNCTIONS_WORKER_SOURCE = {
|
|
4
|
+
"deno.d.ts": "/**\n * Ambient types for IDE / tsserver (runtime is Deno in Docker).\n * Kept in sync with `@supatype/cli` edge-function ambient (`packages/cli/deno.d.ts`).\n */\n\ninterface DenoEnv {\n get(key: string): string | undefined\n set(key: string, value: string): void\n delete(key: string): void\n has(key: string): boolean\n toObject(): { [key: string]: string }\n}\n\ndeclare namespace Deno {\n const env: DenoEnv\n\n namespace errors {\n class NotFound extends Error {}\n class PermissionDenied extends Error {}\n }\n\n interface DirEntry {\n name: string\n isFile: boolean\n isDirectory: boolean\n isSymlink: boolean\n }\n\n interface FileInfo {\n isFile: boolean\n isDirectory: boolean\n isSymlink: boolean\n size: number\n mtime: Date | null\n }\n\n function readDir(path: string): AsyncIterable<DirEntry>\n function stat(path: string): Promise<FileInfo>\n function utime(path: string, atime: Date | number, mtime: Date | number): Promise<void>\n function readTextFile(path: string | URL): Promise<string>\n\n /** What `serve` returns: stopping it (stop.ts) waits for the requests in flight. */\n interface HttpServer {\n /** Stops taking connections; resolves once the requests in flight have finished. */\n shutdown(): Promise<void>\n /** Resolves when the server has closed. */\n readonly finished: Promise<void>\n }\n\n function serve(\n options: { port: number; hostname?: string; onListen?: (params: { hostname: string; port: number }) => void },\n handler: (req: Request) => Response | Promise<Response>,\n ): HttpServer\n\n // What stop.ts uses to exit on a stop signal.\n const build: { readonly os: \"darwin\" | \"linux\" | \"android\" | \"windows\" | \"freebsd\" | \"netbsd\" | \"aix\" | \"solaris\" | \"illumos\" }\n function addSignalListener(signal: \"SIGTERM\" | \"SIGINT\", handler: () => void): void\n function exit(code?: number): never\n\n // What tests/ uses to start the worker as a child process and give it a functions directory.\n function test(name: string, fn: () => void | Promise<void>): void\n function execPath(): string\n function makeTempDir(options?: { prefix?: string }): Promise<string>\n function makeTempFile(options?: { prefix?: string; suffix?: string }): Promise<string>\n function mkdir(path: string, options?: { recursive?: boolean }): Promise<void>\n function writeTextFile(path: string, data: string): Promise<void>\n function remove(path: string, options?: { recursive?: boolean }): Promise<void>\n\n interface CommandOptions {\n args?: string[]\n env?: Record<string, string>\n clearEnv?: boolean\n stdout?: \"piped\" | \"inherit\" | \"null\"\n stderr?: \"piped\" | \"inherit\" | \"null\"\n }\n\n interface ChildProcess {\n readonly stdout: ReadableStream<Uint8Array>\n readonly status: Promise<{ success: boolean; code: number }>\n kill(signal?: \"SIGTERM\" | \"SIGKILL\"): void\n }\n\n class Command {\n constructor(command: string, options?: CommandOptions)\n spawn(): ChildProcess\n }\n}\n\n/**\n * The slice of Node's `async_hooks` the worker uses. Deno provides the module at runtime; tsc has no\n * `@types/node` here, and without this the import resolved to nothing and `store` was untyped.\n */\ndeclare module \"node:async_hooks\" {\n export class AsyncLocalStorage<T> {\n getStore(): T | undefined\n run<R>(store: T, callback: () => R): R\n }\n}\n",
|
|
5
|
+
"dotenv.ts": "// Generated from packages/cli/src/dotenv-parse.ts by scripts/functions-worker-source.mjs. Do not\n// edit: change that file and run the script, so the CLI and the worker read .env files alike.\n/**\n * The dotenv parser: one for every reader of a `.env` file, the CLI's and the functions worker's.\n *\n * No imports and no runtime APIs, so the same file runs under Node and Deno. The functions worker\n * carries an exact copy (packages/functions-worker/dotenv.ts), written from this one by\n * scripts/functions-worker-source.mjs and checked in CI, so a function's `ctx.env` reads a value\n * the way the CLI and compose do.\n */\n\n/** `KEY` and the text after its `=` for an assignment line, or null for anything else. */\nexport function splitAssignment(line: string): { key: string; rest: string } | null {\n const trimmed = line.trim().replace(/^export\\s+/, \"\")\n if (trimmed.startsWith(\"#\")) return null\n const eq = trimmed.indexOf(\"=\")\n if (eq <= 0) return null\n const key = trimmed.slice(0, eq).trim()\n return /^[A-Za-z_][A-Za-z0-9_]*$/.test(key) ? { key, rest: trimmed.slice(eq + 1) } : null\n}\n\n/** Index of the quote closing `value`'s opening one, skipping escaped quotes, or -1. */\nfunction closingQuote(value: string, quote: string): number {\n for (let i = 1; i < value.length; i++) {\n if (value[i] === quote && value[i - 1] !== \"\\\\\") return i\n }\n return -1\n}\n\n/**\n * The value of one assignment, read the way Docker Compose's dotenv parser reads it.\n *\n * A quoted value runs to its closing quote and keeps any `#` inside; text after the quote is\n * ignored. An unquoted value ends at the first space followed by `#`, and trailing whitespace is\n * dropped, so `KEY=x # note` is `x` while `KEY=x#y` is `x#y`. Reading ` # note` into the value\n * signed tokens with a secret the stack, reading the same line through compose, did not have.\n */\nfunction envValueOf(rest: string): string {\n const value = rest.trim()\n const quote = value[0]\n if (quote === '\"' || quote === \"'\") {\n const close = closingQuote(value, quote)\n if (close > 0) return value.slice(1, close)\n }\n const comment = value.indexOf(\" #\")\n return (comment === -1 ? value : value.slice(0, comment)).trimEnd()\n}\n\n/**\n * Parse `.env` text into key/value pairs, the one parser every reader of `.env` goes through.\n *\n * Follows Compose on what it shares with it: `#` comments, an optional `export `, quotes, inline\n * comments, and the last assignment of a key winning. Not interpolation or escape sequences in\n * double quotes, which nothing the CLI writes or reads relies on.\n */\nexport function parseEnvText(text: string): Record<string, string> {\n const out: Record<string, string> = {}\n for (const line of text.split(/\\r?\\n/)) {\n const assignment = splitAssignment(line)\n if (assignment !== null) out[assignment.key] = envValueOf(assignment.rest)\n }\n return out\n}\n",
|
|
6
|
+
"invocation.ts": "import { AsyncLocalStorage } from \"node:async_hooks\"\n\n/**\n * What a function is told about the call it is serving, and the store that carries it.\n *\n * # Why this exists at all\n *\n * The worker used to deliver this through `Deno.env`: it set `SUPATYPE_SERVICE_ROLE_KEY` and the\n * rest before calling the handler and restored them afterwards. `Deno.env` is process-global, so\n * two concurrent invocations would read each other's values, a service-role key granted to one\n * route and not the other among them. The defence was a lock held across the *whole* handler, so the\n * worker executed exactly one invocation at a time.\n *\n * That is a throughput property nobody chose: a function waiting two seconds on a third-party API\n * blocked every other function in the project for two seconds, and on cloud there is one worker per\n * project. It was invisible because `supatype dev` generates a router with the same lock, so local\n * behaved exactly like production.\n *\n * Nothing per-invocation goes into the environment now. It is passed to the handler as a second\n * argument and carried here for the things a handler cannot be handed directly, so there is no\n * global to protect and no reason to serialise.\n *\n * # What is *not* here\n *\n * `SUPATYPE_URL`, `SUPATYPE_ANON_KEY` and the other invariants. Those are set once by compose or by\n * the deployment and never differ between invocations, so they stay in the environment where they\n * already are. The old code read each one out of the environment and set it straight back, which\n * looked like scoping and achieved nothing.\n */\nexport interface FunctionContext {\n /** Unique to this invocation. Every log line it writes carries the same value. */\n readonly executionId: string\n /** The function or hook route being served. */\n readonly functionName: string\n /**\n * The project's API base URL, reachable from inside this container: for calling the API from the\n * function. Under compose it is `http://kong:8000`, a name nothing outside the stack resolves.\n */\n readonly url: string\n /**\n * The project's public address, the gateway URL a browser or an app uses: for links you give to\n * people (an email, a redirect, a URL in a response). Falls back to `url` when the deployment did\n * not set `SUPATYPE_PUBLIC_URL`, and the worker warns once at start when it does.\n */\n readonly publicUrl: string\n readonly anonKey: string\n /**\n * Present only for a route the project granted it.\n *\n * Withheld from the process environment before any handler is imported, so a function that was\n * not granted it cannot reach it by reading `Deno.env` either.\n */\n readonly serviceRoleKey?: string\n /**\n * A raw Postgres connection URL. Off by default: present only when the operator sets\n * `SUPATYPE_FUNCTIONS_DB_URL`, which compose hands this worker as `SUPATYPE_DB_URL` (and joins it\n * to the `functions-db` network when the URL names the stack's `db`).\n *\n * It connects as whatever role the URL names and is not a request through the API, so row rules\n * and field masking do not apply to it. The operator should give it a least-privilege role\n * granted only what the functions need, never the admin URL. A credential: never returned or\n * logged.\n */\n readonly dbUrl?: string\n readonly region: string\n /**\n * Values from the functions directory's `.env.local` (or `SUPATYPE_SHARED_ENV_FILE`), then those\n * `functions env set` gave a self-hosted project (`SUPATYPE_FUNCTION_ENV_FILE`), then\n * `.env.<function>.local`, which wins. Per route, and read again on every call.\n *\n * They are here, never in `Deno.env`: that is the worker's one process environment, shared by\n * every call running at once, so a value put there for one function would reach every other.\n */\n readonly env: Readonly<Record<string, string>>\n}\n\n/** The parts the worker needs internally but a handler has no use for. */\ninterface InvocationStore {\n readonly context: FunctionContext\n /**\n * The hook-depth header to carry onto outbound calls, when this invocation is a hook.\n *\n * Here rather than patched onto `globalThis.fetch` per call. That patch was the second global\n * mutation the lock was protecting: two concurrent hooks would patch over each other, and the\n * first to finish would restore the other's patch.\n */\n readonly hookDepth: string | null\n}\n\nconst store = new AsyncLocalStorage<InvocationStore>()\n\n/** Run an invocation with its context available to everything it calls. */\nexport function runInvocation<T>(\n context: FunctionContext,\n hookDepth: string | null,\n run: () => Promise<T>,\n): Promise<T> {\n return store.run({ context, hookDepth }, run)\n}\n\n/** The invocation being served on this call stack, or undefined outside one. */\nexport function currentInvocation(): FunctionContext | undefined {\n return store.getStore()?.context\n}\n\n/** The hook depth to propagate, or null when this is not a hook call. */\nexport function currentHookDepth(): string | null {\n return store.getStore()?.hookDepth ?? null\n}\n",
|
|
7
|
+
"logging.ts": "import { currentInvocation } from \"./invocation.ts\"\n\n/**\n * Structured invocation logging, and a live tail over it.\n *\n * # Why structured, and why this exact shape\n *\n * The worker used to write `GET /functions/v1/foo → 200 (12ms)` to its own stdout and nothing else.\n * On cloud, `infra/k8s/platform/logging.yaml` runs Promtail into Loki with a pipeline that parses\n * each line as JSON and labels on `project_ref`, `service` and `level`, taking the timestamp from a\n * `timestamp` field in Go's `2006-01-02T15:04:05.000Z` layout. A plain-text line survives none of\n * that: it is collected, matches no expression, and is indexed under no project.\n *\n * So the fields below are not a taste; they are the contract that pipeline already expects.\n * `toISOString()` produces exactly three fractional digits and a `Z`, which is that layout.\n *\n * # Why a tail rather than a store\n *\n * Cloud has Loki, with retention per tier. Self-host has eleven services and no log store, and\n * adding one changes the footprint of every self-hosted deployment, so for release the self-host\n * answer is a live tail: attach, see what happens while attached, detach. Nothing is written down,\n * nothing lands in the project's own Postgres, and no service is added.\n *\n * The ring buffer exists only so that attaching does not start from an empty screen.\n *\n * # Why the context comes from AsyncLocalStorage\n *\n * `console` is global and invocations now genuinely run concurrently, so a captured line has to be\n * attributed to the invocation that wrote it rather than to whichever one happens to be current. A\n * module-level \"current request\" would mis-attribute every interleaved line.\n *\n * The store is `invocation.ts`, shared with the context a handler is passed, so a log line and the\n * function that wrote it cannot disagree about which call they belong to.\n */\n\n/** What every line carries, whether the worker wrote it or a function did. */\nexport interface LogLine {\n timestamp: string\n level: \"debug\" | \"info\" | \"warn\" | \"error\"\n service: \"functions-worker\"\n project_ref: string\n /** The invocation, or absent for a line the worker wrote outside one. */\n request_id?: string\n /** The function or hook route, when there is one. */\n function?: string\n message: string\n /** Present on the line that completes an invocation. */\n duration_ms?: number\n status?: number\n}\n\n/**\n * The real console methods, captured before anything is patched.\n *\n * Emitting through the patched `console` would call the patch again, which is an unbounded\n * recursion that takes the worker down on its first log line.\n */\nconst realConsole = {\n debug: console.debug.bind(console),\n info: console.info.bind(console),\n log: console.log.bind(console),\n warn: console.warn.bind(console),\n error: console.error.bind(console),\n}\n\nfunction projectRef(): string {\n const env = (key: string): string => Deno.env.get(key)?.trim() ?? \"\"\n // Self-host sets the first; cloud's templates use the managed and dedicated spellings. Falling\n // back to \"unknown\" rather than \"\" keeps the Loki label present, since a line with no\n // `project_ref` is indexed under no project and is effectively lost.\n return env(\"SUPATYPE_PROJECT_REF\") || env(\"SUPATYPE_MANAGED_PROJECT_REF\") || env(\"DEDICATED_PROJECT_REF\") || \"unknown\"\n}\n\nconst TAIL_BUFFER_LINES = Math.max(\n 0,\n parseInt(Deno.env.get(\"SUPATYPE_LOG_TAIL_BUFFER\") ?? \"500\", 10) || 500,\n)\n\nconst buffer: LogLine[] = []\nconst subscribers = new Set<(line: LogLine) => void>()\n/** How to end each open tail, so a stopping worker is not held by a stream that never ends. */\nconst openTails = new Set<() => void>()\n\n/** Ends every open tail; a tailing client reconnects to the worker that replaces this one. */\nexport function closeTails(): void {\n for (const close of [...openTails]) close()\n}\n\nfunction record(line: LogLine): void {\n if (TAIL_BUFFER_LINES > 0) {\n buffer.push(line)\n if (buffer.length > TAIL_BUFFER_LINES) buffer.shift()\n }\n for (const send of subscribers) {\n try {\n send(line)\n } catch {\n // A subscriber whose stream has gone is removed when its cancel handler runs. Throwing here\n // would lose the line for everybody else, and drop it from stdout too.\n }\n }\n}\n\n/** Everything except the message, so a caller only has to supply what it knows. */\nfunction baseLine(level: LogLine[\"level\"]): Omit<LogLine, \"message\"> {\n const current = currentInvocation()\n return {\n timestamp: new Date().toISOString(),\n level,\n service: \"functions-worker\",\n project_ref: projectRef(),\n ...(current !== undefined && {\n request_id: current.executionId,\n function: current.functionName,\n }),\n }\n}\n\n/** Write one line as JSON on stdout, and give it to anybody tailing. */\nexport function emit(line: LogLine): void {\n record(line)\n const write = line.level === \"error\" ? realConsole.error : realConsole.log\n write(JSON.stringify(line))\n}\n\n/** A line the worker itself is writing, at this level, inside whatever invocation is current. */\nexport function log(level: LogLine[\"level\"], message: string, extra: Partial<LogLine> = {}): void {\n emit({ ...baseLine(level), message, ...extra })\n}\n\n/**\n * Replace `console` so that a function's own output is structured and attributable.\n *\n * A function author writes `console.log(\"saved\", id)` and expects it to appear. It used to reach the\n * container's stdout unstructured and unlabelled, so on cloud it was dropped by the pipeline and on\n * self-host it was mixed in with every other invocation's output with nothing to tell them apart.\n *\n * Arguments are formatted the way a console does rather than JSON-stringified: `console.error(err)`\n * on an `Error` should say what went wrong, not `{}`.\n */\nexport function installStructuredLogging(): void {\n const levels: Array<[keyof typeof realConsole, LogLine[\"level\"]]> = [\n [\"debug\", \"debug\"],\n [\"info\", \"info\"],\n [\"log\", \"info\"],\n [\"warn\", \"warn\"],\n [\"error\", \"error\"],\n ]\n for (const [method, level] of levels) {\n console[method] = (...args: unknown[]): void => {\n emit({ ...baseLine(level), message: args.map(format).join(\" \") })\n }\n }\n}\n\nfunction format(value: unknown): string {\n if (typeof value === \"string\") return value\n if (value instanceof Error) return value.stack ?? `${value.name}: ${value.message}`\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n // Circular, or a BigInt. Neither is a reason to lose the line.\n return String(value)\n }\n}\n\n/**\n * The live tail, as server-sent events.\n *\n * Replays the buffer first so attaching does not start blank, then streams. `retry` is set so a\n * dropped connection reconnects on its own; a tail that silently stops is worse than no tail.\n */\nexport function tailResponse(): Response {\n const encoder = new TextEncoder()\n let unsubscribe = (): void => {}\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n const send = (line: LogLine): void => {\n controller.enqueue(encoder.encode(`data: ${JSON.stringify(line)}\\n\\n`))\n }\n controller.enqueue(encoder.encode(\"retry: 2000\\n\\n\"))\n for (const line of buffer) send(line)\n\n const close = (): void => {\n unsubscribe()\n controller.close()\n }\n subscribers.add(send)\n openTails.add(close)\n unsubscribe = () => {\n subscribers.delete(send)\n openTails.delete(close)\n }\n },\n cancel() {\n unsubscribe()\n },\n })\n\n return new Response(stream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n // Nothing between here and the reader may buffer a stream whose whole purpose is to arrive as\n // it happens.\n \"X-Accel-Buffering\": \"no\",\n },\n })\n}\n\n/** For tests: what is currently in the replay buffer. */\nexport function bufferedLines(): readonly LogLine[] {\n return buffer\n}\n",
|
|
8
|
+
"main.ts": "/**\n * Standalone edge-functions worker (per-project or per-function).\n * The image runs it, and so do native `supatype dev` and `supatype functions serve`, from the copy\n * the CLI carries (scripts/functions-worker-source.mjs), so a function behaves the same in each.\n */\n\nimport { parseEnvText } from \"./dotenv.ts\"\nimport { FUNCTION_ENTRY_FILE, functionRouteName, isHookName } from \"./routes.ts\"\nimport { exitOnStop } from \"./stop.ts\"\nimport {\n currentHookDepth,\n runInvocation,\n type FunctionContext,\n} from \"./invocation.ts\"\nimport {\n closeTails,\n installStructuredLogging,\n log,\n tailResponse,\n} from \"./logging.ts\"\n\ninstallStructuredLogging()\n// Once, at startup. Hook depth then comes from the invocation store rather than from a patch\n// applied and reverted around every call.\ninstallHookDepthPropagation()\n\n/**\n * Route names the worker answers itself.\n *\n * Underscore-prefixed, the convention Deno Deploy and Supabase both use, so a reserved route cannot\n * collide with a function somebody has already deployed. Discovery warns if one is shadowed rather\n * than silently winning.\n */\nconst RESERVED_ROUTES = new Set([\"_logs\"])\n\ntype Handler = (req: Request, ctx: FunctionContext) => Response | Promise<Response>\n\ninterface DiscoveredRoute {\n name: string\n entrypoint: string\n}\n\n/**\n * Root for public functions, or \"\" when this worker serves none.\n *\n * Empty is a real configuration, not a mistake: a per-hook worker mounts a hooks root and nothing else,\n * and its pod has no functions directory to point at. Requiring this one made such a pod crashloop,\n * which the API server sees as the hook refusing to answer, failing every write to its table. Startup\n * still fails when *both* roots are empty, since a worker with no source at all is a misconfiguration.\n */\nfunction functionsRoot(): string {\n const root = (\n Deno.env.get(\"SUPATYPE_FUNCTIONS_ROOT\") ??\n Deno.env.get(\"SUPATYPE_DENO_FUNCTIONS_DIR\") ??\n \"\"\n ).trim()\n if (!root) return \"\"\n return root.endsWith(\"/\") ? root.slice(0, -1) : root\n}\n\n/**\n * Root for **model hooks**, served under a `hooks/` route prefix.\n *\n * Hooks are procedural: the API server calls them around a write, while everything under the\n * functions root is a public endpoint anyone holding the anon key can invoke. Keeping them in one\n * worker rather than two costs a project no extra pod; keeping them under a route prefix is what lets\n * the gateway refuse them from outside, so the separation is structural rather than a deny-list that\n * a stale manifest could empty.\n */\nfunction hooksRoot(): string {\n const root = (Deno.env.get(\"SUPATYPE_HOOKS_ROOT\") ?? \"\").trim()\n if (!root) return \"\"\n return root.endsWith(\"/\") ? root.slice(0, -1) : root\n}\n\n/** Route prefix for hook handlers. The gateway refuses this prefix on the public path. */\nconst HOOKS_ROUTE_PREFIX = \"hooks/\"\n\n/** A comma-separated route list as a set, empty entries dropped. */\nfunction parseRoutes(text: string): Set<string> {\n return new Set(\n text\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0),\n )\n}\n\n/** The routes file as last read: kept while its modification time and size are unchanged. */\nlet routesFileRead: { mtime: number; size: number; routes: Set<string> } | null = null\n\n/**\n * The routes in `file`, read again only when its modification time or size changed: one stat a\n * call. Undefined when it has not been written (the environment's list applies); none when it is\n * there but cannot be read.\n */\nasync function routesFromFile(file: string): Promise<Set<string> | undefined> {\n let info: Deno.FileInfo\n try {\n info = await Deno.stat(file)\n } catch (err) {\n return err instanceof Deno.errors.NotFound ? undefined : new Set()\n }\n const mtime = info.mtime?.getTime() ?? -1\n if (routesFileRead !== null && routesFileRead.mtime === mtime && routesFileRead.size === info.size) return routesFileRead.routes\n try {\n routesFileRead = { mtime, size: info.size, routes: parseRoutes(await Deno.readTextFile(file)) }\n } catch {\n routesFileRead = null\n return new Set()\n }\n return routesFileRead.routes\n}\n\n/**\n * Public function routes allowed to see `SUPATYPE_SERVICE_ROLE_KEY`, looked up on every call: from\n * the file `SUPATYPE_SERVICE_ROLE_ROUTES_FILE` names once it is written, else\n * `SUPATYPE_SERVICE_ROLE_ROUTES`. Native dev writes the file when `functions.serviceRole` changes,\n * and a self-hosted control plane on every deploy, so a route taken off the list loses the key on its\n * next call, with no restart; the environment is fixed when the worker starts. A routes file that is\n * there but cannot be read grants nothing.\n *\n * Hooks do not appear here: they get the key by default (see serviceRoleGranted). This list is for\n * the public surface, where the default is nothing.\n */\nasync function serviceRoleRoutes(): Promise<Set<string>> {\n const file = Deno.env.get(\"SUPATYPE_SERVICE_ROLE_ROUTES_FILE\")\n const fromFile = file ? await routesFromFile(file) : undefined\n return fromFile ?? parseRoutes(Deno.env.get(\"SUPATYPE_SERVICE_ROLE_ROUTES\") ?? \"\")\n}\n\n/** The function every entry of a hook or validator map names (table, then event or column, then the entry). */\nfunction functionsNamed(map: unknown): string[] {\n if (typeof map !== \"object\" || map === null) return []\n return Object.values(map).flatMap((entries: unknown) =>\n typeof entries !== \"object\" || entries === null\n ? []\n : Object.values(entries).flatMap((entry: unknown) =>\n typeof entry === \"object\" && entry !== null && \"function\" in entry && typeof entry.function === \"string\" ? [entry.function] : [],\n ),\n )\n}\n\n/**\n * The hooks the stack's manifest maps (its `hooks` and `validators`), from the file\n * `SUPATYPE_MANIFEST_PATH` names, the one the server reads; read on each call, which only a hook\n * route with no code makes. Null when no manifest is named (Cloud's worker), or the one named cannot\n * be read or parsed (caught mid-rewrite, say): the caller then fails closed.\n */\nasync function mappedHookNames(): Promise<Set<string> | null> {\n const path = (Deno.env.get(\"SUPATYPE_MANIFEST_PATH\") ?? \"\").trim()\n if (!path) return null\n let parsed: unknown\n try {\n parsed = JSON.parse(await Deno.readTextFile(path))\n } catch {\n return null\n }\n if (typeof parsed !== \"object\" || parsed === null) return null\n const maps = [\"hooks\" in parsed ? parsed.hooks : undefined, \"validators\" in parsed ? parsed.validators : undefined]\n return new Set(maps.flatMap(functionsNamed))\n}\n\n/**\n * Whether a hook route the worker has no code for answers 503 (the hook cannot be reached, and the\n * server refuses the write for it) rather than 404 (no such hook). With the manifest's map, only a\n * name it maps. Without one, every name that passes the hook-name rule: it fails closed, since a 404\n * is read by the server as the hook rejecting the write.\n */\nasync function unreachableHook(name: string): Promise<boolean> {\n const mapped = await mappedHookNames()\n if (mapped !== null) return mapped.has(name)\n return isHookName(name)\n}\n\n/**\n * Whether a route may see the service-role key.\n *\n * **Hooks: yes.** A hook is procedural, only the API server calls it, around a write the caller was\n * already permitted to make, and the gateway refuses its route from outside, so it is not reachable\n * by anyone who could choose to invoke it. Requiring each one to be listed would be friction with no\n * attacker to stop, and it is the same trust a trigger or a migration already has.\n *\n * **Public functions: only if named.** Those *are* invocable by anyone holding the anon key, so an\n * ambient admin credential there is read and write access past every access rule in the schema,\n * handed to code the internet can call.\n */\nasync function serviceRoleGranted(route: string): Promise<boolean> {\n if (route.startsWith(HOOKS_ROUTE_PREFIX)) return true\n return (await serviceRoleRoutes()).has(route)\n}\n\n/**\n * Take the service-role key out of the process environment, returning it for scoped re-injection.\n *\n * **Before handlers are imported**, which is the whole point: a handler's module body runs at import\n * time, so a key still in `Deno.env` then is a key any handler can copy and keep. Withholding it\n * afterwards would be theatre.\n *\n * The default is now \"no admin credential\". A function is a public endpoint, anyone holding the anon\n * key can invoke one, and an ambient service-role key made every one of them able to read and write\n * past every access rule in the schema. Opting in is a line in `supatype.config.ts`, which is\n * reviewable; ambient privilege is not.\n */\nasync function withholdServiceRoleKey(): Promise<string> {\n const key = Deno.env.get(\"SUPATYPE_SERVICE_ROLE_KEY\") ?? \"\"\n if (key) Deno.env.delete(\"SUPATYPE_SERVICE_ROLE_KEY\")\n const keyFile = (Deno.env.get(\"SUPATYPE_SERVICE_ROLE_KEY_FILE\") ?? \"\").trim()\n return keyFile ? await readServiceRoleKeyFile(keyFile) : key\n}\n\n/**\n * The service-role key from `path`, or \"\" (no function is given it) when the file cannot be read.\n *\n * For a worker run under `deno run --watch`, as native `supatype dev` and `supatype functions serve`\n * run it. A reload evaluates this module again in the same process, whose environment the first\n * evaluation already took the key out of, so a key from the environment is there once only. The\n * file is still there however the earlier evaluation ended. Its path stays in the environment: a\n * function able to read the disk can read the file whether or not it is told where it is, and the\n * key a function is handed is still decided by serviceRoleGranted alone.\n */\nasync function readServiceRoleKeyFile(path: string): Promise<string> {\n try {\n return (await Deno.readTextFile(path)).trim()\n } catch (err) {\n log(\"error\", `No function is given the service-role key: could not read ${path} (${errorText(err)})`)\n return \"\"\n }\n}\n\nasync function discoverRoutes(root: string): Promise<DiscoveredRoute[]> {\n const single = Deno.env.get(\"SUPATYPE_FUNCTION_NAME\")?.trim()\n const out: DiscoveredRoute[] = []\n\n // The catch has to wrap the *iteration*: `Deno.readDir` returns its iterable without touching the\n // filesystem, so a missing directory raises NotFound on the first `next()`, not here. A root that\n // does not exist is ordinary, a project with functions but no hooks has no hooks directory, and\n // letting it throw would fail startup and take that project's working functions down with it.\n try {\n // routes.ts is the rule a self-hosted control plane lists functions by too.\n for await (const entry of Deno.readDir(root)) {\n const fullPath = `${root}/${entry.name}`\n const name = entry.isDirectory || entry.isFile ? functionRouteName(entry.name, entry.isDirectory ? \"directory\" : \"file\") : undefined\n if (name === undefined || (single && name !== single)) continue\n const entrypoint = entry.isDirectory ? `${fullPath}/${FUNCTION_ENTRY_FILE}` : fullPath\n try {\n await Deno.stat(entrypoint)\n out.push({ name, entrypoint })\n } catch {\n // A directory with no entry module is not a route.\n }\n }\n } catch (err) {\n if (!(err instanceof Deno.errors.NotFound)) throw err\n }\n\n return out.sort((a, b) => a.name.localeCompare(b.name))\n}\n\nfunction entrypointImportUrl(entrypoint: string): string {\n const normalized = entrypoint.replace(/\\\\/g, \"/\")\n if (normalized.startsWith(\"file://\")) return normalized\n // A Windows absolute path is not a URL: `new URL(\"C:/x\")` reads the drive letter as the scheme, and\n // Deno then refuses to import scheme \"c\". Invisible in a Linux container, where every root starts\n // with \"/\", and fatal the moment this worker runs on a developer's machine.\n if (/^[A-Za-z]:\\//.test(normalized)) return `file:///${normalized}`\n if (normalized.startsWith(\"/\")) return `file://${normalized}`\n return new URL(normalized, import.meta.url).href\n}\n\n/**\n * A function's exported handler. A boundary: what can be checked is that it is a function; what it\n * takes and returns is the function author's contract with the worker, which only calling it tests.\n */\nfunction isHandler(value: unknown): value is Handler {\n return typeof value === \"function\"\n}\n\n/** The module's `default` export, else its `handler` export. */\nfunction exportedHandler(mod: unknown): unknown {\n if (typeof mod !== \"object\" || mod === null) return undefined\n const fallback = \"handler\" in mod ? mod.handler : undefined\n return (\"default\" in mod ? mod.default : undefined) ?? fallback\n}\n\nasync function loadHandlers(routes: DiscoveredRoute[]): Promise<Record<string, Handler>> {\n const handlers: Record<string, Handler> = {}\n\n for (const route of routes) {\n // The reserved route wins, because the worker answers it before the handler lookup. Say so\n // rather than leaving an author wondering why their function returns an event stream.\n if (RESERVED_ROUTES.has(route.name)) {\n log(\"warn\", `Function \"${route.name}\" is shadowed: the worker reserves that route`, {\n function: route.name,\n })\n continue\n }\n handlers[route.name] = await loadHandler(route)\n }\n\n return handlers\n}\n\n/**\n * The route's handler, or, when its module fails to import or exports no handler, one that answers\n * the route with a 500 saying why. The first such module used to stop the worker starting, so one\n * broken function took every function in the project down with it. The message goes out as JSON,\n * so the escape codes come out of it: a client has no terminal to colour.\n */\nasync function loadHandler(route: DiscoveredRoute): Promise<Handler> {\n try {\n // A module loaded by URL is typed `any`; read its exports as unknown until checked.\n const mod: unknown = await import(entrypointImportUrl(route.entrypoint))\n const handler = exportedHandler(mod)\n if (!isHandler(handler)) throw new Error('it has neither a default export nor a named \"handler\" export')\n return handler\n } catch (err) {\n const message = `Function \"${route.name}\" failed to load: ${errorText(err)}`\n log(\"error\", message, { function: route.name })\n return () => jsonError(\"function_load_failed\", message, 500)\n }\n}\n\n/**\n * Terminal escape codes. Deno colours a missing module's location in its message, piped or not,\n * and a handler's own error can carry them too.\n */\nconst TERMINAL_ESCAPES = /\\u001b\\[[0-9;?]*[A-Za-z]/g\n\n/**\n * What a thrown value says: an Error's message, anything else as a string, without escape codes,\n * since it goes out as JSON and a client has no terminal to colour.\n */\nfunction errorText(err: unknown): string {\n return (err instanceof Error ? err.message : String(err)).replace(TERMINAL_ESCAPES, \"\")\n}\n\n/** A JSON error answer, `{ error: code, message, ...extra }`, as every route of the worker gives one. */\nfunction jsonError(code: string, message: string, status: number, extra: Record<string, unknown> = {}): Response {\n return new Response(JSON.stringify({ error: code, message, ...extra }), {\n status,\n headers: { \"Content-Type\": \"application/json\" },\n })\n}\n\nconst port = parseInt(Deno.env.get(\"PORT\") ?? \"8001\", 10)\n// Order matters: withhold, then import. See withholdServiceRoleKey.\nconst serviceRoleKey = await withholdServiceRoleKey()\nconst root = functionsRoot()\nconst routes = root ? await discoverRoutes(root) : []\nconst handlers = await loadHandlers(routes)\n\n// Hooks are namespaced so one worker can serve both without a name in `hooks/` ever shadowing, or\n// being reachable as: a public function of the same name.\nconst hooksDir = hooksRoot()\nif (!root && !hooksDir) {\n throw new Error(\n \"SUPATYPE_FUNCTIONS_ROOT or SUPATYPE_HOOKS_ROOT is required (a worker with neither serves nothing)\",\n )\n}\nif (hooksDir) {\n const hookRoutes = await discoverRoutes(hooksDir)\n const hookHandlers = await loadHandlers(hookRoutes)\n for (const [name, handler] of Object.entries(hookHandlers)) {\n handlers[HOOKS_ROUTE_PREFIX + name] = handler\n }\n}\n\n// A worker pinned to one route still has to find it, and with two roots \"absent from this one\" is not\n// \"absent everywhere\": a per-hook pod names its hook and has no functions directory at all. Checked\n// once, after both roots, so the failure means what it says, and it stays a failure, because a pod\n// serving nothing would answer 404 to the API server, which reads as the hook refusing to answer and\n// fails every write to its table.\nconst single = Deno.env.get(\"SUPATYPE_FUNCTION_NAME\")?.trim()\nif (single && Object.keys(handlers).length === 0) {\n throw new Error(\n `Handler \"${single}\" not found under ${root}` + (hooksDir ? ` or ${hooksDir}` : \"\"),\n )\n}\n\nconsole.log(\n `[functions-worker] ${Object.keys(handlers).length} handler(s) on :${port}` +\n (Deno.env.get(\"SUPATYPE_FUNCTION_NAME\") ? ` (single: ${Deno.env.get(\"SUPATYPE_FUNCTION_NAME\")})` : \"\"),\n)\n\n// Falls back to the hooks root: a per-hook worker has no functions directory, and the shared env file\n// is looked for beside whichever source this worker actually has.\nconst normalizedFunctionsDir = root || hooksDir\nconst sharedEnvPath =\n Deno.env.get(\"SUPATYPE_SHARED_ENV_FILE\") ?? `${normalizedFunctionsDir}/.env.local`\n\n\n\n/** The variables in the env file at `path`, read as the CLI and compose read one; none if it is absent. */\nasync function readEnvFile(path: string): Promise<Record<string, string>> {\n if (!path) return {}\n try {\n return parseEnvText(await Deno.readTextFile(path))\n } catch {\n return {}\n }\n}\n\n/**\n * The values `functions env set` gave a self-hosted project: the control plane's JSON map, which\n * compose names here. Without it a value set through the control plane never reached a function.\n * Read on every call, like the env files, so a set or unset is seen without a restart.\n */\nconst managedEnvPath = (Deno.env.get(\"SUPATYPE_FUNCTION_ENV_FILE\") ?? \"\").trim()\n\nasync function readManagedEnv(): Promise<Record<string, string>> {\n if (!managedEnvPath) return {}\n let parsed: unknown\n try {\n parsed = JSON.parse(await Deno.readTextFile(managedEnvPath))\n } catch {\n return {}\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return {}\n return Object.fromEntries(Object.entries(parsed).filter((entry): entry is [string, string] => typeof entry[1] === \"string\"))\n}\n\n/**\n * The shared env file, then the managed values, then the function's own file, which wins. The three\n * are read together: every call waits for them.\n */\nasync function scopedEnvForFunction(fnName: string): Promise<Record<string, string>> {\n const [shared, managed, fnVars] = await Promise.all([\n readEnvFile(sharedEnvPath),\n readManagedEnv(),\n readEnvFile(`${normalizedFunctionsDir}/.env.${fnName}.local`),\n ])\n return { ...shared, ...managed, ...fnVars }\n}\n\nconst HOOK_DEPTH_HEADER = \"x-supatype-hook-depth\"\n\n/**\n * Carry the hook-depth header onto calls a hook makes back into the stack.\n *\n * Patched once, at startup, rather than per invocation. The old version replaced `globalThis.fetch`\n * for the duration of a call and restored it afterwards, which is only safe while exactly one\n * invocation runs at a time: two concurrent hooks would patch over each other, and the first to\n * finish would restore the other's patch. That mutation was half the reason for the lock.\n *\n * Depth comes from the invocation store, so this closure holds no per-call state at all.\n */\nfunction installHookDepthPropagation(): void {\n const original = globalThis.fetch\n globalThis.fetch = (input: Request | URL | string, init?: RequestInit): Promise<Response> => {\n const depth = currentHookDepth()\n const stack = stackOrigin()\n if (depth === null || stack === null) return original(input, init)\n\n const url = input instanceof Request ? input.url : String(input)\n if (!url.startsWith(stack)) return original(input, init)\n\n const request = new Request(input, init)\n request.headers.set(HOOK_DEPTH_HEADER, depth)\n return original(request)\n }\n}\n\n/**\n * The database URL a function may use, when the deployment gave the worker one: off unless the\n * operator set SUPATYPE_FUNCTIONS_DB_URL (see `FunctionContext.dbUrl`).\n */\nfunction dbUrlForFunctions(): string | undefined {\n const raw = Deno.env.get(\"SUPATYPE_DB_URL\") ?? Deno.env.get(\"DATABASE_URL\")\n return raw === undefined || raw.trim() === \"\" ? undefined : raw\n}\n\n/** The stack's own origin, or null when this worker was not told how to reach it. */\nfunction stackOrigin(): string | null {\n const raw = Deno.env.get(\"SUPATYPE_INTERNAL_URL\") ?? Deno.env.get(\"SUPATYPE_URL\")\n if (raw === undefined || raw.trim() === \"\") return null\n try {\n return new URL(raw).origin\n } catch {\n return null\n }\n}\n\n/**\n * The project's public address, handed to every function as `ctx.publicUrl` (see FunctionContext).\n *\n * Read once, at start: it never differs between invocations, and a deployment that left it unset\n * should be told once rather than on every call. The fallback is `ctx.url`, which under compose is\n * an in-stack name, so a link built from it would reach nobody; the warning says so.\n */\nfunction resolvePublicUrl(): string {\n const configured = (Deno.env.get(\"SUPATYPE_PUBLIC_URL\") ?? \"\").trim()\n if (configured !== \"\") return configured\n const internal = Deno.env.get(\"SUPATYPE_URL\") ?? \"\"\n log(\n \"warn\",\n \"SUPATYPE_PUBLIC_URL is not set, so ctx.publicUrl falls back to ctx.url \" +\n `(${internal || \"unset\"}), which may be an address only this stack can reach`,\n )\n return internal\n}\n\nconst publicUrl = resolvePublicUrl()\n\n\n// `onListen` is supplied so Deno does not print its own \"Listening on …\" line. That line goes to\n// stderr, which this worker's patched console reports as `level: \"error\"`, and on cloud `level` is\n// a Loki label, so every startup would appear in the dashboards as an error.\n// Every address in its container; `functions serve` and native dev name 127.0.0.1.\nconst hostname = Deno.env.get(\"SUPATYPE_FUNCTIONS_HOST\") ?? \"0.0.0.0\"\nconst server = Deno.serve({\n hostname,\n port,\n onListen: ({ hostname, port: bound }) => {\n log(\"info\", `functions-worker listening on http://${hostname}:${bound}`)\n },\n}, async (req: Request): Promise<Response> => {\n const url = new URL(req.url)\n const pathParts = url.pathname.replace(/^\\/functions\\/v1\\/?/, \"\").split(\"/\").filter(Boolean)\n // A hook is addressed as `hooks/<name>`, so the first segment alone is not the handler key. With no\n // second segment no hook name is built: the path is looked up as the plain route \"hooks\", a 404\n // unless a function has that name, so `hooks/<name>` always carries a name the request sent.\n const fnName =\n pathParts[0] === \"hooks\" && pathParts[1]\n ? HOOKS_ROUTE_PREFIX + pathParts[1]\n : pathParts[0] ?? \"\"\n\n // Answered by the worker itself, before the handler lookup, so a project with no functions at all\n // still has a tail.\n if (RESERVED_ROUTES.has(fnName)) {\n if (fnName === \"_logs\") return tailResponse()\n }\n\n // A hook the map names with no code here (a new hook whose deploy failed) cannot be reached: 503,\n // which the server's hook dispatch treats as unavailable and refuses the write for. A 404 read as\n // the hook rejecting the write, with a \"not found\" message. Any other name stays a 404\n // (unreachableHook).\n if (fnName.startsWith(HOOKS_ROUTE_PREFIX) && !handlers[fnName]) {\n const hook = fnName.slice(HOOKS_ROUTE_PREFIX.length)\n if (await unreachableHook(hook)) return jsonError(\"hook_unavailable\", `Hook \"${hook}\" is not deployed`, 503)\n }\n if (!fnName || !handlers[fnName]) {\n const message = fnName ? `Function \"${fnName}\" not found` : \"No function specified\"\n return jsonError(\"not_found\", message, 404, { available: Object.keys(handlers) })\n }\n\n // Nothing goes into the process environment, so nothing has to be taken back out and nothing has\n // to be serialised. This used to hold a lock across the whole handler, which meant the worker ran\n // one invocation at a time: a function waiting on a third-party API blocked every other function\n // in the project for as long as it waited.\n const dbUrl = dbUrlForFunctions()\n const context: FunctionContext = {\n executionId: crypto.randomUUID(),\n functionName: fnName,\n url: Deno.env.get(\"SUPATYPE_URL\") ?? \"\",\n publicUrl,\n anonKey: Deno.env.get(\"SUPATYPE_ANON_KEY\") ?? \"\",\n // From the closure, not the environment: the key was withheld before any handler was imported,\n // and only a route the project granted it receives it here.\n ...(serviceRoleKey && (await serviceRoleGranted(fnName)) && { serviceRoleKey }),\n ...(dbUrl !== undefined && { dbUrl }),\n region: Deno.env.get(\"SUPATYPE_REGION\") ?? \"local\",\n env: await scopedEnvForFunction(fnName),\n }\n\n const start = performance.now()\n\n try {\n const response = await runInvocation(context, req.headers.get(HOOK_DEPTH_HEADER), async () =>\n handlers[fnName]!(req, context),\n )\n log(\"info\", `${req.method} /functions/v1/${fnName} → ${response.status}`, {\n request_id: context.executionId,\n function: fnName,\n status: response.status,\n duration_ms: Number((performance.now() - start).toFixed(1)),\n })\n return response\n } catch (err) {\n const message = errorText(err)\n log(\"error\", message, {\n request_id: context.executionId,\n function: fnName,\n status: 500,\n duration_ms: Number((performance.now() - start).toFixed(1)),\n })\n return jsonError(\"function_error\", message, 500)\n }\n})\n// A restart of its container waited out the stop timeout without this, and must not cut off the\n// requests in flight (stop.ts). A log tail never ends on its own, so it is closed first.\nexitOnStop(() => {\n closeTails()\n return server.shutdown()\n})\n",
|
|
9
|
+
"routes.ts": "// Generated from packages/shared/src/function-routes.ts by scripts/functions-worker-source.mjs. Do\n// not edit: change that file and run the script, so the worker and the control plane agree.\n/**\n * Which entries of a functions or hooks directory the functions worker serves, and by what route\n * name. The worker discovers its routes by this rule and a self-hosted control plane lists them by\n * it, so the list names exactly what answers. The worker cannot import this package: the generator\n * (scripts/functions-worker-source.mjs) copies this file into it as routes.ts, so it must import\n * nothing.\n */\n\n/** The module a directory route runs; a directory without one is not a route. */\nexport const FUNCTION_ENTRY_FILE = \"index.ts\"\n\n/**\n * The route the worker serves for `entry`, or undefined for an entry it skips. `_` and `.` prefixed\n * entries are never routes (`_shared`, `.git`). A directory is the route of its name, when it holds\n * {@link FUNCTION_ENTRY_FILE}, which the caller checks. A file is the route of its name without\n * `.ts`; a declaration file (`.d.ts`) and anything else is not one.\n */\nexport function functionRouteName(entry: string, kind: \"directory\" | \"file\"): string | undefined {\n if (entry.startsWith(\"_\") || entry.startsWith(\".\")) return undefined\n if (kind === \"directory\") return entry\n return entry.endsWith(\".ts\") && !entry.endsWith(\".d.ts\") ? entry.slice(0, -\".ts\".length) : undefined\n}\n\n/**\n * A hook name: letters of either case, digits, `-` and `_`, starting with a letter or digit. Wider\n * than a function name, because the CLI and Cloud take a hook's name from the schema and its folder\n * as written (`onUserCreate`): Cloud stores it as a ConfigMap key, and the worker skips a name that\n * starts with `_` or `.`. Still one path segment: nothing in it can name a parent, a separator or a\n * hidden entry.\n */\nexport const HOOK_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/\n\n/** The hook rule, said for a person. */\nexport const HOOK_NAME_RULE = 'use letters, digits, \"-\" and \"_\", starting with a letter or digit'\n\n/** Whether `name` passes the hook-name rule. */\nexport function isHookName(name: unknown): name is string {\n return typeof name === \"string\" && HOOK_NAME.test(name)\n}\n",
|
|
10
|
+
"stop.ts": "/**\n * The worker stops when it is told to. In its container it runs as PID 1, and PID 1 gets no default\n * action for SIGTERM or SIGINT: with no handler, `docker restart` and `docker stop` waited out the\n * whole stop timeout (10 s) before killing it, so every self-host deploy that restarted the worker\n * took more than ten seconds. The compose file also gives it an init (`init: true`).\n *\n * On SIGTERM it does not exit mid-request: a deploy restarts the worker, and exiting at once cut off\n * every invocation in flight. It stops taking requests, lets those it has finish, then exits; bounded\n * by {@link drainGraceMs}. SIGINT (Ctrl+C in dev or `functions serve`) and a second signal while\n * draining exit at once: someone at a terminal is not kept waiting.\n */\n\n/**\n * How long in-flight requests get to finish when nothing says otherwise: under the 5 s the dev\n * process manager waits before it kills the worker, so a stop in dev is never slower than a kill.\n */\nexport const DRAIN_GRACE_MS = 4_000\n\n/** The longest drain the environment may ask for; more would outlast any stop timeout in use. */\nexport const MAX_DRAIN_GRACE_MS = 60_000\n\n/**\n * The drain grace `SUPATYPE_FUNCTIONS_DRAIN_MS` asks for, in whole milliseconds, capped at\n * {@link MAX_DRAIN_GRACE_MS}; {@link DRAIN_GRACE_MS} when it is unset or not a whole number. The\n * self-host compose sets it under its stop_grace_period: there Docker allows 10 s, and a 4 s drain\n * cut off every function with more left at each restart (round 6b, N29).\n */\nexport function drainGraceMs(value: string | undefined): number {\n const text = value?.trim() ?? \"\"\n if (!/^\\d+$/.test(text)) return DRAIN_GRACE_MS\n return Math.min(Number(text), MAX_DRAIN_GRACE_MS)\n}\n\n/** What stopping needs of Deno, replaceable in tests. */\nexport interface StopHooks {\n os: string\n addSignalListener(signal: \"SIGTERM\" | \"SIGINT\", handler: () => void): void\n exit(code: number): void\n}\n\nconst DENO_HOOKS: StopHooks = {\n os: Deno.build.os,\n addSignalListener: (signal, handler) => Deno.addSignalListener(signal, handler),\n exit: (code) => Deno.exit(code),\n}\n\n/** `drain()`, or `graceMs`, whichever ends first; the timer is cleared either way. */\nasync function drainWithin(drain: () => Promise<void>, graceMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const grace = new Promise<void>((done) => (timer = setTimeout(done, graceMs)))\n try {\n await Promise.race([drain().catch(() => undefined), grace])\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * On SIGTERM, drains with `drain` (closing the log tails and the server's `shutdown()`, which stops\n * taking requests and resolves once those in flight have finished) for at most `graceMs`, then exits\n * 0. SIGINT, and any signal while draining, exits at once. Not on Windows, where Deno takes no SIGTERM\n * listener and a process is stopped some other way.\n */\nexport function exitOnStop(\n drain: () => Promise<void>,\n hooks: StopHooks = DENO_HOOKS,\n graceMs = drainGraceMs(Deno.env.get(\"SUPATYPE_FUNCTIONS_DRAIN_MS\")),\n): void {\n if (hooks.os === \"windows\") return\n let draining = false\n const exitNow = (): void => hooks.exit(0)\n hooks.addSignalListener(\"SIGINT\", exitNow)\n hooks.addSignalListener(\"SIGTERM\", () => {\n if (draining) return exitNow()\n draining = true\n void drainWithin(drain, graceMs).then(exitNow)\n })\n}\n",
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=functions-worker-source.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"functions-worker-source.js","sourceRoot":"","sources":["../../src/generated/functions-worker-source.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,8FAA8F;AAC9F,MAAM,CAAC,MAAM,uBAAuB,GAAqC;IACvE,WAAW,EAAE,62GAA62G;IAC13G,WAAW,EAAE,m4FAAm4F;IACh5F,eAAe,EAAE,0iKAA0iK;IAC3jK,YAAY,EAAE,+iQAA+iQ;IAC7jQ,SAAS,EAAE,69zBAA69zB;IACx+zB,WAAW,EAAE,ovEAAovE;IACjwE,SAAS,EAAE,w5GAAw5G;CACp6G,CAAA"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare const PINNED_IMAGES: {
|
|
2
|
+
readonly engine: {
|
|
3
|
+
readonly image: "supatype/schema-engine";
|
|
4
|
+
readonly tag: "v0.8.0";
|
|
5
|
+
readonly commit: "878b4980e53dfd959ad65eecf9df4224f4d611d6";
|
|
6
|
+
};
|
|
7
|
+
readonly server: {
|
|
8
|
+
readonly image: "supatype/server";
|
|
9
|
+
readonly tag: "v2.2.2";
|
|
10
|
+
readonly commit: "00f0ad3e782dbcf5fbb3d2e607aa044d66ba0138";
|
|
11
|
+
};
|
|
12
|
+
readonly postgres: {
|
|
13
|
+
readonly image: "supatype/postgres";
|
|
14
|
+
readonly tag: "17.2.12";
|
|
15
|
+
readonly commit: "ab9020f7691dced4875634dc88dfe500968faa5a";
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
//# sourceMappingURL=release-images.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"release-images.d.ts","sourceRoot":"","sources":["../../src/generated/release-images.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;CAIhB,CAAA"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Generated from release/images.json by scripts/release-images.mjs. Do not edit: run
|
|
2
|
+
// `bash scripts/pin.sh set <engine|server|postgres> <tag>`, which rewrites both.
|
|
3
|
+
export const PINNED_IMAGES = {
|
|
4
|
+
engine: { image: "supatype/schema-engine", tag: "v0.8.0", commit: "878b4980e53dfd959ad65eecf9df4224f4d611d6" },
|
|
5
|
+
server: { image: "supatype/server", tag: "v2.2.2", commit: "00f0ad3e782dbcf5fbb3d2e607aa044d66ba0138" },
|
|
6
|
+
postgres: { image: "supatype/postgres", tag: "17.2.12", commit: "ab9020f7691dced4875634dc88dfe500968faa5a" },
|
|
7
|
+
};
|
|
8
|
+
//# sourceMappingURL=release-images.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"release-images.js","sourceRoot":"","sources":["../../src/generated/release-images.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,iFAAiF;AACjF,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,MAAM,EAAE,EAAE,KAAK,EAAE,wBAAwB,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,0CAA0C,EAAE;IAC9G,MAAM,EAAE,EAAE,KAAK,EAAE,iBAAiB,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,0CAA0C,EAAE;IACvG,QAAQ,EAAE,EAAE,KAAK,EAAE,mBAAmB,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,0CAA0C,EAAE;CACpG,CAAA"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The engine that writes a project's generated files (the types, the client's seed builder, the
|
|
3
|
+
* admin config): `supatype generate` and Docker dev's refresh after a push both ask here.
|
|
4
|
+
*
|
|
5
|
+
* The host engine program, resolved as push resolves the one it writes types with: the pin, else
|
|
6
|
+
* this build's default, or `overrides.engine`. Generating needs no database, and running it in the
|
|
7
|
+
* compose image cost two `docker compose run`s and left the project's network and volume behind
|
|
8
|
+
* (local test round 3, N7). The two used to choose differently, so the types a save wrote and the
|
|
9
|
+
* ones `generate` wrote could come from two engines (decision, round 3).
|
|
10
|
+
*
|
|
11
|
+
* Only a host program that cannot be fetched (`BinaryUnavailable`: offline, a platform or libc with
|
|
12
|
+
* no build) falls back, and only for a Docker project with no engine override, to its own compose
|
|
13
|
+
* engine image. A refusal, an engine too old, or a config error is the answer as it is. A failed
|
|
14
|
+
* fetch is remembered for the process, so an offline dev session does not try the download again
|
|
15
|
+
* on every save, and the caller is told why once, after it has written with the image.
|
|
16
|
+
*/
|
|
17
|
+
import type { ComposeEngine } from "./engine-client.js";
|
|
18
|
+
import { type SupatypeProjectConfig } from "./project-config.js";
|
|
19
|
+
/** How the engine is found, replaceable in tests. */
|
|
20
|
+
export interface GeneratedFilesEngineDeps {
|
|
21
|
+
hostEngine: () => Promise<void>;
|
|
22
|
+
composeEngine: (cwd: string, config: SupatypeProjectConfig) => Promise<ComposeEngine | undefined>;
|
|
23
|
+
}
|
|
24
|
+
/** The engine to write with (undefined: the host program) and, the first time it fell back, why. */
|
|
25
|
+
export interface EngineChoice {
|
|
26
|
+
engine: ComposeEngine | undefined;
|
|
27
|
+
fellBack?: string;
|
|
28
|
+
}
|
|
29
|
+
/** What a caller says, once it has written with the image, about the fallback. */
|
|
30
|
+
export declare const ENGINE_FALLBACK = "The engine program could not be fetched, so the project's engine image wrote the generated files";
|
|
31
|
+
/** The engine to write generated files with: see the file's comment. */
|
|
32
|
+
export declare function generatedFilesEngine(cwd: string, config: SupatypeProjectConfig, deps?: Partial<GeneratedFilesEngineDeps>): Promise<EngineChoice>;
|
|
33
|
+
//# sourceMappingURL=generated-files-engine.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generated-files-engine.d.ts","sourceRoot":"","sources":["../src/generated-files-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAIvD,OAAO,EAA0B,KAAK,qBAAqB,EAAE,MAAM,qBAAqB,CAAA;AAExF,qDAAqD;AACrD,MAAM,WAAW,wBAAwB;IACvC,UAAU,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IAC/B,aAAa,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,qBAAqB,KAAK,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CAAA;CAClG;AAOD,oGAAoG;AACpG,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,aAAa,GAAG,SAAS,CAAA;IACjC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED,kFAAkF;AAClF,eAAO,MAAM,eAAe,qGAAqG,CAAA;AAKjI,wEAAwE;AACxE,wBAAsB,oBAAoB,CACxC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,qBAAqB,EAC7B,IAAI,GAAE,OAAO,CAAC,wBAAwB,CAAM,GAC3C,OAAO,CAAC,YAAY,CAAC,CAavB"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { hasEngineOverride, pinnedVersion } from "./binary-cache.js";
|
|
2
|
+
import { BinaryUnavailable } from "./ensure-binary.js";
|
|
3
|
+
import { errorMessage } from "./error-message.js";
|
|
4
|
+
import { resolveRuntimeProvider } from "./project-config.js";
|
|
5
|
+
const DEFAULT_DEPS = {
|
|
6
|
+
hostEngine: async () => (await import("./engine-client.js")).ensureEngine(),
|
|
7
|
+
composeEngine: async (cwd, config) => (await import("./dev-compose.js")).projectComposeEngine(cwd, config),
|
|
8
|
+
};
|
|
9
|
+
/** What a caller says, once it has written with the image, about the fallback. */
|
|
10
|
+
export const ENGINE_FALLBACK = "The engine program could not be fetched, so the project's engine image wrote the generated files";
|
|
11
|
+
/** Engine versions whose host program could not be fetched in this process. */
|
|
12
|
+
const unavailable = new Set();
|
|
13
|
+
/** The engine to write generated files with: see the file's comment. */
|
|
14
|
+
export async function generatedFilesEngine(cwd, config, deps = {}) {
|
|
15
|
+
const use = { ...DEFAULT_DEPS, ...deps };
|
|
16
|
+
const version = pinnedVersion("engine", config) ?? "this build's";
|
|
17
|
+
if (unavailable.has(version))
|
|
18
|
+
return { engine: await imageOrThrow(cwd, config, use, undefined) };
|
|
19
|
+
try {
|
|
20
|
+
await use.hostEngine();
|
|
21
|
+
return { engine: undefined };
|
|
22
|
+
}
|
|
23
|
+
catch (err) {
|
|
24
|
+
if (!(err instanceof BinaryUnavailable) || resolveRuntimeProvider(config) !== "docker" || hasEngineOverride(config))
|
|
25
|
+
throw err;
|
|
26
|
+
const engine = await imageOrThrow(cwd, config, use, err);
|
|
27
|
+
unavailable.add(version);
|
|
28
|
+
return { engine, fellBack: errorMessage(err) };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** The project's engine image, or an error that keeps the host program's reason beside the image's. */
|
|
32
|
+
async function imageOrThrow(cwd, config, use, hostError) {
|
|
33
|
+
const host = hostError === undefined ? "the engine program could not be fetched earlier" : errorMessage(hostError);
|
|
34
|
+
let image;
|
|
35
|
+
try {
|
|
36
|
+
image = await use.composeEngine(cwd, config);
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
throw new Error(`${host}; the project's engine image could not be used either: ${errorMessage(err)}`, { cause: err });
|
|
40
|
+
}
|
|
41
|
+
if (image === undefined)
|
|
42
|
+
throw hostError instanceof Error ? hostError : new Error(host);
|
|
43
|
+
return image;
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=generated-files-engine.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generated-files-engine.js","sourceRoot":"","sources":["../src/generated-files-engine.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AACpE,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAE,sBAAsB,EAA8B,MAAM,qBAAqB,CAAA;AAQxF,MAAM,YAAY,GAA6B;IAC7C,UAAU,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,oBAAoB,CAAC,CAAC,CAAC,YAAY,EAAE;IAC3E,aAAa,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,kBAAkB,CAAC,CAAC,CAAC,oBAAoB,CAAC,GAAG,EAAE,MAAM,CAAC;CAC3G,CAAA;AAQD,kFAAkF;AAClF,MAAM,CAAC,MAAM,eAAe,GAAG,kGAAkG,CAAA;AAEjI,+EAA+E;AAC/E,MA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C,IAAI,CAAC;QACH,KAAK,GAAG,MAAM,GAAG,CAAC,aAAa,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;IAC9C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,0DAA0D,YAAY,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAA;IACvH,CAAC;IACD,IAAI,KAAK,KAAK,SAAS;QAAE,MAAM,SAAS,YAAY,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,CAAA;IACvF,OAAO,KAAK,CAAA;AACd,CAAC"}
|
package/dist/hook-upload.d.ts
CHANGED
|
@@ -1,27 +1,41 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import { type HookMap } from "@supatype/shared";
|
|
2
|
+
import type { HookFiles } from "./resolve-target.js";
|
|
3
|
+
/** One handler as the deploy body carries it: its entry, flattened, and for a server every file of it. */
|
|
4
|
+
export interface HookHandlerUpload {
|
|
5
|
+
name: string;
|
|
6
|
+
/** The entry module, flattened and import-rewritten. */
|
|
7
|
+
source: string;
|
|
8
|
+
/** Every file of the hook's directory by its `/` path, as the project keeps it (a server only). */
|
|
9
|
+
files?: Record<string, string>;
|
|
10
|
+
}
|
|
11
|
+
/** A hook that failed the checks before upload, and why, said for the person who pushed it. */
|
|
12
|
+
export interface HookFailure {
|
|
13
|
+
name: string;
|
|
14
|
+
reason: string;
|
|
15
|
+
}
|
|
4
16
|
export interface HookUpload {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
/** table → event → config, exactly as the manifest would carry it. */
|
|
11
|
-
map: Record<string, Record<string, ManifestHookEntry>>;
|
|
17
|
+
handlers: HookHandlerUpload[];
|
|
18
|
+
/** table → event → config, exactly as the manifest would carry it: every hook, failed or not. */
|
|
19
|
+
map: HookMap;
|
|
20
|
+
/** The hooks that failed the checks, which the deploy keeps on the target as they are. */
|
|
21
|
+
failed: HookFailure[];
|
|
12
22
|
}
|
|
13
23
|
/**
|
|
14
|
-
* Read the hooks a schema actually names, ready to upload
|
|
24
|
+
* Read the hooks a schema actually names, and the functions its validators name, ready to upload
|
|
25
|
+
* to a target that takes hooks as `hookFiles` says. Validators name functions in the same directory
|
|
26
|
+
* as hooks, and a stack whose map names a validator it was never sent refuses every write to that
|
|
27
|
+
* column.
|
|
15
28
|
*
|
|
16
29
|
* **Named-only**, not every directory under `hooks/`: an unnamed handler would sit on the worker
|
|
17
30
|
* holding the service-role key with nothing able to call it. Uploading it buys nothing and widens what
|
|
18
31
|
* runs with that credential.
|
|
19
32
|
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* the
|
|
33
|
+
* Each hook is checked on its own. One that cannot be uploaded faithfully (no index.ts, a file it
|
|
34
|
+
* imports that would not be sent, a file that cannot be read) is in `failed` with why, said for a
|
|
35
|
+
* terminal, and the others are still sent: uploading it anyway would deploy a hook that fails to
|
|
36
|
+
* import, which reads to the caller as the table's writes being broken for no visible reason.
|
|
23
37
|
*/
|
|
24
|
-
export declare function readHookUpload(cwd: string, hooksDir: string, ast: unknown): HookUpload | null;
|
|
38
|
+
export declare function readHookUpload(cwd: string, hooksDir: string, ast: unknown, hookFiles: HookFiles): HookUpload | null;
|
|
25
39
|
/** The generated adapter as a handler-shaped entry, so it travels with them. */
|
|
26
40
|
export declare function adapterEntry(module: string): {
|
|
27
41
|
name: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hook-upload.d.ts","sourceRoot":"","sources":["../src/hook-upload.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"hook-upload.d.ts","sourceRoot":"","sources":["../src/hook-upload.ts"],"names":[],"mappings":"AAcA,OAAO,EAA6E,KAAK,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAE1H,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAGpD,0GAA0G;AAC1G,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,MAAM,CAAA;IACZ,wDAAwD;IACxD,MAAM,EAAE,MAAM,CAAA;IACd,mGAAmG;IACnG,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAC/B;AAED,+FAA+F;AAC/F,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAA;IACZ,MAAM,EAAE,MAAM,CAAA;CACf;AAED,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,iBAAiB,EAAE,CAAA;IAC7B,iGAAiG;IACjG,GAAG,EAAE,OAAO,CAAA;IACZ,0FAA0F;IAC1F,MAAM,EAAE,WAAW,EAAE,CAAA;CACtB;AAiBD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,cAAc,CAC5B,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,MAAM,EAChB,GAAG,EAAE,OAAO,EACZ,SAAS,EAAE,SAAS,GACnB,UAAU,GAAG,IAAI,CAgBnB;AAiED,gFAAgF;AAChF,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAE7E"}
|
package/dist/hook-upload.js
CHANGED
|
@@ -1,86 +1,115 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Package a project's hooks for a
|
|
2
|
+
* Package a project's hooks, and the functions its validators name, for a stack the push reaches over
|
|
3
|
+
* the network: Cloud, or a linked self-host stack (whose control plane writes them back into the
|
|
4
|
+
* project's layout).
|
|
3
5
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* explained, rather than in the deploy route where a dropped file would be silent.
|
|
6
|
+
* What a hook may be depends on the target (`targetHookSupport`). A managed project
|
|
7
|
+
* has no directory, its worker reads a ConfigMap, whose keys may only contain alphanumerics, `-`,
|
|
8
|
+
* `_` and `.`, so Cloud takes each hook as its one module, flattened here, where it can be checked
|
|
9
|
+
* and explained, rather than in the deploy route where a dropped file would be silent. A server
|
|
10
|
+
* writes the hook's directory back as the project keeps it, so it takes every file the worker loads.
|
|
8
11
|
*/
|
|
9
12
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
10
|
-
import { join, relative } from "node:path";
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* Rewrite the one import a hook handler is generated to make.
|
|
18
|
-
*
|
|
19
|
-
* `../_supatype/hooks.ts` is a path that cannot survive flattening, and it is the specifier our own
|
|
20
|
-
* scaffold writes: so it is rewritten rather than refused. Any *other* relative import is refused
|
|
21
|
-
* below: it would resolve to nothing on the worker, and a hook that fails to import is a hooked table
|
|
22
|
-
* whose writes all start failing.
|
|
23
|
-
*/
|
|
24
|
-
function rewriteAdapterImport(source) {
|
|
25
|
-
return source.split(ADAPTER_IMPORT).join(`./${ADAPTER_KEY}`);
|
|
26
|
-
}
|
|
27
|
-
/** Relative specifiers a flattened layout cannot honour, so the caller can refuse with a real reason. */
|
|
28
|
-
function unsupportedImports(source) {
|
|
13
|
+
import { join, posix, relative } from "node:path";
|
|
14
|
+
import { ADAPTER_IMPORT, ADAPTER_NAME, FLATTENED_ADAPTER_IMPORT, flattenHookSource } from "@supatype/shared";
|
|
15
|
+
import { declaredHooks, declaredValidators, manifestHooks } from "./model-hooks.js";
|
|
16
|
+
import { readWorkerFiles } from "./worker-module-files.js";
|
|
17
|
+
/** Relative specifiers in `source`: `from "./…"` and `import("./…")`, every form resolved against the file's own path. */
|
|
18
|
+
function relativeSpecifiers(source) {
|
|
29
19
|
const found = new Set();
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
const specifier = match[1];
|
|
33
|
-
if (specifier === ADAPTER_IMPORT || specifier === `./${ADAPTER_KEY}`)
|
|
34
|
-
continue;
|
|
35
|
-
found.add(specifier);
|
|
36
|
-
}
|
|
20
|
+
for (const match of source.matchAll(/(?:from|import)\s*\(?\s*["'](\.[^"']*)["']/g))
|
|
21
|
+
found.add(match[1]);
|
|
37
22
|
return [...found].sort();
|
|
38
23
|
}
|
|
39
24
|
/**
|
|
40
|
-
* Read the hooks a schema actually names, ready to upload
|
|
25
|
+
* Read the hooks a schema actually names, and the functions its validators name, ready to upload
|
|
26
|
+
* to a target that takes hooks as `hookFiles` says. Validators name functions in the same directory
|
|
27
|
+
* as hooks, and a stack whose map names a validator it was never sent refuses every write to that
|
|
28
|
+
* column.
|
|
41
29
|
*
|
|
42
30
|
* **Named-only**, not every directory under `hooks/`: an unnamed handler would sit on the worker
|
|
43
31
|
* holding the service-role key with nothing able to call it. Uploading it buys nothing and widens what
|
|
44
32
|
* runs with that credential.
|
|
45
33
|
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
* the
|
|
34
|
+
* Each hook is checked on its own. One that cannot be uploaded faithfully (no index.ts, a file it
|
|
35
|
+
* imports that would not be sent, a file that cannot be read) is in `failed` with why, said for a
|
|
36
|
+
* terminal, and the others are still sent: uploading it anyway would deploy a hook that fails to
|
|
37
|
+
* import, which reads to the caller as the table's writes being broken for no visible reason.
|
|
49
38
|
*/
|
|
50
|
-
export function readHookUpload(cwd, hooksDir, ast) {
|
|
51
|
-
const declared = declaredHooks(ast);
|
|
39
|
+
export function readHookUpload(cwd, hooksDir, ast, hookFiles) {
|
|
40
|
+
const declared = [...declaredHooks(ast), ...declaredValidators(ast)];
|
|
52
41
|
if (declared.length === 0)
|
|
53
42
|
return null;
|
|
54
43
|
const names = [...new Set(declared.map((hook) => hook.function))].sort();
|
|
55
|
-
const
|
|
44
|
+
const root = relative(cwd, hooksDir) || hooksDir;
|
|
56
45
|
const handlers = [];
|
|
46
|
+
const failed = [];
|
|
57
47
|
for (const name of names) {
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
throw new Error(`Hook "${name}" has no ${where}/${name}/index.ts`);
|
|
62
|
-
}
|
|
63
|
-
const extra = readdirSync(dir)
|
|
64
|
-
.filter((file) => file !== "index.ts")
|
|
65
|
-
.filter((file) => statSync(join(dir, file)).isFile() || !file.startsWith("."));
|
|
66
|
-
if (extra.length > 0) {
|
|
67
|
-
throw new Error(`Hook "${name}" has more than one file (${extra.join(", ")}).\n` +
|
|
68
|
-
`A managed stack serves each hook as a single module today, so the others would not be ` +
|
|
69
|
-
`uploaded and the hook would fail to import.\nMove what it needs into index.ts, or run this ` +
|
|
70
|
-
`hook on a self-hosted stack, which mounts the directory as it is.`);
|
|
48
|
+
const hook = { name, dir: join(hooksDir, name), where: posix.join(root.replace(/\\/g, "/"), name) };
|
|
49
|
+
try {
|
|
50
|
+
handlers.push(checkedHandler(hook, hookFiles));
|
|
71
51
|
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
if (unsupported.length > 0) {
|
|
75
|
-
throw new Error(`Hook "${name}" imports ${unsupported.join(", ")}, which a managed stack cannot resolve.\n` +
|
|
76
|
-
`Only the generated ${ADAPTER_IMPORT} survives upload; bare specifiers and URLs are fine.`);
|
|
52
|
+
catch (err) {
|
|
53
|
+
failed.push({ name, reason: err instanceof Error ? err.message : String(err) });
|
|
77
54
|
}
|
|
78
|
-
handlers.push({ name, source: rewriteAdapterImport(source) });
|
|
79
55
|
}
|
|
80
|
-
return { handlers, map: manifestHooks(ast) };
|
|
56
|
+
return { handlers, map: manifestHooks(ast), failed };
|
|
57
|
+
}
|
|
58
|
+
/** One hook as `hookFiles` says the target takes it; throws why when it cannot be uploaded faithfully. */
|
|
59
|
+
function checkedHandler(hook, hookFiles) {
|
|
60
|
+
if (!existsSync(join(hook.dir, "index.ts")))
|
|
61
|
+
throw new Error(`Hook "${hook.name}" has no ${hook.where}/index.ts`);
|
|
62
|
+
return hookFiles === "directory" ? directoryHandler(hook) : entryHandler(hook);
|
|
63
|
+
}
|
|
64
|
+
/** A hook as Supatype Cloud takes it: its index.ts alone, refused when it needs anything beside it. */
|
|
65
|
+
function entryHandler(hook) {
|
|
66
|
+
const extra = readdirSync(hook.dir)
|
|
67
|
+
.filter((file) => file !== "index.ts")
|
|
68
|
+
.filter((file) => statSync(join(hook.dir, file)).isFile() || !file.startsWith("."));
|
|
69
|
+
if (extra.length > 0) {
|
|
70
|
+
throw new Error(`Hook "${hook.name}" has more than one file (${extra.join(", ")}).\n` +
|
|
71
|
+
"Supatype Cloud serves each hook as its one module, so the others would not be uploaded and " +
|
|
72
|
+
`the hook would fail to import.\nMove what it needs into ${hook.where}/index.ts, or import it ` +
|
|
73
|
+
"by package or URL (npm:, jsr:, https:).");
|
|
74
|
+
}
|
|
75
|
+
const source = readFileSync(join(hook.dir, "index.ts"), "utf8");
|
|
76
|
+
// `../_supatype/hooks.ts` cannot survive flattening, and it is the specifier our own scaffold
|
|
77
|
+
// writes, so it is rewritten (@supatype/shared); any other relative import is refused.
|
|
78
|
+
const unsupported = relativeSpecifiers(source).filter((s) => s !== ADAPTER_IMPORT && s !== FLATTENED_ADAPTER_IMPORT);
|
|
79
|
+
if (unsupported.length > 0) {
|
|
80
|
+
throw new Error(`Hook "${hook.name}" imports ${unsupported.join(", ")}, which Supatype Cloud cannot resolve: it ` +
|
|
81
|
+
`serves each hook as its one module.\nOnly the generated ${ADAPTER_IMPORT} survives upload; ` +
|
|
82
|
+
"move the rest into index.ts, or import it by package or URL (npm:, jsr:, https:).");
|
|
83
|
+
}
|
|
84
|
+
return { name: hook.name, source: flattenHookSource(source) };
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* A hook as a server takes it: every file of its directory the worker loads, written back as the
|
|
88
|
+
* project keeps it. Refused when a file imports one outside the directory, which is not sent; the
|
|
89
|
+
* generated adapter beside it is.
|
|
90
|
+
*/
|
|
91
|
+
function directoryHandler(hook) {
|
|
92
|
+
const files = readWorkerFiles(hook.dir);
|
|
93
|
+
const outside = Object.entries(files).flatMap(([path, source]) => importsNotSent(path, source, files));
|
|
94
|
+
if (outside.length > 0) {
|
|
95
|
+
throw new Error(`Hook "${hook.name}" imports ${outside.join(", ")}, outside ${hook.where}/, which is not uploaded ` +
|
|
96
|
+
"with it.\nMove what it needs into the hook's directory, or import it by package or URL (npm:, jsr:, https:).");
|
|
97
|
+
}
|
|
98
|
+
return { name: hook.name, source: flattenHookSource(files["index.ts"] ?? ""), files };
|
|
99
|
+
}
|
|
100
|
+
/** Where the generated adapter is, from the hook's directory: sent with every deploy that has hooks. */
|
|
101
|
+
const ADAPTER_FROM_HOOK = posix.normalize(ADAPTER_IMPORT);
|
|
102
|
+
/** The relative imports of the file at `path` that resolve to no file sent with it, each named with the file it is in. */
|
|
103
|
+
function importsNotSent(path, source, files) {
|
|
104
|
+
return relativeSpecifiers(source)
|
|
105
|
+
.filter((specifier) => {
|
|
106
|
+
const resolved = posix.normalize(posix.join(posix.dirname(path), specifier));
|
|
107
|
+
return resolved !== ADAPTER_FROM_HOOK && files[resolved] === undefined;
|
|
108
|
+
})
|
|
109
|
+
.map((specifier) => (path === "index.ts" ? specifier : `${specifier} (in ${path})`));
|
|
81
110
|
}
|
|
82
111
|
/** The generated adapter as a handler-shaped entry, so it travels with them. */
|
|
83
112
|
export function adapterEntry(module) {
|
|
84
|
-
return { name:
|
|
113
|
+
return { name: ADAPTER_NAME, source: module };
|
|
85
114
|
}
|
|
86
115
|
//# sourceMappingURL=hook-upload.js.map
|
package/dist/hook-upload.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hook-upload.js","sourceRoot":"","sources":["../src/hook-upload.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"hook-upload.js","sourceRoot":"","sources":["../src/hook-upload.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AACzE,OAAO,EAAE,IA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AAI,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,CAAA;AAC/C,CAAC"}
|
|
@@ -5,4 +5,9 @@
|
|
|
5
5
|
* that have no hooks, a generated file nobody imports is a file somebody eventually edits.
|
|
6
6
|
*/
|
|
7
7
|
export declare function generateHooksModule(ast: unknown): string | null;
|
|
8
|
+
/**
|
|
9
|
+
* The module source for `ast`, with no table when no model declares a hook: what a handler just
|
|
10
|
+
* scaffolded imports, so it loads before the push that wires it writes the tables.
|
|
11
|
+
*/
|
|
12
|
+
export declare function hooksModuleSource(ast: unknown): string;
|
|
8
13
|
//# sourceMappingURL=hooks-generator.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks-generator.d.ts","sourceRoot":"","sources":["../src/hooks-generator.ts"],"names":[],"mappings":"AAuCA;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,
|
|
1
|
+
{"version":3,"file":"hooks-generator.d.ts","sourceRoot":"","sources":["../src/hooks-generator.ts"],"names":[],"mappings":"AAuCA;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAE/D;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAmYtD"}
|
package/dist/hooks-generator.js
CHANGED
|
@@ -31,9 +31,14 @@ function hookedModels(ast) {
|
|
|
31
31
|
* that have no hooks, a generated file nobody imports is a file somebody eventually edits.
|
|
32
32
|
*/
|
|
33
33
|
export function generateHooksModule(ast) {
|
|
34
|
+
return hookedModels(ast).length === 0 ? null : hooksModuleSource(ast);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The module source for `ast`, with no table when no model declares a hook: what a handler just
|
|
38
|
+
* scaffolded imports, so it loads before the push that wires it writes the tables.
|
|
39
|
+
*/
|
|
40
|
+
export function hooksModuleSource(ast) {
|
|
34
41
|
const models = hookedModels(ast);
|
|
35
|
-
if (models.length === 0)
|
|
36
|
-
return null;
|
|
37
42
|
const tableEntries = models
|
|
38
43
|
.map((model) => ` ${JSON.stringify(model.table)}: {
|
|
39
44
|
Row: ${indent(denoSafe(generateRowType(model.fields)), 4)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks-generator.js","sourceRoot":"","sources":["../src/hooks-generator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAC1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAA;AAC7D,OAAO,EACL,WAAW,EACX,kBAAkB,EAClB,eAAe,EACf,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,6BAA6B,CAAA;AAOpC,uEAAuE;AACvE,SAAS,YAAY,CAAC,GAAY;IAChC,OAAO,WAAW,CAAC,GAAG,CAAC;SACpB,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QAChB,MAAM,QAAQ,GAAG,QAAQ,CAAC,KAAK,EAAE,aAAa,EAAE,UAAU,CAAC,CAAA;QAC3D,yFAAyF;QACzF,4EAA4E;QAC5E,OAAO,gBAAgB,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,CAAC,IAAI,gBAAgB,CAAC,QAAQ,EAAE,CAAC,UAAU,CAAC,CAAC,CAAA;IAC1F,CAAC,CAAC;QACF,uFAAuF;SACtF,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,gBAAgB,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,wBAAwB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;SAC7F,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAA;AACnD,CAAC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