Navigate

API reference

pyric/storage

72 published symbols from pyric

Generated from the TypeScript declarations shipped at this import path.

Check behavioral conformance

Classes

InspectStorageHandler

Constructors

Constructor
new InspectStorageHandler(): InspectStorageHandler;
Returns

InspectStorageHandler

Methods

execute()
execute(scope: ProjectScope): Promise<InspectStorageResult>;
Parameters
ParameterType
scopeProjectScope
Returns

Promise<InspectStorageResult>


ProvisionStorageHandler

Constructors

Constructor
new ProvisionStorageHandler(): ProvisionStorageHandler;
Returns

ProvisionStorageHandler

Methods

execute()
execute(
   scope: ProjectScope,
   input: ProvisionStorageInput,
onProgress?: ProvisionProgress): Promise<ProvisionStorageOutcome>;
Parameters
ParameterType
scopeProjectScope
inputProvisionStorageInput
onProgress?ProvisionProgress
Returns

Promise<ProvisionStorageOutcome>


StorageError

Storage error carrying a prefixed storage/<code> on .code. Drop-in for err.code === 'storage/object-not-found' branching.

Extends

  • Error

Constructors

Constructor
new StorageError(code: StorageErrorCode, message: string): StorageError;
Parameters
ParameterType
codeStorageErrorCode
messagestring
Returns

StorageError

Overrides
Error.constructor

Properties

PropertyModifierTypeDescription
codereadonly| "storage/invalid-argument" | "storage/unknown" | "storage/object-not-found" | "storage/bucket-not-found" | "storage/project-not-found" | "storage/quota-exceeded" | "storage/unauthenticated" | "storage/unauthorized" | "storage/unauthorized-app" | "storage/retry-limit-exceeded" | "storage/invalid-checksum" | "storage/canceled" | "storage/invalid-event-name" | "storage/invalid-url" | "storage/invalid-default-bucket" | "storage/no-default-bucket" | "storage/cannot-slice-blob" | "storage/server-file-wrong-size" | "storage/no-download-url" | "storage/invalid-argument-count" | "storage/app-deleted" | "storage/invalid-root-operation" | "storage/invalid-format" | "storage/internal-error" | "storage/unsupported-environment"Prefixed code, e.g. storage/object-not-found.

StorageProvisioningError

Pure-fetch client for the Firebase Storage provisioning APIs. Takes an OAuth access token directly — works equally from a Node agent runtime or a browser. Used by:

  • ProvisionStorageHandler server-side via the agent SDK
  • Consumers like the multi-tenant playground via direct import

The caller is responsible for token scope. firebase scope is enough for the :addFirebase + defaultLocation:finalize calls, but NOT for enabling the underlying firebasestorage.googleapis.com service (which is the first-time gate). Service-enable requires cloud-platform scope OR a service account with roles/serviceusage.serviceUsageAdmin. Each function below documents which scope it needs.

Endpoints under play:

  • serviceusage.googleapis.com/v1/projects/{p}/services/{s}:enable
  • firebase.googleapis.com/v1beta1/projects/{p}/defaultLocation:finalize
  • firebasestorage.googleapis.com/v1beta/projects/{p}/buckets
  • firebasestorage.googleapis.com/v1beta/projects/{p}/buckets/{b}:addFirebase
  • firebaserules.googleapis.com/v1/projects/{p}/releases/firebase.storage

Extends

  • Error

Constructors

Constructor
new StorageProvisioningError(
   status: number,
   body: string,
   reason: string,
   message: string): StorageProvisioningError;
Parameters
ParameterType
statusnumber
bodystring
reasonstring
messagestring
Returns

StorageProvisioningError

Overrides
Error.constructor

Properties

PropertyModifierType
bodyreadonlystring
reasonreadonlystring
statusreadonlynumber

Interfaces

CorsRule

A single CORS rule entry, mirroring the GCS bucket CORS schema. See https://cloud.google.com/storage/docs/cross-origin#cors-elements.

Properties

PropertyType
maxAgeSeconds?number
methodstring[]
originstring[]
responseHeader?string[]

EvaluationInput

Properties

PropertyType
requestStorageRequest
resourceStorageResource

EvaluationResult

Properties

PropertyTypeDescription
allowedboolean-
evaluatedExpressionsnumberExpressions the evaluation counted, in the unit of production’s per-request limit of 1000 (the Firestore rules unit; see TestResult.evaluatedExpressions in pyric/rules). The count spans every allow rule and match block evaluated for the request.
reasonsstring[]Human-readable explanation of why — used by Slice 8’s integration to populate storage/unauthorized error messages.
resourceLimit?RulesResourceLimitSet when the request reached the 1000-expression limit, which denies it with production’s message.

FirebaseStorage

Public opaque handle. Carries a Target via TARGET_SYMBOL; never inspected by consumer code, which interacts with storage only through ref and the operation free functions.

Properties

PropertyModifierType
[TARGET_SYMBOL]readonlySandboxTarget
app?readonlyFirebaseApp

FirebaseStorageBucket

Properties

PropertyType
bucketIdstring
namestring
reconciling?boolean

FirestoreLookup

Injected capability that lets a Storage rule read Firestore documents (firestore.get(path) / firestore.exists(path)), WITHOUT the pure evaluator importing the Firestore sandbox. The enforcement layer builds one from the sandbox’s admin Firestore accessor (a synchronous in-memory read) and passes it into evaluateStorageRules; pure/test callers that omit it get the deny-with-reason “unsupported” behavior instead.

Paths are the document path RELATIVE to the database — the collection/doc form sandbox.admin.getDocument expects — after the evaluator has stripped the /databases/<db>/documents/ prefix from the rule’s path literal.

Methods

exists()
exists(path: string): boolean;

Whether a document exists at path.

Parameters
ParameterType
pathstring
Returns

boolean

get()
get(path: string): Record<string, unknown>;

The document’s fields, or null when the document does not exist.

Parameters
ParameterType
pathstring
Returns

Record<string, unknown>


FullMetadata

Server-set + client-settable fields read back from uploadBytes / getMetadata / updateMetadata. Server-set fields (bucket, fullPath, name, generation, metageneration, timeCreated, updated, size) are populated by the upload pipeline; client-settable fields round-trip from SettableMetadata.

Extends

Properties

PropertyType
bucketstring
cacheControl?string
contentDisposition?string
contentEncoding?string
contentLanguage?string
contentType?string
customMetadata?{ [key: string]: string; }
fullPathstring
generationstring
md5Hash?string
metagenerationstring
namestring
sizenumber
timeCreatedstring
updatedstring

InspectStorageResult

Properties

PropertyType
buckets{ bucketId: string; name: string; }[]
defaultLocationstring
serviceState"enabled" | "unknown" | "disabled"

ListResult

Mirrors firebase/storage’s ListResult. nextPageToken is undefined for listAll; query pyric can-i-use storage/list for the current availability of the separate paginated operation.

Properties

PropertyType
itemsStorageReference[]
nextPageToken?string
prefixesStorageReference[]

ProvisionStorageInput

Shapes for the Storage provisioning + status tools.

Types only — the agent-tool parameter schemas live inline in tools.ts as JSON Schema (the ToolHandler contract).

Properties

PropertyTypeDescription
bucketId?stringOverride the default Firebase Storage bucket ID. Defaults to {projectId}.firebasestorage.app.
cors?{ maxAgeSeconds?: number; method: string[]; origin: string[]; responseHeader?: string[]; }[]CORS rules to apply to the bucket. Required for browser-side reads/writes from a non-Firebase origin. Omit to leave existing CORS untouched.
locationId?stringDefault GCP resources location to use when the project has not been finalized yet. IRREVERSIBLE once set. Common values: us-central, nam5, eur3. Default: us-central.
rules?stringStorage rules source to deploy after the bucket is linked. Optional; when omitted, whatever rules are currently released (possibly the deny-all default) stay in place.

ProvisionStorageOptions

Properties

PropertyTypeDescription
bucketId?stringOverride the default Firebase Storage bucket ID. Defaults to {projectId}.firebasestorage.app — the bucket Firebase Console creates automatically.
cors?CorsRule[]CORS rules to apply to the bucket after it’s linked. Required for browser-side reads/writes from a non-Firebase origin — buckets created via the Cloud Console (vs Firebase Console) often ship with no CORS configuration, which manifests as No 'Access-Control-Allow-Origin' header on the first XMLHttpRequest from a hosted page. Pass defaultPlaygroundCors(origin) for a sensible starter config, or a custom array. Omit to leave the bucket’s CORS alone.
locationId?stringDefault GCP resources location to use if the project hasn’t been finalized yet. Ignored when the location is already set. Default: 'us-central'.
onProgress?ProvisionProgressOptional progress callback, invoked at each provisioning step boundary.
rules?stringStorage rules source to deploy after the bucket is linked. When omitted, no rules are deployed (the project keeps whatever rules were last released — possibly the default deny-all).

ProvisionStorageResult

Properties

PropertyType
bucketCreatedboolean
bucketIdstring
corsAppliedboolean
locationFinalizedboolean
locationIdstring
oktrue
rulesDeployedboolean
rulesetName?string
serviceEnabledboolean

SandboxTarget

Sandbox target — IDB-backed, identity from SandboxContext, rules enforced in-process via enforce.ts.

Properties

PropertyModifierTypeDescription
admin?readonlybooleanRules-bypass admin plane. true only on handles minted by the INTERNAL getAdminStorageSandbox factory (exported via pyric/storage/internal, never the public surface): operations on an admin handle skip rule evaluation entirely — the storage mirror of getAdminFirestore / getAdminDatabase. The public modular surface stays rules-honest; this exists so hosts (the SharedWorker’s actAs: { mode: 'admin' } lens) can serve firebase-admin semantics against the same shared store.
bucketreadonlystring-
bucketName?readonlystringThe name the caller knows this bucket by, which Storage rules see in place of the store key bucket (see sandbox/rules-bucket-name.ts). Absent when the caller named none, and the rules then see the store key.
caller?readonlyEventCallerThe connection an operation-scoped handle serves; see EventCaller.
contextreadonlySandboxContext-
currentAuth?readonly() => { tenant?: string; token?: Record<string, unknown>; uid: string; }App handles resolve auth at operation time; explicit contexts stay frozen.
kindreadonly"sandbox"-
sandboxreadonlySandbox-
servicePromisereadonlyPromise<StorageService>-

SettableMetadata

Client-settable fields. Passed to uploadBytes / uploadString / updateMetadata. Every field is optional — the upload pipeline fills any unsupplied client fields with sane defaults (e.g. contentType falls back to application/octet-stream).

Extended by

Properties

PropertyType
cacheControl?string
contentDisposition?string
contentEncoding?string
contentLanguage?string
contentType?string
customMetadata?{ [key: string]: string; }

StorageAdminToolDeps

Properties

PropertyTypeDescription
scopeProjectScopeProject identity + token resolver.

StorageAuth

Identity passed in with the request. null is anonymous.

Properties

PropertyTypeDescription
tenant?stringMulti-tenant identity. The evaluator projects it into request.auth.token.firebase.tenant through the sandbox context’s shared normalization, preserving any explicit nested value.
token?Record<string, unknown>-
uidstring-

StorageOptions

Options for getStorageSandbox.

Properties

PropertyTypeDescription
bucket?stringBucket identifier recorded on uploaded metadata and used to isolate storage persistence across multiple buckets.
crossServiceIam?CrossServiceIamModel the production Storage→Firestore IAM dependency (see CrossServiceIam). Defaults to 'granted'. Like rules, only honored on the FIRST storage call per Sandbox; a LATER, DIFFERING value throws instead of silently flipping the mode.
dbName?stringOverride the IndexedDB database name. Tests pass per-case unique names so state doesn’t leak between runs. Only takes effect on the FIRST call per Sandbox.
projectId?stringProject identity used to derive the default IndexedDB database name (pyric-storage:<projectId> — see storageDbName). IndexedDB is origin-scoped, so without this every project served on the same localhost port shared one storage database (issue #359). Ignored when an explicit dbName is given; only honored on the FIRST call per Sandbox. Hosts pass their project identity here (pyric sandbox passes the served project’s key; app handles pass options.projectId).
rules?stringStorage rules source. Parsed eagerly so a malformed string throws at config time. Only honored on the FIRST call per Sandbox.

StorageReference

Public reference shape. Methods are inherited from the impl classes below; the interface is exported so consumer code can name the type without depending on the impls.

Properties

PropertyModifierType
bucketreadonlystring
fullPathreadonlystring
namereadonlystring
parentreadonlyStorageReference
rootreadonlyStorageReference
storagereadonlyFirebaseStorage

Methods

toString()
toString(): string;
Returns

string


StorageRequest

Inbound request bindings the rules see.

Properties

PropertyTypeDescription
authStorageAuth-
methodStorageRequestMethod-
pathstringPath of the object the request targets.
resource?StorageRequestResourcePer-Firebase: on writes, request.resource describes the about-to-write object. Omit for reads (the rules language treats request.resource as unset there).

StorageResource

Existing-object bindings (for resource.*). null when no object exists yet (creates).

The object-identity/time fields carry GOOGLE CLOUD STORAGE semantics, not the client SDK’s FullMetadata semantics — the two disagree on name:

  • rules resource.name is the object’s FULL path within the bucket (uploads/pic.png), the GCS object-name convention. The client SDK’s FullMetadata.name is the LAST path segment (pic.png). The adapter (resourceFromStored) therefore sources name from the persisted record’s fullPath, NOT its name.
  • timeCreated / updated are ISO-8601 strings here (the persisted shape); the evaluator converts them to Timestamp values when it builds the binding, so they compare against request.time and against each other. Production types them as timestamp and rejects an int in their place (“Received: int < timestamp”).
  • The update-time field is updated. There is NO resource.timeUpdated in the Storage rules language.

A field left undefined reads as ABSENT, which production treats as an evaluation error that denies (see RuleError).

Properties

PropertyTypeDescription
bucket?stringBucket the object lives in.
cacheControl?stringCache-Control header value.
contentDisposition?stringContent-Disposition header value.
contentEncoding?stringContent-Encoding header value.
contentLanguage?stringContent-Language header value.
contentType?string-
crc32c?stringBase64-encoded CRC32C checksum.
etag?stringHTTP entity tag.
generation?numberContent generation (production types it int).
md5Hash?stringBase64-encoded MD5 digest.
metadata?Record<string, string>-
metageneration?numberMetadata generation (production types it int).
name?stringFull object path within the bucket, e.g. uploads/pic.png.
sizenumber-
timeCreated?stringISO-8601 creation time.
updated?stringISO-8601 time of the most recent content/metadata update.

StorageRules

Opaque parsed-rules handle returned by parseStorageRules.


UploadResult

Return shape of uploadBytes / uploadString.

Properties

PropertyType
metadataFullMetadata
refStorageReference

UploadTask

Extends

Properties

PropertyModifierType
snapshotreadonlyUploadTaskSnapshot

Methods

cancel()
cancel(): boolean;
Returns

boolean

on()
on(
   event: string,
   nextOrObserver?:
  | (snapshot: UploadTaskSnapshot) => unknown
  | {
  complete?: () => unknown;
  error?: (error: Error | StorageError) => unknown;
  next?: (snapshot: UploadTaskSnapshot) => unknown;
},
   error?: (error: Error | StorageError) => unknown,
   complete?: () => unknown): () => void;
Parameters
ParameterType
eventstring
nextOrObserver?| (snapshot: UploadTaskSnapshot) => unknown | { complete?: () => unknown; error?: (error: Error | StorageError) => unknown; next?: (snapshot: UploadTaskSnapshot) => unknown; }
error?(error: Error | StorageError) => unknown
complete?() => unknown
Returns
(): void;
Returns

void

pause()
pause(): boolean;
Returns

boolean

resume()
resume(): boolean;
Returns

boolean


UploadTaskSnapshot

Properties

PropertyModifierType
bytesTransferredreadonlynumber
metadatareadonlyFullMetadata
refreadonlyStorageReference
statereadonlyTaskState
taskreadonlyUploadTask
totalBytesreadonlynumber

Type Aliases

CrossServiceIam

type CrossServiceIam = "granted" | "denied";

Cross-service IAM posture for firestore.get()/exists() in Storage rules.

Production Storage rules can read Firestore ONLY when the project’s Storage service agent holds roles/firebaserules.firestoreServiceAgent. 'granted' (the default, the common configured-project state) serves lookups from the same-sandbox Firestore store; 'denied' makes every EXECUTED lookup fail exactly like production without the role (error to rule denies), while short-circuited lookups are never executed and stay unaffected. Captured boundary: conformance observation stdlib-realstorage-p3-lookup-budget (registry row storage-rules#134).


ProvisionStorageErrorCode

type ProvisionStorageErrorCode =
  | "PERMISSION_DENIED"
  | "SERVICE_DISABLED"
  | "LOCATION_FINALIZE_FAILED"
  | "BUCKET_CREATE_FAILED"
  | "RULES_DEPLOY_FAILED"
  | "CORS_UPDATE_FAILED"
  | "UNKNOWN";

ProvisionStorageOutcome

type ProvisionStorageOutcome =
  | {
  bucketCreated: boolean;
  bucketId: string;
  corsApplied: boolean;
  locationFinalized: boolean;
  locationId: string | null;
  rulesDeployed: boolean;
  rulesetName?: string;
  serviceEnabled: boolean;
  success: true;
}
  | {
  error: {
     code: ProvisionStorageErrorCode;
     message: string;
     recoverable: boolean;
  };
  success: false;
};

ServiceEnableState

type ServiceEnableState = "enabled" | "disabled" | "unknown";

StorageErrorCode

type StorageErrorCode = typeof StorageErrorCode[keyof typeof StorageErrorCode];

StorageGrantVerb

type StorageGrantVerb = StorageMethod | StorageVerb;

A verb token that may appear in an allow clause.


StorageMethod

type StorageMethod = "read" | "write";

Coarse permission umbrellas. read covers get + list; write covers create + update + delete.


StorageRequestMethod

type StorageRequestMethod = StorageMethod | StorageVerb;

What a caller records as the request’s operation. Callers pass the precise granular verb; the coarse forms remain accepted so the umbrella semantics are symmetric.


StorageVerb

type StorageVerb = "get" | "list" | "create" | "update" | "delete";

Granular operation verbs. Production Storage maps each operation to exactly one of these: download / getMetadata → get list → list upload, whether or not an object exists at the path → create updateMetadata → update delete → delete On an upload over an existing object, resource is the stored object.


StringFormat

type StringFormat = typeof StringFormat[keyof typeof StringFormat];

Target

type Target = SandboxTarget;

TaskEvent

type TaskEvent = "state_changed";

TaskState

type TaskState = "running" | "paused" | "success" | "canceled" | "error";

Variables

deleteObject

const deleteObject: typeof rawdeleteObject;

getBlob

const getBlob: typeof rawgetBlob;

getBytes

const getBytes: typeof rawgetBytes;

getDownloadURL

const getDownloadURL: typeof rawgetDownloadURL;

getMetadata

const getMetadata: typeof rawgetMetadata;

listAll

const listAll: typeof rawlistAll;

StorageErrorCode

const StorageErrorCode: {
  APP_DELETED: "app-deleted";
  BUCKET_NOT_FOUND: "bucket-not-found";
  CANCELED: "canceled";
  CANNOT_SLICE_BLOB: "cannot-slice-blob";
  INTERNAL_ERROR: "internal-error";
  INVALID_ARGUMENT: "invalid-argument";
  INVALID_ARGUMENT_COUNT: "invalid-argument-count";
  INVALID_CHECKSUM: "invalid-checksum";
  INVALID_DEFAULT_BUCKET: "invalid-default-bucket";
  INVALID_EVENT_NAME: "invalid-event-name";
  INVALID_FORMAT: "invalid-format";
  INVALID_ROOT_OPERATION: "invalid-root-operation";
  INVALID_URL: "invalid-url";
  NO_DEFAULT_BUCKET: "no-default-bucket";
  NO_DOWNLOAD_URL: "no-download-url";
  OBJECT_NOT_FOUND: "object-not-found";
  PROJECT_NOT_FOUND: "project-not-found";
  QUOTA_EXCEEDED: "quota-exceeded";
  RETRY_LIMIT_EXCEEDED: "retry-limit-exceeded";
  SERVER_FILE_WRONG_SIZE: "server-file-wrong-size";
  UNAUTHENTICATED: "unauthenticated";
  UNAUTHORIZED: "unauthorized";
  UNAUTHORIZED_APP: "unauthorized-app";
  UNKNOWN: "unknown";
  UNSUPPORTED_ENVIRONMENT: "unsupported-environment";
};

Unprefixed Firebase Storage error codes.

Type Declaration

APP_DELETED
readonly APP_DELETED: "app-deleted";

BUCKET_NOT_FOUND
readonly BUCKET_NOT_FOUND: "bucket-not-found";

CANCELED
readonly CANCELED: "canceled";

CANNOT_SLICE_BLOB
readonly CANNOT_SLICE_BLOB: "cannot-slice-blob";

INTERNAL_ERROR
readonly INTERNAL_ERROR: "internal-error";

INVALID_ARGUMENT
readonly INVALID_ARGUMENT: "invalid-argument";

INVALID_ARGUMENT_COUNT
readonly INVALID_ARGUMENT_COUNT: "invalid-argument-count";

INVALID_CHECKSUM
readonly INVALID_CHECKSUM: "invalid-checksum";

INVALID_DEFAULT_BUCKET
readonly INVALID_DEFAULT_BUCKET: "invalid-default-bucket";

INVALID_EVENT_NAME
readonly INVALID_EVENT_NAME: "invalid-event-name";

INVALID_FORMAT
readonly INVALID_FORMAT: "invalid-format";

INVALID_ROOT_OPERATION
readonly INVALID_ROOT_OPERATION: "invalid-root-operation";

INVALID_URL
readonly INVALID_URL: "invalid-url";

NO_DEFAULT_BUCKET
readonly NO_DEFAULT_BUCKET: "no-default-bucket";

NO_DOWNLOAD_URL
readonly NO_DOWNLOAD_URL: "no-download-url";

OBJECT_NOT_FOUND
readonly OBJECT_NOT_FOUND: "object-not-found";

PROJECT_NOT_FOUND
readonly PROJECT_NOT_FOUND: "project-not-found";

QUOTA_EXCEEDED
readonly QUOTA_EXCEEDED: "quota-exceeded";

RETRY_LIMIT_EXCEEDED
readonly RETRY_LIMIT_EXCEEDED: "retry-limit-exceeded";

SERVER_FILE_WRONG_SIZE
readonly SERVER_FILE_WRONG_SIZE: "server-file-wrong-size";

UNAUTHENTICATED
readonly UNAUTHENTICATED: "unauthenticated";

UNAUTHORIZED
readonly UNAUTHORIZED: "unauthorized";

UNAUTHORIZED_APP
readonly UNAUTHORIZED_APP: "unauthorized-app";

UNKNOWN
readonly UNKNOWN: "unknown";

UNSUPPORTED_ENVIRONMENT
readonly UNSUPPORTED_ENVIRONMENT: "unsupported-environment";

StringFormat

const StringFormat: {
  BASE64: "base64";
  BASE64URL: "base64url";
  DATA_URL: "data_url";
  RAW: "raw";
};

Encodings accepted by Firebase Storage string uploads.

Type Declaration

BASE64
readonly BASE64: "base64";

BASE64URL
readonly BASE64URL: "base64url";

DATA_URL
readonly DATA_URL: "data_url";

RAW
readonly RAW: "raw";

TARGET_SYMBOL

const TARGET_SYMBOL: unique symbol;

Hidden property on every FirebaseStorage handle. Carries the sandbox state free functions share without exposing it publicly. Registered globally (Symbol.for) so src and dist module copies recognize handles and share per-sandbox service state across package boundaries.


updateMetadata

const updateMetadata: typeof rawupdateMetadata;

uploadBytes

const uploadBytes: typeof rawuploadBytes;

uploadBytesResumable

const uploadBytesResumable: typeof rawuploadBytesResumable;

uploadString

const uploadString: typeof rawuploadString;

Functions

addFirebaseToBucket()

function addFirebaseToBucket(
   accessToken: string,
   projectId: string,
bucketId: string): Promise<FirebaseStorageBucket>;

Link a Cloud Storage bucket to Firebase Storage. Idempotent — if the bucket is already Firebase-linked, the API returns 200 with the existing record. The bucket must already exist as a GCS resource; for the default Firebase bucket name ({projectId}.firebasestorage.app), Firebase auto-creates it on first :addFirebase call.

Parameters

ParameterType
accessTokenstring
projectIdstring
bucketIdstring

Returns

Promise<FirebaseStorageBucket>


connectStorageEmulator()

function connectStorageEmulator(
   _storage: FirebaseStorage,
   _host: string,
   _port: number,
   _options?: {
  mockUserToken?: string | Record<string, unknown>;
}): void;

Accepted no-op because the selected Storage backend already is local.

Parameters

ParameterType
_storageFirebaseStorage
_hoststring
_portnumber
_options?{ mockUserToken?: string | Record<string, unknown>; }
_options.mockUserToken?string | Record<string, unknown>

Returns

void


createStorageAdminTools()

function createStorageAdminTools(deps: StorageAdminToolDeps): ToolHandler<unknown, unknown>[];

Bundles:

  • storage_get_status
  • storage_provision

Parameters

ParameterType
depsStorageAdminToolDeps

Returns

ToolHandler<unknown, unknown>[]


defaultPlaygroundCors()

function defaultPlaygroundCors(hostingOrigin: string): CorsRule[];

Default rule for a browser playground hosted on Firebase Hosting. Allows GET/POST/PUT/DELETE/HEAD/OPTIONS from the Hosting origin

  • common localhost dev ports, with response headers needed by the Firebase Storage Web SDK.

Parameters

ParameterType
hostingOriginstring

Returns

CorsRule[]


deployStorageRules()

function deployStorageRules(
   accessToken: string,
   projectId: string,
   source: string,
   bucketId?: string): Promise<{
  rulesetName: string;
}>;

Deploy a Storage rules source for a specific bucket. Firebase Storage uses per-bucket release names — projects/{p}/releases/firebase.storage/{bucketId} — for actual rule application. The project-wide firebase.storage release exists as a legacy alias but isn’t bound to any bucket in modern projects; deploying to it leaves the bucket’s deny-all rule unchanged.

Defaults bucketId to {projectId}.firebasestorage.app (the Firebase default bucket name). Pass an override when targeting a non-default bucket.

Parameters

ParameterType
accessTokenstring
projectIdstring
sourcestring
bucketId?string

Returns

Promise<{ rulesetName: string; }>


enableStorageService()

function enableStorageService(accessToken: string, projectId: string): Promise<void>;

Enable firebasestorage.googleapis.com on the project. Requires serviceusage.services.enable IAM permission — included in roles/owner, roles/editor (deprecated), or roles/serviceusage.serviceUsageAdmin. The default Firebase Admin SDK service account does NOT have this; the caller’s token must either be a user-OAuth with cloud-platform scope or a SA with the elevated role.

Long-running operation under the hood; the response carries an operation name. We don’t poll — the response 200 is enough signal for our purposes, and a brief settle delay handles propagation.

Parameters

ParameterType
accessTokenstring
projectIdstring

Returns

Promise<void>


evaluateStorageRules()

function evaluateStorageRules(
   rules: StorageRules,
   input: EvaluationInput,
   now?: Date,
   firestoreLookup?: FirestoreLookup,
   observation?: StorageEvaluationObservation): EvaluationResult;

Parameters

ParameterType
rulesStorageRules
inputEvaluationInput
now?Date
firestoreLookup?FirestoreLookup
observation?StorageEvaluationObservation

Returns

EvaluationResult


finalizeDefaultLocation()

function finalizeDefaultLocation(
   accessToken: string,
   projectId: string,
locationId: string): Promise<void>;

Set the project’s default GCP resources location. IRREVERSIBLE — once set, the location cannot be changed. Skip-if-set is the caller’s job; this function unconditionally calls :finalize.

Per observed behavior, :finalize 404s on projects that already have resources provisioned (RTDB, Hosting) without a default location. The error path surfaces that to the caller.

Parameters

ParameterType
accessTokenstring
projectIdstring
locationIdstring

Returns

Promise<void>


getBucketCors()

function getBucketCors(accessToken: string, bucketId: string): Promise<CorsRule[]>;

Read the current CORS configuration for a bucket.

Parameters

ParameterType
accessTokenstring
bucketIdstring

Returns

Promise<CorsRule[]>


getDefaultLocation()

function getDefaultLocation(accessToken: string, projectId: string): Promise<string>;

Read the project’s current default GCP resources location. Returns null when the project hasn’t been finalized yet — e.g. brand-new Firebase projects with no resources. firebase scope is sufficient.

Parameters

ParameterType
accessTokenstring
projectIdstring

Returns

Promise<string>


getStorage()

function getStorage(app?: FirebaseApp, bucketUrl?: string): AppFirebaseStorage;

Resolve the Firebase-shaped Storage service associated with an app.

Parameters

ParameterType
app?FirebaseApp
bucketUrl?string

Returns

AppFirebaseStorage


getStorageSandbox()

function getStorageSandbox(target:
  | Sandbox
  | SandboxContext, options?: StorageOptions): FirebaseStorage;

Construct (or return cached) a sandbox-backed FirebaseStorage handle. Accepts either a bare Sandbox (anonymous identity wired up via sandbox.withAuth(null)) or an explicit SandboxContext. Idempotent on SandboxContext identity.

Parameters

ParameterType
target| Sandbox | SandboxContext
options?StorageOptions

Returns

FirebaseStorage


getStorageServiceState()

function getStorageServiceState(accessToken: string, projectId: string): Promise<ServiceEnableState>;

Probe whether the firebasestorage.googleapis.com service is enabled on the project. Cheap, uses Service Usage GET. Requires serviceusage.services.get permission (the default Firebase Admin SDK SA has this; user OAuth tokens with firebase scope do not).

Returns 'unknown' on permission failures so callers can downgrade to “try the operation; observe SERVICE_DISABLED” rather than block.

Parameters

ParameterType
accessTokenstring
projectIdstring

Returns

Promise<ServiceEnableState>


listFirebaseBuckets()

function listFirebaseBuckets(accessToken: string, projectId: string): Promise<FirebaseStorageBucket[]>;

List Firebase-linked Storage buckets on the project. Returns an empty list when none exist yet. Throws when the underlying service is disabled — callers should check getStorageServiceState first if they want to distinguish.

Parameters

ParameterType
accessTokenstring
projectIdstring

Returns

Promise<FirebaseStorageBucket[]>


parseStorageRules()

function parseStorageRules(source: string): StorageRules;

Parse a Storage rules source into an opaque handle. Throws SyntaxError on malformed input. Used by Slice 8’s getStorage(ctx, { rules }) to validate upfront.

Parameters

ParameterType
sourcestring

Returns

StorageRules


provisionStorage()

function provisionStorage(
   accessToken: string,
   projectId: string,
options?: ProvisionStorageOptions): Promise<ProvisionStorageResult>;

End-to-end Storage enablement + provisioning. Each step is idempotent (probe before mutating); the result reports what was actually done.

Permission requirements (caller’s token):

  • roles/serviceusage.serviceUsageAdmin (or Owner) — to enable the service when it’s disabled
  • cloud-platform OAuth scope (or firebase if service already enabled)

The handler throws StorageProvisioningError with the underlying reason (e.g. AUTH_PERMISSION_DENIED, SERVICE_DISABLED) so the caller can route to actionable UX.

Parameters

ParameterType
accessTokenstring
projectIdstring
options?ProvisionStorageOptions

Returns

Promise<ProvisionStorageResult>


ref()

Call Signature

function ref(storage: FirebaseStorage, path?: string): StorageReference;

Construct a reference. Two overloads matching Firebase:

ref(storage, path?) — path is bucket-rooted. Omit for root. A gs:// or download URL names its object, as ./url.ts describes. ref(parent, path) — path is relative to parent.fullPath.

Parameters
ParameterType
storageFirebaseStorage
path?string
Returns

StorageReference

Call Signature

function ref(parent: StorageReference, path: string): StorageReference;

Construct a reference. Two overloads matching Firebase:

ref(storage, path?) — path is bucket-rooted. Omit for root. A gs:// or download URL names its object, as ./url.ts describes. ref(parent, path) — path is relative to parent.fullPath.

Parameters
ParameterType
parentStorageReference
pathstring
Returns

StorageReference


setBucketCors()

function setBucketCors(
   accessToken: string,
   bucketId: string,
cors: CorsRule[]): Promise<void>;

Replace the bucket’s CORS configuration. Pass an empty array to clear all rules. The GCS API replaces (not merges) the cors field on PATCH.

Parameters

ParameterType
accessTokenstring
bucketIdstring
corsCorsRule[]

Returns

Promise<void>